openai_dart library

Dart client for the OpenAI API.

This is the main entry point providing access to modern APIs including:

  • Chat Completions (GPT-4, GPT-4o, etc.)
  • Responses API (recommended unified API with built-in tools)
  • Embeddings, Images, Audio, Files, Batches, Fine-tuning, Moderations

For deprecated Assistants API, import package:openai_dart/openai_dart_assistants.dart. For Realtime API, import package:openai_dart/openai_dart_realtime.dart.

Quick Start

import 'package:openai_dart/openai_dart.dart';

final client = OpenAIClient.fromEnvironment();

final response = await client.chat.completions.create(
  ChatCompletionCreateRequest(
    model: 'gpt-4o',
    messages: [ChatMessage.user('Hello!')],
  ),
);

print(response.text);

Classes

AccumulatedChoice
A read-only snapshot of a single accumulated choice's state.
AddUploadPartRequest
A request to add a part to an upload.
Annotation
Annotation for output content (citations, etc.).
ApiKeyProvider
Provides API key authentication for the OpenAI API.
ApproximateLocation
Approximate user location for localized web search results.
AssistantMessage
An assistant message containing a response or tool calls.
AssistantsResource
Resource for Assistants API operations (Beta).
AssistantTextContent
Text content for assistant messages.
AudioContentPart
An audio content part for audio input.
AudioResource
Resource for audio operations.
AuthInterceptor
Interceptor that adds authentication headers to requests.
AuthProvider
Abstract interface for providing authentication credentials.
AutomaticThreadTitlingParam
Automatic thread titling parameter.
AutoOrDouble
A value that can be "auto" or a double.
AutoOrDoubleAuto
Represents "auto" for a double field.
AutoOrDoubleValue
Represents a specific double value.
AutoOrInt
A value that can be "auto" or an integer.
AutoOrIntAuto
Represents "auto" for an integer field.
AutoOrIntValue
Represents a specific integer value.
AzureApiKeyProvider
Provides Azure OpenAI Service authentication.
Batch
A batch job for processing many requests asynchronously.
BatchError
A single batch error.
BatchErrors
Errors that occurred during batch processing.
BatchesResource
Resource for batch operations.
BatchList
A list of batches.
BatchRequestCounts
Request counts for a batch.
BetaResource
Resource for Beta API features.
ChatAudioConfig
Configuration for audio output in chat completions.
ChatChoice
A single completion choice.
ChatCompletion
A chat completion response from the OpenAI API.
ChatCompletionCreateRequest
Request for creating a chat completion.
ChatCompletionsResource
Resource for chat completions operations.
ChatDelta
The delta content in a streaming chunk.
ChatkitConfigurationParam
ChatKit configuration parameter.
ChatkitResource
Resource for ChatKit operations.
ChatkitSessionsResource
Resource for ChatKit session operations.
ChatkitThread
A ChatKit thread.
ChatkitThreadItemsResource
Resource for ChatKit thread item operations.
ChatkitThreadList
A list of ChatKit threads.
ChatkitThreadsResource
Resource for ChatKit thread operations.
ChatkitThreadStatus
Thread status.
ChatkitWorkflow
Workflow metadata for a ChatKit session.
ChatkitWorkflowTracing
Tracing configuration for a ChatKit workflow.
ChatMessage
A message in a chat conversation.
ChatResource
Resource for chat-related operations.
ChatSession
A ChatKit session.
ChatSessionAutomaticThreadTitling
Automatic thread titling configuration.
ChatSessionChatkitConfiguration
ChatKit feature configuration for a session.
ChatSessionFileUpload
File upload settings for a session.
ChatSessionHistory
History retention settings for a session.
ChatSessionRateLimits
Rate limits for a ChatKit session.
ChatStreamAccumulator
Helper class for accumulating streaming chunks into a complete response.
ChatStreamChoice
A single choice in a streaming response.
ChatStreamEvent
A streaming event from the chat completions API.
CheckpointMetrics
Training metrics for a checkpoint.
ClickAction
A click action at specific coordinates.
CodeInterpreterCallOutputItem
A code interpreter call output item.
CodeInterpreterContainer
Container configuration for the code interpreter tool.
CodeInterpreterContainerAuto
Auto-create a container for code execution.
CodeInterpreterContainerId
Use an existing container by ID.
CodeInterpreterImageOutput
Image output from code interpreter execution.
CodeInterpreterLogsOutput
Log output from code interpreter execution.
CodeInterpreterOutput
Output from a code interpreter execution.
CodeInterpreterTool
Code interpreter tool for executing code.
CompactionOutputItem
A compaction item emitted by responses.compact.
CompactResponseRequest
Request to compact response conversation state.
ComparisonFilter
A comparison filter for file search metadata.
CompleteUploadRequest
A request to complete an upload.
Completion
A completion response (legacy API).
CompletionChoice
A choice in a completion response.
CompletionPrompt
A prompt for completions.
CompletionPromptText
A single text prompt.
CompletionPromptTexts
Multiple text prompts.
CompletionPromptTokenLists
Multiple prompts as lists of token IDs.
CompletionPromptTokens
A prompt as token IDs.
CompletionRequest
A request to generate completions (legacy API).
CompletionsContentSource
Completions source from inline content.
CompletionsFileSource
Completions source from a file.
CompletionsResource
Resource for Completions API operations (Legacy).
CompletionsRunDataSource
Completions-based data source for evaluation runs.
CompletionsSource
Source for completions data.
CompletionTokensDetails
Detailed breakdown of completion tokens.
CompoundFilter
A compound filter that combines multiple filters with a logical operator.
ComputerAction
An action performed by the computer use tool.
ComputerCallOutputItem
A computer use tool call output item.
ComputerTool
Computer tool (GA) for controlling a computer.
ComputerUseTool
Computer use tool for controlling a computer.
Container
A container for isolated execution environments.
ContainerExpiration
Container expiration configuration.
ContainerFile
A file within a container.
ContainerFileCitation
Container file citation annotation.
ContainerFileList
A list of container files.
ContainerFilesResource
Resource for container file operations.
ContainerList
A list of containers.
ContainerNetworkPolicy
Network access policy for a code interpreter container.
ContainerNetworkPolicyAllowlist
Allow network access to specific hosts.
ContainerNetworkPolicyDisabled
Disable network access for the container.
ContainerReferenceEnvironment
A container reference environment for shell execution.
ContainersResource
Resource for container operations.
ContentPart
A part of a multimodal message content.
ContentPartAddedEvent
Event emitted when a content part is added.
ContentPartDoneEvent
Event emitted when a content part is complete.
ContextManagement
Context management configuration for responses requests.
Conversation
A server-side conversation that stores messages for the Responses API.
ConversationCodeInterpreterCallItem
A code interpreter call item in a conversation.
ConversationComputerCallItem
A computer call item in a conversation.
ConversationComputerCallOutputItem
A computer call output item in a conversation.
ConversationContent
Content within a conversation item.
ConversationCreateRequest
Request to create a new conversation.
ConversationDeletedResource
The result of deleting a conversation.
ConversationFileSearchCallItem
A file search call item in a conversation.
ConversationFunctionCallItem
A function call item in a conversation.
ConversationFunctionCallOutputItem
A function call output item in a conversation.
ConversationImageGenerationCallItem
An image generation call item in a conversation.
ConversationImageUrlContent
Image URL content for conversation items.
ConversationInputFileContent
Input file content in a conversation.
ConversationInputImageContent
Input image content in a conversation.
ConversationInputTextContent
Input text content in a conversation.
ConversationItem
An item stored in a conversation.
ConversationItemList
A paginated list of conversation items.
ConversationItemsResource
Resource for conversation items operations.
ConversationLocalShellCallItem
A local shell call item in a conversation.
ConversationLocalShellCallOutputItem
A local shell call output item in a conversation.
ConversationMcpApprovalRequestItem
An MCP approval request item in a conversation.
ConversationMcpApprovalResponseItem
An MCP approval response item in a conversation.
ConversationMcpCallItem
An MCP call item in a conversation.
ConversationMcpListToolsItem
An MCP list tools item in a conversation.
ConversationMessageItem
A message item in a conversation.
ConversationOutputTextContent
Output text content in a conversation.
ConversationReasoningItem
A reasoning item in a conversation.
ConversationReasoningTextContent
Reasoning text content from reasoning models.
ConversationRefusalContent
Refusal content in a conversation.
ConversationRole
The role of a message in a conversation.
ConversationsResource
Resource for conversations operations.
ConversationSummaryTextContent
Summary text content from reasoning output.
ConversationTextContent
Simple text content (used in some conversation contexts).
ConversationToolSearchCallItem
A tool search call item in a conversation.
ConversationToolSearchOutputItem
A tool search output item in a conversation.
ConversationUnknownContent
Unknown content type (for forward compatibility).
ConversationUnknownItem
An unknown item type (for forward compatibility).
ConversationUpdateRequest
Request to update an existing conversation.
ConversationWebSearchCallItem
A web search call item in a conversation.
CreateBatchRequest
A request to create a batch.
CreateChatSessionRequest
Request to create a new ChatKit session.
CreateContainerRequest
Request to create a new container.
CreateEvalRequest
Request to create a new evaluation.
CreateEvalRunRequest
Request to create a new evaluation run.
CreateFineTuningIntegration
A request to create a fine-tuning integration.
CreateFineTuningJobRequest
A request to create a fine-tuning job.
CreateResponseRequest
Request to create a response.
CreateUploadRequest
A request to create an upload.
CreateVideoRemixRequest
Request to create a video remix.
CreateVideoRequest
Request to create a new video generation job.
CreateWandbIntegration
A request to create a W&B integration.
CustomDataSourceConfig
Custom data source configuration with user-defined schema.
CustomTool
A custom tool (type: 'custom').
DeleteChatkitThreadResponse
The response from deleting a ChatKit thread.
DeleteContainerFileResponse
The response from deleting a container file.
DeleteContainerResponse
The response from deleting a container.
DeletedSkill
Delete response for a skill.
DeletedSkillVersion
Delete response for a skill version.
DeleteEvalResponse
Response from deleting an evaluation.
DeleteEvalRunResponse
Response from deleting an evaluation run.
DeleteFileResponse
The response from deleting a file.
DeleteModelResponse
The response from deleting a model.
DeleteResponseResult
Response for a delete operation.
DeleteVideoResponse
The response from deleting a video.
DeveloperMessage
A developer message for multi-turn developer instructions.
DoubleClickAction
A double-click action at specific coordinates.
DragAction
A drag action along a path of coordinates.
Embedding
A single embedding object.
EmbeddingInput
The input for embedding generation.
EmbeddingInputText
A single text string input.
EmbeddingInputTextList
Multiple text strings input.
EmbeddingInputTokens
Token IDs input.
EmbeddingInputTokensList
Multiple token ID arrays input.
EmbeddingRequest
A request to generate embeddings for input text.
EmbeddingResponse
A response from the embeddings API.
EmbeddingsResource
Resource for generating embeddings.
EmbeddingUsage
Token usage statistics for an embedding request.
ErrorEvent
Event emitted when an error occurs.
ErrorInterceptor
Interceptor that handles error responses from the API.
Eval
An evaluation definition for testing LLM integrations.
EvalApiError
An error from the Evals API.
EvalDataSourceConfig
Configuration for the data source used in evaluations.
EvalGrader
A grader (testing criterion) for evaluating model outputs.
EvalList
A paginated list of evaluations.
EvalOutputItem
An output item from an evaluation run.
EvalOutputItemList
A paginated list of evaluation output items.
EvalOutputItemResult
A grading result for an output item.
EvalOutputItemSample
Sample data from model evaluation.
EvalOutputItemsResource
Resource for evaluation output item operations.
EvalRun
An evaluation run executing tests against model outputs.
EvalRunDataSource
Data source configuration for an evaluation run.
EvalRunList
A paginated list of evaluation runs.
EvalRunPerModelUsage
Token usage for a specific model in an evaluation run.
EvalRunPerTestingCriteriaResult
Results for a specific testing criterion (grader) in an evaluation run.
EvalRunResultCounts
Result counts for an evaluation run.
EvalRunsResource
Resource for evaluation run operations.
EvalSampleMessage
A message in a sample.
EvalSampleUsage
Token usage for a sample.
EvalSamplingParams
Sampling parameters for model generation during evaluation.
EvalsResource
Resource for the Evals API.
FileCitation
File citation annotation.
FileList
A list of files.
FileObject
A file that has been uploaded to OpenAI.
FilePathAnnotation
File path annotation.
FileSearchCallOutputItem
A file search call output item.
FileSearchFilter
A filter for file search metadata.
FileSearchRankingOptions
Ranking options for file search.
FileSearchTool
File search tool for searching vector stores.
FilesResource
Resource for file operations.
FileUploadParam
File upload parameter.
FineTuneDPOHyperparameters
Hyperparameters for DPO fine-tuning.
FineTuneDPOMethod
Configuration for the DPO fine-tuning method.
FineTuneMethod
The method used for fine-tuning.
FineTuneReinforcementHyperparameters
Hyperparameters for reinforcement fine-tuning.
FineTuneReinforcementMethod
Configuration for the reinforcement fine-tuning method.
FineTuneSupervisedMethod
Configuration for the supervised fine-tuning method.
FineTuningCheckpoint
A fine-tuning checkpoint.
FineTuningCheckpointList
A list of fine-tuning checkpoints.
FineTuningError
An error from fine-tuning.
FineTuningEvent
A fine-tuning job event.
FineTuningEventList
A list of fine-tuning events.
FineTuningIntegration
A fine-tuning integration (e.g., Weights & Biases).
FineTuningJob
A fine-tuning job for customizing a model.
FineTuningJobList
A list of fine-tuning jobs.
FineTuningJobsResource
Resource for fine-tuning job operations.
FineTuningResource
Resource for Fine-tuning API operations.
FunctionCall
A function call within a tool call.
FunctionCallArgumentsDeltaEvent
Event emitted when function call arguments are generated (delta).
FunctionCallArgumentsDoneEvent
Event emitted when function call arguments are complete.
FunctionCallDelta
A function call delta in a streaming chunk.
FunctionCallItem
A function call item.
FunctionCallOutput
The output of a function call.
FunctionCallOutputContent
A list of content items output from a function call.
FunctionCallOutputItem
A function call output item.
FunctionCallOutputItemResponse
A function call output item in the response.
FunctionCallOutputString
A string output from a function call.
FunctionDefinition
A function definition for a tool.
FunctionTool
A function tool.
GeneratedImage
A generated image.
HistoryParam
History parameter.
Hyperparameters
Hyperparameters for a fine-tuning job.
HyperparametersRequest
Hyperparameters request for creating a fine-tuning job.
ImageContentPart
An image URL content part.
ImageEditJsonRequest
JSON request for image edits.
ImageEditRequest
A request to edit an existing image.
ImageGenerationCallOutputItem
An image generation call output item.
ImageGenerationRequest
A request to generate images from a text prompt.
ImageGenerationTool
Image generation tool for creating images.
ImageReference
Reference an input image by URL/data URL or uploaded file ID.
ImageResponse
A response from the images API.
ImagesResource
Resource for image operations.
ImageVariationRequest
A request to create variations of an image.
IncompleteDetails
Details about why a response is incomplete.
InfOrInt
A value that can be "inf" (infinity) or an integer.
InfOrIntInf
Represents infinity for an integer field.
InfOrIntValue
Represents a specific integer value.
InputContent
Input content for messages.
InputFileContent
File content via URL, file ID, or base64-encoded data.
InputImageContent
Image content via URL or file ID.
InputItemList
A list of input items with pagination.
InputMessage
Input message for model sampling.
InputMessages
Input messages configuration for model sampling.
InputMessagesItemReference
Item reference-based input messages for pre-built trajectories.
InputMessagesTemplate
Template-based input messages with variable substitution support.
InputTextContent
Text content for user, system, and developer messages.
InputTextOutputContent
Input text content preserved in compact output.
InputTokenCountResponse
Response from the input tokens count endpoint.
InputTokensDetails
Detailed breakdown of input tokens.
InputTokensResource
Resource for input tokens counting operations.
InputVideoContent
Video content via URL.
Interceptor
Base interface for HTTP request interceptors.
InterceptorChain
Builds and executes an interceptor chain.
Item
Input item for a response request.
ItemReference
Reference to a previously created item.
ItemsCreateRequest
Request to add items to a conversation.
JsonlContentSource
JSONL source from inline content.
JsonlFileSource
JSONL source from a file ID.
JsonlRunDataSource
JSONL file-based data source for evaluation runs.
JsonlSource
Source for JSONL data.
JsonObjectFormat
JSON object response format.
JsonObjectResponseFormat
JSON object response format.
JsonSchemaFormat
JSON schema response format.
JsonSchemaResponseFormat
JSON schema response format for structured outputs.
KeyPressAction
A keypress action to press keyboard keys.
LabelModelGrader
Uses an AI model to classify outputs into predefined labels.
LabelModelInput
Input message for a label model grader.
LocalShellCallOutputItem
A local shell call output item.
LocalShellCallOutputResultItem
A local shell call output result item.
LocalShellEnvironment
A local environment for shell execution.
LocalShellExecAction
Typed action for a local shell call.
LocalShellTool
Local shell tool for command execution in a local environment.
LoggingInterceptor
Interceptor that logs HTTP requests and responses.
LogProb
Log probability information for a token.
Logprobs
Log probability information for a token.
LogsDataSourceConfig
Logs-based data source configuration.
McpCallOutputItem
An MCP (Model Context Protocol) call output item.
McpTool
Model Context Protocol (MCP) tool.
MessageItem
A message item in a conversation.
MessageOutputItem
A message output item.
MessagesResource
Resource for Messages API operations (Beta).
Model
Information about an OpenAI model.
ModelList
A list of models.
ModelsResource
Resource for model operations.
ModerationCategories
Moderation category flags.
ModerationCategoryAppliedInputTypes
The input type(s) that each category score applies to.
ModerationCategoryScores
Moderation category confidence scores.
ModerationInput
Input for moderation.
ModerationInputItem
A single item in a multi-modal moderation input.
ModerationInputItemImageUrl
An image URL input item for multi-modal moderation.
ModerationInputItemText
A text input item for multi-modal moderation.
ModerationInputMultiModal
Multi-modal input for moderation (text and/or images).
ModerationInputText
A single text string input for moderation.
ModerationInputTextList
Multiple text strings input for moderation.
ModerationRequest
A request to check content for harmful material.
ModerationResponse
A moderation response.
ModerationResult
The moderation result for a single input.
ModerationsResource
Resource for content moderation operations.
MoveAction
A move action to move the cursor to coordinates.
NamespaceAllowedTool
Marker interface for tools that may appear inside a NamespaceTool.
NamespaceTool
Namespace tool for grouping tools under a namespace.
OpenAIClient
The main client for interacting with the OpenAI API.
OpenAIConfig
Configuration for the OpenAI client.
OpenRouterProviderPreferences
Provider routing preferences for OpenRouter.
OpenRouterReasoning
Reasoning configuration for OpenRouter.
OpenRouterUsageConfig
Usage configuration for OpenRouter.
OrganizationApiKeyProvider
Provides organization-scoped authentication for the OpenAI API.
OutputContent
Output content from model.
OutputItem
Output item from a response.
OutputItemAddedEvent
Event emitted when an output item is added.
OutputItemDoneEvent
Event emitted when an output item is complete.
OutputTextAnnotationAddedEvent
Event emitted when a text annotation is added.
OutputTextContent
Text output content.
OutputTextDeltaEvent
Event emitted when text is generated (delta).
OutputTextDoneEvent
Event emitted when text generation is complete.
OutputTokensDetails
Detailed breakdown of output tokens.
PlainTextFormat
Plain text response format.
Prediction
Predicted output for faster responses.
PromptTokensDetails
Detailed breakdown of prompt tokens.
PythonGrader
Runs custom Python code for evaluation.
RateLimitsParam
Rate limits parameter.
RealtimeCallsResource
Resource for Realtime WebRTC call operations.
RealtimeConnection
A connection to a realtime session.
RealtimeResource
Resource for Realtime API operations.
RealtimeSessionsResource
Resource for Realtime HTTP API operations.
ReasoningConfig
Configuration for reasoning models.
ReasoningDetail
Details about model reasoning, returned by some providers.
ReasoningItem
A reasoning item from reasoning models.
ReasoningSummaryContent
Content within a reasoning summary.
ReasoningSummaryPartAddedEvent
Event emitted when a reasoning summary part is added.
ReasoningSummaryPartDoneEvent
Event emitted when a reasoning summary part is complete.
ReasoningSummaryTextDeltaEvent
Event emitted when reasoning summary text is generated (delta).
ReasoningSummaryTextDoneEvent
Event emitted when reasoning summary text is complete.
ReasoningTextContent
Reasoning text content from reasoning models.
ReasoningTextDeltaEvent
Event emitted when reasoning text is generated (delta).
ReasoningTextDoneEvent
Event emitted when reasoning text is complete.
RefusalContent
Refusal content when model declines to respond.
RefusalDeltaEvent
Event emitted when refusal content is generated (delta).
RefusalDoneEvent
Event emitted when refusal generation is complete.
RequestContext
Context for an HTTP request/response.
ResourceBase
Base class for all API resources.
Response
A response from the Responses API.
ResponseAudioDeltaEvent
Event emitted when audio content is generated (delta).
ResponseAudioDoneEvent
Event emitted when audio generation is complete.
ResponseAudioTranscriptDeltaEvent
Event emitted when audio transcript is generated (delta).
ResponseAudioTranscriptDoneEvent
Event emitted when audio transcript is complete.
ResponseCodeInterpreterCallCodeDeltaEvent
Event emitted when code interpreter code is generated (delta).
ResponseCodeInterpreterCallCodeDoneEvent
Event emitted when code interpreter code generation is complete.
ResponseCodeInterpreterCallCompletedEvent
Event emitted when a code interpreter call is completed.
ResponseCodeInterpreterCallInProgressEvent
Event emitted when a code interpreter call is in progress.
ResponseCodeInterpreterCallInterpretingEvent
Event emitted when a code interpreter call is interpreting.
ResponseCompaction
A compacted response object returned by responses.compact.
ResponseCompletedEvent
Event emitted when a response is completed.
ResponseCreatedEvent
Event emitted when a response is created.
ResponseCustomToolCallInputDeltaEvent
Event emitted when custom tool call input is generated (delta).
ResponseCustomToolCallInputDoneEvent
Event emitted when custom tool call input is complete.
ResponseError
Error details for a failed response.
ResponseFailedEvent
Event emitted when a response fails.
ResponseFileSearchCallCompletedEvent
Event emitted when a file search call is completed.
ResponseFileSearchCallInProgressEvent
Event emitted when a file search call is in progress.
ResponseFileSearchCallSearchingEvent
Event emitted when a file search call is searching.
ResponseFormat
Specifies the format that the model must output.
ResponseImageGenerationCallCompletedEvent
Event emitted when an image generation call is completed.
ResponseImageGenerationCallGeneratingEvent
Event emitted when an image generation call is generating.
ResponseImageGenerationCallInProgressEvent
Event emitted when an image generation call is in progress.
ResponseImageGenerationCallPartialImageEvent
Event emitted when a partial image is generated.
ResponseIncompleteEvent
Event emitted when a response is incomplete.
ResponseInProgressEvent
Event emitted when a response is in progress.
ResponseInput
Input for a response request.
ResponseInputItems
A list of items input for multi-turn conversations.
ResponseInputItemsResource
Resource for response input items operations.
ResponseInputRawJson
Raw JSON input from output items (e.g. compact output).
ResponseInputText
Simple text input for a response request.
ResponseList
A list of responses with pagination.
ResponseMcpCallArgumentsDeltaEvent
Event emitted when MCP call arguments are generated (delta).
ResponseMcpCallArgumentsDoneEvent
Event emitted when MCP call arguments are complete.
ResponseMcpCallCompletedEvent
Event emitted when an MCP call is completed.
ResponseMcpCallFailedEvent
Event emitted when an MCP call fails.
ResponseMcpCallInProgressEvent
Event emitted when an MCP call is in progress.
ResponseMcpListToolsCompletedEvent
Event emitted when MCP list tools is completed.
ResponseMcpListToolsFailedEvent
Event emitted when MCP list tools fails.
ResponseMcpListToolsInProgressEvent
Event emitted when MCP list tools is in progress.
ResponseMetadata
Metadata from an API response.
ResponseQueuedEvent
Event emitted when a response is queued for processing.
ResponsesContentSource
Responses source from inline content.
ResponsesFileSource
Responses source from a file.
ResponsesResource
Resource for responses operations.
ResponsesRunDataSource
Responses-based data source for evaluation runs.
ResponsesSource
Source for responses data.
ResponseStreamAccumulator
Accumulates streaming events into a complete response.
ResponseStreamEvent
A streaming event from the Responses API.
ResponseTool
Tool definition for the Responses API.
ResponseToolChoice
Tool choice specification.
ResponseToolChoiceAllowedTools
Model can only call the specified tools.
ResponseToolChoiceAuto
Model automatically decides whether to call tools.
ResponseToolChoiceFunction
Model must call the specified function.
ResponseToolChoiceNone
No tool should be called.
ResponseToolChoiceRequired
Model must call at least one tool.
ResponseUsage
Token usage statistics for a response.
ResponseWebSearchCallCompletedEvent
Event emitted when a web search call is completed.
ResponseWebSearchCallInProgressEvent
Event emitted when a web search call is in progress.
ResponseWebSearchCallSearchingEvent
Event emitted when a web search call is searching.
RetryPolicy
Retry policy configuration.
RetryWrapper
Wraps HTTP transport execution with retry logic.
RunsResource
Resource for Runs API operations (Beta).
ScoreModelGrader
Uses an AI model to assign numeric scores.
ScoreModelInput
Input message for a score model grader.
ScreenshotAction
A screenshot action to capture the current screen.
ScrollAction
A scroll action at specific coordinates.
SetDefaultSkillVersionRequest
Request to update the default skill version.
ShellCallAction
Shell call action payload.
ShellCallExitOutcome
Normal shell call completion with an exit code.
ShellCallOutcome
Execution outcome for a shell call output chunk.
ShellCallOutputContent
A single shell output chunk.
ShellCallOutputItem
A shell call output item.
ShellCallOutputResultItem
A shell call output result item.
ShellCallTimeoutOutcome
Shell call timeout outcome.
ShellEnvironment
The execution environment for a shell call.
ShellTool
Hosted shell tool for command execution.
Skill
A skill resource.
SkillList
Paginated list of Skill resources.
SkillsResource
Resource for Skills API operations.
SkillUploadFile
Uploadable skill file entry for multipart requests.
SkillVersion
A skill version resource.
SkillVersionList
Paginated list of SkillVersion resources.
SkillVersionsResource
Resource for skill versions operations.
SpecificFunctionChoice
A specific function that can be selected.
SpecificToolChoice
A specific tool that can be selected.
SpeechRequest
A request to generate speech from text.
SpeechResource
Resource for text-to-speech operations.
SseEvent
A Server-Sent Event.
SseParser
Parses Server-Sent Events (SSE) streams.
StopSequence
Stop sequences for completions.
StopSequenceMultiple
Multiple stop sequences.
StopSequenceSingle
A single stop sequence.
StoredCompletionsSource
Completions source from stored completions.
StoredResponsesSource
Responses source from stored responses.
StreamOptions
Options for streaming responses.
StringCheckGrader
Pattern matching grader that checks strings against patterns.
SummaryTextContent
Summary text content from reasoning models.
SystemMessage
A system message that sets behavior and context.
TextConfig
Configuration for text output.
TextContentPart
A text content part.
TextFormat
Text output format.
TextResponseFormat
Text response format (default).
TextSimilarityGrader
Compares text similarity using a specified metric.
ThreadItem
A thread item in a ChatKit thread.
ThreadItemList
A list of thread items.
ThreadsResource
Resource for Threads API operations (Beta).
TokenLogprob
Log probability information for a single token.
Tool
A tool available for the model to call.
ToolCall
A tool call made by the model.
ToolCallDelta
A tool call delta in a streaming chunk.
ToolChoice
Controls which tool the model should use.
ToolChoiceAuto
Let the model decide whether to call a tool.
ToolChoiceFunction
Force the model to call a specific function.
ToolChoiceNone
Disable tool calling.
ToolChoiceRequired
Force the model to call a tool.
ToolMessage
A tool message containing the result of a tool call.
ToolSearchCallItemParam
A tool search call input item.
ToolSearchCallOutputItem
A tool search call output item.
ToolSearchOutputItem
A tool search output item containing discovered tools.
ToolSearchOutputItemParam
A tool search output input item.
ToolSearchTool
Tool search tool for searching available tools.
TopLogProb
Alternative token with its log probability.
TopLogprob
Information about a top log probability token alternative.
TracingParam
Tracing parameter.
TranscriptionRequest
A request to transcribe audio into text.
TranscriptionResponse
A transcription response.
TranscriptionSegment
A segment in a verbose transcription response.
TranscriptionsResource
Resource for transcription (speech-to-text) operations.
TranscriptionVerboseResponse
A verbose transcription response with additional metadata.
TranscriptionWord
A word with timing information.
TranslationRequest
A request to translate audio into English text.
TranslationResponse
A translation response.
TranslationsResource
Resource for audio translation operations.
TranslationVerboseResponse
A verbose translation response with additional metadata.
TypeAction
A type action to type text.
UnknownEvent
An event with an unrecognized type.
UnknownNamespaceTool
An unknown namespace tool for forward compatibility.
UpdateEvalRequest
Request to update an existing evaluation.
Upload
An upload object.
UploadPart
An upload part.
UploadsResource
Resource for multipart upload operations.
UrlCitation
URL citation annotation.
Usage
Token usage statistics for a request.
UserMessage
A user message containing text, images, or audio.
UserMessageContent
Content for a user message.
UserPartsContent
Multiple content parts for a user message.
UserTextContent
Simple text content for a user message.
VectorStoreFilesResource
Resource for Vector Store Files operations.
VectorStoresResource
Resource for Vector Stores API operations (Beta).
Video
A generated video job.
VideoError
Error information for a failed video generation.
VideoList
A list of videos.
VideosResource
Resource for video generation operations (Sora).
WaitAction
A wait action to pause execution.
WandbIntegration
Weights & Biases integration configuration.
WebSearchCallOutputItem
A web search call output item.
WebSearchLocation
Approximate location parameters for web search.
WebSearchOptions
Web search options for the Chat Completions API.
WebSearchTool
Web search tool for searching the web.
WebSearchUserLocation
User location wrapper for web search in Chat Completions.
WorkflowParam
Workflow parameter for creating a session.

