# 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.
### Polling Helpers
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
helper functions which will poll the status until it reaches a terminal state and then return the resulting object.
If an API method results in an action which could benefit from polling there will be a corresponding version of the
method ending in '\_and_poll'.
For instance to create a Run and poll until it reaches a terminal state you can run:
```python
run = client.beta.threads.runs.create_and_poll(
thread_id=thread.id,
assistant_id=assistant.id,
)
```
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)
### Bulk Upload Helpers
When creating an interacting with vector stores, you can use the polling helpers to monitor the status of operations.
For convenience, we also provide a bulk upload helper to allow you to simultaneously upload several files at once.
```python
sample_files = [Path("sample-paper.pdf"), ...]
batch = await client.vector_stores.file_batches.upload_and_poll(
store.id,
files=sample_files,
)
```
### Streaming Helpers
The SDK also includes helpers to process streams and handle the incoming events.
```python
with client.beta.threads.runs.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 also provide helper methods for things like:
- Serializing back into JSON, `model.to_json()`
- Converting to a dictionary, `model.to_dict()`
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())
```
Altern
没有合适的资源?快使用搜索试试~ 我知道了~
使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip
共360个文件
py:332个
md:6个
json:3个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 114 浏览量
2024-05-15
10:16:51
上传
评论
收藏 416KB ZIP 举报
温馨提示
使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip
资源推荐
资源详情
资源评论
收起资源包目录
使用Python调用OpenAI接口-OpenAI接口调用python库源码.zip (360个子文件)
bootstrap 414B
Brewfile 14B
check-release-environment 683B
Dockerfile 316B
format 107B
mypy.ini 1KB
release-please-config.json 1KB
devcontainer.json 1KB
.release-please-manifest.json 21B
.keep 242B
.keep 227B
lint 174B
requirements-dev.lock 3KB
requirements.lock 1KB
CHANGELOG.md 56KB
api.md 25KB
README.md 20KB
helpers.md 8KB
CONTRIBUTING.md 4KB
SECURITY.md 1KB
mock 901B
publish-pypi 106B
runs.py 149KB
threads.py 101KB
completions.py 68KB
_base_client.py 66KB
test_client.py 59KB
completions.py 58KB
test_runs.py 52KB
test_threads.py 50KB
_assistants.py 41KB
assistants.py 40KB
_validators.py 35KB
file_batches.py 30KB
_response.py 29KB
vector_stores.py 27KB
files.py 27KB
_models.py 27KB
jobs.py 27KB
files.py 26KB
messages.py 26KB
images.py 25KB
test_models.py 24KB
test_messages.py 22KB
_client.py 22KB
azure.py 22KB
test_jobs.py 20KB
test_files.py 19KB
test_assistants.py 19KB
batches.py 18KB
test_file_batches.py 18KB
test_vector_stores.py 17KB
test_completions.py 16KB
test_files.py 16KB
_legacy_response.py 16KB
test_transform.py 14KB
_streaming.py 13KB
_transform.py 13KB
thread_create_and_run_params.py 13KB
test_batches.py 13KB
steps.py 12KB
_utils.py 12KB
test_images.py 11KB
transcriptions.py 11KB
embeddings.py 11KB
models.py 10KB
completion_create_params.py 10KB
__init__.py 10KB
test_steps.py 10KB
run_create_params.py 9KB
translations.py 9KB
test_completions.py 9KB
test_models.py 9KB
test_streaming.py 8KB
speech.py 8KB
run.py 8KB
completion_create_params.py 8KB
_cli.py 7KB
moderations.py 7KB
assistant_stream_event.py 7KB
checkpoints.py 6KB
_compat.py 6KB
completions.py 6KB
_types.py 6KB
assistant_create_params.py 6KB
test_speech.py 6KB
test_response.py 6KB
test_module_client.py 6KB
completions.py 5KB
ruffen-docs.py 5KB
image.py 5KB
migrate.py 5KB
_qs.py 5KB
test_checkpoints.py 5KB
assistant.py 5KB
chat_completion_chunk.py 5KB
thread_create_params.py 5KB
beta.py 5KB
audio.py 5KB
test_embeddings.py 5KB
共 360 条
- 1
- 2
- 3
- 4
资源评论
FL1768317420
- 粉丝: 4708
- 资源: 4913
下载权益
C知道特权
VIP文章
课程特权
开通VIP
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功