openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
README.md
715lines · modeblame
08b8179aDavid Schnurr2 years ago | 1 | # OpenAI Python API library |
3c6d4cd6Greg Brockman5 years ago | 2 | |
08b8179aDavid Schnurr2 years ago | 3 | [](https://pypi.org/project/openai/) |
3c6d4cd6Greg Brockman5 years ago | 4 | |
08b8179aDavid Schnurr2 years ago | 5 | The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.7+ |
| 6 | application. The library includes type definitions for all request params and response fields, | |
| 7 | and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx). | |
| 8 | | |
| 9 | It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/). | |
| 10 | | |
| 11 | ## Documentation | |
| 12 | | |
2e8ea52bstainless-app[bot]1 years ago | 13 | The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs). The full API of this library can be found in [api.md](api.md). |
3c6d4cd6Greg Brockman5 years ago | 14 | |
| 15 | ## Installation | |
| 16 | | |
448ac7d0Stainless Bot2 years ago | 17 | > [!IMPORTANT] |
db6cd764Stainless Bot2 years ago | 18 | > The SDK was rewritten in v1, which was released November 6th 2023. See the [v1 migration guide](https://github.com/openai/openai-python/discussions/742), which includes scripts to automatically update your code. |
448ac7d0Stainless Bot2 years ago | 19 | |
3c6d4cd6Greg Brockman5 years ago | 20 | ```sh |
1879c97aStainless Bot2 years ago | 21 | # install from PyPI |
6d217096Robert Craigie2 years ago | 22 | pip install openai |
3c6d4cd6Greg Brockman5 years ago | 23 | ``` |
| 24 | | |
08b8179aDavid Schnurr2 years ago | 25 | ## Usage |
| 26 | | |
986f3128Stainless Bot2 years ago | 27 | The full API of this library can be found in [api.md](api.md). |
376dd199Logan Kilpatrick2 years ago | 28 | |
| 29 | ```python | |
fb5ba01cStainless Bot2 years ago | 30 | import os |
08b8179aDavid Schnurr2 years ago | 31 | from openai import OpenAI |
| 32 | | |
| 33 | client = OpenAI( | |
fb5ba01cStainless Bot2 years ago | 34 | # This is the default and can be omitted |
| 35 | api_key=os.environ.get("OPENAI_API_KEY"), | |
08b8179aDavid Schnurr2 years ago | 36 | ) |
| 37 | | |
| 38 | chat_completion = client.chat.completions.create( | |
| 39 | messages=[ | |
| 40 | { | |
| 41 | "role": "user", | |
| 42 | "content": "Say this is a test", | |
| 43 | } | |
| 44 | ], | |
| 45 | model="gpt-3.5-turbo", | |
| 46 | ) | |
376dd199Logan Kilpatrick2 years ago | 47 | ``` |
| 48 | | |
08b8179aDavid Schnurr2 years ago | 49 | While you can provide an `api_key` keyword argument, |
| 50 | we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) | |
| 51 | to add `OPENAI_API_KEY="My API Key"` to your `.env` file | |
| 52 | so that your API Key is not stored in source control. | |
3c6d4cd6Greg Brockman5 years ago | 53 | |
192b8f2bDan Corin1 years ago | 54 | ### Vision |
| 55 | | |
| 56 | With a hosted image: | |
| 57 | | |
| 58 | ```python | |
| 59 | response = client.chat.completions.create( | |
| 60 | model="gpt-4o-mini", | |
| 61 | messages=[ | |
| 62 | { | |
| 63 | "role": "user", | |
| 64 | "content": [ | |
| 65 | {"type": "text", "text": prompt}, | |
| 66 | { | |
| 67 | "type": "image_url", | |
| 68 | "image_url": {"url": f"{img_url}"}, | |
| 69 | }, | |
| 70 | ], | |
| 71 | } | |
| 72 | ], | |
| 73 | ) | |
| 74 | ``` | |
| 75 | | |
| 76 | With the image as a base64 encoded string: | |
| 77 | | |
| 78 | ```python | |
| 79 | response = client.chat.completions.create( | |
| 80 | model="gpt-4o-mini", | |
| 81 | messages=[ | |
| 82 | { | |
| 83 | "role": "user", | |
| 84 | "content": [ | |
| 85 | {"type": "text", "text": prompt}, | |
| 86 | { | |
| 87 | "type": "image_url", | |
| 88 | "image_url": {"url": f"data:{img_type};base64,{img_b64_str}"}, | |
| 89 | }, | |
| 90 | ], | |
| 91 | } | |
| 92 | ], | |
| 93 | ) | |
| 94 | ``` | |
| 95 | | |
595f3b36Stainless Bot2 years ago | 96 | ### Polling Helpers |
| 97 | | |
5b20698dStainless Bot2 years ago | 98 | When interacting with the API some actions such as starting a Run and adding files to vector stores are asynchronous and take time to complete. The SDK includes |
595f3b36Stainless Bot2 years ago | 99 | helper functions which will poll the status until it reaches a terminal state and then return the resulting object. |
137f38baNino Risteski2 years ago | 100 | If an API method results in an action that could benefit from polling there will be a corresponding version of the |
595f3b36Stainless Bot2 years ago | 101 | method ending in '\_and_poll'. |
| 102 | | |
| 103 | For instance to create a Run and poll until it reaches a terminal state you can run: | |
| 104 | | |
| 105 | ```python | |
| 106 | run = client.beta.threads.runs.create_and_poll( | |
| 107 | thread_id=thread.id, | |
| 108 | assistant_id=assistant.id, | |
| 109 | ) | |
| 110 | ``` | |
| 111 | | |
| 112 | More information on the lifecycle of a Run can be found in the [Run Lifecycle Documentation](https://platform.openai.com/docs/assistants/how-it-works/run-lifecycle) | |
| 113 | | |
5b20698dStainless Bot2 years ago | 114 | ### Bulk Upload Helpers |
| 115 | | |
137f38baNino Risteski2 years ago | 116 | When creating and interacting with vector stores, you can use polling helpers to monitor the status of operations. |
5b20698dStainless Bot2 years ago | 117 | For convenience, we also provide a bulk upload helper to allow you to simultaneously upload several files at once. |
| 118 | | |
| 119 | ```python | |
| 120 | sample_files = [Path("sample-paper.pdf"), ...] | |
| 121 | | |
| 122 | batch = await client.vector_stores.file_batches.upload_and_poll( | |
| 123 | store.id, | |
| 124 | files=sample_files, | |
| 125 | ) | |
| 126 | ``` | |
| 127 | | |
5cfb125aStainless Bot2 years ago | 128 | ### Streaming Helpers |
| 129 | | |
137f38baNino Risteski2 years ago | 130 | The SDK also includes helpers to process streams and handle incoming events. |
5cfb125aStainless Bot2 years ago | 131 | |
| 132 | ```python | |
595f3b36Stainless Bot2 years ago | 133 | with client.beta.threads.runs.stream( |
5cfb125aStainless Bot2 years ago | 134 | thread_id=thread.id, |
| 135 | assistant_id=assistant.id, | |
| 136 | instructions="Please address the user as Jane Doe. The user has a premium account.", | |
| 137 | ) as stream: | |
| 138 | for event in stream: | |
| 139 | # Print the text from text delta events | |
| 140 | if event.type == "thread.message.delta" and event.data.delta.content: | |
| 141 | print(event.data.delta.content[0].text) | |
| 142 | ``` | |
| 143 | | |
| 144 | More information on streaming helpers can be found in the dedicated documentation: [helpers.md](helpers.md) | |
| 145 | | |
08b8179aDavid Schnurr2 years ago | 146 | ## Async usage |
3c6d4cd6Greg Brockman5 years ago | 147 | |
08b8179aDavid Schnurr2 years ago | 148 | Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call: |
ede08829Jakub Roztocil3 years ago | 149 | |
08b8179aDavid Schnurr2 years ago | 150 | ```python |
fb5ba01cStainless Bot2 years ago | 151 | import os |
08b8179aDavid Schnurr2 years ago | 152 | import asyncio |
| 153 | from openai import AsyncOpenAI | |
ede08829Jakub Roztocil3 years ago | 154 | |
08b8179aDavid Schnurr2 years ago | 155 | client = AsyncOpenAI( |
fb5ba01cStainless Bot2 years ago | 156 | # This is the default and can be omitted |
| 157 | api_key=os.environ.get("OPENAI_API_KEY"), | |
08b8179aDavid Schnurr2 years ago | 158 | ) |
ede08829Jakub Roztocil3 years ago | 159 | |
| 160 | | |
08b8179aDavid Schnurr2 years ago | 161 | async def main() -> None: |
| 162 | chat_completion = await client.chat.completions.create( | |
| 163 | messages=[ | |
| 164 | { | |
| 165 | "role": "user", | |
| 166 | "content": "Say this is a test", | |
| 167 | } | |
| 168 | ], | |
| 169 | model="gpt-3.5-turbo", | |
| 170 | ) | |
ede08829Jakub Roztocil3 years ago | 171 | |
| 172 | | |
08b8179aDavid Schnurr2 years ago | 173 | asyncio.run(main()) |
2b21516eAtty Eleti3 years ago | 174 | ``` |
ede08829Jakub Roztocil3 years ago | 175 | |
08b8179aDavid Schnurr2 years ago | 176 | Functionality between the synchronous and asynchronous clients is otherwise identical. |
| 177 | | |
2b23eb53Stainless Bot2 years ago | 178 | ## Streaming responses |
08b8179aDavid Schnurr2 years ago | 179 | |
| 180 | We provide support for streaming responses using Server Side Events (SSE). | |
d53d9efbRachel Lim5 years ago | 181 | |
08b8179aDavid Schnurr2 years ago | 182 | ```python |
| 183 | from openai import OpenAI | |
| 184 | | |
| 185 | client = OpenAI() | |
d53d9efbRachel Lim5 years ago | 186 | |
08b8179aDavid Schnurr2 years ago | 187 | stream = client.chat.completions.create( |
| 188 | model="gpt-4", | |
| 189 | messages=[{"role": "user", "content": "Say this is a test"}], | |
| 190 | stream=True, | |
| 191 | ) | |
54c7c512Stainless Bot2 years ago | 192 | for chunk in stream: |
a3da0196Stainless Bot2 years ago | 193 | print(chunk.choices[0].delta.content or "", end="") |
d53d9efbRachel Lim5 years ago | 194 | ``` |
| 195 | | |
08b8179aDavid Schnurr2 years ago | 196 | The async client uses the exact same interface. |
d53d9efbRachel Lim5 years ago | 197 | |
| 198 | ```python | |
08b8179aDavid Schnurr2 years ago | 199 | from openai import AsyncOpenAI |
| 200 | | |
| 201 | client = AsyncOpenAI() | |
| 202 | | |
a3da0196Stainless Bot2 years ago | 203 | |
dfe1c8daSahand Sojoodi2 years ago | 204 | async def main(): |
| 205 | stream = await client.chat.completions.create( | |
| 206 | model="gpt-4", | |
| 207 | messages=[{"role": "user", "content": "Say this is a test"}], | |
| 208 | stream=True, | |
| 209 | ) | |
| 210 | async for chunk in stream: | |
a3da0196Stainless Bot2 years ago | 211 | print(chunk.choices[0].delta.content or "", end="") |
| 212 | | |
dfe1c8daSahand Sojoodi2 years ago | 213 | |
| 214 | asyncio.run(main()) | |
53e5ba4bt-asutedjo4 years ago | 215 | ``` |
2b21516eAtty Eleti3 years ago | 216 | |
08b8179aDavid Schnurr2 years ago | 217 | ## Module-level client |
d53d9efbRachel Lim5 years ago | 218 | |
08b8179aDavid Schnurr2 years ago | 219 | > [!IMPORTANT] |
| 220 | > We highly recommend instantiating client instances instead of relying on the global client. | |
d53d9efbRachel Lim5 years ago | 221 | |
08b8179aDavid Schnurr2 years ago | 222 | We also expose a global client instance that is accessible in a similar fashion to versions prior to v1. |
6572ef4fZheNing Hu3 years ago | 223 | |
08b8179aDavid Schnurr2 years ago | 224 | ```py |
| 225 | import openai | |
62b73b9bAtty Eleti3 years ago | 226 | |
08b8179aDavid Schnurr2 years ago | 227 | # optional; defaults to `os.environ['OPENAI_API_KEY']` |
| 228 | openai.api_key = '...' | |
| 229 | | |
| 230 | # all client options can be configured just like the `OpenAI` instantiation counterpart | |
| 231 | openai.base_url = "https://..." | |
| 232 | openai.default_headers = {"x-foo": "true"} | |
| 233 | | |
| 234 | completion = openai.chat.completions.create( | |
| 235 | model="gpt-4", | |
| 236 | messages=[ | |
| 237 | { | |
| 238 | "role": "user", | |
| 239 | "content": "How do I output all files in a directory using Python?", | |
| 240 | }, | |
| 241 | ], | |
| 242 | ) | |
62b73b9bAtty Eleti3 years ago | 243 | print(completion.choices[0].message.content) |
| 244 | ``` | |
| 245 | | |
137f38baNino Risteski2 years ago | 246 | The API is the exact same as the standard client instance-based API. |
376dd199Logan Kilpatrick2 years ago | 247 | |
08b8179aDavid Schnurr2 years ago | 248 | This is intended to be used within REPLs or notebooks for faster iteration, **not** in application code. |
2b21516eAtty Eleti3 years ago | 249 | |
08b8179aDavid Schnurr2 years ago | 250 | We recommend that you always instantiate a client (e.g., with `client = OpenAI()`) in application code because: |
2b21516eAtty Eleti3 years ago | 251 | |
08b8179aDavid Schnurr2 years ago | 252 | - It can be difficult to reason about where client options are configured |
| 253 | - It's not possible to change certain client options without potentially causing race conditions | |
| 254 | - It's harder to mock for testing purposes | |
| 255 | - It's not possible to control cleanup of network connections | |
| 256 | | |
| 257 | ## Using types | |
| 258 | | |
47656567Stainless Bot2 years ago | 259 | 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 | 260 | |
47656567Stainless Bot2 years ago | 261 | - Serializing back into JSON, `model.to_json()` |
| 262 | - Converting to a dictionary, `model.to_dict()` | |
2b21516eAtty Eleti3 years ago | 263 | |
08b8179aDavid Schnurr2 years ago | 264 | 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 | 265 | |
08b8179aDavid Schnurr2 years ago | 266 | ## Pagination |
0e21703eTed Sanders4 years ago | 267 | |
08b8179aDavid Schnurr2 years ago | 268 | List methods in the OpenAI API are paginated. |
| 269 | | |
| 270 | This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually: | |
0e21703eTed Sanders4 years ago | 271 | |
| 272 | ```python | |
ff5add01stainless-app[bot]1 years ago | 273 | from openai import OpenAI |
0e21703eTed Sanders4 years ago | 274 | |
08b8179aDavid Schnurr2 years ago | 275 | client = OpenAI() |
0e21703eTed Sanders4 years ago | 276 | |
08b8179aDavid Schnurr2 years ago | 277 | all_jobs = [] |
| 278 | # Automatically fetches more pages as needed. | |
| 279 | for job in client.fine_tuning.jobs.list( | |
| 280 | limit=20, | |
| 281 | ): | |
| 282 | # Do something with job here | |
| 283 | all_jobs.append(job) | |
| 284 | print(all_jobs) | |
0e21703eTed Sanders4 years ago | 285 | ``` |
| 286 | | |
08b8179aDavid Schnurr2 years ago | 287 | Or, asynchronously: |
0e21703eTed Sanders4 years ago | 288 | |
08b8179aDavid Schnurr2 years ago | 289 | ```python |
| 290 | import asyncio | |
ff5add01stainless-app[bot]1 years ago | 291 | from openai import AsyncOpenAI |
0e21703eTed Sanders4 years ago | 292 | |
08b8179aDavid Schnurr2 years ago | 293 | client = AsyncOpenAI() |
0e21703eTed Sanders4 years ago | 294 | |
| 295 | | |
08b8179aDavid Schnurr2 years ago | 296 | async def main() -> None: |
| 297 | all_jobs = [] | |
| 298 | # Iterate through items across all pages, issuing requests as needed. | |
| 299 | async for job in client.fine_tuning.jobs.list( | |
| 300 | limit=20, | |
| 301 | ): | |
| 302 | all_jobs.append(job) | |
| 303 | print(all_jobs) | |
0e21703eTed Sanders4 years ago | 304 | |
62b51ca0Boris Dayma4 years ago | 305 | |
08b8179aDavid Schnurr2 years ago | 306 | asyncio.run(main()) |
| 307 | ``` | |
2942bf4bLogan Kilpatrick2 years ago | 308 | |
08b8179aDavid Schnurr2 years ago | 309 | 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 | 310 | |
08b8179aDavid Schnurr2 years ago | 311 | ```python |
| 312 | first_page = await client.fine_tuning.jobs.list( | |
| 313 | limit=20, | |
| 314 | ) | |
| 315 | if first_page.has_next_page(): | |
| 316 | print(f"will fetch next page using these details: {first_page.next_page_info()}") | |
| 317 | next_page = await first_page.get_next_page() | |
| 318 | print(f"number of items we just fetched: {len(next_page.data)}") | |
| 319 | | |
| 320 | # Remove `await` for non-async usage. | |
62b51ca0Boris Dayma4 years ago | 321 | ``` |
| 322 | | |
08b8179aDavid Schnurr2 years ago | 323 | Or just work directly with the returned data: |
0e21703eTed Sanders4 years ago | 324 | |
08b8179aDavid Schnurr2 years ago | 325 | ```python |
| 326 | first_page = await client.fine_tuning.jobs.list( | |
| 327 | limit=20, | |
| 328 | ) | |
e389823bMorgan McGuire2 years ago | 329 | |
08b8179aDavid Schnurr2 years ago | 330 | print(f"next page cursor: {first_page.after}") # => "next page cursor: ..." |
| 331 | for job in first_page.data: | |
| 332 | print(job.id) | |
e389823bMorgan McGuire2 years ago | 333 | |
08b8179aDavid Schnurr2 years ago | 334 | # Remove `await` for non-async usage. |
| 335 | ``` | |
e389823bMorgan McGuire2 years ago | 336 | |
08b8179aDavid Schnurr2 years ago | 337 | ## Nested params |
3c00e856hallacy3 years ago | 338 | |
08b8179aDavid Schnurr2 years ago | 339 | Nested parameters are dictionaries, typed using `TypedDict`, for example: |
3c00e856hallacy3 years ago | 340 | |
| 341 | ```python | |
08b8179aDavid Schnurr2 years ago | 342 | from openai import OpenAI |
3c00e856hallacy3 years ago | 343 | |
08b8179aDavid Schnurr2 years ago | 344 | client = OpenAI() |
| 345 | | |
aa681899Stainless Bot2 years ago | 346 | completion = client.chat.completions.create( |
| 347 | messages=[ | |
| 348 | { | |
| 349 | "role": "user", | |
| 350 | "content": "Can you generate an example json object describing a fruit?", | |
| 351 | } | |
| 352 | ], | |
9c8789c2Stainless Bot2 years ago | 353 | model="gpt-3.5-turbo-1106", |
aa681899Stainless Bot2 years ago | 354 | response_format={"type": "json_object"}, |
| 355 | ) | |
08b8179aDavid Schnurr2 years ago | 356 | ``` |
3c00e856hallacy3 years ago | 357 | |
2b23eb53Stainless Bot2 years ago | 358 | ## File uploads |
dc33cb9dMichelle Pokrass3 years ago | 359 | |
08b8179aDavid Schnurr2 years ago | 360 | Request parameters that correspond to file uploads can be passed as `bytes`, 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 | 361 | |
376dd199Logan Kilpatrick2 years ago | 362 | ```python |
08b8179aDavid Schnurr2 years ago | 363 | from pathlib import Path |
| 364 | from openai import OpenAI | |
| 365 | | |
| 366 | client = OpenAI() | |
| 367 | | |
| 368 | client.files.create( | |
| 369 | file=Path("input.jsonl"), | |
| 370 | purpose="fine-tune", | |
| 371 | ) | |
dc33cb9dMichelle Pokrass3 years ago | 372 | ``` |
| 373 | | |
08b8179aDavid Schnurr2 years ago | 374 | 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 | 375 | |
08b8179aDavid Schnurr2 years ago | 376 | ## Handling errors |
376dd199Logan Kilpatrick2 years ago | 377 | |
08b8179aDavid Schnurr2 years ago | 378 | 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 | 379 | |
08b8179aDavid Schnurr2 years ago | 380 | When the API returns a non-success status code (that is, 4xx or 5xx |
| 381 | response), a subclass of `openai.APIStatusError` is raised, containing `status_code` and `response` properties. | |
62b73b9bAtty Eleti3 years ago | 382 | |
08b8179aDavid Schnurr2 years ago | 383 | All errors inherit from `openai.APIError`. |
| 384 | | |
| 385 | ```python | |
| 386 | import openai | |
| 387 | from openai import OpenAI | |
| 388 | | |
| 389 | client = OpenAI() | |
| 390 | | |
| 391 | try: | |
8dab1421Stainless Bot2 years ago | 392 | client.fine_tuning.jobs.create( |
| 393 | model="gpt-3.5-turbo", | |
| 394 | training_file="file-abc123", | |
08b8179aDavid Schnurr2 years ago | 395 | ) |
| 396 | except openai.APIConnectionError as e: | |
| 397 | print("The server could not be reached") | |
| 398 | print(e.__cause__) # an underlying Exception, likely raised within httpx. | |
| 399 | except openai.RateLimitError as e: | |
| 400 | print("A 429 status code was received; we should back off a bit.") | |
| 401 | except openai.APIStatusError as e: | |
| 402 | print("Another non-200-range status code was received") | |
| 403 | print(e.status_code) | |
| 404 | print(e.response) | |
62b73b9bAtty Eleti3 years ago | 405 | ``` |
| 406 | | |
08b8179aDavid Schnurr2 years ago | 407 | Error codes are as followed: |
| 408 | | |
| 409 | | Status Code | Error Type | | |
| 410 | | ----------- | -------------------------- | | |
| 411 | | 400 | `BadRequestError` | | |
| 412 | | 401 | `AuthenticationError` | | |
| 413 | | 403 | `PermissionDeniedError` | | |
| 414 | | 404 | `NotFoundError` | | |
| 415 | | 422 | `UnprocessableEntityError` | | |
| 416 | | 429 | `RateLimitError` | | |
| 417 | | >=500 | `InternalServerError` | | |
| 418 | | N/A | `APIConnectionError` | | |
| 419 | | |
4b302346Robert Craigie1 years ago | 420 | ## Request IDs |
| 421 | | |
| 422 | > For more information on debugging requests, see [these docs](https://platform.openai.com/docs/api-reference/debugging-requests) | |
| 423 | | |
| 424 | 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. | |
| 425 | | |
| 426 | ```python | |
| 427 | completion = await client.chat.completions.create( | |
| 428 | messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-4" | |
| 429 | ) | |
| 430 | print(completion._request_id) # req_123 | |
| 431 | ``` | |
| 432 | | |
| 433 | Note that unlike other properties that use an `_` prefix, the `_request_id` property | |
| 434 | *is* public. Unless documented otherwise, *all* other `_` prefix properties, | |
| 435 | methods and modules are *private*. | |
| 436 | | |
| 437 | | |
08b8179aDavid Schnurr2 years ago | 438 | ### Retries |
376dd199Logan Kilpatrick2 years ago | 439 | |
08b8179aDavid Schnurr2 years ago | 440 | Certain errors are automatically retried 2 times by default, with a short exponential backoff. |
| 441 | Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, | |
| 442 | 429 Rate Limit, and >=500 Internal errors are all retried by default. | |
0abf6413Andrew Chen Wang3 years ago | 443 | |
08b8179aDavid Schnurr2 years ago | 444 | You can use the `max_retries` option to configure or disable retry settings: |
0abf6413Andrew Chen Wang3 years ago | 445 | |
| 446 | ```python | |
08b8179aDavid Schnurr2 years ago | 447 | from openai import OpenAI |
| 448 | | |
| 449 | # Configure the default for all requests: | |
| 450 | client = OpenAI( | |
| 451 | # default is 2 | |
| 452 | max_retries=0, | |
| 453 | ) | |
| 454 | | |
| 455 | # Or, configure per-request: | |
| 456 | client.with_options(max_retries=5).chat.completions.create( | |
| 457 | messages=[ | |
| 458 | { | |
| 459 | "role": "user", | |
| 460 | "content": "How can I get the name of the current day in Node.js?", | |
| 461 | } | |
| 462 | ], | |
| 463 | model="gpt-3.5-turbo", | |
| 464 | ) | |
0abf6413Andrew Chen Wang3 years ago | 465 | ``` |
| 466 | | |
08b8179aDavid Schnurr2 years ago | 467 | ### Timeouts |
0abf6413Andrew Chen Wang3 years ago | 468 | |
08b8179aDavid Schnurr2 years ago | 469 | By default requests time out after 10 minutes. You can configure this with a `timeout` option, |
| 470 | which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/#fine-tuning-the-configuration) object: | |
376dd199Logan Kilpatrick2 years ago | 471 | |
08b8179aDavid Schnurr2 years ago | 472 | ```python |
| 473 | from openai import OpenAI | |
| 474 | | |
| 475 | # Configure the default for all requests: | |
| 476 | client = OpenAI( | |
1381f46eStainless Bot2 years ago | 477 | # 20 seconds (default is 10 minutes) |
08b8179aDavid Schnurr2 years ago | 478 | timeout=20.0, |
| 479 | ) | |
| 480 | | |
| 481 | # More granular control: | |
| 482 | client = OpenAI( | |
| 483 | timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), | |
| 484 | ) | |
| 485 | | |
| 486 | # Override per-request: | |
2a678e30Stainless Bot2 years ago | 487 | client.with_options(timeout=5.0).chat.completions.create( |
08b8179aDavid Schnurr2 years ago | 488 | messages=[ |
| 489 | { | |
| 490 | "role": "user", | |
| 491 | "content": "How can I list all files in a directory using Python?", | |
| 492 | } | |
| 493 | ], | |
| 494 | model="gpt-3.5-turbo", | |
| 495 | ) | |
0abf6413Andrew Chen Wang3 years ago | 496 | ``` |
| 497 | | |
08b8179aDavid Schnurr2 years ago | 498 | On timeout, an `APITimeoutError` is thrown. |
376dd199Logan Kilpatrick2 years ago | 499 | |
08b8179aDavid Schnurr2 years ago | 500 | Note that requests that time out are [retried twice by default](#retries). |
376dd199Logan Kilpatrick2 years ago | 501 | |
08b8179aDavid Schnurr2 years ago | 502 | ## Advanced |
376dd199Logan Kilpatrick2 years ago | 503 | |
08b8179aDavid Schnurr2 years ago | 504 | ### Logging |
376dd199Logan Kilpatrick2 years ago | 505 | |
08b8179aDavid Schnurr2 years ago | 506 | We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module. |
376dd199Logan Kilpatrick2 years ago | 507 | |
08b8179aDavid Schnurr2 years ago | 508 | You can enable logging by setting the environment variable `OPENAI_LOG` to `debug`. |
376dd199Logan Kilpatrick2 years ago | 509 | |
08b8179aDavid Schnurr2 years ago | 510 | ```shell |
| 511 | $ export OPENAI_LOG=debug | |
376dd199Logan Kilpatrick2 years ago | 512 | ``` |
| 513 | | |
08b8179aDavid Schnurr2 years ago | 514 | ### How to tell whether `None` means `null` or missing |
dc33cb9dMichelle Pokrass3 years ago | 515 | |
08b8179aDavid Schnurr2 years ago | 516 | 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 | 517 | |
08b8179aDavid Schnurr2 years ago | 518 | ```py |
| 519 | if response.my_field is None: | |
| 520 | if 'my_field' not in response.model_fields_set: | |
| 521 | print('Got json like {}, without a "my_field" key present at all.') | |
| 522 | else: | |
| 523 | print('Got json like {"my_field": null}.') | |
| 524 | ``` | |
376dd199Logan Kilpatrick2 years ago | 525 | |
08b8179aDavid Schnurr2 years ago | 526 | ### Accessing raw response data (e.g. headers) |
376dd199Logan Kilpatrick2 years ago | 527 | |
86379b44Stainless Bot2 years ago | 528 | The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g., |
08b8179aDavid Schnurr2 years ago | 529 | |
| 530 | ```py | |
| 531 | from openai import OpenAI | |
| 532 | | |
| 533 | client = OpenAI() | |
| 534 | response = client.chat.completions.with_raw_response.create( | |
| 535 | messages=[{ | |
| 536 | "role": "user", | |
| 537 | "content": "Say this is a test", | |
| 538 | }], | |
| 539 | model="gpt-3.5-turbo", | |
| 540 | ) | |
| 541 | print(response.headers.get('X-My-Header')) | |
| 542 | | |
| 543 | completion = response.parse() # get the object that `chat.completions.create()` would have returned | |
| 544 | print(completion) | |
376dd199Logan Kilpatrick2 years ago | 545 | ``` |
| 546 | | |
86379b44Stainless Bot2 years ago | 547 | These methods return an [`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. |
| 548 | | |
| 549 | For the sync client this will mostly be the same with the exception | |
| 550 | of `content` & `text` will be methods instead of properties. In the | |
| 551 | async client, all methods will be async. | |
| 552 | | |
| 553 | A migration script will be provided & the migration in general should | |
| 554 | be smooth. | |
| 555 | | |
| 556 | #### `.with_streaming_response` | |
| 557 | | |
| 558 | The above interface eagerly reads the full response body when you make the request, which may not always be what you want. | |
| 559 | | |
| 560 | 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. | |
| 561 | | |
| 562 | 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. | |
| 563 | | |
| 564 | ```python | |
| 565 | with client.chat.completions.with_streaming_response.create( | |
| 566 | messages=[ | |
| 567 | { | |
| 568 | "role": "user", | |
| 569 | "content": "Say this is a test", | |
| 570 | } | |
| 571 | ], | |
| 572 | model="gpt-3.5-turbo", | |
| 573 | ) as response: | |
| 574 | print(response.headers.get("X-My-Header")) | |
| 575 | | |
| 576 | for line in response.iter_lines(): | |
| 577 | print(line) | |
| 578 | ``` | |
| 579 | | |
| 580 | The context manager is required so that the response will reliably be closed. | |
3c6d4cd6Greg Brockman5 years ago | 581 | |
73869eeeStainless Bot2 years ago | 582 | ### Making custom/undocumented requests |
| 583 | | |
7931ebaaStainless Bot2 years ago | 584 | This library is typed for convenient access to the documented API. |
73869eeeStainless Bot2 years ago | 585 | |
| 586 | If you need to access undocumented endpoints, params, or response properties, the library can still be used. | |
| 587 | | |
| 588 | #### Undocumented endpoints | |
| 589 | | |
| 590 | To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other | |
| 591 | http verbs. Options on the client will be respected (such as retries) will be respected when making this | |
| 592 | request. | |
| 593 | | |
| 594 | ```py | |
| 595 | import httpx | |
| 596 | | |
| 597 | response = client.post( | |
| 598 | "/foo", | |
| 599 | cast_to=httpx.Response, | |
| 600 | body={"my_param": True}, | |
| 601 | ) | |
| 602 | | |
| 603 | print(response.headers.get("x-foo")) | |
| 604 | ``` | |
| 605 | | |
802819c8Stainless Bot2 years ago | 606 | #### Undocumented request params |
73869eeeStainless Bot2 years ago | 607 | |
| 608 | If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request | |
| 609 | options. | |
| 610 | | |
802819c8Stainless Bot2 years ago | 611 | #### Undocumented response properties |
73869eeeStainless Bot2 years ago | 612 | |
| 613 | To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You | |
| 614 | can also get all the extra fields on the Pydantic model as a dict with | |
| 615 | [`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra). | |
| 616 | | |
08b8179aDavid Schnurr2 years ago | 617 | ### Configuring the HTTP client |
376dd199Logan Kilpatrick2 years ago | 618 | |
08b8179aDavid Schnurr2 years ago | 619 | 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 | 620 | |
08b8179aDavid Schnurr2 years ago | 621 | - Support for proxies |
| 622 | - Custom transports | |
d3254d12stainless-app[bot]2 years ago | 623 | - Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality |
376dd199Logan Kilpatrick2 years ago | 624 | |
| 625 | ```python | |
347363edStainless Bot2 years ago | 626 | from openai import OpenAI, DefaultHttpxClient |
08b8179aDavid Schnurr2 years ago | 627 | |
| 628 | client = OpenAI( | |
0733934fStainless Bot2 years ago | 629 | # Or use the `OPENAI_BASE_URL` env var |
38dd5348Adrian Cole1 years ago | 630 | base_url="http://my.test.server.example.com:8083/v1", |
347363edStainless Bot2 years ago | 631 | http_client=DefaultHttpxClient( |
08b8179aDavid Schnurr2 years ago | 632 | proxies="http://my.test.proxy.example.com", |
| 633 | transport=httpx.HTTPTransport(local_address="0.0.0.0"), | |
| 634 | ), | |
| 635 | ) | |
| 636 | ``` | |
| 637 | | |
f8f01a61stainless-app[bot]1 years ago | 638 | You can also customize the client on a per-request basis by using `with_options()`: |
| 639 | | |
| 640 | ```python | |
| 641 | client.with_options(http_client=DefaultHttpxClient(...)) | |
| 642 | ``` | |
| 643 | | |
08b8179aDavid Schnurr2 years ago | 644 | ### Managing HTTP resources |
| 645 | | |
| 646 | 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. | |
| 647 | | |
| 648 | ## Microsoft Azure OpenAI | |
| 649 | | |
6e7d8548Scott Addie2 years ago | 650 | To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI` |
08b8179aDavid Schnurr2 years ago | 651 | class instead of the `OpenAI` class. |
| 652 | | |
| 653 | > [!IMPORTANT] | |
| 654 | > The Azure API shape differs from the core API shape which means that the static types for responses / params | |
| 655 | > won't always be correct. | |
376dd199Logan Kilpatrick2 years ago | 656 | |
08b8179aDavid Schnurr2 years ago | 657 | ```py |
| 658 | from openai import AzureOpenAI | |
376dd199Logan Kilpatrick2 years ago | 659 | |
08b8179aDavid Schnurr2 years ago | 660 | # gets the API Key from environment variable AZURE_OPENAI_API_KEY |
| 661 | client = AzureOpenAI( | |
6e7d8548Scott Addie2 years ago | 662 | # https://learn.microsoft.com/azure/ai-services/openai/reference#rest-api-versioning |
819ae68dJackYu2 years ago | 663 | api_version="2023-07-01-preview", |
6e7d8548Scott Addie2 years ago | 664 | # https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource |
08b8179aDavid Schnurr2 years ago | 665 | azure_endpoint="https://example-endpoint.openai.azure.com", |
| 666 | ) | |
| 667 | | |
| 668 | completion = client.chat.completions.create( | |
| 669 | model="deployment-name", # e.g. gpt-35-instant | |
| 670 | messages=[ | |
| 671 | { | |
| 672 | "role": "user", | |
| 673 | "content": "How do I output all files in a directory using Python?", | |
| 674 | }, | |
| 675 | ], | |
| 676 | ) | |
47656567Stainless Bot2 years ago | 677 | print(completion.to_json()) |
376dd199Logan Kilpatrick2 years ago | 678 | ``` |
3c6d4cd6Greg Brockman5 years ago | 679 | |
08b8179aDavid Schnurr2 years ago | 680 | In addition to the options provided in the base `OpenAI` client, the following options are provided: |
| 681 | | |
7758c54bStainless Bot2 years ago | 682 | - `azure_endpoint` (or the `AZURE_OPENAI_ENDPOINT` environment variable) |
08b8179aDavid Schnurr2 years ago | 683 | - `azure_deployment` |
7758c54bStainless Bot2 years ago | 684 | - `api_version` (or the `OPENAI_API_VERSION` environment variable) |
| 685 | - `azure_ad_token` (or the `AZURE_OPENAI_AD_TOKEN` environment variable) | |
08b8179aDavid Schnurr2 years ago | 686 | - `azure_ad_token_provider` |
| 687 | | |
6e7d8548Scott Addie2 years ago | 688 | 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 | 689 | |
| 690 | ## Versioning | |
| 691 | | |
| 692 | 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: | |
| 693 | | |
| 694 | 1. Changes that only affect static types, without breaking runtime behavior. | |
| 695 | 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)_. | |
| 696 | 3. Changes that we do not expect to impact the vast majority of users in practice. | |
| 697 | | |
| 698 | We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. | |
| 699 | | |
| 700 | We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-python/issues) with questions, bugs, or suggestions. | |
| 701 | | |
fee10404stainless-app[bot]1 years ago | 702 | ### Determining the installed version |
| 703 | | |
| 704 | 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. | |
| 705 | | |
| 706 | You can determine the version that is being used at runtime with: | |
| 707 | | |
| 708 | ```py | |
| 709 | import openai | |
| 710 | print(openai.__version__) | |
| 711 | ``` | |
| 712 | | |
08b8179aDavid Schnurr2 years ago | 713 | ## Requirements |
3c6d4cd6Greg Brockman5 years ago | 714 | |
08b8179aDavid Schnurr2 years ago | 715 | Python 3.7 or higher. |