Calling OpenAI APIs from code
Steps
a. Get openAI API Key
b. Call openai APIs using Postman
Place API_KEY got in step-1 in Authorization Header
GET https://api.openai.com/v1/models
Header
Authorization: Bearer API_KEY
POST https://api.openai.com/v1/chat/completions
Header
Authorization: Bearer API_KEY
Body
{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "What is capital of France?"}],
"temperature": 0.7
}
c. Calling APIs using Code
Create a Virtual Environment (Windows)
//Install python from Microsoft Store
> python
Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z
// Create venv
> python -m venv ./python_venv
>
// Activate venv
> cd python_venv
> Scripts\activate
(python_venv) path\python_venv>
Install openai inside Virtual Env
// Install openai
(python_venv) c:\go-here\Code\python\virtual_avatar> pip install openai
//Set API Key in User environment variable
OPENAI_API_KEY = value
Call openai API from Code
from openai import OpenAI
def get_chatgpt_response():
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content":
"You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
{"role": "user", "content":
"Compose a poem that explains the concept of recursion in programming."}
]
)
OR
def get_chatgpt_response():
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": "What's Capital of Russia?"
}
]
)
print(completion.choices[0].message) //Moscow
get_chatgpt_response()
Senior QA Engineer at Mtree Software Pvt Ltd, Noida
2 周Bas bhai..time aacha nahi chal raha..apna number bhej
Senior QA Engineer at Mtree Software Pvt Ltd, Noida
2 周Great bhai