# OpenAI Python API library
[](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 下载量 14 浏览量
2024-05-15
10:16:51
上传
评论 1
收藏 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
资源推荐
资源详情
资源评论



























收起资源包目录





































































































共 360 条
- 1
- 2
- 3
- 4
资源评论


海神之光.
- 粉丝: 6118
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


最新资源
- 三位厦门大学的学生面对小学期的python大作业他们将用什么样的作品水水而过
- QT6 画家 QPainter 的源代码带注释 1300 行 本类奠定了 QT 的绘图基础
- 基于 MySQL 与 Python 的选课大作业及校招填表辅助系统
- 网站建设方案(人才网).doc
- 新建文件夹福建省莆田市基于云计算的电子政务公共平台顶层设计【阶段成果】v1.5.doc
- 行业网站建设方案.doc
- 基于JSP的酒店客房管理系统.doc
- 武汉大学分析化学课件-第26章-分析仪器测量电路、信号处理及计算机应用基础.ppt
- 基于网络环境的集体备课研究课题研究报告.docx
- 网络营销SEO精简版.pptx
- 软件委托开发流程及相关规范(211215095509).pdf
- 数控铣床加工中心编程实例PPT培训课件.ppt
- 计算机网络基础(继续教育试题及答案).docx
- 网络会计对传统会计的影响及发展【会计实务操作教程】.pptx
- 行政事业单位会计信息化建设路径.doc
- 网络营销内涵.pptx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈



安全验证
文档复制为VIP权益,开通VIP直接复制
