# OpenAI Python API library
[![PyPI version](https://img.shields.io/pypi/v/openai.svg)](https://pypi.org/project/openai/)
The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.7+
application. The library includes type definitions for all request params and response fields,
and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).
It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/).
## Documentation
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).
## Installation
> [!IMPORTANT]
> 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.
```sh
# install from PyPI
pip install openai
```
## Usage
The full API of this library can be found in [api.md](api.md).
```python
import os
from openai import OpenAI
client = OpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-3.5-turbo",
)
```
While you can provide an `api_key` keyword argument,
we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)
to add `OPENAI_API_KEY="My API Key"` to your `.env` file
so that your API Key is not stored in source control.
### Streaming Helpers
The SDK also includes helpers to process streams and handle the incoming events.
```python
with client.beta.threads.runs.create_and_stream(
thread_id=thread.id,
assistant_id=assistant.id,
instructions="Please address the user as Jane Doe. The user has a premium account.",
) as stream:
for event in stream:
# Print the text from text delta events
if event.type == "thread.message.delta" and event.data.delta.content:
print(event.data.delta.content[0].text)
```
More information on streaming helpers can be found in the dedicated documentation: [helpers.md](helpers.md)
## Async usage
Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call:
```python
import os
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)
async def main() -> None:
chat_completion = await client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-3.5-turbo",
)
asyncio.run(main())
```
Functionality between the synchronous and asynchronous clients is otherwise identical.
## Streaming Responses
We provide support for streaming responses using Server Side Events (SSE).
```python
from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Say this is a test"}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")
```
The async client uses the exact same interface.
```python
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def main():
stream = await client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Say this is a test"}],
stream=True,
)
async for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")
asyncio.run(main())
```
## Module-level client
> [!IMPORTANT]
> We highly recommend instantiating client instances instead of relying on the global client.
We also expose a global client instance that is accessible in a similar fashion to versions prior to v1.
```py
import openai
# optional; defaults to `os.environ['OPENAI_API_KEY']`
openai.api_key = '...'
# all client options can be configured just like the `OpenAI` instantiation counterpart
openai.base_url = "https://..."
openai.default_headers = {"x-foo": "true"}
completion = openai.chat.completions.create(
model="gpt-4",
messages=[
{
"role": "user",
"content": "How do I output all files in a directory using Python?",
},
],
)
print(completion.choices[0].message.content)
```
The API is the exact same as the standard client instance based API.
This is intended to be used within REPLs or notebooks for faster iteration, **not** in application code.
We recommend that you always instantiate a client (e.g., with `client = OpenAI()`) in application code because:
- It can be difficult to reason about where client options are configured
- It's not possible to change certain client options without potentially causing race conditions
- It's harder to mock for testing purposes
- It's not possible to control cleanup of network connections
## Using types
Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev), which provide helper methods for things like:
- Serializing back into JSON, `model.model_dump_json(indent=2, exclude_unset=True)`
- Converting to a dictionary, `model.model_dump(exclude_unset=True)`
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`.
## Pagination
List methods in the OpenAI API are paginated.
This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:
```python
import openai
client = OpenAI()
all_jobs = []
# Automatically fetches more pages as needed.
for job in client.fine_tuning.jobs.list(
limit=20,
):
# Do something with job here
all_jobs.append(job)
print(all_jobs)
```
Or, asynchronously:
```python
import asyncio
import openai
client = AsyncOpenAI()
async def main() -> None:
all_jobs = []
# Iterate through items across all pages, issuing requests as needed.
async for job in client.fine_tuning.jobs.list(
limit=20,
):
all_jobs.append(job)
print(all_jobs)
asyncio.run(main())
```
Alternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages:
```python
first_page = await client.fine_tuning.jobs.list(
limit=20,
)
if first_page.has_next_page():
print(f"will fetch next page using these details: {first_page.next_page_info()}")
next_page = await first_page.get_next_page()
print(f"number of items we just fetched: {len(next_page.data)}")
# Remove `await` for non-async usage.
```
Or just work directly with the returned data:
```python
first_page = await client.fine_tuning.jobs.list(
limit=20,
)
print(f"next page cursor: {first_page.after}") # => "next page cursor: ..."
for job in first_page.data:
print(job.id)
# Remove `await` for non-async usage.
```
## Nested params
Nested parameters are dictionaries, typed using `TypedDict`, for example:
```python
from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Can you generate an example json object describing a fruit?",
}
],
model="gpt-3.5-turbo-1106",
response_format={"type": "json_object"},
)
```
## File Uploads
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)`.
```
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
OpenAI python库openai1.14.2安装文件 (235个子文件)
.gitignore 82B
.keep 224B
LICENSE 11KB
README.md 17KB
PKG-INFO 19KB
runs.py 72KB
completions.py 71KB
_base_client.py 62KB
completions.py 56KB
threads.py 47KB
_assistants.py 40KB
_validators.py 34KB
assistants.py 30KB
_response.py 28KB
files.py 25KB
images.py 24KB
jobs.py 24KB
messages.py 22KB
_models.py 22KB
azure.py 21KB
_client.py 20KB
files.py 19KB
_legacy_response.py 15KB
_transform.py 13KB
files.py 12KB
steps.py 12KB
_streaming.py 12KB
_utils.py 11KB
transcriptions.py 11KB
embeddings.py 10KB
completion_create_params.py 10KB
models.py 10KB
__init__.py 9KB
translations.py 9KB
speech.py 8KB
completion_create_params.py 7KB
_cli.py 7KB
moderations.py 6KB
completions.py 6KB
_compat.py 6KB
assistant_stream_event.py 6KB
_types.py 6KB
completions.py 5KB
image.py 5KB
migrate.py 5KB
_qs.py 5KB
audio.py 4KB
run.py 4KB
chat_completion_chunk.py 4KB
thread_create_and_run_params.py 4KB
moderation.py 4KB
_typing.py 4KB
__init__.py 4KB
_exceptions.py 4KB
_files.py 4KB
run_step.py 3KB
beta.py 3KB
audio.py 3KB
fine_tuning_job.py 3KB
pagination.py 3KB
message.py 3KB
job_create_params.py 3KB
run_create_params.py 3KB
__init__.py 2KB
fine_tuning.py 2KB
files.py 2KB
chat.py 2KB
chat_completion.py 2KB
_module_client.py 2KB
_sync.py 2KB
transcription_create_params.py 2KB
image_generate_params.py 2KB
__init__.py 2KB
assistant.py 2KB
assistant_update_params.py 2KB
_old_api.py 2KB
_proxy.py 2KB
embedding_create_params.py 2KB
assistant_create_params.py 2KB
__init__.py 2KB
image_edit_params.py 2KB
code_interpreter_tool_call.py 2KB
chat_completion_token_logprob.py 2KB
__init__.py 2KB
__init__.py 2KB
thread_create_params.py 2KB
chat_completion_assistant_message_param.py 2KB
run_submit_tool_outputs_params.py 2KB
fine_tunes.py 2KB
__init__.py 1KB
translation_create_params.py 1KB
__init__.py 1KB
code_interpreter_tool_call_delta.py 1KB
image_create_variation_params.py 1KB
_progress.py 1KB
models.py 1KB
chat_completion_message.py 1KB
speech_create_params.py 1KB
step_list_params.py 1KB
file_list_params.py 1KB
共 235 条
- 1
- 2
- 3
资源评论
王为为
- 粉丝: 0
- 资源: 1
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- MI4407-VB一款SOP8封装P-Channel场效应MOS管
- java实验2.doc
- opencv-基于c++实现的opencv图像处理算法之区域生长分割算法.zip
- MI3475-VB一款SOT23封装P-Channel场效应MOS管
- Fortran语言教程&案例&相关项目资源
- Labview 互斥按钮
- java小说人物分析.doc
- opencv-基于c++实现的opencv图像处理算法之双线性插值算法.zip
- 《STM32单片机+DHT11温湿度+MQ甲醛浓度+BH1750光照强度+按键+OLED屏幕+蜂鸣器+继电器》源代码
- python爬虫基础知识原理及Scrapy框架以及scrapy-redis分布式策略入门知识.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功