Python OpenAI
openai is a powerful Python library for interacting with OpenAI's series of models and services.
openai encapsulates all RESTful API calls, allowing developers to easily integrate powerful AI capabilities into their own Python applications, such as natural language processing, image generation, and speech recognition.
Main features:
- Text generation: use models such as GPT-4 or GPT-5 to generate articles, code, summaries, dialogues, etc.
- Image generation: create images from text descriptions via the DALL-E model.
- Embeddings: convert text into vector representations, commonly used for semantic search, text classification, clustering, etc.
- Speech to text: transcribe audio files into text using the Whisper model.
- Fine-tuning: train a more targeted model by providing your own dataset.
- Assistants API: build complex applications that understand context, call tools, and interact over the long term.
openai open-source address:https://github.com/openai/openai-python

How to use?
Environment requirements:
- Python version: 3.9 and above.
- Dependencies: httpx (default), aiohttp (optional), websockets (required for Realtime API).
First, you need to install the openai library with pip:
pip install openai
或
pip3 install openai
Then go to the OpenAI official website https://platform.openai.com/ register an account, and generate an API Key on the API key page.
Check the installed version:
import openai
print(openai.__version__) # 输出当前 SDK 版本
Example
import
os
from
openai
import
OpenAI
client
=
OpenAI
(
This is the default and can be omitted
api_key
=
"your applied API key"
,
)
response
=
client.
responses
.
create
(
model
=
"gpt-4o"
,
instructions
=
"You are a coding assistant that talks like a pirate."
,
input
=
"How do I check if a Python object is an instance of a class?"
,
)
(
response.
output_text
)
Parameter Description:
| Parameter name | Required | Type | Description |
|---|---|---|---|
api_key |
Is | str |
The applied OpenAI key |
model |
Is | str |
Specifies the OpenAI large model to use, determining capability, reasoning level, and cost |
instructions |
No | str |
System-level instruction (System Prompt) that defines the model's identity, behavior, and expression style; it takes priority over input |
input |
Is | str / list |
User input content describing the specific problem or task |
Third-party models
Currently, accessing openai in China is still somewhat troublesome; many domestic providers also support openai, such as DeepSeek, Qwen, and GLM.
DeepSeek
The DeepSeek API is fully compatible with the OpenAI API format; with only minor configuration changes, you can directly use the OpenAI SDK or compatible tools to access the DeepSeek API.
| Parameters | Value / Description |
|---|---|
| base_url | Required, fixed value:https://api.deepseek.com(you can also fill in https://api.deepseek.com/v1, only for OpenAI compatibility; v1 is unrelated to the model version) |
| api_key | Required; you must first apply for a dedicated API Key on the DeepSeek official website (application address:https://platform.deepseek.com/) |
| model |
Required, the model to set: |
deepseek-v4-flashcorresponds to DeepSeek'snon-thinking mode, with fast response speed, suitable for general Q&A.deepseek-v4-procorresponds to DeepSeek'sthinking mode, with stronger reasoning ability, suitable for complex problem solving.Example
import
os
from
openai
import
OpenAI
client
=
OpenAI
(
api_key
=
os
.
environ
.
get
(
'DEEPSEEK_API_KEY'
)
,
It is recommended to configure via environment variables; you can also hardcode it (not recommended)
base_url
=
"https://api.deepseek.com"
)
response
=
client.
chat
.
completions
.
create
(
model
=
"deepseek-v4-flash"
,
messages
=
[
{
"role"
:
"system"
,
"content"
:
"You are a helpful assistant"
}
,
{
"role"
:
"user"
,
"content"
:
"Hello"
}
,
]
,
stream
=
False
stream=False for non-streaming (returns all at once), stream=True for streaming (returns in real time)
)
(
response.
choices
[
0
]
.
message
.
content
)
Usage
Next we use the OpenAI SDK to access the Tongyi Qianwen model on the Bailian service.
Non-streaming call example
Example
from
openai
import
OpenAI
import
os
def
get_response
(
)
:
client
=
OpenAI
(
api_key
=
"sk-xxx"
,
Please use the Alibaba Cloud Bailian API Key
base_url
=
"https://dashscope.aliyuncs.com/compatible-mode/v1"
,
Fill in the base_url of the DashScope SDK
)
completion
=
client.
chat
.
completions
.
create
(
model
=
"qwen-plus"
,
Here we use qwen-plus as an example; you can change the model name as needed. Model list: https://help.aliyun.com/zh/model-studio/getting-started/models
messages
=
[
{
'role'
:
'system'
,
'content'
:
'You are a helpful assistant.'
}
,
{
'role'
:
'user'
,
'content'
:
'Who are you?'
}
]
)
json data
#print(completion.model_dump_json())
(
completion.
choices
[
0
]
.
message
.
content
)
if
name
==
'main'
:
get_response
(
)
Running the code yields the following result:
我是通义千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!
Streaming call example
Example
from
openai
import
OpenAI
def
get_response
(
)
:
client
=
OpenAI
(
api_key
=
"sk-xxx"
,
base_url
=
"https://dashscope.aliyuncs.com/compatible-mode/v1"
,
)
completion
=
client.
chat
.
completions
.
create
(
model
=
"qwen-plus"
,
messages
=
[
{
'role'
:
'system'
,
'content'
:
'You are a helpful assistant.'
}
,
{
'role'
:
'user'
,
'content'
:
'Who are you?'
}
]
,
stream
=
True
,
stream_options
=
{
"include_usage"
:
True
}
)
for
chunk
in
completion:
the chunk may not have choices or delta
if
hasattr
(
chunk
,
"choices"
)
and
len
(
chunk
.
choices
)
0
:
choice
=
chunk
.
choices
[
0
]
if
hasattr
(
choice
,
"delta"
)
and
hasattr
(
choice.
delta
,
"content"
)
:
(
choice.
delta
.
content
,
end
=
''
,
flush
=
True
)
if
name
==
'main'
:
get_response
(
)
Running the code yields the following result:
我是通义千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。如果你有任何问题或需要帮助,欢迎随时告诉我!
Special features
Vision feature
Supports image input (URL or Base64 encoded) for multimodal interaction.
Image URL input:
Example
prompt
=
"What is in this image?"
img_url
=
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2023_06_08_Raccoon1.jpg/1599px-2023_06_08_Raccoon1.jpg"
response
=
client.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
[
{
"role"
:
"user"
,
"content"
:
[
{
"type"
:
"input_text"
,
"text"
: prompt
}
,
{
"type"
:
"input_image"
,
"image_url"
: img_url
}
,
]
,
}
]
,
)
(
response.
output_text
)
Base64 encoded image input:
Example
import
base64
from
openai
import
OpenAI
client
=
OpenAI
(
)
prompt
=
"What is in this image?"
Read a local image and encode it as Base64
with
open
(
"path/to/image.png"
,
"rb"
)
as
image_file:
b64_image
=
base64
.
b64encode
(
image_file.
read
(
)
)
.
decode
(
"utf-8"
)
response
=
client.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
[
{
"role"
:
"user"
,
"content"
:
[
{
"type"
:
"input_text"
,
"text"
: prompt
}
,
{
"type"
:
"input_image"
,
"image_url"
: f
"data:image/png;base64,{b64_image}"
}
,
]
,
}
]
,
)
Async usage
Replace OpenAI with AsyncOpenAI, and call the API via await:
Basic async example:
Example
import
os
import
asyncio
from
openai
import
AsyncOpenAI
client
=
AsyncOpenAI
(
api_key
=
os
.
environ
.
get
(
"OPENAI_API_KEY"
)
,
)
async
def
main
(
)
None
:
response
=
await client.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
"Explain disestablishmentarianism to a smart five year old."
)
(
response.
output_text
)
asyncio.
run
(
main
(
)
)
Optimize for async scenarios (aiohttp backend); install the extended version:
pip install openai[aiohttp]
aiohttp backend optimization:
Example
import
os
import
asyncio
from
openai
import
DefaultAioHttpClient
,
AsyncOpenAI
async
def
main
(
)
None
:
Context manager ensures resource release
async
with
AsyncOpenAI
(
api_key
=
os
.
environ
.
get
(
"OPENAI_API_KEY"
)
,
http_client
=
DefaultAioHttpClient
(
)
,
Enable the aiohttp backend
)
as
client:
chat_completion
=
await client.
chat
.
completions
.
create
(
messages
=
[
{
"role"
:
"user"
,
"content"
:
"Say this is a test"
}
]
,
model
=
"gpt-5.2"
,
)
asyncio.
run
(
main
(
)
)
Streaming responses
Obtain responses in real time based on Server Side Events (SSE); the synchronous / asynchronous interfaces are consistent.
Synchronous streaming example:
Example
from
openai
import
OpenAI
client
=
OpenAI
(
)
stream
=
client.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
"Write a one-sentence bedtime story about a unicorn."
,
stream
=
True
,
Enable streaming output
)
for
event
in
stream:
(
event
)
Print the response segment by segment
Asynchronous streaming example:
Example
import
asyncio
from
openai
import
AsyncOpenAI
client
=
AsyncOpenAI
(
)
async
def
main
(
)
:
stream
=
await client.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
"Write a one-sentence bedtime story about a unicorn."
,
stream
=
True
,
)
async
for
event
in
stream:
(
event
)
asyncio.
run
(
main
(
)
)
Realtime API
Low-latency multimodal conversation (text / audio), implemented over WebSocket, depending on the websockets library.
Basic text example:
Example
import
asyncio
from
openai
import
AsyncOpenAI
async
def
main
(
)
:
client
=
AsyncOpenAI
(
)
Establish a real-time connection
async
with
client.
realtime
.
connect
(
model
=
"gpt-realtime"
)
as
connection:
Update session configuration (output text only)
await connection.
session
.
update
(
session
=
{
"type"
:
"realtime"
,
"output_modalities"
:
[
"text"
]
}
)
Send a user message
await connection.
conversation
.
item
.
create
(
item
=
{
"type"
:
"message"
,
"role"
:
"user"
,
"content"
:
[
{
"type"
:
"input_text"
,
"text"
:
"Say hello!"
}
]
,
}
)
Trigger the model response
await connection.
response
.
create
(
)
Listen for real-time events
async
for
event
in
connection:
if
event.
type
==
"response.output_text.delta"
:
(
event.
delta
,
flush
=
True
,
end
=
""
)
Print text fragments in real time
elif
event.
type
==
"response.output_text.done"
:
(
)
New line after the response ends
elif
event.
type
==
"response.done"
:
break
Stop listening
asyncio.
run
(
main
(
)
)
Realtime API error handling:
Example
import
asyncio
from
openai
import
AsyncOpenAI
client
=
AsyncOpenAI
(
)
async
def
main
(
)
:
async
with
client.
realtime
.
connect
(
model
=
"gpt-realtime"
)
as
connection:
async
for
event
in
connection:
if
event.
type
==
'error'
:
Capture and handle error events (the connection is not dropped)
(
f
"Error type: {event.error.type}"
)
(
f
"Error code: {event.error.code}"
)
(
f
"Error message: {event.error.message}"
)
asyncio.
run
(
main
(
)
)
Reference manual
The following table contains:
- Core initialization: synchronous uses
OpenAI, async usesAsyncOpenAI, Azure usesAzureOpenAI; it is recommended to configure the API Key via environment variables. - Text generation: the new version prefers
responses.create(), classic scenarios usechat.completions.create(); streaming output requires settingstream=True。 - Advanced capabilities: support for multimodal (image input), Realtime API, file upload/fine-tuning; error handling requires catching
APIErrorsubclass; timeout/retry can be flexibly configured.
Installation and import
Install the official SDK:
pip install --upgrade openai
Import the core class:
from openai import OpenAI, AsyncOpenAI, AzureOpenAI
Create a client
Create a standard OpenAI client:
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY")
Create a client via environment variables:
import os
from openai import OpenAI
os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
client = OpenAI()
Set request timeout and retry count:
client = OpenAI(
timeout=30,
max_retries=2
)
Text generation (Responses API)
The most basic text generation request:
response = client.responses.create(
model="gpt-5.2",
input="Explain what Python is in one sentence"
)
print(response.output_text)
Constrain model behavior via instructions:
response = client.responses.create(
model="gpt-5.2",
instructions="你是一个严谨的 Python 教程作者",
input="Explain what list comprehension is"
)
print(response.output_text)
Multi-turn conversation
Use the input array to build contextual conversation:
response = client.responses.create(
model="gpt-5.2",
input=[
{"role": "user", "content": "Python 是什么?"},
{"role": "assistant", "content": "Python 是一门高级编程语言。"},
{"role": "user", "content": "它适合做什么?"}
]
)
print(response.output_text)
Structured output (JSON Schema)
Require the model to return JSON data conforming to the Schema:
response = client.responses.create(
model="gpt-5.2",
response_format={
"type": "json_schema",
"json_schema": {
"name": "tech_summary",
"schema": {
"type": "object",
"properties": {
"title": {"type": "string"},
"summary": {"type": "string"}
},
"required": ["title", "summary"]
}
}
},
input="Introduction to asyncio"
)
print(response.output_parsed)
Tool calling (Function Calling)
Define tools and let the model automatically decide whether to call them:
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取城市天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
}
]
response = client.responses.create(
model="gpt-5.2",
tools=tools,
input="What's the weather like in Beijing today?"
)
print(response.output)
Streaming output
Synchronous streaming output:
with client.responses.stream(
model="gpt-5.2",
input="Write a Python example code snippet"
) as stream:
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="")
Asynchronous streaming output:
stream = await client.responses.create(
model="gpt-5.2",
input="Explain what generative AI is",
stream=True
)
async for event in stream:
print(event)
Async calls (AsyncOpenAI)
Use the async client in asyncio:
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def main():
response = await client.responses.create(
model="gpt-5.2",
input="Explain what an event loop is"
)
print(response.output_text)
asyncio.run(main())
Realtime API
Use WebSocket for low-latency real-time conversation:
async with client.realtime.connect(model="gpt-realtime") as conn:
await conn.session.update(
session={"type": "realtime", "output_modalities": ["text"]}
)
await conn.conversation.item.create(
item={
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "你好"}]
}
)
async for event in conn:
print(event)
Image generation
Generate an image from text:
image = client.images.generate(
model="gpt-image-1",
prompt="一只在写代码的猫",
size="1024x1024"
)
print(image.data[0].url)
Embedding generation (Embeddings)
Generate text vector embeddings:
embedding = client.embeddings.create(
model="text-embedding-3-small",
input="Hello world"
)
print(embedding.data[0].embedding)
Speech to text (Speech to Text)
Convert an audio file to text:
audio_file = open("speech.mp3", "rb")
transcript = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
print(transcript.text)
Text to speech (Text to Speech)
Convert text to a speech file:
speech = client.audio.speech.create(
model="gpt-4o-mini-tts",
voice="alloy",
input="Hello, welcome to OpenAI"
)
with open("output.mp3", "wb") as f:
f.write(speech)
File management (Files API)
Upload a file:
from pathlib import Path
client.files.create(
file=Path("data.jsonl"),
purpose="fine-tune"
)
List files:
files = client.files.list()
for f in files:
print(f.id, f.filename)
Delete a file:
client.files.delete(file_id="file-xxx")
Model fine-tuning (Fine-tuning Jobs)
Create a fine-tuning task:
job = client.fine_tuning.jobs.create(
training_file="file-xxx",
model="gpt-3.5-turbo"
)
print(job.id, job.status)
Webhook verification
Verify and parse the Webhook request:
event = client.webhooks.unwrap(request_body, request_headers)
Verify signature only:
client.webhooks.verify_signature(request_body, request_headers)
Error handling
Catch exceptions thrown by the SDK:
import openai
try:
client.responses.create(
model="gpt-5.2",
input="test"
)
except openai.RateLimitError as e:
print("触发速率限制:", e)
except openai.APIConnectionError as e:
print("连接失败:", e)
Get the Request ID of a failed request:
try:
client.responses.create(model="gpt-5.2", input="test")
except openai.APIStatusError as exc:
print(exc.request_id)
Azure OpenAI compatibility
Initialize the Azure OpenAI client:
from openai import AzureOpenAI
client = AzureOpenAI(
api_version="2023-07-01-preview",
azure_endpoint="https://xxx.openai.azure.com"
)
Version and logs
Check the SDK version:
import openai
print(openai.__version__)
Enable SDK debug logging:
export OPENAI_LOG=debug
More API references:https://github.com/openai/openai-python/blob/main/api.md