openai/openai-python

GitHub: openai/openai-python

OpenAI 官方推出的 Python 库,为 Python 3.9+ 应用程序提供便捷且类型安全的 OpenAI REST API 访问能力。

Stars: 31017 | Forks: 4839

# OpenAI Python API 库 [![PyPI version](https://img.shields.io/pypi/v/openai.svg?label=pypi%20(stable))](https://pypi.org/project/openai/) OpenAI Python 库为任何 Python 3.9+ 应用程序提供了便捷访问 OpenAI REST API 的方式。该库包含了所有请求参数和响应字段的类型定义,并提供了基于 [httpx](https://github.com/encode/httpx) 的同步和异步客户端。 它是使用 [Stainless](https://stainlessapi.com/) 从我们的 [OpenAPI 规范](https://github.com/openai/openai-openapi) 生成的。 ## 文档 REST API 文档可在 [platform.openai.com](https://platform.openai.com/docs/api-reference) 上找到。该库的完整 API 可在 [api.md](api.md) 中找到。 ## 安装 ``` # 从 PyPI 安装 pip install openai ``` ## 用法 该库的完整 API 可在 [api.md](api.md) 中找到。 与 OpenAI 模型交互的主要 API 是 [Responses API](https://platform.openai.com/docs/api-reference/responses)。你可以使用以下代码从模型生成文本。 ``` import os from openai import OpenAI client = OpenAI( # This is the default and can be omitted api_key=os.environ.get("OPENAI_API_KEY"), ) response = client.responses.create( model="gpt-5.5", 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) ``` 之前用于生成文本的标准(将无限期支持)是 [Chat Completions API](https://platform.openai.com/docs/api-reference/chat)。你可以使用该 API 并通过以下代码从模型生成文本。 ``` from openai import OpenAI client = OpenAI() completion = client.chat.completions.create( model="gpt-5.5", 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) ``` 虽然你可以提供 `api_key` 关键字参数,但我们建议使用 [python-dotenv](https://pypi.org/project/python-dotenv/) 将 `OPENAI_API_KEY="My API Key"` 添加到你的 `.env` 文件中, 这样你的 API 密钥就不会被存储在源代码控制中。 [在此处获取 API 密钥](https://platform.openai.com/settings/organization/api-keys)。 ### 工作负载身份认证 对于像云托管的 Kubernetes、Azure 和 Google Cloud Platform 这样的安全、自动化环境,你可以使用来自云身份提供商的短期 token 进行工作负载身份认证,而不是使用长期有效的 API 密钥。 #### Kubernetes(service account token) ``` from openai import OpenAI from openai.auth import k8s_service_account_token_provider client = OpenAI( workload_identity={ "identity_provider_id": "idp-123", "service_account_id": "sa-456", "provider": k8s_service_account_token_provider( "/var/run/secrets/kubernetes.io/serviceaccount/token" ), }, ) response = client.chat.completions.create( model="gpt-5.5", messages=[{"role": "user", "content": "Hello!"}], ) ``` #### Azure(managed identity) ``` from openai import OpenAI from openai.auth import azure_managed_identity_token_provider client = OpenAI( workload_identity={ "identity_provider_id": "idp-123", "service_account_id": "sa-456", "provider": azure_managed_identity_token_provider( resource="https://management.azure.com/", ), }, ) ``` #### Google Cloud Platform(compute engine metadata) ``` from openai import OpenAI from openai.auth import gcp_id_token_provider client = OpenAI( workload_identity={ "identity_provider_id": "idp-123", "service_account_id": "sa-456", "provider": gcp_id_token_provider(audience="https://api.openai.com/v1"), }, ) ``` #### 自定义 subject token 提供程序 ``` from openai import OpenAI def get_custom_token() -> str: return "your-jwt-token" client = OpenAI( workload_identity={ "identity_provider_id": "idp-123", "service_account_id": "sa-456", "provider": { "token_type": "jwt", "get_token": get_custom_token, }, } ) ``` 你还可以自定义 token 刷新缓冲区(默认在过期前 1200 秒(20 分钟)): ``` from openai import OpenAI from openai.auth import k8s_service_account_token_provider client = OpenAI( workload_identity={ "identity_provider_id": "idp-123", "service_account_id": "sa-456", "provider": k8s_service_account_token_provider("/var/token"), "refresh_buffer_seconds": 120.0, } ) ``` ### 视觉 使用图片 URL: ``` 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.5", input=[ { "role": "user", "content": [ {"type": "input_text", "text": prompt}, {"type": "input_image", "image_url": f"{img_url}"}, ], } ], ) ``` 使用 base64 编码字符串作为图片: ``` import base64 from openai import OpenAI client = OpenAI() prompt = "What is in this image?" 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.5", input=[ { "role": "user", "content": [ {"type": "input_text", "text": prompt}, {"type": "input_image", "image_url": f"data:image/png;base64,{b64_image}"}, ], } ], ) ``` ## 异步用法 只需导入 `AsyncOpenAI` 而不是 `OpenAI`,并在每次 API 调用时使用 `await`: ``` import os import asyncio from openai import AsyncOpenAI client = AsyncOpenAI( # This is the default and can be omitted api_key=os.environ.get("OPENAI_API_KEY"), ) async def main() -> None: response = await client.responses.create( model="gpt-5.5", input="Explain disestablishmentarianism to a smart five year old." ) print(response.output_text) asyncio.run(main()) ``` 除此之外,同步和异步客户端的功能完全相同。 ### 使用 aiohttp 默认情况下,异步客户端使用 `httpx` 进行 HTTP 请求。但是,为了提高并发性能,你也可以使用 `aiohttp` 作为 HTTP 后端。 你可以通过安装 `aiohttp` 来启用它: ``` # 从 PyPI 安装 pip install openai[aiohttp] ``` 然后,你可以通过实例化客户端时传入 `http_client=DefaultAioHttpClient()` 来启用它: ``` import os import asyncio from openai import DefaultAioHttpClient from openai import AsyncOpenAI async def main() -> None: async with AsyncOpenAI( api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: chat_completion = await client.chat.completions.create( messages=[ { "role": "user", "content": "Say this is a test", } ], model="gpt-5.5", ) asyncio.run(main()) ``` ## 流式响应 我们支持使用 Server Side Events (SSE) 进行流式响应。 ``` from openai import OpenAI client = OpenAI() stream = client.responses.create( model="gpt-5.5", 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.5", input="Write a one-sentence bedtime story about a unicorn.", stream=True, ) async for event in stream: print(event) asyncio.run(main()) ``` ## Realtime API Realtime API 使你能够构建低延迟、多模态的对话体验。它目前支持将文本和音频作为输入和输出,并通过 WebSocket 连接支持[函数调用](https://platform.openai.com/docs/guides/function-calling)。 在底层,SDK 使用 [`websockets`](https://websockets.readthedocs.io/en/stable/) 库来管理连接。 Realtime API 通过客户端发送的事件和服务器发送的事件的组合来工作。客户端可以发送事件来执行诸如更新会话配置或发送文本和音频输入等操作。当音频响应完成或收到模型的文本响应时,服务器事件会进行确认。完整的事件参考可以在[这里](https://platform.openai.com/docs/api-reference/realtime-client-events)找到,指南可以在[这里](https://platform.openai.com/docs/guides/realtime)找到。 基于文本的基本示例: ``` import asyncio from openai import AsyncOpenAI async def main(): client = AsyncOpenAI() async with client.realtime.connect(model="gpt-realtime-2") as connection: await connection.session.update( session={"type": "realtime", "output_modalities": ["text"]} ) await connection.conversation.item.create( item={ "type": "message", "role": "user", "content": [{"type": "input_text", "text": "Say hello!"}], } ) await connection.response.create() async for event in connection: if event.type == "response.output_text.delta": print(event.delta, flush=True, end="") elif event.type == "response.output_text.done": print() elif event.type == "response.done": break asyncio.run(main()) ``` 然而,Realtime API 的真正魔力在于处理音频输入/输出,请参阅此示例 [TUI 脚本](https://github.com/openai/openai-python/blob/main/examples/realtime/push_to_talk_app.py) 获取完整的示例。 ### Realtime 错误处理 每当发生错误时,Realtime API 都会发送一个 [`error` event](https://platform.openai.com/docs/guides/realtime-model-capabilities#error-handling),并且连接将保持打开并可用。这意味着你需要自己处理它,因为当收到 `error` 事件时,SDK _不会直接引发错误_。 ``` client = AsyncOpenAI() async with client.realtime.connect(model="gpt-realtime-2") as connection: ... async for event in connection: if event.type == 'error': print(event.error.type) print(event.error.code) print(event.error.event_id) print(event.error.message) ``` ## 使用类型 嵌套的请求参数是 [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict)。响应是 [Pydantic models](https://docs.pydantic.dev),它们还提供了用于以下操作的辅助方法: - 序列化回 JSON,`model.to_json()` - 转换为字典,`model.to_dict()` 类型化的请求和响应在你的编辑器中提供了自动补全和文档。如果你希望在 VS Code 中看到类型错误以便更早地发现 bug,请将 `python.analysis.typeCheckingMode` 设置为 `basic`。 ## 分页 OpenAI API 中的列表方法支持分页。 该库为每个列表响应提供了自动分页迭代器,因此你不必手动请求连续的页面: ``` from openai import OpenAI client = OpenAI() all_jobs = [] # 根据需要自动获取更多页面。 for job in client.fine_tuning.jobs.list( limit=20, ): # Do something with job here all_jobs.append(job) print(all_jobs) ``` 或者,异步方式: ``` import asyncio from openai import AsyncOpenAI client = AsyncOpenAI() async def main() -> None: all_jobs = [] # Iterate through items across all pages, issuing requests as needed. async for job in client.fine_tuning.jobs.list( limit=20, ): all_jobs.append(job) print(all_jobs) asyncio.run(main()) ``` 或者,你可以使用 `.has_next_page()`、`.next_page_info()` 或 `.get_next_page()` 方法来更精细地控制页面处理: ``` first_page = await client.fine_tuning.jobs.list( limit=20, ) if first_page.has_next_page(): print(f"will fetch next page using these details: {first_page.next_page_info()}") next_page = await first_page.get_next_page() print(f"number of items we just fetched: {len(next_page.data)}") # 对于非 async 用法,请移除 `await`。 ``` 或者直接使用返回的数据: ``` first_page = await client.fine_tuning.jobs.list( limit=20, ) print(f"next page cursor: {first_page.after}") # => "next page cursor: ..." for job in first_page.data: print(job.id) # 对于非 async 用法,请移除 `await`。 ``` ## 嵌套参数 嵌套参数是使用 `TypedDict` 进行类型标注的字典,例如: ``` from openai import OpenAI client = OpenAI() response = client.responses.create( input=[ { "role": "user", "content": "How much ?", } ], model="gpt-5.5", text={"format": {"type": "json_object"}}, ) ``` ## 文件上传 与文件上传相对应的请求参数可以作为 `bytes`、[`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) 实例或 `(filename, contents, media type)` 元组传入。 ``` from pathlib import Path from openai import OpenAI client = OpenAI() client.files.create( file=Path("input.jsonl"), purpose="fine-tune", ) ``` 异步客户端使用完全相同的接口。如果你传入一个 [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) 实例,文件内容将被自动异步读取。 ## Webhook 验证 验证 webhook 签名是_可选的,但鼓励使用_。 有关 webhook 的更多信息,请参阅 [API 文档](https://platform.openai.com/docs/guides/webhooks)。 ### 解析 webhook payload 对于大多数用例,你可能希望同时验证 webhook 并解析 payload。为了实现这一点,我们提供了 `client.webhooks.unwrap()` 方法,该方法会解析 webhook 请求并验证它是否由 OpenAI 发送。如果签名无效,此方法将引发错误。 请注意,`body` 参数必须是从服务器发送的原始 JSON 字符串(不要先解析它)。在验证 webhook 是从 OpenAI 发送的之后,`.unwrap()` 方法会为你将此 JSON 解析为一个事件对象。 ``` from openai import OpenAI from flask import Flask, request app = Flask(__name__) client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default @app.route("/webhook", methods=["POST"]) def webhook(): request_body = request.get_data(as_text=True) try: event = client.webhooks.unwrap(request_body, request.headers) if event.type == "response.completed": print("Response completed:", event.data) elif event.type == "response.failed": print("Response failed:", event.data) else: print("Unhandled event type:", event.type) return "ok" except Exception as e: print("Invalid signature:", e) return "Invalid signature", 400 if __name__ == "__main__": app.run(port=8000) ``` ### 直接验证 webhook payload 在某些情况下,你可能希望将验证 webhook 与解析 payload 分开进行。如果你更喜欢单独处理这些步骤,我们提供了 `client.webhooks.verify_signature()` 方法来_仅验证_ webhook 请求的签名。与 `.unwrap()` 一样,如果签名无效,此方法将引发错误。 请注意,`body` 参数必须是从服务器发送的原始 JSON 字符串(不要先解析它)。然后,你需要在验证签名后自行解析 body。 ``` import json from openai import OpenAI from flask import Flask, request app = Flask(__name__) client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default @app.route("/webhook", methods=["POST"]) def webhook(): request_body = request.get_data(as_text=True) try: client.webhooks.verify_signature(request_body, request.headers) # Parse the body after verification event = json.loads(request_body) print("Verified event:", event) return "ok" except Exception as e: print("Invalid signature:", e) return "Invalid signature", 400 if __name__ == "__main__": app.run(port=8000) ``` ## 处理错误 当库无法连接到 API 时(例如,由于网络连接问题或超时),会引发 `openai.APIConnectionError` 的子类。 当 API 返回非成功状态码(即 4xx 或 5xx 响应)时,会引发 `openai.APIStatusError` 的子类,其中包含 `status_code` 和 `response` 属性。 所有错误都继承自 `openai.APIError`。 ``` import openai from openai import OpenAI client = OpenAI() try: client.fine_tuning.jobs.create( model="gpt-4o", training_file="file-abc123", ) except openai.APIConnectionError as e: print("The server could not be reached") print(e.__cause__) # an underlying Exception, likely raised within httpx. except openai.RateLimitError as e: print("A 429 status code was received; we should back off a bit.") except openai.APIStatusError as e: print("Another non-200-range status code was received") print(e.status_code) print(e.response) ``` 错误码如下: | 状态码 | 错误类型 | | ----------- | -------------------------- | | 400 | `BadRequestError` | | 401 | `AuthenticationError` | | 403 | `PermissionDeniedError` | | 404 | `NotFoundError` | | 422 | `UnprocessableEntityError` | | 429 | `RateLimitError` | | >=500 | `InternalServerError` | | N/A | `APIConnectionError` | ## 请求 ID SDK 中的所有对象响应都提供了一个 `_request_id` 属性,该属性源自 `x-request-id` 响应头,以便你可以快速记录失败的请求并将其报告给 OpenAI。 ``` response = await client.responses.create( model="gpt-5.5", input="Say 'this is a test'.", ) print(response._request_id) # req_123 ``` 请注意,与使用 `_` 前缀的其他属性不同,`_request_id` 属性_是_公开的。除非另有说明,_所有_其他带有 `_` 前缀的属性、方法和模块都是_私有的_。 ``` import openai try: completion = await client.chat.completions.create( messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-5.5" ) except openai.APIStatusError as exc: print(exc.request_id) # req_123 raise exc ``` ## 重试 默认情况下,某些错误会自动重试 2 次,并带有短暂的指数退避。 连接错误(例如,由于网络连接问题)、408 Request Timeout、409 Conflict、429 Rate Limit 和 >=500 Internal 错误默认都会重试。 你可以使用 `max_retries` 选项来配置或禁用重试设置: ``` from openai import OpenAI # 为所有请求配置默认值: client = OpenAI( # default is 2 max_retries=0, ) # 或者,按请求进行配置: client.with_options(max_retries=5).chat.completions.create( messages=[ { "role": "user", "content": "How can I get the name of the current day in JavaScript?", } ], model="gpt-5.5", ) ``` ## 超时 默认情况下,请求会在 10 分钟后超时。你可以使用 `timeout` 选项对其进行配置,该选项接受一个 float 或 [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) 对象: ``` from openai import OpenAI # 为所有请求配置默认值: client = OpenAI( # 20 seconds (default is 10 minutes) timeout=20.0, ) # 更精细的控制: client = OpenAI( timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), ) # 按请求覆盖: client.with_options(timeout=5.0).chat.completions.create( messages=[ { "role": "user", "content": "How can I list all files in a directory using Python?", } ], model="gpt-5.5", ) ``` 超时时,会引发 `APITimeoutError` 错误。 请注意,超时的请求[默认重试两次](#retries)。 ## 进阶 ### 日志记录 我们使用标准库的 [`logging`](https://docs.python.org/3/library/logging.html) 模块。 你可以通过将环境变量 `OPENAI_LOG` 设置为 `info` 来启用日志记录。 ``` $ export OPENAI_LOG=info ``` 或者设置为 `debug` 以获取更详细的日志记录。 ### 如何判断 `None` 表示 `null` 还是缺失 在 API 响应中,一个字段可能是明确的 `null`,或者完全缺失;无论哪种情况,它在此库中的值都是 `None`。你可以使用 `.model_fields_set` 来区分这两种情况: ``` if response.my_field is None: if 'my_field' not in response.model_fields_set: print('Got json like {}, without a "my_field" key present at all.') else: print('Got json like {"my_field": null}.') ``` ### 访问原始响应数据(例如 headers) 可以通过在任何 HTTP 方法调用前加上 `.with_raw_response.` 来访问“原始” Response 对象,例如: ``` from openai import OpenAI client = OpenAI() response = client.chat.completions.with_raw_response.create( messages=[{ "role": "user", "content": "Say this is a test", }], model="gpt-5.5", ) print(response.headers.get('X-My-Header')) completion = response.parse() # get the object that `chat.completions.create()` would have returned print(completion) ``` 这些方法返回一个 [`LegacyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) 对象。这是一个遗留类,因为我们将在下一个主版本中稍微更改它。 对于同步客户端,除了 `content` 和 `text` 将是方法而不是属性之外,其余大部分将保持不变。在异步客户端中,所有方法都将是异步的。 我们将提供一个迁移脚本,并且整个迁移过程应该是顺利的。 #### `.with_streamingResponse` 当你发出请求时,上述接口会立即读取完整的响应体,这可能并不总是你想要的。 要流式传输响应体,请改用 `.with_streaming_response`,它需要一个上下文管理器,并且只有在你调用 `.read()`、`.text()`、`.json()`、`.iter_bytes()`、`.iter_text()`、`.iter_lines()` 或 `.parse()` 时才会读取响应体。在异步客户端中,这些是异步方法。 因此,`.with_streaming_response` 方法返回一个不同的 [`APIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) 对象,而异步客户端返回一个 [`AsyncAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) 对象。 ``` with client.chat.completions.with_streaming_response.create( messages=[ { "role": "user", "content": "Say this is a test", } ], model="gpt-5.5", ) as response: print(response.headers.get("X-My-Header")) for line in response.iter_lines(): print(line) ``` 上下文管理器是必需的,以便确保响应被可靠地关闭。 ### 发起自定义/未记录的请求 该库进行了类型标注,以便于访问已记录的 API。 如果你需要访问未记录的 endpoints、params 或响应属性,仍然可以使用该库。 #### 未记录的 endpoints 要对未记录的 endpoints 发起请求,你可以使用 `client.get`、`client.post` 和其他 http 动词发起请求。发起此请求时,客户端上的选项(例如重试)将被遵守。 ``` import httpx response = client.post( "/foo", cast_to=httpx.Response, body={"my_param": True}, ) print(response.headers.get("x-foo")) ``` #### 未记录的请求参数 如果你想显式发送一个额外的参数,你可以使用 `extra_query`、`extra_body` 和 `extra_headers` 请求选项来实现。 #### 未记录的响应属性 要访问未记录的响应属性,你可以像访问 `response.unknown_prop` 一样访问这些额外字段。你也可以使用 [`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra) 将 Pydantic 模型上的所有额外字段作为 dict 获取。 ### 配置 HTTP 客户端 你可以直接覆盖 [httpx client](https://www.python-httpx.org/api/#client) 以根据你的用例进行自定义,包括: - 支持 [proxies](https://www.python-httpx.org/advanced/proxies/) - 自定义 [transports](https://www.python-httpx.org/advanced/transports/) - 额外的 [高级](https://www.python-httpx.org/advanced/clients/) 功能 ``` import httpx from openai import OpenAI, DefaultHttpxClient client = OpenAI( # Or use the `OPENAI_BASE_URL` env var base_url="http://my.test.server.example.com:8083/v1", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` 你也可以使用 `with_options()` 在每个请求的基础上自定义客户端: ``` client.with_options(http_client=DefaultHttpxClient(...)) ``` ### 管理 HTTP 资源 默认情况下,每当客户端被[垃圾回收](https://docs.python.org/3/reference/datamodel.html#object.__del__)时,该库都会关闭底层的 HTTP 连接。如果需要,你可以使用 `.close()` 方法手动关闭客户端,或者在退出时使用上下文管理器关闭。 ``` from openai import OpenAI with OpenAI() as client: # make requests here ... # HTTP client 现已关闭 ``` ## Microsoft Azure OpenAI 要将此库与 [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview) 一起使用,请使用 `AzureOpenAI` 类而不是 `OpenAI` 类。 ``` from openai import AzureOpenAI # 从环境变量 AZURE_OPENAI_API_KEY 获取 API Key client = AzureOpenAI( # https://learn.microsoft.com/azure/ai-services/openai/reference#rest-api-versioning api_version="2023-07-01-preview", # https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource azure_endpoint="https://example-endpoint.openai.azure.com", ) completion = client.chat.completions.create( model="deployment-name", # e.g. gpt-35-instant messages=[ { "role": "user", "content": "How do I output all files in a directory using Python?", }, ], ) print(completion.to_json()) ``` 除了基础 `OpenAI` 客户端中提供的选项外,还提供了以下选项: - `azure_endpoint`(或 `AZURE_OPENAI_ENDPOINT` 环境变量- `azure_deployment` - `api_version`(或 `OPENAI_API_VERSION` 环境变量) - `azure_ad_token`(或 `AZURE_OPENAI_AD_TOKEN` 环境变量) - `azure_ad_token_provider` 使用 Microsoft Entra ID(以前称为 Azure Active Directory)的客户端示例可以在[这里](https://github.com/openai/openai-python/blob/main/examples/azure_ad.py)找到。 ## Amazon Bedrock 要将此库与 [Amazon Bedrock 的兼容 OpenAI 的 API](https://docs.aws.amazon.com/bedrock/latest/userguide/models-api-compatibility.html) 一起使用,请使用 `BedrockOpenAI` 类而不是 `OpenAI` 类。 ``` from openai import BedrockOpenAI # 从 AWS_BEARER_TOKEN_BEDROCK 获取 bearer token,并从 AWS_REGION/AWS_DEFAULT_REGION 获取 region client = BedrockOpenAI() response = client.responses.create( model="openai.gpt-5.4", input="Say hello!", ) print(response.output_text) ``` `BedrockOpenAI` 配置了 AWS bearer auth 和 Bedrock Mantle endpoint,然后使用正常的 SDK 资源。AWS 控制支持哪些 endpoints 和功能;不支持的方法调用会通过 SDK 显示提供程序正常的 HTTP 错误。 传入 `base_url` 或设置 `AWS_BEDROCK_BASE_URL` 以覆盖派生的 `https://bedrock-mantle..api.aws/openai/v1` endpoint。旧的模块客户端支持 `openai.api_type = "amazon-bedrock"` 或 `OPENAI_API_TYPE=amazon-bedrock`。 将 `AWS_BEARER_TOKEN_BEDROCK` 设置为 [Amazon Bedrock API key](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html)。要自行刷新 token,请传入一个 provider 而不是 `api_key`: ``` client = BedrockOpenAI( aws_region="us-west-2", bedrock_token_provider=lambda: refresh_bedrock_token(), ) ``` ## 版本控制 此包通常遵循 [SemVer](https://semver.org/spec/v2.0.0.html) 约定,尽管某些向后不兼容的更改可能会作为次要版本发布: 1. 仅影响静态类型而不破坏运行时行为的更改。 2. 对库内部结构的技术上是公开但并不打算或未记录供外部使用的更改。_(如果你依赖于此类内部结构,请打开一个 GitHub issue 告诉我们。)_ 3. 我们预计在实践中不会影响绝大多数用户的更改。 我们非常重视向后兼容性,并努力确保你可以依赖平滑的升级体验。 我们热切期待你的反馈;如果有任何问题、bug 或建议,请打开一个 [issue](https://www.github.com/openai/openai-python/issues)。 ### 确定已安装的版本 如果你已经升级到最新版本,但没有看到你期望的任何新功能,那么你的 python 环境可能仍在使用旧版本。 你可以使用以下命令确定在运行时使用的版本: ``` import openai print(openai.__version__) ``` ## 要求 Python 3.9 或更高版本。 ## 贡献 请参阅[贡献文档](./CONTRIBUTING.md)。
标签:API SDK, DLL 劫持, OpenAI, Python, 人工智能, 内存规避, 大语言模型, 开发库, 无后门, 用户模式Hook绕过, 运行时操纵, 逆向工具