openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.80.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

README.md

740lines · modecode

1# OpenAI Python API library
2
3[![PyPI version](https://img.shields.io/pypi/v/openai.svg)](https://pypi.org/project/openai/)
4
5The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.8+
6application. The library includes type definitions for all request params and response fields,
7and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).
8
9It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/).
10
11## Documentation
12
13The 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).
14
15## Installation
16
17```sh
18# install from PyPI
19pip install openai
20```
21
22## Usage
23
24The full API of this library can be found in [api.md](api.md).
25
26The 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.
27
28```python
29import os
30from openai import OpenAI
31
32client = OpenAI(
33 # This is the default and can be omitted
34 api_key=os.environ.get("OPENAI_API_KEY"),
35)
36
37response = client.responses.create(
38 model="gpt-4o",
39 instructions="You are a coding assistant that talks like a pirate.",
40 input="How do I check if a Python object is an instance of a class?",
41)
42
43print(response.output_text)
44```
45
46The 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.
47
48```python
49from openai import OpenAI
50
51client = OpenAI()
52
53completion = client.chat.completions.create(
54 model="gpt-4o",
55 messages=[
56 {"role": "developer", "content": "Talk like a pirate."},
57 {
58 "role": "user",
59 "content": "How do I check if a Python object is an instance of a class?",
60 },
61 ],
62)
63
64print(completion.choices[0].message.content)
65```
66
67While you can provide an `api_key` keyword argument,
68we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)
69to add `OPENAI_API_KEY="My API Key"` to your `.env` file
70so that your API key is not stored in source control.
71[Get an API key here](https://platform.openai.com/settings/organization/api-keys).
72
73### Vision
74
75With an image URL:
76
77```python
78prompt = "What is in this image?"
79img_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2023_06_08_Raccoon1.jpg/1599px-2023_06_08_Raccoon1.jpg"
80
81response = client.responses.create(
82 model="gpt-4o-mini",
83 input=[
84 {
85 "role": "user",
86 "content": [
87 {"type": "input_text", "text": prompt},
88 {"type": "input_image", "image_url": f"{img_url}"},
89 ],
90 }
91 ],
92)
93```
94
95With the image as a base64 encoded string:
96
97```python
98import base64
99from openai import OpenAI
100
101client = OpenAI()
102
103prompt = "What is in this image?"
104with open("path/to/image.png", "rb") as image_file:
105 b64_image = base64.b64encode(image_file.read()).decode("utf-8")
106
107response = client.responses.create(
108 model="gpt-4o-mini",
109 input=[
110 {
111 "role": "user",
112 "content": [
113 {"type": "input_text", "text": prompt},
114 {"type": "input_image", "image_url": f"data:image/png;base64,{b64_image}"},
115 ],
116 }
117 ],
118)
119```
120
121## Async usage
122
123Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call:
124
125```python
126import os
127import asyncio
128from openai import AsyncOpenAI
129
130client = AsyncOpenAI(
131 # This is the default and can be omitted
132 api_key=os.environ.get("OPENAI_API_KEY"),
133)
134
135
136async def main() -> None:
137 response = await client.responses.create(
138 model="gpt-4o", input="Explain disestablishmentarianism to a smart five year old."
139 )
140 print(response.output_text)
141
142
143asyncio.run(main())
144```
145
146Functionality between the synchronous and asynchronous clients is otherwise identical.
147
148## Streaming responses
149
150We provide support for streaming responses using Server Side Events (SSE).
151
152```python
153from openai import OpenAI
154
155client = OpenAI()
156
157stream = client.responses.create(
158 model="gpt-4o",
159 input="Write a one-sentence bedtime story about a unicorn.",
160 stream=True,
161)
162
163for event in stream:
164 print(event)
165```
166
167The async client uses the exact same interface.
168
169```python
170import asyncio
171from openai import AsyncOpenAI
172
173client = AsyncOpenAI()
174
175
176async def main():
177 stream = client.responses.create(
178 model="gpt-4o",
179 input="Write a one-sentence bedtime story about a unicorn.",
180 stream=True,
181 )
182
183 for event in stream:
184 print(event)
185
186
187asyncio.run(main())
188```
189
190## Realtime API beta
191
192The 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.
193
194Under the hood the SDK uses the [`websockets`](https://websockets.readthedocs.io/en/stable/) library to manage connections.
195
196The 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).
197
198Basic text based example:
199
200```py
201import asyncio
202from openai import AsyncOpenAI
203
204async def main():
205 client = AsyncOpenAI()
206
207 async with client.beta.realtime.connect(model="gpt-4o-realtime-preview") as connection:
208 await connection.session.update(session={'modalities': ['text']})
209
210 await connection.conversation.item.create(
211 item={
212 "type": "message",
213 "role": "user",
214 "content": [{"type": "input_text", "text": "Say hello!"}],
215 }
216 )
217 await connection.response.create()
218
219 async for event in connection:
220 if event.type == 'response.text.delta':
221 print(event.delta, flush=True, end="")
222
223 elif event.type == 'response.text.done':
224 print()
225
226 elif event.type == "response.done":
227 break
228
229asyncio.run(main())
230```
231
232However 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.
233
234### Realtime error handling
235
236Whenever 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.
237
238```py
239client = AsyncOpenAI()
240
241async with client.beta.realtime.connect(model="gpt-4o-realtime-preview") as connection:
242 ...
243 async for event in connection:
244 if event.type == 'error':
245 print(event.error.type)
246 print(event.error.code)
247 print(event.error.event_id)
248 print(event.error.message)
249```
250
251## Using types
252
253Nested 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:
254
255- Serializing back into JSON, `model.to_json()`
256- Converting to a dictionary, `model.to_dict()`
257
258Typed 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`.
259
260## Pagination
261
262List methods in the OpenAI API are paginated.
263
264This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:
265
266```python
267from openai import OpenAI
268
269client = OpenAI()
270
271all_jobs = []
272# Automatically fetches more pages as needed.
273for job in client.fine_tuning.jobs.list(
274 limit=20,
275):
276 # Do something with job here
277 all_jobs.append(job)
278print(all_jobs)
279```
280
281Or, asynchronously:
282
283```python
284import asyncio
285from openai import AsyncOpenAI
286
287client = AsyncOpenAI()
288
289
290async def main() -> None:
291 all_jobs = []
292 # Iterate through items across all pages, issuing requests as needed.
293 async for job in client.fine_tuning.jobs.list(
294 limit=20,
295 ):
296 all_jobs.append(job)
297 print(all_jobs)
298
299
300asyncio.run(main())
301```
302
303Alternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages:
304
305```python
306first_page = await client.fine_tuning.jobs.list(
307 limit=20,
308)
309if first_page.has_next_page():
310 print(f"will fetch next page using these details: {first_page.next_page_info()}")
311 next_page = await first_page.get_next_page()
312 print(f"number of items we just fetched: {len(next_page.data)}")
313
314# Remove `await` for non-async usage.
315```
316
317Or just work directly with the returned data:
318
319```python
320first_page = await client.fine_tuning.jobs.list(
321 limit=20,
322)
323
324print(f"next page cursor: {first_page.after}") # => "next page cursor: ..."
325for job in first_page.data:
326 print(job.id)
327
328# Remove `await` for non-async usage.
329```
330
331## Nested params
332
333Nested parameters are dictionaries, typed using `TypedDict`, for example:
334
335```python
336from openai import OpenAI
337
338client = OpenAI()
339
340response = client.chat.responses.create(
341 input=[
342 {
343 "role": "user",
344 "content": "How much ?",
345 }
346 ],
347 model="gpt-4o",
348 response_format={"type": "json_object"},
349)
350```
351
352## File uploads
353
354Request 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)`.
355
356```python
357from pathlib import Path
358from openai import OpenAI
359
360client = OpenAI()
361
362client.files.create(
363 file=Path("input.jsonl"),
364 purpose="fine-tune",
365)
366```
367
368The 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.
369
370## Handling errors
371
372When 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.
373
374When the API returns a non-success status code (that is, 4xx or 5xx
375response), a subclass of `openai.APIStatusError` is raised, containing `status_code` and `response` properties.
376
377All errors inherit from `openai.APIError`.
378
379```python
380import openai
381from openai import OpenAI
382
383client = OpenAI()
384
385try:
386 client.fine_tuning.jobs.create(
387 model="gpt-4o",
388 training_file="file-abc123",
389 )
390except openai.APIConnectionError as e:
391 print("The server could not be reached")
392 print(e.__cause__) # an underlying Exception, likely raised within httpx.
393except openai.RateLimitError as e:
394 print("A 429 status code was received; we should back off a bit.")
395except openai.APIStatusError as e:
396 print("Another non-200-range status code was received")
397 print(e.status_code)
398 print(e.response)
399```
400
401Error codes are as follows:
402
403| Status Code | Error Type |
404| ----------- | -------------------------- |
405| 400 | `BadRequestError` |
406| 401 | `AuthenticationError` |
407| 403 | `PermissionDeniedError` |
408| 404 | `NotFoundError` |
409| 422 | `UnprocessableEntityError` |
410| 429 | `RateLimitError` |
411| >=500 | `InternalServerError` |
412| N/A | `APIConnectionError` |
413
414## Request IDs
415
416> For more information on debugging requests, see [these docs](https://platform.openai.com/docs/api-reference/debugging-requests)
417
418All 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.
419
420```python
421response = await client.responses.create(
422 model="gpt-4o-mini",
423 input="Say 'this is a test'.",
424)
425print(response._request_id) # req_123
426```
427
428Note that unlike other properties that use an `_` prefix, the `_request_id` property
429_is_ public. Unless documented otherwise, _all_ other `_` prefix properties,
430methods and modules are _private_.
431
432> [!IMPORTANT]
433> If you need to access request IDs for failed requests you must catch the `APIStatusError` exception
434
435```python
436import openai
437
438try:
439 completion = await client.chat.completions.create(
440 messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-4"
441 )
442except openai.APIStatusError as exc:
443 print(exc.request_id) # req_123
444 raise exc
445```
446
447## Retries
448
449Certain errors are automatically retried 2 times by default, with a short exponential backoff.
450Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,
451429 Rate Limit, and >=500 Internal errors are all retried by default.
452
453You can use the `max_retries` option to configure or disable retry settings:
454
455```python
456from openai import OpenAI
457
458# Configure the default for all requests:
459client = OpenAI(
460 # default is 2
461 max_retries=0,
462)
463
464# Or, configure per-request:
465client.with_options(max_retries=5).chat.completions.create(
466 messages=[
467 {
468 "role": "user",
469 "content": "How can I get the name of the current day in JavaScript?",
470 }
471 ],
472 model="gpt-4o",
473)
474```
475
476## Timeouts
477
478By default requests time out after 10 minutes. You can configure this with a `timeout` option,
479which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object:
480
481```python
482from openai import OpenAI
483
484# Configure the default for all requests:
485client = OpenAI(
486 # 20 seconds (default is 10 minutes)
487 timeout=20.0,
488)
489
490# More granular control:
491client = OpenAI(
492 timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
493)
494
495# Override per-request:
496client.with_options(timeout=5.0).chat.completions.create(
497 messages=[
498 {
499 "role": "user",
500 "content": "How can I list all files in a directory using Python?",
501 }
502 ],
503 model="gpt-4o",
504)
505```
506
507On timeout, an `APITimeoutError` is thrown.
508
509Note that requests that time out are [retried twice by default](#retries).
510
511## Advanced
512
513### Logging
514
515We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.
516
517You can enable logging by setting the environment variable `OPENAI_LOG` to `info`.
518
519```shell
520$ export OPENAI_LOG=info
521```
522
523Or to `debug` for more verbose logging.
524
525### How to tell whether `None` means `null` or missing
526
527In 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`:
528
529```py
530if response.my_field is None:
531 if 'my_field' not in response.model_fields_set:
532 print('Got json like {}, without a "my_field" key present at all.')
533 else:
534 print('Got json like {"my_field": null}.')
535```
536
537### Accessing raw response data (e.g. headers)
538
539The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,
540
541```py
542from openai import OpenAI
543
544client = OpenAI()
545response = client.chat.completions.with_raw_response.create(
546 messages=[{
547 "role": "user",
548 "content": "Say this is a test",
549 }],
550 model="gpt-4o",
551)
552print(response.headers.get('X-My-Header'))
553
554completion = response.parse() # get the object that `chat.completions.create()` would have returned
555print(completion)
556```
557
558These 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.
559
560For the sync client this will mostly be the same with the exception
561of `content` & `text` will be methods instead of properties. In the
562async client, all methods will be async.
563
564A migration script will be provided & the migration in general should
565be smooth.
566
567#### `.with_streaming_response`
568
569The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
570
571To 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.
572
573As 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.
574
575```python
576with client.chat.completions.with_streaming_response.create(
577 messages=[
578 {
579 "role": "user",
580 "content": "Say this is a test",
581 }
582 ],
583 model="gpt-4o",
584) as response:
585 print(response.headers.get("X-My-Header"))
586
587 for line in response.iter_lines():
588 print(line)
589```
590
591The context manager is required so that the response will reliably be closed.
592
593### Making custom/undocumented requests
594
595This library is typed for convenient access to the documented API.
596
597If you need to access undocumented endpoints, params, or response properties, the library can still be used.
598
599#### Undocumented endpoints
600
601To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other
602http verbs. Options on the client will be respected (such as retries) when making this request.
603
604```py
605import httpx
606
607response = client.post(
608 "/foo",
609 cast_to=httpx.Response,
610 body={"my_param": True},
611)
612
613print(response.headers.get("x-foo"))
614```
615
616#### Undocumented request params
617
618If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request
619options.
620
621#### Undocumented response properties
622
623To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You
624can also get all the extra fields on the Pydantic model as a dict with
625[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).
626
627### Configuring the HTTP client
628
629You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:
630
631- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)
632- Custom [transports](https://www.python-httpx.org/advanced/transports/)
633- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality
634
635```python
636import httpx
637from openai import OpenAI, DefaultHttpxClient
638
639client = OpenAI(
640 # Or use the `OPENAI_BASE_URL` env var
641 base_url="http://my.test.server.example.com:8083/v1",
642 http_client=DefaultHttpxClient(
643 proxy="http://my.test.proxy.example.com",
644 transport=httpx.HTTPTransport(local_address="0.0.0.0"),
645 ),
646)
647```
648
649You can also customize the client on a per-request basis by using `with_options()`:
650
651```python
652client.with_options(http_client=DefaultHttpxClient(...))
653```
654
655### Managing HTTP resources
656
657By 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.
658
659```py
660from openai import OpenAI
661
662with OpenAI() as client:
663 # make requests here
664 ...
665
666# HTTP client is now closed
667```
668
669## Microsoft Azure OpenAI
670
671To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI`
672class instead of the `OpenAI` class.
673
674> [!IMPORTANT]
675> The Azure API shape differs from the core API shape which means that the static types for responses / params
676> won't always be correct.
677
678```py
679from openai import AzureOpenAI
680
681# gets the API Key from environment variable AZURE_OPENAI_API_KEY
682client = AzureOpenAI(
683 # https://learn.microsoft.com/azure/ai-services/openai/reference#rest-api-versioning
684 api_version="2023-07-01-preview",
685 # https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource
686 azure_endpoint="https://example-endpoint.openai.azure.com",
687)
688
689completion = client.chat.completions.create(
690 model="deployment-name", # e.g. gpt-35-instant
691 messages=[
692 {
693 "role": "user",
694 "content": "How do I output all files in a directory using Python?",
695 },
696 ],
697)
698print(completion.to_json())
699```
700
701In addition to the options provided in the base `OpenAI` client, the following options are provided:
702
703- `azure_endpoint` (or the `AZURE_OPENAI_ENDPOINT` environment variable)
704- `azure_deployment`
705- `api_version` (or the `OPENAI_API_VERSION` environment variable)
706- `azure_ad_token` (or the `AZURE_OPENAI_AD_TOKEN` environment variable)
707- `azure_ad_token_provider`
708
709An 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).
710
711## Versioning
712
713This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
714
7151. Changes that only affect static types, without breaking runtime behavior.
7162. 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.)_
7173. Changes that we do not expect to impact the vast majority of users in practice.
718
719We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
720
721We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-python/issues) with questions, bugs, or suggestions.
722
723### Determining the installed version
724
725If 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.
726
727You can determine the version that is being used at runtime with:
728
729```py
730import openai
731print(openai.__version__)
732```
733
734## Requirements
735
736Python 3.8 or higher.
737
738## Contributing
739
740See [the contributing documentation](./CONTRIBUTING.md).