Openai-python
lastmod 2024-03-02created 2024-02-299 edits
The official Python library for the OpenAI API
Install
Sync example
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",
)
Async example
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())
Streaming Responses
We provide support for streaming responses using Server Side Events (SSE).
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.
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())
How to fine-tune
- A Story of Someone with Many Dreams :: OpenAI GPT Fine-Tuning guide - Building your own GPT model
- Implementing a recommendation system with the OpenAI ChatGPT API (feat. HuggingFace)
Endpoints
Audio
Chat
Create chat completion
Creates a model response for the given chat conversation.
The chat completion object
Represents a chat completion response returned by the model, based on the provided input.
The chat completion chunk object
Represents a streamed chunk of a chat completion response returned by the model, based on the provided input.
Embeddings
Fine-tuning
Files
Images
Models
Moderations
Troubleshooting
429 Status Code
See also
Favorite site
Guide
- A Story of Someone with Many Dreams :: Using GPT3 (GPT3.5) with the Python OpenAI API (Feat. ChatGPT)
- (2024 UPDATE) OpenAI Python API tutorial - Using the chat function (1) - TeddyNote
Pages that link here