openai 是 [[OpenAI]] 公司开发的 [[Python]] 库,用于访问 OpenAI REST API,支持异步请求(由 [[httpx]] 支持)。
另外,许多第三方服务也支持通过 openai 库访问其 API,如 [[open-webui]] 等。
安装
pip install openai
使用
如果是第三方接口除了 api_key 参数外,还需要传递 base_url 参数:
from openai import OpenAI
client = OpenAI(api_key="api_key", base_url="https://api.openai.com/v1")
下面例子中,不再重复上面两行代码。
Responses API
文本
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?",)
print(response.output_text)
图像
response = client.responses.create( model="gpt-4o-mini", input=[ { "role": "user", "content": [ {"type": "input_text", "text": prompt}, {"type": "input_image", "image_url": f"{img_url}"}, ], } ],)
如果是 [[base64]] 编码图片,参数名不变,但是需要在编码前加上 data:image/png;base64,
前缀:
input=[ { "role": "user", "content": [ {"type": "input_text", "text": prompt}, {"type": "input_image", "image_url": f"data:image/png;base64,{b64_image}"}, ], }]
异步
async def main() -> None: response = await client.responses.create( model="gpt-4o", input="Explain disestablishmentarianism to a smart five year old." ) print(response.output_text)
asyncio.run(main())
Chat Completions API
文本
completion = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "developer", "content": "Talk like a pirate."}, { "role": "user", "content": "How do I check if a Python object is an instance of a class?", }, ],)
print(completion.choices[0].message.content)
图像
completion = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "user", "content": [ {"type": "text", "text": prompt}, { "type": "image_url", "image_url": {"url": f"{img_url}"}, }, ], } ])
print(completion.choices[0].message.content)
base64 编码图片同上。