OpenAIProvider wraps the official OpenAI Python SDK. It supports non-streaming and streaming chat, tool calling, and multimodal (vision) prompts for compatible models.
Installation
Constructor parameters
The OpenAI model ID to use. Examples:
"gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "o1-mini". Must be a model available in your OpenAI project.Your OpenAI secret key. If omitted, the provider reads
OPENAI_API_KEY from the environment. Raises ValueError if neither is set.Extra keyword arguments forwarded to the underlying
openai.OpenAI() client constructor. Use this to set a custom base_url (e.g., for OpenAI-compatible endpoints), timeout, max_retries, or http_client.Basic usage
Streaming
Provide anon_token callback to receive each token as it arrives. The callback can be synchronous or async:
chat_stream assembles the full response from streamed chunks and returns a ChatCompletionMessage object once streaming completes. Tool-call chunks are reconstructed correctly.
Tool calling
tool_choice="auto" so the model decides when to call a tool.
Vision / multimodal
Use a vision-capable model (gpt-4o, gpt-4o-mini) and pass a list of content parts:
image_url values:
- Local file path
https://image URLdata:image/...;base64,...inline data
Using OpenAI-compatible endpoints
Pass a custombase_url to target any OpenAI-compatible API (e.g., LM Studio, Together AI, Anyscale):
Troubleshooting
ValueError: OpenAI API key is required
ValueError: OpenAI API key is required
The
api_key argument was not passed and OPENAI_API_KEY is not set in the environment. Set the environment variable or pass api_key directly to the constructor.ValueError: OpenAI model returned empty response
ValueError: OpenAI model returned empty response
The model returned a response with neither text content nor tool calls. This can happen with certain system prompts or with reasoning models in restricted modes. Check your
system_message and ensure the model you selected is available in your project.AuthenticationError: Incorrect API key
AuthenticationError: Incorrect API key
Double-check the key starts with
sk- and matches a live key in your OpenAI dashboard. Keys are not shared across organisations.RateLimitError: You exceeded your current quota
RateLimitError: You exceeded your current quota
You have hit your usage tier’s rate or spend limit. Either add credits, request a tier upgrade, or implement retries with exponential back-off using the
max_retries kwarg on the client.Model not found / 404 on a specific model
Model not found / 404 on a specific model
Some models (e.g.
gpt-4) require explicit access in the OpenAI console. Use gpt-4o-mini for broad availability or verify the model is enabled for your project.