client = OpenAI( # This is the default and can be omitted
api_key="你申请的 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?", )
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"
prompt ="What is in this image?" # 读取本地图片并编码为 Base64 withopen("path/to/image.png","rb")as image_file:
b64_image =base64.b64encode(image_file.read()).decode("utf-8")
async def main() ->None:
response = await client.responses.create(
model="gpt-5.2", input="Explain disestablishmentarianism to a smart five year old." ) print(response.output_text)
asyncio.run(main())
异步场景优化(aiohttp 后端),安装扩展版本:
pip install openai[aiohttp]
aiohttp 后端优化:
importos import asyncio from openai import DefaultAioHttpClient, AsyncOpenAI
async def main() ->None: # 上下文管理器确保资源释放
async with AsyncOpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
http_client=DefaultAioHttpClient(),# 启用 aiohttp 后端 )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)
基于 Server Side Events (SSE) 实时获取响应,同步 / 异步接口一致。
同步流式示例:
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,# 开启流式输出 )
for event in stream: print(event)# 逐段打印响应
异步流式示例:
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: print(event)
async def main():
async with client.realtime.connect(model="gpt-realtime")as connection:
async for event in connection: if event.type=='error': # 捕获并处理错误事件(连接不会断开) print(f"错误类型:{event.error.type}") print(f"错误码:{event.error.code}") print(f"错误信息:{event.error.message}")
asyncio.run(main())
参考手册
以下表格包含的内容为:
核心初始化:同步用 OpenAI、异步用 AsyncOpenAI、Azure 用 AzureOpenAI,推荐通过环境变量配置 API Key。