Enums

AbortionStage
The stage at which the request was aborted.
AudioFormat
Audio format for audio input/output.
BatchEndpoint
Batch endpoint options.
BatchStatus
Batch status values.
ChatAudioFormat
Audio format options for chat audio output.
ChatAudioVoice
Voice options for chat audio output.
ChatModality
Output modality for chat completions.
ChatSessionStatus
Session lifecycle status.
ClickButton
The mouse button used in a click action.
CompletionWindow
Completion window options.
EmbeddingEncodingFormat
The encoding format for embeddings.
EvalOutputItemStatus
Status filter for listing output items.
EvalRunStatus
Status of an evaluation run.
FileInputDetail
The detail level for file input processing.
FilePurpose
The intended purpose of a file.
FileStatus
File processing status.
FineTuningStatus
Fine-tuning job status values.
FinishReason
Reason why the model stopped generating tokens.
FunctionCallOutputStatus
The status of a function call output.
FunctionCallStatus
The status of a function call.
ImageBackground
Background options for JSON image edits.
ImageDetail
Image detail level for vision models.
ImageEditJsonQuality
JSON image edit quality options.
ImageEditJsonSize
JSON image edit size options.
ImageInputFidelity
Input fidelity options.
ImageModerationLevel
Moderation level options for JSON image edits.
ImageOutputFormat
Output format options for JSON image edits.
ImageQuality
Image quality options.
ImageResponseFormat
Image response format options.
ImageSize
Image size options.
ImageStyle
Image style options.
Include
Additional data to include in the response.
ItemStatus
The status of an item.
MessagePhase
The phase of a message in a response.
MessageRole
The role of a message in a conversation.
PromptCacheRetention
The retention policy for prompt cache entries.
ReasoningEffort
Reasoning effort level for reasoning models.
ReasoningSummary
Reasoning summary generation mode.
ResponseStatus
The status of a response.
SearchContentType
The type of content to search for in web search.
ServiceTier
Service tier for request processing.
SpeechResponseFormat
Audio output formats for speech generation.
SpeechVoice
Available voices for text-to-speech.
StringCheckOperation
Operations for string check grader.
TextSimilarityMetric
Metrics for text similarity comparison.
TimestampGranularity
Timestamp granularity options.
ToolChoiceMode
Tool choice mode for allowed tools.
ToolSearchExecutionType
The execution type for tool search.
TranscriptionResponseFormat
The response format for transcription.
Truncation
Truncation strategy for long inputs.
UploadStatus
Upload status.
Verbosity
Verbosity level for output.
VideoContentVariant
Video content variant for download.
VideoSeconds
Video duration in seconds.
VideoSize
Video resolution.
VideoStatus
Current lifecycle status of a video job.

