Prerequisites
Before you begin, make sure you have:1
Installed the SDK
2
Set up your API key
Using the Responses API
The Responses API is the primary way to interact with OpenAI models. It provides a simplified interface for generating text.Basic Text Generation
Create your first response:The
api_key parameter is optional. If not provided, the client automatically reads from the OPENAI_API_KEY environment variable.Simple Input
For straightforward queries, you can pass just the input text:Vision Input
Process images alongside text:Using the Chat Completions API
The Chat Completions API is the previous standard for generating text, and is supported indefinitely.Basic Chat Completion
Message Roles
The Chat Completions API uses different message roles:- developer: System-level instructions for the model’s behavior
- user: User messages in the conversation
- assistant: Previous assistant responses (for conversation history)
Streaming Responses
Stream responses in real-time for a better user experience:Async Usage
For async applications, useAsyncOpenAI instead of OpenAI:
The async client provides identical functionality to the sync client, but all methods use
await.Error Handling
Handle API errors gracefully:Error Types
The SDK provides specific exception types for different errors:Common Configuration
Timeouts
Set custom timeout values:Retries
Configure retry behavior:Custom Base URL
Use a custom API endpoint:Next Steps
Now that you’ve made your first API call, explore more advanced features:Responses API
Learn more about the Responses API
Chat Completions
Explore the Chat Completions API
Streaming
Master streaming responses
Error Handling
Handle errors like a pro