openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
README.md
965lines · modeblame
08b8179aDavid Schnurr2 years ago | 1 | # OpenAI Python API library |
3c6d4cd6Greg Brockman5 years ago | 2 | |
db5c3504stainless-app[bot]11 months ago | 3 | <!-- prettier-ignore --> |
| 4 | [)](https://pypi.org/project/openai/) | |
3c6d4cd6Greg Brockman5 years ago | 5 | |
3f52ac84stainless-app[bot]7 months ago | 6 | The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.9+ |
08b8179aDavid Schnurr2 years ago | 7 | application. The library includes type definitions for all request params and response fields, |
| 8 | and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx). | |
| 9 | | |
| 10 | It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/). | |
| 11 | | |
| 12 | ## Documentation | |
| 13 | | |
2954945eRobert Craigie1 years ago | 14 | The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs/api-reference). The full API of this library can be found in [api.md](api.md). |
3c6d4cd6Greg Brockman5 years ago | 15 | |
| 16 | ## Installation | |
| 17 | | |
| 18 | ```sh | |
1879c97aStainless Bot2 years ago | 19 | # install from PyPI |
6d217096Robert Craigie2 years ago | 20 | pip install openai |
3c6d4cd6Greg Brockman5 years ago | 21 | ``` |
| 22 | | |
08b8179aDavid Schnurr2 years ago | 23 | ## Usage |
| 24 | | |
986f3128Stainless Bot2 years ago | 25 | The full API of this library can be found in [api.md](api.md). |
376dd199Logan Kilpatrick2 years ago | 26 | |
2954945eRobert Craigie1 years ago | 27 | The primary API for interacting with OpenAI models is the [Responses API](https://platform.openai.com/docs/api-reference/responses). You can generate text from the model with the code below. |
| 28 | | |
376dd199Logan Kilpatrick2 years ago | 29 | ```python |
fb5ba01cStainless Bot2 years ago | 30 | import os |
08b8179aDavid Schnurr2 years ago | 31 | from openai import OpenAI |
| 32 | | |
| 33 | client = OpenAI( | |
2954945eRobert Craigie1 years ago | 34 | # This is the default and can be omitted |
| 35 | api_key=os.environ.get("OPENAI_API_KEY"), | |
| 36 | ) | |
| 37 | | |
| 38 | response = client.responses.create( | |
84e0c1d0Charlie Guo5 months ago | 39 | model="gpt-5.2", |
2954945eRobert Craigie1 years ago | 40 | instructions="You are a coding assistant that talks like a pirate.", |
| 41 | input="How do I check if a Python object is an instance of a class?", | |
08b8179aDavid Schnurr2 years ago | 42 | ) |
| 43 | | |
2954945eRobert Craigie1 years ago | 44 | print(response.output_text) |
| 45 | ``` | |
| 46 | | |
| 47 | The previous standard (supported indefinitely) for generating text is the [Chat Completions API](https://platform.openai.com/docs/api-reference/chat). You can use that API to generate text from the model with the code below. | |
| 48 | | |
| 49 | ```python | |
| 50 | from openai import OpenAI | |
| 51 | | |
| 52 | client = OpenAI() | |
| 53 | | |
| 54 | completion = client.chat.completions.create( | |
84e0c1d0Charlie Guo5 months ago | 55 | model="gpt-5.2", |
08b8179aDavid Schnurr2 years ago | 56 | messages=[ |
2954945eRobert Craigie1 years ago | 57 | {"role": "developer", "content": "Talk like a pirate."}, |
08b8179aDavid Schnurr2 years ago | 58 | { |
| 59 | "role": "user", | |
2954945eRobert Craigie1 years ago | 60 | "content": "How do I check if a Python object is an instance of a class?", |
| 61 | }, | |
08b8179aDavid Schnurr2 years ago | 62 | ], |
| 63 | ) | |
2954945eRobert Craigie1 years ago | 64 | |
| 65 | print(completion.choices[0].message.content) | |
376dd199Logan Kilpatrick2 years ago | 66 | ``` |
| 67 | | |
08b8179aDavid Schnurr2 years ago | 68 | While you can provide an `api_key` keyword argument, |
| 69 | we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) | |
| 70 | to add `OPENAI_API_KEY="My API Key"` to your `.env` file | |
2954945eRobert Craigie1 years ago | 71 | so that your API key is not stored in source control. |
| 72 | [Get an API key here](https://platform.openai.com/settings/organization/api-keys). | |
3c6d4cd6Greg Brockman5 years ago | 73 | |
5be95364Kar Petrosyan2 months ago | 74 | ### Workload Identity Authentication |
| 75 | | |
| 76 | For secure, automated environments like cloud-managed Kubernetes, Azure, and Google Cloud Platform, you can use workload identity authentication with short-lived tokens from cloud identity providers instead of long-lived API keys. | |
| 77 | | |
| 78 | #### Kubernetes (service account tokens) | |
| 79 | | |
| 80 | ```python | |
| 81 | from openai import OpenAI | |
| 82 | from openai.auth import k8s_service_account_token_provider | |
| 83 | | |
| 84 | client = OpenAI( | |
| 85 | workload_identity={ | |
| 86 | "client_id": "your-client-id", | |
| 87 | "identity_provider_id": "idp-123", | |
| 88 | "service_account_id": "sa-456", | |
| 89 | "provider": k8s_service_account_token_provider( | |
| 90 | "/var/run/secrets/kubernetes.io/serviceaccount/token" | |
| 91 | ), | |
| 92 | }, | |
| 93 | organization="org-xyz", | |
| 94 | project="proj-abc", | |
| 95 | ) | |
| 96 | | |
| 97 | response = client.chat.completions.create( | |
| 98 | model="gpt-4", | |
| 99 | messages=[{"role": "user", "content": "Hello!"}], | |
| 100 | ) | |
| 101 | ``` | |
| 102 | | |
| 103 | #### Azure (managed identity) | |
| 104 | | |
| 105 | ```python | |
| 106 | from openai import OpenAI | |
| 107 | from openai.auth import azure_managed_identity_token_provider | |
| 108 | | |
| 109 | client = OpenAI( | |
| 110 | workload_identity={ | |
| 111 | "client_id": "your-client-id", | |
| 112 | "identity_provider_id": "idp-123", | |
| 113 | "service_account_id": "sa-456", | |
| 114 | "provider": azure_managed_identity_token_provider( | |
| 115 | resource="https://management.azure.com/", | |
| 116 | ), | |
| 117 | }, | |
| 118 | ) | |
| 119 | ``` | |
| 120 | | |
| 121 | #### Google Cloud Platform (compute engine metadata) | |
| 122 | | |
| 123 | ```python | |
| 124 | from openai import OpenAI | |
| 125 | from openai.auth import gcp_id_token_provider | |
| 126 | | |
| 127 | client = OpenAI( | |
| 128 | workload_identity={ | |
| 129 | "client_id": "your-client-id", | |
| 130 | "identity_provider_id": "idp-123", | |
| 131 | "service_account_id": "sa-456", | |
| 132 | "provider": gcp_id_token_provider(audience="https://api.openai.com/v1"), | |
| 133 | }, | |
| 134 | ) | |
| 135 | ``` | |
| 136 | | |
| 137 | #### Custom subject token provider | |
| 138 | | |
| 139 | ```python | |
| 140 | from openai import OpenAI | |
| 141 | | |
| 142 | | |
| 143 | def get_custom_token() -> str: | |
| 144 | return "your-jwt-token" | |
| 145 | | |
| 146 | | |
| 147 | client = OpenAI( | |
| 148 | workload_identity={ | |
| 149 | "client_id": "your-client-id", | |
| 150 | "identity_provider_id": "idp-123", | |
| 151 | "service_account_id": "sa-456", | |
| 152 | "provider": { | |
| 153 | "token_type": "jwt", | |
| 154 | "get_token": get_custom_token, | |
| 155 | }, | |
| 156 | } | |
| 157 | ) | |
| 158 | ``` | |
| 159 | | |
| 160 | You can also customize the token refresh buffer (default is 1200 seconds (20 minutes) before expiration): | |
| 161 | | |
| 162 | ```python | |
| 163 | from openai import OpenAI | |
| 164 | from openai.auth import k8s_service_account_token_provider | |
| 165 | | |
| 166 | client = OpenAI( | |
| 167 | workload_identity={ | |
| 168 | "client_id": "your-client-id", | |
| 169 | "identity_provider_id": "idp-123", | |
| 170 | "service_account_id": "sa-456", | |
| 171 | "provider": k8s_service_account_token_provider("/var/token"), | |
| 172 | "refresh_buffer_seconds": 120.0, | |
| 173 | } | |
| 174 | ) | |
| 175 | ``` | |
| 176 | | |
192b8f2bDan Corin1 years ago | 177 | ### Vision |
| 178 | | |
2954945eRobert Craigie1 years ago | 179 | With an image URL: |
192b8f2bDan Corin1 years ago | 180 | |
| 181 | ```python | |
2954945eRobert Craigie1 years ago | 182 | prompt = "What is in this image?" |
| 183 | img_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2023_06_08_Raccoon1.jpg/1599px-2023_06_08_Raccoon1.jpg" | |
| 184 | | |
| 185 | response = client.responses.create( | |
84e0c1d0Charlie Guo5 months ago | 186 | model="gpt-5.2", |
2954945eRobert Craigie1 years ago | 187 | input=[ |
192b8f2bDan Corin1 years ago | 188 | { |
| 189 | "role": "user", | |
| 190 | "content": [ | |
2954945eRobert Craigie1 years ago | 191 | {"type": "input_text", "text": prompt}, |
| 192 | {"type": "input_image", "image_url": f"{img_url}"}, | |
192b8f2bDan Corin1 years ago | 193 | ], |
| 194 | } | |
| 195 | ], | |
| 196 | ) | |
| 197 | ``` | |
| 198 | | |
| 199 | With the image as a base64 encoded string: | |
| 200 | | |
| 201 | ```python | |
2954945eRobert Craigie1 years ago | 202 | import base64 |
| 203 | from openai import OpenAI | |
| 204 | | |
| 205 | client = OpenAI() | |
| 206 | | |
| 207 | prompt = "What is in this image?" | |
| 208 | with open("path/to/image.png", "rb") as image_file: | |
| 209 | b64_image = base64.b64encode(image_file.read()).decode("utf-8") | |
| 210 | | |
| 211 | response = client.responses.create( | |
84e0c1d0Charlie Guo5 months ago | 212 | model="gpt-5.2", |
2954945eRobert Craigie1 years ago | 213 | input=[ |
192b8f2bDan Corin1 years ago | 214 | { |
| 215 | "role": "user", | |
| 216 | "content": [ | |
2954945eRobert Craigie1 years ago | 217 | {"type": "input_text", "text": prompt}, |
| 218 | {"type": "input_image", "image_url": f"data:image/png;base64,{b64_image}"}, | |
192b8f2bDan Corin1 years ago | 219 | ], |
| 220 | } | |
| 221 | ], | |
| 222 | ) | |
| 223 | ``` | |
| 224 | | |
08b8179aDavid Schnurr2 years ago | 225 | ## Async usage |
3c6d4cd6Greg Brockman5 years ago | 226 | |
08b8179aDavid Schnurr2 years ago | 227 | Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call: |
ede08829Jakub Roztocil3 years ago | 228 | |
08b8179aDavid Schnurr2 years ago | 229 | ```python |
fb5ba01cStainless Bot2 years ago | 230 | import os |
08b8179aDavid Schnurr2 years ago | 231 | import asyncio |
| 232 | from openai import AsyncOpenAI | |
ede08829Jakub Roztocil3 years ago | 233 | |
08b8179aDavid Schnurr2 years ago | 234 | client = AsyncOpenAI( |
2954945eRobert Craigie1 years ago | 235 | # This is the default and can be omitted |
| 236 | api_key=os.environ.get("OPENAI_API_KEY"), | |
08b8179aDavid Schnurr2 years ago | 237 | ) |
ede08829Jakub Roztocil3 years ago | 238 | |
| 239 | | |
08b8179aDavid Schnurr2 years ago | 240 | async def main() -> None: |
2954945eRobert Craigie1 years ago | 241 | response = await client.responses.create( |
84e0c1d0Charlie Guo5 months ago | 242 | model="gpt-5.2", input="Explain disestablishmentarianism to a smart five year old." |
08b8179aDavid Schnurr2 years ago | 243 | ) |
2954945eRobert Craigie1 years ago | 244 | print(response.output_text) |
ede08829Jakub Roztocil3 years ago | 245 | |
| 246 | | |
08b8179aDavid Schnurr2 years ago | 247 | asyncio.run(main()) |
2b21516eAtty Eleti3 years ago | 248 | ``` |
ede08829Jakub Roztocil3 years ago | 249 | |
08b8179aDavid Schnurr2 years ago | 250 | Functionality between the synchronous and asynchronous clients is otherwise identical. |
| 251 | | |
c62e9907stainless-app[bot]1 years ago | 252 | ### With aiohttp |
| 253 | | |
| 254 | By default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend. | |
| 255 | | |
| 256 | You can enable this by installing `aiohttp`: | |
| 257 | | |
| 258 | ```sh | |
| 259 | # install from PyPI | |
| 260 | pip install openai[aiohttp] | |
| 261 | ``` | |
| 262 | | |
| 263 | Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`: | |
| 264 | | |
| 265 | ```python | |
bd988473stainless-app[bot]6 months ago | 266 | import os |
c62e9907stainless-app[bot]1 years ago | 267 | import asyncio |
| 268 | from openai import DefaultAioHttpClient | |
| 269 | from openai import AsyncOpenAI | |
| 270 | | |
| 271 | | |
| 272 | async def main() -> None: | |
| 273 | async with AsyncOpenAI( | |
bd988473stainless-app[bot]6 months ago | 274 | api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted |
c62e9907stainless-app[bot]1 years ago | 275 | http_client=DefaultAioHttpClient(), |
| 276 | ) as client: | |
| 277 | chat_completion = await client.chat.completions.create( | |
| 278 | messages=[ | |
| 279 | { | |
| 280 | "role": "user", | |
| 281 | "content": "Say this is a test", | |
| 282 | } | |
| 283 | ], | |
84e0c1d0Charlie Guo5 months ago | 284 | model="gpt-5.2", |
c62e9907stainless-app[bot]1 years ago | 285 | ) |
| 286 | | |
| 287 | | |
| 288 | asyncio.run(main()) | |
| 289 | ``` | |
| 290 | | |
2b23eb53Stainless Bot2 years ago | 291 | ## Streaming responses |
08b8179aDavid Schnurr2 years ago | 292 | |
| 293 | We provide support for streaming responses using Server Side Events (SSE). | |
d53d9efbRachel Lim5 years ago | 294 | |
08b8179aDavid Schnurr2 years ago | 295 | ```python |
| 296 | from openai import OpenAI | |
| 297 | | |
| 298 | client = OpenAI() | |
d53d9efbRachel Lim5 years ago | 299 | |
2954945eRobert Craigie1 years ago | 300 | stream = client.responses.create( |
84e0c1d0Charlie Guo5 months ago | 301 | model="gpt-5.2", |
2954945eRobert Craigie1 years ago | 302 | input="Write a one-sentence bedtime story about a unicorn.", |
08b8179aDavid Schnurr2 years ago | 303 | stream=True, |
| 304 | ) | |
2954945eRobert Craigie1 years ago | 305 | |
| 306 | for event in stream: | |
| 307 | print(event) | |
d53d9efbRachel Lim5 years ago | 308 | ``` |
| 309 | | |
08b8179aDavid Schnurr2 years ago | 310 | The async client uses the exact same interface. |
d53d9efbRachel Lim5 years ago | 311 | |
| 312 | ```python | |
db0aa22cAdel Basli1 years ago | 313 | import asyncio |
08b8179aDavid Schnurr2 years ago | 314 | from openai import AsyncOpenAI |
| 315 | | |
| 316 | client = AsyncOpenAI() | |
| 317 | | |
a3da0196Stainless Bot2 years ago | 318 | |
dfe1c8daSahand Sojoodi2 years ago | 319 | async def main(): |
f588695fstainless-app[bot]1 years ago | 320 | stream = await client.responses.create( |
84e0c1d0Charlie Guo5 months ago | 321 | model="gpt-5.2", |
2954945eRobert Craigie1 years ago | 322 | input="Write a one-sentence bedtime story about a unicorn.", |
dfe1c8daSahand Sojoodi2 years ago | 323 | stream=True, |
| 324 | ) | |
d53d9efbRachel Lim5 years ago | 325 | |
f588695fstainless-app[bot]1 years ago | 326 | async for event in stream: |
2954945eRobert Craigie1 years ago | 327 | print(event) |
08b8179aDavid Schnurr2 years ago | 328 | |
| 329 | | |
2954945eRobert Craigie1 years ago | 330 | asyncio.run(main()) |
62b73b9bAtty Eleti3 years ago | 331 | ``` |
| 332 | | |
3d3d16abstainless-app[bot]10 months ago | 333 | ## Realtime API |
488ec04bRobert Craigie1 years ago | 334 | |
| 335 | The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as [function calling](https://platform.openai.com/docs/guides/function-calling) through a WebSocket connection. | |
| 336 | | |
| 337 | Under the hood the SDK uses the [`websockets`](https://websockets.readthedocs.io/en/stable/) library to manage connections. | |
| 338 | | |
255677d7Robert Craigie1 years ago | 339 | The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found [here](https://platform.openai.com/docs/api-reference/realtime-client-events) and a guide can be found [here](https://platform.openai.com/docs/guides/realtime). |
488ec04bRobert Craigie1 years ago | 340 | |
| 341 | Basic text based example: | |
| 342 | | |
| 343 | ```py | |
| 344 | import asyncio | |
| 345 | from openai import AsyncOpenAI | |
| 346 | | |
| 347 | async def main(): | |
| 348 | client = AsyncOpenAI() | |
| 349 | | |
3d3d16abstainless-app[bot]10 months ago | 350 | async with client.realtime.connect(model="gpt-realtime") as connection: |
35cb4e9bDan Martins8 months ago | 351 | await connection.session.update( |
| 352 | session={"type": "realtime", "output_modalities": ["text"]} | |
| 353 | ) | |
488ec04bRobert Craigie1 years ago | 354 | |
| 355 | await connection.conversation.item.create( | |
| 356 | item={ | |
| 357 | "type": "message", | |
| 358 | "role": "user", | |
| 359 | "content": [{"type": "input_text", "text": "Say hello!"}], | |
| 360 | } | |
| 361 | ) | |
| 362 | await connection.response.create() | |
| 363 | | |
| 364 | async for event in connection: | |
35cb4e9bDan Martins8 months ago | 365 | if event.type == "response.output_text.delta": |
488ec04bRobert Craigie1 years ago | 366 | print(event.delta, flush=True, end="") |
| 367 | | |
35cb4e9bDan Martins8 months ago | 368 | elif event.type == "response.output_text.done": |
488ec04bRobert Craigie1 years ago | 369 | print() |
| 370 | | |
| 371 | elif event.type == "response.done": | |
| 372 | break | |
| 373 | | |
| 374 | asyncio.run(main()) | |
| 375 | ``` | |
| 376 | | |
6935dfdcRobert Craigie1 years ago | 377 | However the real magic of the Realtime API is handling audio inputs / outputs, see this example [TUI script](https://github.com/openai/openai-python/blob/main/examples/realtime/push_to_talk_app.py) for a fully fledged example. |
488ec04bRobert Craigie1 years ago | 378 | |
| 379 | ### Realtime error handling | |
| 380 | | |
2954945eRobert Craigie1 years ago | 381 | Whenever an error occurs, the Realtime API will send an [`error` event](https://platform.openai.com/docs/guides/realtime-model-capabilities#error-handling) and the connection will stay open and remain usable. This means you need to handle it yourself, as _no errors are raised directly_ by the SDK when an `error` event comes in. |
488ec04bRobert Craigie1 years ago | 382 | |
| 383 | ```py | |
| 384 | client = AsyncOpenAI() | |
| 385 | | |
3d3d16abstainless-app[bot]10 months ago | 386 | async with client.realtime.connect(model="gpt-realtime") as connection: |
488ec04bRobert Craigie1 years ago | 387 | ... |
| 388 | async for event in connection: | |
| 389 | if event.type == 'error': | |
| 390 | print(event.error.type) | |
| 391 | print(event.error.code) | |
| 392 | print(event.error.event_id) | |
| 393 | print(event.error.message) | |
| 394 | ``` | |
| 395 | | |
08b8179aDavid Schnurr2 years ago | 396 | ## Using types |
| 397 | | |
47656567Stainless Bot2 years ago | 398 | Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like: |
f4b9655fStainless Bot2 years ago | 399 | |
47656567Stainless Bot2 years ago | 400 | - Serializing back into JSON, `model.to_json()` |
| 401 | - Converting to a dictionary, `model.to_dict()` | |
2b21516eAtty Eleti3 years ago | 402 | |
08b8179aDavid Schnurr2 years ago | 403 | Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`. |
0e21703eTed Sanders4 years ago | 404 | |
08b8179aDavid Schnurr2 years ago | 405 | ## Pagination |
0e21703eTed Sanders4 years ago | 406 | |
08b8179aDavid Schnurr2 years ago | 407 | List methods in the OpenAI API are paginated. |
| 408 | | |
| 409 | This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually: | |
0e21703eTed Sanders4 years ago | 410 | |
| 411 | ```python | |
ff5add01stainless-app[bot]1 years ago | 412 | from openai import OpenAI |
0e21703eTed Sanders4 years ago | 413 | |
08b8179aDavid Schnurr2 years ago | 414 | client = OpenAI() |
0e21703eTed Sanders4 years ago | 415 | |
08b8179aDavid Schnurr2 years ago | 416 | all_jobs = [] |
| 417 | # Automatically fetches more pages as needed. | |
| 418 | for job in client.fine_tuning.jobs.list( | |
| 419 | limit=20, | |
| 420 | ): | |
| 421 | # Do something with job here | |
| 422 | all_jobs.append(job) | |
| 423 | print(all_jobs) | |
0e21703eTed Sanders4 years ago | 424 | ``` |
| 425 | | |
08b8179aDavid Schnurr2 years ago | 426 | Or, asynchronously: |
0e21703eTed Sanders4 years ago | 427 | |
08b8179aDavid Schnurr2 years ago | 428 | ```python |
| 429 | import asyncio | |
ff5add01stainless-app[bot]1 years ago | 430 | from openai import AsyncOpenAI |
0e21703eTed Sanders4 years ago | 431 | |
08b8179aDavid Schnurr2 years ago | 432 | client = AsyncOpenAI() |
0e21703eTed Sanders4 years ago | 433 | |
| 434 | | |
08b8179aDavid Schnurr2 years ago | 435 | async def main() -> None: |
| 436 | all_jobs = [] | |
| 437 | # Iterate through items across all pages, issuing requests as needed. | |
| 438 | async for job in client.fine_tuning.jobs.list( | |
| 439 | limit=20, | |
| 440 | ): | |
| 441 | all_jobs.append(job) | |
| 442 | print(all_jobs) | |
0e21703eTed Sanders4 years ago | 443 | |
62b51ca0Boris Dayma4 years ago | 444 | |
08b8179aDavid Schnurr2 years ago | 445 | asyncio.run(main()) |
| 446 | ``` | |
2942bf4bLogan Kilpatrick2 years ago | 447 | |
08b8179aDavid Schnurr2 years ago | 448 | Alternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages: |
2942bf4bLogan Kilpatrick2 years ago | 449 | |
08b8179aDavid Schnurr2 years ago | 450 | ```python |
| 451 | first_page = await client.fine_tuning.jobs.list( | |
| 452 | limit=20, | |
| 453 | ) | |
| 454 | if first_page.has_next_page(): | |
| 455 | print(f"will fetch next page using these details: {first_page.next_page_info()}") | |
| 456 | next_page = await first_page.get_next_page() | |
| 457 | print(f"number of items we just fetched: {len(next_page.data)}") | |
| 458 | | |
| 459 | # Remove `await` for non-async usage. | |
62b51ca0Boris Dayma4 years ago | 460 | ``` |
| 461 | | |
08b8179aDavid Schnurr2 years ago | 462 | Or just work directly with the returned data: |
0e21703eTed Sanders4 years ago | 463 | |
08b8179aDavid Schnurr2 years ago | 464 | ```python |
| 465 | first_page = await client.fine_tuning.jobs.list( | |
| 466 | limit=20, | |
| 467 | ) | |
e389823bMorgan McGuire2 years ago | 468 | |
08b8179aDavid Schnurr2 years ago | 469 | print(f"next page cursor: {first_page.after}") # => "next page cursor: ..." |
| 470 | for job in first_page.data: | |
| 471 | print(job.id) | |
e389823bMorgan McGuire2 years ago | 472 | |
08b8179aDavid Schnurr2 years ago | 473 | # Remove `await` for non-async usage. |
| 474 | ``` | |
e389823bMorgan McGuire2 years ago | 475 | |
08b8179aDavid Schnurr2 years ago | 476 | ## Nested params |
3c00e856hallacy3 years ago | 477 | |
08b8179aDavid Schnurr2 years ago | 478 | Nested parameters are dictionaries, typed using `TypedDict`, for example: |
3c00e856hallacy3 years ago | 479 | |
| 480 | ```python | |
08b8179aDavid Schnurr2 years ago | 481 | from openai import OpenAI |
3c00e856hallacy3 years ago | 482 | |
08b8179aDavid Schnurr2 years ago | 483 | client = OpenAI() |
| 484 | | |
2954945eRobert Craigie1 years ago | 485 | response = client.chat.responses.create( |
| 486 | input=[ | |
aa681899Stainless Bot2 years ago | 487 | { |
| 488 | "role": "user", | |
2954945eRobert Craigie1 years ago | 489 | "content": "How much ?", |
aa681899Stainless Bot2 years ago | 490 | } |
| 491 | ], | |
84e0c1d0Charlie Guo5 months ago | 492 | model="gpt-5.2", |
aa681899Stainless Bot2 years ago | 493 | response_format={"type": "json_object"}, |
| 494 | ) | |
08b8179aDavid Schnurr2 years ago | 495 | ``` |
3c00e856hallacy3 years ago | 496 | |
2b23eb53Stainless Bot2 years ago | 497 | ## File uploads |
dc33cb9dMichelle Pokrass3 years ago | 498 | |
acf68ef3stainless-app[bot]1 years ago | 499 | Request parameters that correspond to file uploads can be passed as `bytes`, or a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`. |
dc33cb9dMichelle Pokrass3 years ago | 500 | |
376dd199Logan Kilpatrick2 years ago | 501 | ```python |
08b8179aDavid Schnurr2 years ago | 502 | from pathlib import Path |
| 503 | from openai import OpenAI | |
| 504 | | |
| 505 | client = OpenAI() | |
| 506 | | |
| 507 | client.files.create( | |
| 508 | file=Path("input.jsonl"), | |
| 509 | purpose="fine-tune", | |
| 510 | ) | |
dc33cb9dMichelle Pokrass3 years ago | 511 | ``` |
| 512 | | |
08b8179aDavid Schnurr2 years ago | 513 | The async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically. |
376dd199Logan Kilpatrick2 years ago | 514 | |
18e0b36astainless-app[bot]1 years ago | 515 | ## Webhook Verification |
| 516 | | |
| 517 | Verifying webhook signatures is _optional but encouraged_. | |
| 518 | | |
4f99c4e6David Meadows1 years ago | 519 | For more information about webhooks, see [the API docs](https://platform.openai.com/docs/guides/webhooks). |
| 520 | | |
18e0b36astainless-app[bot]1 years ago | 521 | ### Parsing webhook payloads |
| 522 | | |
| 523 | For most use cases, you will likely want to verify the webhook and parse the payload at the same time. To achieve this, we provide the method `client.webhooks.unwrap()`, which parses a webhook request and verifies that it was sent by OpenAI. This method will raise an error if the signature is invalid. | |
| 524 | | |
| 525 | Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). The `.unwrap()` method will parse this JSON for you into an event object after verifying the webhook was sent from OpenAI. | |
| 526 | | |
| 527 | ```python | |
| 528 | from openai import OpenAI | |
| 529 | from flask import Flask, request | |
| 530 | | |
| 531 | app = Flask(__name__) | |
| 532 | client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default | |
| 533 | | |
| 534 | | |
| 535 | @app.route("/webhook", methods=["POST"]) | |
| 536 | def webhook(): | |
| 537 | request_body = request.get_data(as_text=True) | |
| 538 | | |
| 539 | try: | |
| 540 | event = client.webhooks.unwrap(request_body, request.headers) | |
| 541 | | |
| 542 | if event.type == "response.completed": | |
| 543 | print("Response completed:", event.data) | |
| 544 | elif event.type == "response.failed": | |
| 545 | print("Response failed:", event.data) | |
| 546 | else: | |
| 547 | print("Unhandled event type:", event.type) | |
| 548 | | |
| 549 | return "ok" | |
| 550 | except Exception as e: | |
| 551 | print("Invalid signature:", e) | |
| 552 | return "Invalid signature", 400 | |
| 553 | | |
| 554 | | |
| 555 | if __name__ == "__main__": | |
| 556 | app.run(port=8000) | |
| 557 | ``` | |
| 558 | | |
| 559 | ### Verifying webhook payloads directly | |
| 560 | | |
| 561 | In some cases, you may want to verify the webhook separately from parsing the payload. If you prefer to handle these steps separately, we provide the method `client.webhooks.verify_signature()` to _only verify_ the signature of a webhook request. Like `.unwrap()`, this method will raise an error if the signature is invalid. | |
| 562 | | |
| 563 | Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). You will then need to parse the body after verifying the signature. | |
| 564 | | |
| 565 | ```python | |
| 566 | import json | |
| 567 | from openai import OpenAI | |
| 568 | from flask import Flask, request | |
| 569 | | |
| 570 | app = Flask(__name__) | |
| 571 | client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default | |
| 572 | | |
| 573 | | |
| 574 | @app.route("/webhook", methods=["POST"]) | |
| 575 | def webhook(): | |
| 576 | request_body = request.get_data(as_text=True) | |
| 577 | | |
| 578 | try: | |
| 579 | client.webhooks.verify_signature(request_body, request.headers) | |
| 580 | | |
| 581 | # Parse the body after verification | |
| 582 | event = json.loads(request_body) | |
| 583 | print("Verified event:", event) | |
| 584 | | |
| 585 | return "ok" | |
| 586 | except Exception as e: | |
| 587 | print("Invalid signature:", e) | |
| 588 | return "Invalid signature", 400 | |
| 589 | | |
| 590 | | |
| 591 | if __name__ == "__main__": | |
| 592 | app.run(port=8000) | |
| 593 | ``` | |
| 594 | | |
08b8179aDavid Schnurr2 years ago | 595 | ## Handling errors |
376dd199Logan Kilpatrick2 years ago | 596 | |
08b8179aDavid Schnurr2 years ago | 597 | When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `openai.APIConnectionError` is raised. |
2b21516eAtty Eleti3 years ago | 598 | |
08b8179aDavid Schnurr2 years ago | 599 | When the API returns a non-success status code (that is, 4xx or 5xx |
| 600 | response), a subclass of `openai.APIStatusError` is raised, containing `status_code` and `response` properties. | |
62b73b9bAtty Eleti3 years ago | 601 | |
08b8179aDavid Schnurr2 years ago | 602 | All errors inherit from `openai.APIError`. |
| 603 | | |
| 604 | ```python | |
| 605 | import openai | |
| 606 | from openai import OpenAI | |
| 607 | | |
| 608 | client = OpenAI() | |
| 609 | | |
| 610 | try: | |
8dab1421Stainless Bot2 years ago | 611 | client.fine_tuning.jobs.create( |
23444ed9Stainless Bot1 years ago | 612 | model="gpt-4o", |
8dab1421Stainless Bot2 years ago | 613 | training_file="file-abc123", |
08b8179aDavid Schnurr2 years ago | 614 | ) |
| 615 | except openai.APIConnectionError as e: | |
| 616 | print("The server could not be reached") | |
| 617 | print(e.__cause__) # an underlying Exception, likely raised within httpx. | |
| 618 | except openai.RateLimitError as e: | |
| 619 | print("A 429 status code was received; we should back off a bit.") | |
| 620 | except openai.APIStatusError as e: | |
| 621 | print("Another non-200-range status code was received") | |
| 622 | print(e.status_code) | |
| 623 | print(e.response) | |
62b73b9bAtty Eleti3 years ago | 624 | ``` |
| 625 | | |
fee9c81bstainless-app[bot]1 years ago | 626 | Error codes are as follows: |
08b8179aDavid Schnurr2 years ago | 627 | |
| 628 | | Status Code | Error Type | | |
| 629 | | ----------- | -------------------------- | | |
| 630 | | 400 | `BadRequestError` | | |
| 631 | | 401 | `AuthenticationError` | | |
| 632 | | 403 | `PermissionDeniedError` | | |
| 633 | | 404 | `NotFoundError` | | |
| 634 | | 422 | `UnprocessableEntityError` | | |
| 635 | | 429 | `RateLimitError` | | |
| 636 | | >=500 | `InternalServerError` | | |
| 637 | | N/A | `APIConnectionError` | | |
| 638 | | |
4b302346Robert Craigie1 years ago | 639 | ## Request IDs |
| 640 | | |
| 641 | > For more information on debugging requests, see [these docs](https://platform.openai.com/docs/api-reference/debugging-requests) | |
| 642 | | |
| 643 | All object responses in the SDK provide a `_request_id` property which is added from the `x-request-id` response header so that you can quickly log failing requests and report them back to OpenAI. | |
| 644 | | |
| 645 | ```python | |
2954945eRobert Craigie1 years ago | 646 | response = await client.responses.create( |
84e0c1d0Charlie Guo5 months ago | 647 | model="gpt-5.2", |
2954945eRobert Craigie1 years ago | 648 | input="Say 'this is a test'.", |
4b302346Robert Craigie1 years ago | 649 | ) |
2954945eRobert Craigie1 years ago | 650 | print(response._request_id) # req_123 |
4b302346Robert Craigie1 years ago | 651 | ``` |
| 652 | | |
| 653 | Note that unlike other properties that use an `_` prefix, the `_request_id` property | |
2954945eRobert Craigie1 years ago | 654 | _is_ public. Unless documented otherwise, _all_ other `_` prefix properties, |
| 655 | methods and modules are _private_. | |
4b302346Robert Craigie1 years ago | 656 | |
709926ffRobert Craigie1 years ago | 657 | > [!IMPORTANT] |
| 658 | > If you need to access request IDs for failed requests you must catch the `APIStatusError` exception | |
| 659 | | |
| 660 | ```python | |
| 661 | import openai | |
| 662 | | |
| 663 | try: | |
| 664 | completion = await client.chat.completions.create( | |
84e0c1d0Charlie Guo5 months ago | 665 | messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-5.2" |
709926ffRobert Craigie1 years ago | 666 | ) |
| 667 | except openai.APIStatusError as exc: | |
| 668 | print(exc.request_id) # req_123 | |
| 669 | raise exc | |
| 670 | ``` | |
| 671 | | |
2954945eRobert Craigie1 years ago | 672 | ## Retries |
376dd199Logan Kilpatrick2 years ago | 673 | |
08b8179aDavid Schnurr2 years ago | 674 | Certain errors are automatically retried 2 times by default, with a short exponential backoff. |
| 675 | Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, | |
| 676 | 429 Rate Limit, and >=500 Internal errors are all retried by default. | |
0abf6413Andrew Chen Wang3 years ago | 677 | |
08b8179aDavid Schnurr2 years ago | 678 | You can use the `max_retries` option to configure or disable retry settings: |
0abf6413Andrew Chen Wang3 years ago | 679 | |
| 680 | ```python | |
08b8179aDavid Schnurr2 years ago | 681 | from openai import OpenAI |
| 682 | | |
| 683 | # Configure the default for all requests: | |
| 684 | client = OpenAI( | |
| 685 | # default is 2 | |
| 686 | max_retries=0, | |
| 687 | ) | |
| 688 | | |
| 689 | # Or, configure per-request: | |
| 690 | client.with_options(max_retries=5).chat.completions.create( | |
| 691 | messages=[ | |
| 692 | { | |
| 693 | "role": "user", | |
23444ed9Stainless Bot1 years ago | 694 | "content": "How can I get the name of the current day in JavaScript?", |
08b8179aDavid Schnurr2 years ago | 695 | } |
| 696 | ], | |
84e0c1d0Charlie Guo5 months ago | 697 | model="gpt-5.2", |
08b8179aDavid Schnurr2 years ago | 698 | ) |
0abf6413Andrew Chen Wang3 years ago | 699 | ``` |
| 700 | | |
2954945eRobert Craigie1 years ago | 701 | ## Timeouts |
0abf6413Andrew Chen Wang3 years ago | 702 | |
08b8179aDavid Schnurr2 years ago | 703 | By default requests time out after 10 minutes. You can configure this with a `timeout` option, |
90e3d396Guspan Tanadi1 years ago | 704 | which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object: |
376dd199Logan Kilpatrick2 years ago | 705 | |
08b8179aDavid Schnurr2 years ago | 706 | ```python |
| 707 | from openai import OpenAI | |
| 708 | | |
| 709 | # Configure the default for all requests: | |
| 710 | client = OpenAI( | |
1381f46eStainless Bot2 years ago | 711 | # 20 seconds (default is 10 minutes) |
08b8179aDavid Schnurr2 years ago | 712 | timeout=20.0, |
| 713 | ) | |
| 714 | | |
| 715 | # More granular control: | |
| 716 | client = OpenAI( | |
| 717 | timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), | |
| 718 | ) | |
| 719 | | |
| 720 | # Override per-request: | |
2a678e30Stainless Bot2 years ago | 721 | client.with_options(timeout=5.0).chat.completions.create( |
08b8179aDavid Schnurr2 years ago | 722 | messages=[ |
| 723 | { | |
| 724 | "role": "user", | |
| 725 | "content": "How can I list all files in a directory using Python?", | |
| 726 | } | |
| 727 | ], | |
84e0c1d0Charlie Guo5 months ago | 728 | model="gpt-5.2", |
08b8179aDavid Schnurr2 years ago | 729 | ) |
0abf6413Andrew Chen Wang3 years ago | 730 | ``` |
| 731 | | |
08b8179aDavid Schnurr2 years ago | 732 | On timeout, an `APITimeoutError` is thrown. |
376dd199Logan Kilpatrick2 years ago | 733 | |
08b8179aDavid Schnurr2 years ago | 734 | Note that requests that time out are [retried twice by default](#retries). |
376dd199Logan Kilpatrick2 years ago | 735 | |
08b8179aDavid Schnurr2 years ago | 736 | ## Advanced |
376dd199Logan Kilpatrick2 years ago | 737 | |
08b8179aDavid Schnurr2 years ago | 738 | ### Logging |
376dd199Logan Kilpatrick2 years ago | 739 | |
08b8179aDavid Schnurr2 years ago | 740 | We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module. |
376dd199Logan Kilpatrick2 years ago | 741 | |
f6199d60stainless-app[bot]1 years ago | 742 | You can enable logging by setting the environment variable `OPENAI_LOG` to `info`. |
376dd199Logan Kilpatrick2 years ago | 743 | |
08b8179aDavid Schnurr2 years ago | 744 | ```shell |
f6199d60stainless-app[bot]1 years ago | 745 | $ export OPENAI_LOG=info |
376dd199Logan Kilpatrick2 years ago | 746 | ``` |
| 747 | | |
f6199d60stainless-app[bot]1 years ago | 748 | Or to `debug` for more verbose logging. |
| 749 | | |
08b8179aDavid Schnurr2 years ago | 750 | ### How to tell whether `None` means `null` or missing |
dc33cb9dMichelle Pokrass3 years ago | 751 | |
08b8179aDavid Schnurr2 years ago | 752 | In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`: |
3c6d4cd6Greg Brockman5 years ago | 753 | |
08b8179aDavid Schnurr2 years ago | 754 | ```py |
| 755 | if response.my_field is None: | |
| 756 | if 'my_field' not in response.model_fields_set: | |
| 757 | print('Got json like {}, without a "my_field" key present at all.') | |
| 758 | else: | |
| 759 | print('Got json like {"my_field": null}.') | |
| 760 | ``` | |
376dd199Logan Kilpatrick2 years ago | 761 | |
08b8179aDavid Schnurr2 years ago | 762 | ### Accessing raw response data (e.g. headers) |
376dd199Logan Kilpatrick2 years ago | 763 | |
86379b44Stainless Bot2 years ago | 764 | The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g., |
08b8179aDavid Schnurr2 years ago | 765 | |
| 766 | ```py | |
| 767 | from openai import OpenAI | |
| 768 | | |
| 769 | client = OpenAI() | |
| 770 | response = client.chat.completions.with_raw_response.create( | |
| 771 | messages=[{ | |
| 772 | "role": "user", | |
| 773 | "content": "Say this is a test", | |
| 774 | }], | |
84e0c1d0Charlie Guo5 months ago | 775 | model="gpt-5.2", |
08b8179aDavid Schnurr2 years ago | 776 | ) |
| 777 | print(response.headers.get('X-My-Header')) | |
| 778 | | |
| 779 | completion = response.parse() # get the object that `chat.completions.create()` would have returned | |
| 780 | print(completion) | |
376dd199Logan Kilpatrick2 years ago | 781 | ``` |
| 782 | | |
16315f22stainless-app[bot]1 years ago | 783 | These methods return a [`LegacyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) object. This is a legacy class as we're changing it slightly in the next major version. |
86379b44Stainless Bot2 years ago | 784 | |
| 785 | For the sync client this will mostly be the same with the exception | |
| 786 | of `content` & `text` will be methods instead of properties. In the | |
| 787 | async client, all methods will be async. | |
| 788 | | |
| 789 | A migration script will be provided & the migration in general should | |
| 790 | be smooth. | |
| 791 | | |
| 792 | #### `.with_streaming_response` | |
| 793 | | |
| 794 | The above interface eagerly reads the full response body when you make the request, which may not always be what you want. | |
| 795 | | |
| 796 | To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods. | |
| 797 | | |
| 798 | As such, `.with_streaming_response` methods return a different [`APIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object, and the async client returns an [`AsyncAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object. | |
| 799 | | |
| 800 | ```python | |
| 801 | with client.chat.completions.with_streaming_response.create( | |
| 802 | messages=[ | |
| 803 | { | |
| 804 | "role": "user", | |
| 805 | "content": "Say this is a test", | |
| 806 | } | |
| 807 | ], | |
84e0c1d0Charlie Guo5 months ago | 808 | model="gpt-5.2", |
86379b44Stainless Bot2 years ago | 809 | ) as response: |
| 810 | print(response.headers.get("X-My-Header")) | |
| 811 | | |
| 812 | for line in response.iter_lines(): | |
| 813 | print(line) | |
| 814 | ``` | |
| 815 | | |
| 816 | The context manager is required so that the response will reliably be closed. | |
3c6d4cd6Greg Brockman5 years ago | 817 | |
73869eeeStainless Bot2 years ago | 818 | ### Making custom/undocumented requests |
| 819 | | |
7931ebaaStainless Bot2 years ago | 820 | This library is typed for convenient access to the documented API. |
73869eeeStainless Bot2 years ago | 821 | |
| 822 | If you need to access undocumented endpoints, params, or response properties, the library can still be used. | |
| 823 | | |
| 824 | #### Undocumented endpoints | |
| 825 | | |
| 826 | To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other | |
fee9c81bstainless-app[bot]1 years ago | 827 | http verbs. Options on the client will be respected (such as retries) when making this request. |
73869eeeStainless Bot2 years ago | 828 | |
| 829 | ```py | |
| 830 | import httpx | |
| 831 | | |
| 832 | response = client.post( | |
| 833 | "/foo", | |
| 834 | cast_to=httpx.Response, | |
| 835 | body={"my_param": True}, | |
| 836 | ) | |
| 837 | | |
| 838 | print(response.headers.get("x-foo")) | |
| 839 | ``` | |
| 840 | | |
802819c8Stainless Bot2 years ago | 841 | #### Undocumented request params |
73869eeeStainless Bot2 years ago | 842 | |
| 843 | If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request | |
| 844 | options. | |
| 845 | | |
802819c8Stainless Bot2 years ago | 846 | #### Undocumented response properties |
73869eeeStainless Bot2 years ago | 847 | |
| 848 | To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You | |
| 849 | can also get all the extra fields on the Pydantic model as a dict with | |
| 850 | [`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra). | |
| 851 | | |
08b8179aDavid Schnurr2 years ago | 852 | ### Configuring the HTTP client |
376dd199Logan Kilpatrick2 years ago | 853 | |
08b8179aDavid Schnurr2 years ago | 854 | You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including: |
376dd199Logan Kilpatrick2 years ago | 855 | |
6a1ab551stainless-app[bot]1 years ago | 856 | - Support for [proxies](https://www.python-httpx.org/advanced/proxies/) |
| 857 | - Custom [transports](https://www.python-httpx.org/advanced/transports/) | |
d3254d12stainless-app[bot]2 years ago | 858 | - Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality |
376dd199Logan Kilpatrick2 years ago | 859 | |
| 860 | ```python | |
6a1ab551stainless-app[bot]1 years ago | 861 | import httpx |
347363edStainless Bot2 years ago | 862 | from openai import OpenAI, DefaultHttpxClient |
08b8179aDavid Schnurr2 years ago | 863 | |
| 864 | client = OpenAI( | |
0733934fStainless Bot2 years ago | 865 | # Or use the `OPENAI_BASE_URL` env var |
38dd5348Adrian Cole1 years ago | 866 | base_url="http://my.test.server.example.com:8083/v1", |
347363edStainless Bot2 years ago | 867 | http_client=DefaultHttpxClient( |
6a1ab551stainless-app[bot]1 years ago | 868 | proxy="http://my.test.proxy.example.com", |
08b8179aDavid Schnurr2 years ago | 869 | transport=httpx.HTTPTransport(local_address="0.0.0.0"), |
| 870 | ), | |
| 871 | ) | |
| 872 | ``` | |
| 873 | | |
f8f01a61stainless-app[bot]1 years ago | 874 | You can also customize the client on a per-request basis by using `with_options()`: |
| 875 | | |
| 876 | ```python | |
| 877 | client.with_options(http_client=DefaultHttpxClient(...)) | |
| 878 | ``` | |
| 879 | | |
08b8179aDavid Schnurr2 years ago | 880 | ### Managing HTTP resources |
| 881 | | |
| 882 | By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting. | |
| 883 | | |
588935e2stainless-app[bot]1 years ago | 884 | ```py |
| 885 | from openai import OpenAI | |
| 886 | | |
| 887 | with OpenAI() as client: | |
| 888 | # make requests here | |
| 889 | ... | |
| 890 | | |
| 891 | # HTTP client is now closed | |
| 892 | ``` | |
| 893 | | |
08b8179aDavid Schnurr2 years ago | 894 | ## Microsoft Azure OpenAI |
| 895 | | |
6e7d8548Scott Addie2 years ago | 896 | To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI` |
08b8179aDavid Schnurr2 years ago | 897 | class instead of the `OpenAI` class. |
| 898 | | |
| 899 | > [!IMPORTANT] | |
| 900 | > The Azure API shape differs from the core API shape which means that the static types for responses / params | |
| 901 | > won't always be correct. | |
376dd199Logan Kilpatrick2 years ago | 902 | |
08b8179aDavid Schnurr2 years ago | 903 | ```py |
| 904 | from openai import AzureOpenAI | |
376dd199Logan Kilpatrick2 years ago | 905 | |
08b8179aDavid Schnurr2 years ago | 906 | # gets the API Key from environment variable AZURE_OPENAI_API_KEY |
| 907 | client = AzureOpenAI( | |
6e7d8548Scott Addie2 years ago | 908 | # https://learn.microsoft.com/azure/ai-services/openai/reference#rest-api-versioning |
819ae68dJackYu2 years ago | 909 | api_version="2023-07-01-preview", |
6e7d8548Scott Addie2 years ago | 910 | # https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource |
08b8179aDavid Schnurr2 years ago | 911 | azure_endpoint="https://example-endpoint.openai.azure.com", |
| 912 | ) | |
| 913 | | |
| 914 | completion = client.chat.completions.create( | |
| 915 | model="deployment-name", # e.g. gpt-35-instant | |
| 916 | messages=[ | |
| 917 | { | |
| 918 | "role": "user", | |
| 919 | "content": "How do I output all files in a directory using Python?", | |
| 920 | }, | |
| 921 | ], | |
| 922 | ) | |
47656567Stainless Bot2 years ago | 923 | print(completion.to_json()) |
376dd199Logan Kilpatrick2 years ago | 924 | ``` |
3c6d4cd6Greg Brockman5 years ago | 925 | |
08b8179aDavid Schnurr2 years ago | 926 | In addition to the options provided in the base `OpenAI` client, the following options are provided: |
| 927 | | |
7758c54bStainless Bot2 years ago | 928 | - `azure_endpoint` (or the `AZURE_OPENAI_ENDPOINT` environment variable) |
08b8179aDavid Schnurr2 years ago | 929 | - `azure_deployment` |
7758c54bStainless Bot2 years ago | 930 | - `api_version` (or the `OPENAI_API_VERSION` environment variable) |
| 931 | - `azure_ad_token` (or the `AZURE_OPENAI_AD_TOKEN` environment variable) | |
08b8179aDavid Schnurr2 years ago | 932 | - `azure_ad_token_provider` |
| 933 | | |
6e7d8548Scott Addie2 years ago | 934 | An example of using the client with Microsoft Entra ID (formerly known as Azure Active Directory) can be found [here](https://github.com/openai/openai-python/blob/main/examples/azure_ad.py). |
08b8179aDavid Schnurr2 years ago | 935 | |
| 936 | ## Versioning | |
| 937 | | |
| 938 | This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: | |
| 939 | | |
| 940 | 1. Changes that only affect static types, without breaking runtime behavior. | |
e502d301Josiah Altschuler1 years ago | 941 | 2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_ |
08b8179aDavid Schnurr2 years ago | 942 | 3. Changes that we do not expect to impact the vast majority of users in practice. |
| 943 | | |
| 944 | We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. | |
| 945 | | |
| 946 | We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-python/issues) with questions, bugs, or suggestions. | |
| 947 | | |
fee10404stainless-app[bot]1 years ago | 948 | ### Determining the installed version |
| 949 | | |
| 950 | If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version. | |
| 951 | | |
| 952 | You can determine the version that is being used at runtime with: | |
| 953 | | |
| 954 | ```py | |
| 955 | import openai | |
| 956 | print(openai.__version__) | |
| 957 | ``` | |
| 958 | | |
08b8179aDavid Schnurr2 years ago | 959 | ## Requirements |
3c6d4cd6Greg Brockman5 years ago | 960 | |
3f52ac84stainless-app[bot]7 months ago | 961 | Python 3.9 or higher. |
a3001d8dStainless Bot1 years ago | 962 | |
| 963 | ## Contributing | |
| 964 | | |
| 965 | See [the contributing documentation](./CONTRIBUTING.md). |