Mixins

StreamingResource
Mixin that adds streaming capabilities to a ResourceBase.

Extensions

ChatChoiceExtension on ChatChoice
Extension methods for ChatChoice objects.
ChatCompletionExtension on ChatCompletion
Extension methods for ChatCompletion objects.
ChatMessageListExtension on List<ChatMessage>
Extension methods for lists of ChatMessage objects.
ChatStreamExtension on Stream<ChatStreamEvent>
Extension methods for chat streaming.
JsonMapExtension on Map<String, dynamic>
Extension methods for JSON map access.
ListPageSizeHeuristicsExtension on List<T>
Extension providing heuristic pagination checks for lists.
ResponseStreamEventExtensions on ResponseStreamEvent
Extension methods for ResponseStreamEvent.
SseEventExtension on Map<String, dynamic>
Extension to handle SSE event types in parsed JSON.

Constants

jsonEncoder → const JsonEncoder
JSON encoding with proper handling of special values.
unsetCopyWithValue → const Object
Sentinel value used to distinguish between "not set" and "set to null".

Functions

createApiException({required int statusCode, required String message, String? type, String? code, String? param, String? requestId, Map<String, dynamic>? body, Duration? retryAfter, Object? cause}) ApiException
Creates the appropriate exception based on HTTP status code.
encodeJson(Object? value) String
Encodes an object to JSON string, omitting null values.
encodePrettyJson(Object? value) String
Encodes an object to pretty-printed JSON string.
generateCorrelationId() String
Generates a unique correlation ID for request tracing.
generateRequestId() String
Generates a unique request ID.
parseJson(String? source) Map<String, dynamic>?
Parses a JSON string safely.
parseJsonArray(String? source) List<Map<String, dynamic>>
Parses a JSON array string safely.
removeNulls(Map<String, dynamic> map) Map<String, dynamic>
Removes null values from a map recursively.

Typedefs

InterceptorNext = Future<Response> Function(RequestContext context)
Function signature for interceptor chain continuation.
ReasoningDeltaEvent = ReasoningTextDeltaEvent
Use ReasoningTextDeltaEvent instead.
ReasoningDoneEvent = ReasoningTextDoneEvent
Use ReasoningTextDoneEvent instead.

Exceptions / Errors

AbortedException
Exception thrown when a request is aborted.
ApiException
Exception thrown when the API returns an error response.
AuthenticationException
Exception thrown when authentication fails (HTTP 401).
BadRequestException
Exception thrown when the request is invalid (HTTP 400).
ConflictException
Exception thrown when the request conflicts with current state (HTTP 409).
ConnectionException
Exception thrown when a network connection cannot be established.
InternalServerException
Exception thrown when an internal server error occurs (HTTP 5xx).
NotFoundException
Exception thrown when a resource is not found (HTTP 404).
OpenAIException
Base exception class for all OpenAI client errors.
ParseException
Exception thrown when response parsing fails.
PermissionDeniedException
Exception thrown when access is denied (HTTP 403).
RateLimitException
Exception thrown when rate limited (HTTP 429).
RequestTimeoutException
Exception thrown when a request times out.
StreamException
Exception thrown when streaming fails.
UnprocessableEntityException
Exception thrown when the request cannot be processed (HTTP 422).