openai_dart 11.0.1
openai_dart: ^11.0.1 copied to clipboard
Dart client for the OpenAI REST APIs and realtime WebSocket/WebRTC workflows with type-safe access to GPT, image, audio, and Responses APIs.
11.0.1 #
11.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
What changed #
This release adds typed Decisions, persistent Responses WebSockets, Live sessions, signed webhooks and Safety retrieval, plus the core saved-agent, durable-session, hosted-environment and Vault workflows. It also corrects request/response contracts across containers, caching, Chat audio, tools and file audio, so applications must review the migration guidance for the APIs they use. The minimum Dart SDK remains 3.12; existing HTTP/SSE and Realtime entry points remain available.
Decisions: classification and scoring #
Use client.decisions.create(...) to ask multiple typed questions about shared input and receive ordered predicate, choice, score or refusal answers. Inputs can be text, inline image bytes/data URLs, or publicly accessible HTTP(S) image references; string and boolean choices remain distinct, and scores can be fractional. Image references are preserved without a client-side download or normalization; the service checks validity and accessibility.
Responses expose cache-write usage for this workflow. Decisions have no model-event streaming mode, and tools, file IDs and audio are outside the supported input shape. See the Decisions example and remote/inline image example.
Responses: persistent connections and explicit orchestration #
client.responses.connect() opens a persistent WebSocket connection with a default lane and named streamId lanes. Applications can warm state, continue from an actual returned response ID, interleave lane-aware events and await explicit connection cleanup. streamId selects routing; previousResponseId selects ancestry. Existing HTTP and SSE calls continue to work.
Mid-turn steering sends corrections with typed accepted/pending/failed acknowledgments. Beta tool-result injection returns developer-owned results and distinguishes committed from uncommitted outcomes. Opt-in recovery requires a preparation callback, refreshes authentication and queues only newly unsent frames within a bounded UTF-8 byte budget; submitted or attempted work is never automatically replayed. The application remains responsible for deciding how to continue work whose outcome is unknown.
Native connections support configured authentication headers. Browser connections require an explicit headerless configuration and an authenticated backend WebSocket proxy because browsers cannot send custom handshake headers. Examples cover persistent connections, steering, recovery and multi-agent injection.
Responses tools, reasoning and cache controls #
Async function/custom tools retain their execution flags and call metadata through returned calls, streams, conversations and replay. Typed custom-call input supports faithful continuation. Reasoning configuration updates change subsequent effort through input history while keeping request-level settings stable.
GA web search becomes the default for the web-search factories, with domain filters, external-access settings, result budgets, image controls and exact includes. Explicit preview tools retain their wire values; use an explicit preview type if the application depends on preview behavior. Hosted, local and existing-container shell configurations gain typed calls/results, skills, writable replay models and command/output stream events with independent stdout/stderr fragments.
Compaction-in-progress events now have a typed variant. Access-program selection and effective response metadata are exposed without changing omitted-field behavior. Tool-search records preserve arbitrary returned arguments and nullable hosted IDs, while writable definitions and returned records enforce their separate contracts.
Responses cache options add prewarming/comparison controls and typed diagnostics; Chat and compaction retain their narrower options type. PromptCacheRetention.inMemory now serializes as in_memory, while legacy in-memory input remains readable. Retention and TTL describe different policies and are not interchangeable. See the cache example and the migration guide for the Responses options type change.
Chat, images and container correctness #
Chat completions now preserve audio output, replay assistant audio by ID, and accumulate audio fragments independently per choice. Detailed cache-write, image and text token counters survive ordinary and usage-only stream responses. Obfuscation remains metadata and does not enter accumulated output. Value equality, hashing and copies include the documented fields, so same-ID snapshots can compare differently when their contents differ.
Image generation and multipart image editing now require an explicit model, including their streaming variants. Raw model IDs remain supported; JSON image editing retains its separate optional-model/server-default contract. Container memory uses typed 1g/4g/16g/64g values, network allowlists use allowed_domains, creation requires a name, and returned expiration/network information has distinct response types. Collection-bearing container models own immutable snapshots.
Structured permanent billing/spend/quota failures stop automatic replay. Valid server retry hints are minimum delays; a hint beyond the automatic wait bound returns the original error instead of retrying early. Transient/unknown-provider 429 behavior remains available. The retry example demonstrates the behavior locally.
Speech, file audio, custom voices and Live #
Speech supports instructions, typed named/custom voice references and built-in voice conveniences, plus raw byte streaming and typed SSE audio/usage alongside buffered generation. Chat voices use the same AudioVoice interface, with marin/cedar and AAC conveniences; Chat pcm16 remains distinct from Speech pcm.
File-audio requests/responses retain strict parsing and immutable collection snapshots. Buffered methods support cancellation, and translation has explicit verbose and raw-output methods that preserve subtitle whitespace. Collection/byte/JSON-bearing constructors lose const; scalar-only constructors remain const. Voice-consent CRUD and custom voice creation preserve original recordings, enforce the documented limits and protect private sample/consent data in automatic diagnostics. Custom voice use still depends on service eligibility and permissions; the client does not provide microphone capture or invent consent.
client.live.sessions adds HTTP signaling and explicit WebRTC/SIP call controls, recording downloads and REST forks. Primary and sideband WebSockets expose typed events and role-safe commands. Stored-session forks use a separate connection, transcript helpers group captions with SDK timing semantics, and typed media data channels borrow caller media. Application task restoration, tool execution and media/hardware ownership remain explicit; forks do not automatically replay audio or side effects. See the README Live workflows.
Signed webhooks, Safety and monitoring #
Verify original webhook strings/bytes locally through the standalone verifier or client.webhooks, without an API key or HTTP request. The parser covers 26 published received event variants and preserves future event/metadata JSON. Project endpoint management includes CRUD, rotation, testing and event-type discovery; revealed signing secrets remain caller-readable while built-in diagnostics redact them.
client.safety retrieves project alerts and organization cases referenced by verified notifications, including nullable detailed explanations. Shared monitoring details survive HTTP failures, failed Responses and WebSocket errors without changing the original failure or triggering continuation. Canonical SSE errors serialize as flat nullable fields, with documented legacy input compatibility. These are retrieval and inspection APIs, not automatic remediation workflows.
Agents, durable sessions, environments and Vaults #
client.agents provides saved-agent CRUD with persisted function, MCP, web-search and computer-use configuration. Durable sessions support JSON/SSE creation, persistent typed observation and explicit submission of messages, function results, browser approvals and cancellation. HTTP acceptance, observer closure and execution completion remain distinct. Root-session items, turns and turn items are readable; currently published OTLP traces use root-turn pagination. Subagent inspection and child history keep coordinator and child timelines separate, including closed children that resume.
Hosted environments can be prewarmed from reusable templates. File methods copy Files API references or bounded inline bytes into connected environments and page live workspace files; session artifacts are separately published immutable snapshots that can be downloaded incrementally, including after environment expiry. Inline configuration limits are 5 MiB per decoded file and 10 MiB per configuration.
client.vaults provides Vault CRUD and write-only credential creation/rotation, with safe returned authentication metadata. Secret writes and readable metadata use distinct models. No local function executor, automatic session runner/result collector, portable file convenience layer or environment-lifecycle webhook helper is added in this release. The implemented core HTTP operations remain usable directly, and the README contains offline workflows.
Compatibility and upgrade priorities #
Upgrade the dependency to openai_dart: ^11.0.0, then run the analyzer and application tests. The v10.x → v11.0.0 migration guide preserves detailed before/after examples for every reviewed contract correction, including:
- Required explicit image models, container names and returned nullable fields.
- Typed/open audio voices, nullable translation task/annotations/error fields, and explicit raw/verbose translation output methods.
- The Responses cache-options type split and canonical cache-retention spelling.
- GA web-search default selection, complete shell/tool-search returned contracts and request replay boundaries.
- New sealed variants for custom-call inputs, reasoning-update items, compaction, steering and injection; update exhaustive switches rather than treating these known events as unknown fallbacks.
- Immutable collection-bearing models, wider value equality/hash contracts, stricter malformed-known JSON rejection and changed retry timing/classification.
HTTP/2 adoption is deferred. The local evaluation demonstrated concurrent connection savings, but cancellation, buffering/backpressure and repeated SSE compatibility blocked a general recommendation; it did not change the production transport or demonstrate faster OpenAI inference. Follow-up #408 waits for released fixes and runtime evidence. Deferred Agents conveniences, Admin/legacy parity and runtime configuration changes also remain outside this release; completing the bounded milestone is not a claim of full API/SDK parity.
Commits #
- BREAKING FEAT: add speech voices and byte/SSE streaming (#374). (f76a2e8c)
- BREAKING FEAT: add beta WebSocket tool-result injection (#356). (1e63d6b9)
- BREAKING FEAT: add mid-turn Responses steering (#354). (eeaa8e7b)
- BREAKING FEAT: add persistent Responses WebSocket transport (#353). (b1c7b023)
- BREAKING FEAT: add typed compaction progress events (#350). (4110c174)
- BREAKING FEAT: add hosted shell, replay and stream events (#349). (9e0b572b)
- BREAKING FEAT: add GA web search controls and results (#348). (43b826f3)
- BREAKING FEAT: add persistent reasoning updates (#347). (6b0a66f3)
- BREAKING FEAT: support async function and custom tools (#346). (433cca33)
- BREAKING FEAT: support Chat audio output, replay, and streams (#331). (82232226)
- BREAKING FEAT: preserve Chat usage and stream obfuscation (#330). (c65f3e96)
- BREAKING FEAT: add cache controls and diagnostics (#329). (7da31335)
- BREAKING FIX: correct Chat voices and file audio contracts (#375). (98e67ac9)
- BREAKING FIX: preserve monitoring errors and flat SSE (#365). (fca1a3f4)
- BREAKING FIX: preserve tool-search calls and definitions (#352). (9944b421)
- BREAKING FIX: require generation and multipart image models (#333). (5eae6db7)
- BREAKING FIX: honor quota failures and server retry hints (#332). (aa6ebfaa)
- BREAKING FIX: correct container configuration contracts (#327). (d92ab258)
- FEAT: add subagent inspection and history (#406). (750a4f45)
- FEAT: add environment files and session artifacts (#405). (7fcfb3f7)
- FEAT: add hosted environments and templates (#404). (435b4cf0)
- FEAT: add Vaults and write-only credentials (#403). (9a31d51d)
- FEAT: add session history and OTLP traces (#402). (c3a31911)
- FEAT: add durable sessions and raw event streams (#401). (7893afa2)
- FEAT: add saved agent CRUD and configuration (#400). (c1df2019)
- FEAT: expose Safety alert explanations (#384). (08f9594d)
- FEAT: accept HTTP(S) Decisions image URLs (#383). (bc89ad9a)
- FEAT: add Live forks and transcript helpers (#380). (a7907e4d)
- FEAT: add primary and sideband Live WebSockets (#379). (d00ee5cf)
- FEAT: Live HTTP sessions and call controls (#378). (98b32e69)
- FEAT: add custom voice creation (#377). (3e2b488e)
- FEAT: add voice consent management (#376). (2856c21e)
- FEAT: retrieve safety alerts and organization cases (#364). (a466e850)
- FEAT: manage project webhook endpoints (#363). (b5159171)
- FEAT: verify and parse signed webhook events (#362). (eea142bf)
- FEAT: add opt-in Responses WebSocket recovery (#355). (22b8cfda)
- FEAT: add Responses access-program selection (#351). (f5b8d085)
- FEAT: add Decisions API (#319). (0d852337)
- FIX: use canonical cache retention wire values (#328). (6d378a0c)
- CHORE: evaluate HTTP/2 transport compatibility (#407). (c23f36a8)
10.0.1 #
Fixes Responses parsing for compatible providers such as Agnes that return prompt_tokens and completion_tokens, preserving their reported counts and cached/reasoning token details. Standard Responses fields take precedence when present, and serialization continues to use standard Responses field names.
10.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
Adds GPT Image 2.5 Sunburst and Flare, including their dated snapshots, plus xhigh/max quality for image generation and editing. ImageSize becomes an immutable value class that accepts custom resolutions and preserves custom, transient, and future sizes in ordinary and streaming responses. Existing size constants remain available, but enum-only APIs and exhaustive size/quality switches require migration; see the Migration Guide.
9.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
Requires Dart 3.12 or later; upgrade your Dart SDK or the Dart SDK bundled with Flutter before updating this package.
8.1.0 #
ReasoningDetail now round-trips OpenRouter reasoning_details payloads exactly — explicit null values, nested unknown data, and ordered detail chunks all survive parsing and re-serialization, which OpenRouter requires when reasoning is replayed between requests. The type also exposes typed id, format, index, summary, and signature fields plus a ReasoningDetail.withAdditionalProperties factory for future non-reserved fields, stream accumulation retains explicitly empty reasoning arrays, and ChatDelta equality and hashing now account for tool calls and reasoning details.
8.0.1 #
Fixes a LinkedHashMap failure on Dart 3.13.2 that broke streaming multipart requests. The client added a JSON content-type header and later removed it, and MultipartRequest.finalize() reinserting the same case-insensitive key then threw. Streaming multipart requests now build their headers directly and add the required SSE Accept header, leaving the generated multipart boundary owned by package:http.
8.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
Adds Fast mode (ServiceTier.fast, up to 2.5× faster processing, replacing Priority Processing) and a full modernization of the GPT-Transcribe generation — chunking strategy control, logprobs, keyword hints, multi-language input, speaker diarization, and new createStream()/createDiarized()/createRaw() methods on client.audio.transcriptions. Also adds a client.contentProvenanceChecks resource for detecting OpenAI C2PA and SynthID provenance signals, and syncs the pinned spec to GPT-5.6 with programmatic tool calling, explicit prompt caching, and a multi-agent Responses beta. Breaking: TranscriptionResponseFormat is renamed to AudioResponseFormat (a deprecated typedef keeps old code compiling), TranslationRequest.responseFormat now uses a dedicated TranslationResponseFormat enum, TranscriptionVerboseResponse.task is now String?, InputAudioTranscriptionCompletedEvent.usage is now a typed TranscriptUsage?, and multipart array fields switch to spec-correct bracket-repeated encoding. See the Migration Guide.
7.0.1 #
Fixes buildUrl collapsing repeated query keys carried by the base URL (?k=a&k=b) to the last value — a proxy/gateway base URL with duplicate keys now keeps all of them on every request. Single-value behavior (including Azure api-version handling) is unchanged.
7.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
Syncs openai_dart to the latest OpenAI OpenAPI spec. Adds a reasoning context mode — ReasoningConfig.context (new ReasoningContext enum: auto/currentTurn/allTurns) controls which reasoning items are rendered back to the model on later turns, and the effective mode is now surfaced on the response (which also carries reasoning + truncation, so it's no longer silently dropped). Also adds MCP Secure Tunnel and connector addressing for remote MCP tools via McpTool.tunnelId and McpTool.connectorId. The single breaking change has limited real-world impact: to express the spec's server_url/connector_id/tunnel_id one-of, McpTool.serverUrl is now nullable (String?) — existing code that always passed serverUrl continues to compile and behave the same; only callers that read McpTool.serverUrl must now handle null. See the Migration Guide.
6.2.0 #
Adds support for the new moderation scores feature on the Chat Completions and Responses APIs — pass a moderation object on a request to receive moderation results for both the model input and the generated output, surfaced as sealed input/output outcomes (ChatCompletion.moderation, ChatStreamEvent.moderation, Response.moderation) and captured by ChatStreamAccumulator for streaming. All new fields are additive and nullable. Also marks the image-model id constants OpenAI has deprecated or removed with @Deprecated (retained for compatibility), leaving ImageModels.gptImage2 as the only recommended image model, and refreshes the canonical spec.
6.1.0 #
Adds two new OpenAI Responses features from the latest spec: the additional_tools item — surfacing extra tool definitions mid-conversation — across the input, output, and conversation-item unions, and a personality style preset on the input-token-count request (responses.inputTokens.count), modeled as a sealed Personality type with friendly/pragmatic presets plus a custom(...) escape hatch for forward compatibility. Also completes the MessageRole enum with the spec's critic, discriminator, and tool values, which previously collapsed to unknown.
6.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
Migrates the Realtime API client to the GA shape from OpenAI's Voice Intelligence drop (2026-05-07): a nested audio.{input,output} config block, sealed unions for audio formats / turn detection / truncation / tracing, new RealtimeReasoning, parallelToolCalls, transcription delay, and the realtime translation surface (gpt-realtime-translate + gpt-realtime-whisper) via connectTranslation(...) and the new client-secret methods. Adds DX helpers RealtimeConnection.sendUserMessage(text) and appendAudioBytes(...), plus a lenient event parser that returns UnknownRealtimeEvent instead of throwing. Also adds an optional serviceTier and a typed CompactionTriggerItem to the /responses/compact surface. Breaking: the impact is confined to the Realtime API (client.realtime / client.realtimeSessions) — audio fields moved under audio.{input,output}, several enums became sealed unions (RealtimeAudioFormats, RealtimeAudioInputTurnDetection), the legacy create()/createTranscription() HTTP methods are replaced by client-secret flows, and spec-dropped fields (RealtimeSession.temperature, RealtimeSessionCreateResponse.clientSecret) are removed. The Chat Completions and Responses APIs are unaffected.
5.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
Adds support for GPT-5.5 (gpt-5.5 and the gpt-5.5-2026-04-23 snapshot) across the ChatModel enum and all examples, and exposes the new prompt_cache_retention field on the /v1/responses/{response_id}/compact endpoint via CompactResponseRequest. Also fixes a StateError that affected non-streaming requests using abortTrigger (#209). Breaking: FunctionCallStatus is realigned to match the OpenAI spec (inProgress/completed/incomplete) — the non-spec failed value is removed (#208). The breaking surface is intentionally small: any code that referenced FunctionCallStatus.failed was already rejected by the API at runtime, so the practical impact is limited — but we follow strict semver and ship the enum change as a major bump regardless.
4.3.0 #
Adds support for GPT Image 2 (gpt-image-2) — surfacing the full GPT-image parameter surface on ImageGenerationRequest and ImageEditRequest (background, moderation, output format/compression, streaming, input fidelity), expanded ImageQuality and ImageSize enums, token-based usage metadata on ImageResponse, and a new ImageModels constants class. Also expands the ReasoningEffort enum with none, minimal, and xhigh to match the latest OpenAI spec and the per-model support matrix for gpt-5.1, gpt-5-pro, and models after gpt-5.1-codex-max.
4.2.0 #
Re-introduces the detail field on InputFileContent via a new FileInputDetail enum (high/low) for controlling how thoroughly the model processes file inputs, following the same pattern as the existing ImageDetail enum. Also refreshes the OpenAPI spec to the latest upstream version.
4.1.0 #
Adds a phase property to ConversationMessageItem to match the latest OpenAI spec. The field labels assistant messages as either commentary (intermediate thinking) or final_answer, which prevents performance degradation when resending conversation history to models like gpt-5.3-codex.
4.0.1 #
4.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
Adds FileContentPart and RefusalContentPart to the Chat Completions API — completing the content part union with support for sending PDFs/documents and representing model refusals. The InputFileContent.data() and InputContent.fileData() factories now require a mediaType parameter and construct proper data URL format (raw base64 was rejected by the API). Also adds ToolChoiceAllowedTools and ToolChoiceCustom variants for constraining tool selection, and narrows InputTokensResource.count toolChoice from Object? to ResponseToolChoice?.
- BREAKING FEAT: Add FileContentPart and RefusalContentPart (#152). (821eea60)
- FEAT: Add ToolChoiceAllowedTools and ToolChoiceCustom variants (#161). (f0940801)
- DOCS: Improve toolkit and skills from PR #152 lessons (#153). (f55de1ec)
- DOCS: Overhaul root README and add semver bullet to all packages (#151). (e6af33dd)
3.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
Replaces the ServiceTier enum with an extensible class to preserve provider-specific tier values on round-trip serialization. Adds missing type and param fields to ResponseError and makes code nullable. Adds custom tool call support to the Responses API, modifier keys for computer use actions, and expands the Video API with edit, extend, and character endpoints. Removes FileInputDetail enum and detail parameter from InputFileContent. Also fixes toolkit verification warnings, adds docs coverage for 14 resources with new example files, standardizes equality helper locations, and adds llms.txt ecosystem files.
- BREAKING FEAT: Improve spec compliance for ServiceTier and ResponseError (#133). (487231d2)
- BREAKING FEAT: Update OpenAPI spec with custom tools, video expansion, and computer action keys (#143). (b08ba7b9)
- FIX: Resolve toolkit verification warnings across packages (#122). (634bdda2)
- REFACTOR: Standardize equality helpers location across packages (#123). (34086102)
- DOCS: Un-exclude 14 resources from docs verification (#121). (2a2966ad)
- DOCS: Overhaul READMEs and add llms.txt ecosystem (#149). (98f11483)
- TEST: Add OpenRouter integration test (#114). (46a75724)
2.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
Made non-streaming response parsing robust for third-party OpenAI-compatible providers (AWS Bedrock proxies, Ollama, vLLM, TogetherAI, OpenRouter, etc.) by relaxing strict casts in fromJson while keeping constructor invariants strict. Added ResponseStreamExtensions for convenient stream event filtering/mapping, copyWith methods to all ResponseStreamEvent subtypes and ChatMessage/ContentPart, and updated RunStep, Message, Tool, and EmbeddingRequest models with additional fields from the latest API spec.
1.4.0 #
This release improves streaming error handling by detecting and surfacing errors embedded in chat and other streaming responses. It also updates model references to the latest gpt-realtime-1.5 and gpt-audio-1.5 models, and documents WebRTC support for the Realtime API.
- FEAT: Detect inline streaming errors (#91). (9f0eaf37)
- FEAT: Update model references to gpt-realtime-1.5 and gpt-audio-1.5 (#83). (30d27274)
- FIX: Detect and throw errors embedded in chat streaming data (#87). (7bdeaaa5)
- DOCS: Improve READMEs with badges, sponsor section, and vertex_ai deprecation (#90). (5741f2f3)
- DOCS: Document WebRTC support in Realtime API (#84). (2f385378)
1.3.0 #
1.2.0 #
Added support for GPT-5.4 and the new Responses API agent capabilities released alongside it — tool search (deferred tool loading at runtime), built-in computer use, and 1M-token context with message phases. Also added multi-modal moderation, fine-tune management methods, and missing ChatCompletionCreateRequest fields. Fixed handling of unknown streaming event types.
- FEAT: GPT-5.4, tool search, computer use & message phase support (#69). (3dab848f)
- FEAT: Add missing ChatCompletionCreateRequest fields (#73). (0b06b159)
- FEAT: Add multi-modal moderation, fine-tune methods & missing fields (#76). (8b54049c)
- FIX: Handle unknown streaming event types gracefully (#72). (28a49804)
- REFACTOR: Migrate API skills to the shared api-toolkit CLI (#74). (923cc83e)
- DOCS: Update README with SOTA models and Responses API (#68). (ff6d2774)
- CHORE: Add .pubignore to exclude .agents/ and specs/ from publishing (#78). (0ff199bf)
1.1.0 #
Added baseUrl and defaultHeaders parameters to withApiKey constructors, aligned Responses API models with the latest OpenAI spec, fixed null index handling in ToolCallDelta.fromJson, and improved hashCode for list fields.
- FEAT: Add baseUrl and defaultHeaders to withApiKey constructors (#57). (f0dd0caa)
- FIX: Align Responses API models with current OpenAI spec (#59). (a55a67b7)
- FIX: Handle null index in ToolCallDelta.fromJson (#64). (9b3df8a4)
- FIX: Use Object.hashAll() for list fields in hashCode (#65). (4b19abd9)
- REFACTOR: Unify equality_helpers.dart across packages (#67). (ec2897f8)
1.0.1 #
1.0.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
TL;DR: Complete reimplementation with a new architecture, minimal dependencies, resource-based API, and improved developer experience. Hand-crafted models (no code generation), interceptor-driven architecture, comprehensive error handling, full OpenAI API coverage, and alignment with the latest OpenAI OpenAPI (2026-02-19).
What's new #
- Resource-based API organization:
client.chat.completions— Chat completion creation, streamingclient.responses— Responses API (recommended unified API)client.conversations— Conversation managementclient.embeddings— Text embeddingsclient.audio.speech/audio.transcriptions/audio.translations— Audio APIsclient.images— Image generation, editing, variationsclient.files/client.uploads— File and large upload managementclient.batches— Batch processingclient.models— Model listing and retrievalclient.moderations— Content moderationclient.fineTuning.jobs— Fine-tuning job managementclient.beta.assistants/beta.threads/beta.vectorStores— Assistants API (Beta)client.videos— Sora video generationclient.containers— Code execution containersclient.chatkit— ChatKit sessions and threads (Beta)client.evals— Model evaluationclient.realtime— WebSocket-based Realtime APIclient.completions— Legacy text completions
- Architecture:
- Interceptor chain (Auth → Logging → Error → Transport with Retry wrapper).
- Authentication: API key, organization+key, or Azure via
AuthProviderinterface (ApiKeyProvider,OrganizationApiKeyProvider,AzureApiKeyProvider). - Retry with exponential backoff + jitter (only for idempotent methods on 429, 5xx, timeouts).
- Abortable requests via
abortTriggerparameter. - SSE streaming parser for real-time responses.
- WebSocket support for Realtime API.
- Central
OpenAIConfig(timeouts, retry policy, log level, baseUrl, auth).
- Hand-crafted models:
- No code generation dependencies (no freezed, json_serializable).
- Minimal runtime dependencies (
http,logging,meta,web_socketonly). - Immutable models with
copyWithusing sentinel pattern. - Full type safety with sealed exception hierarchy.
- Improved DX:
- Simplified message creation (e.g.,
ChatMessage.user(),ChatMessage.system()). - Explicit streaming methods (
createStream()vscreate()). - Response helpers (
.text,.hasToolCalls,.allToolCalls). ChatStreamAccumulatorand extension methods (collectText(),textDeltas(),accumulate()).- Rich logging with field redaction for sensitive data.
- Simplified message creation (e.g.,
- Full API coverage:
- Chat completions with tool calling, vision, structured outputs, audio, and predicted outputs.
- Responses API with built-in tool output types (web search, file search, code interpreter, image generation, MCP).
- Videos API (Sora) for video generation and remixing.
- Conversations API for multi-turn conversation management.
- Containers API for isolated code execution environments.
- ChatKit API for session and thread management (Beta).
- Evals API with multiple grader types and data source configurations.
- Realtime API for WebSocket-based audio conversations.
- Full Assistants, Threads, Messages, Runs, and Vector Stores API (Beta, separate import).
Breaking Changes #
- Resource-based API: Methods reorganized under strongly-typed resources:
client.createChatCompletion()→client.chat.completions.create()client.createChatCompletionStream()→client.chat.completions.createStream()client.createEmbedding()→client.embeddings.create()client.createImage()→client.images.generate()client.createSpeech()→client.audio.speech.create()client.createTranscription()→client.audio.transcriptions.create()client.createFineTuningJob()→client.fineTuning.jobs.create()client.uploadFile()→client.files.upload()client.createBatch()→client.batches.create()
- Model class renames:
CreateChatCompletionRequest→ChatCompletionCreateRequestChatCompletionMessage.user(content: ChatCompletionUserMessageContent.string('...'))→ChatMessage.user('...')ChatCompletionMessage.system(content: '...')→ChatMessage.system('...')ChatCompletionTool(type: ..., function: FunctionObject(...))→Tool.function(...)ChatCompletionModel.modelId('gpt-4o')→'gpt-4o'(plain string)EmbeddingInput.string('...')→EmbeddingInput.text('...')CreateImageRequest→ImageGenerationRequestImageSize.v1024x1024→ImageSize.size1024x1024
- Import structure: Assistants and Realtime APIs moved to separate entry points:
import 'package:openai_dart/openai_dart_assistants.dart'for Assistants, Threads, Messages, Runs, Vector Storesimport 'package:openai_dart/openai_dart_realtime.dart'for Realtime API
- Configuration: New
OpenAIConfigwithAuthProviderpattern:OpenAIClient(apiKey: 'KEY')→OpenAIClient(config: OpenAIConfig(authProvider: ApiKeyProvider('KEY')))- Or use
OpenAIClient.fromEnvironment()to readOPENAI_API_KEY. - Or use
OpenAIClient.withApiKey('KEY')for quick setup.
- Exceptions: Replaced
OpenAIClientExceptionwith typed hierarchy:ApiException,AuthenticationException,RateLimitException,NotFoundException,RequestTimeoutException,AbortedException,ConnectionException,ParseException,StreamException.
- Streaming: Use convenience getters and extension methods:
event.choices.first.delta.content→event.textDelta.map()callbacks → Dart 3 switch expressions oristype checks.
- Nullable fields:
Model.created,Model.ownedBy,ChatCompletion.createdare now nullable for OpenAI-compatible provider support. - Session cleanup:
endSession()→close(). - Dependencies: Removed
freezed,json_serializable; now minimal (http,logging,meta,web_socket).
See MIGRATION.md for step-by-step examples and mapping tables.
Commits #
- BREAKING FEAT: Complete v1.0.0 reimplementation (#24). (ed68e31b)
- BREAKING FEAT: Add type-safe ResponseInput and convenience factories (#29). (015307ea)
- BREAKING FIX: Make created and ownedBy nullable for provider compatibility (#30). (5c56f005)
- FEAT: Add Skills API, response compaction, JSON image editing, and batch endpoints (#34). (98128ade)
- FIX: Pre-release documentation and code fixes (#41). (5616f8f3)
- REFACTOR: Align client package architecture across SDK packages (#37). (cf741ee1)
- REFACTOR: Align API surface across all SDK packages (#36). (ed969cc7)
- DOCS: Refactors repository URLs to new location. (76835268)
0.6.1 #
- FEAT: Add image streaming and new GPT image models (#827). (1218d8c3)
- FEAT: Add ImageGenStreamEvent schema for streaming (#834). (eb640052)
- FEAT: Add ImageGenUsage schema for image generation (#833). (aecf79a9)
- FEAT: Add metadata fields to ImagesResponse (#831). (bd94b4c6)
- FEAT: Add prompt_tokens_details to CompletionUsage (#830). (ede649d1)
- FEAT: Add fine-tuning method parameter and schemas (#828). (99d77425)
- FEAT: Add Batch model and usage fields (#826). (b2933f50)
- FEAT: Add OpenRouter-specific sampling parameters (#825). (3dd9075c)
- FIX: Remove default value from image stream parameter (#829). (d94c7063)
- FIX: Fix OpenRouter reasoning type enum parsing (#810) (#824). (44ab2841)
0.6.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions.
- FIX: Correct text content serialization in CreateMessageRequest (#805). (e4569c96)
- FIX: Handle optional space after colon in SSE parser (#779). (9defa827)
- FEAT: Add OpenRouter provider routing support (#794). (6d306bc1)
- FEAT: Add OpenAI-compatible vendor reasoning content support (#793). (e0712c38)
- FEAT: Upgrade to http v1.5.0 (#785). (f7c87790)
- BREAKING BUILD: Require Dart >=3.8.0 (#792). (b887f5c6)
0.5.4+1 #
0.5.4 #
0.5.3 #
0.5.2 #
0.5.1 #
0.5.0 #
- BREAKING FEAT: Align OpenAI API changes (#706). (b8b04ca6)
- FEAT: Add support for web search, gpt-image-1 and list chat completions (#716). (269dea03)
- FEAT: Update OpenAI model catalog (#714). (68df4558)
- FEAT: Change the default value of 'reasoning_effort' from medium to null (#713). (f224572e)
- FEAT: Update dependencies (requires Dart 3.6.0) (#709). (9e3467f7)
- REFACTOR: Remove fetch_client dependency in favor of http v1.3.0 (#659). (0e0a685c)
- REFACTOR: Fix linter issues (#708). (652e7c64)
- DOCS: Fix TruncationObject docs typo. (ee5ed4fd)
- DOCS: Document Azure Assistants API base url (#626). (c3459eea)
0.4.5 #
- FEAT: Support Predicted Outputs (#613). (315fe0fd)
- FEAT: Support streaming audio responses in chat completions (#615). (6da756a8)
- FEAT: Add gpt-4o-2024-11-20 to model catalog (#614). (bf333081)
- FIX: Default store field to null to support Azure and Groq APIs (#608). (21332960)
- FIX: Make first_id and last_id nullable in list endpoints (#607). (7cfc4ddf)
- DOCS: Update OpenAI endpoints descriptions (#612). (10c66888)
- REFACTOR: Add new lint rules and fix issues (#621). (60b10e00)
- REFACTOR: Upgrade api clients generator version (#610). (0c8750e8)
0.4.3 #
- FEAT: Add support for audio in chat completions (#577). (0fb058cd)
- FEAT: Add support for storing outputs for model distillation and metadata (#578). (c9b8bdf4)
- FEAT: Support multi-modal moderations (#576). (45b9f423)
- FIX: submitThreadToolOutputsToRunStream not returning any events (#574). (00803ac7)
- DOCS: Add xAI to list of OpenAI-compatible APIs (#582). (017cb74f)
- DOCS: Fix assistants API outdated documentation (#579). (624c4128)
0.4.2+1 #
- DOCS: Add note about the new openai_realtime_dart client. (44672f0a)
0.4.2 #
0.4.1 #
0.4.0 #
- FEAT: Add support for disabling parallel tool calls (#492). (a91e0719)
- FEAT: Add GPT-4o-mini to model catalog (#497). (faa23aee)
- FEAT: Support chunking strategy in file_search tool (#496). (cfa974a9)
- FEAT: Add support for overrides in the file search tool (#491). (89605638)
- FEAT: Allow to customize OpenAI-Beta header (#502). (5fed8dbb)
- FEAT: Add support for service tier (#494). (0838e4b9)
0.3.3 #
0.3.2+1 #
0.3.2 #
0.3.1 #
0.3.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions. If you are using the Assistants API v1, please refer to the OpenAI docs to see how to migrate to v2.
0.2.1 #
- FEAT: Support for Batch API (#383). (6b89f4a2)
- FEAT: Streaming support for Assistant API (#379). (6ef68196)
- FEAT: Option to specify tool choice in Assistant API (#382). (97d7977a)
- FEAT: JSON mode in Assistant API (#381). (a864dae3)
- FEAT: Max tokens and truncation strategy in Assistant API (#380). (7153167b)
- FEAT: Updated models catalog with GPT-4 Turbo with Vision (#378). (88537540)
- FEAT: Weights & Biases integration for fine-tuning and seed options (#377). (a5fff1bf)
- FEAT: Support for checkpoints in fine-tuning jobs (#376). (69f8e2f9)
0.2.0 #
0.1.7 #
0.1.6 #
0.1.5 #
0.1.4 #
0.1.0+1 #
0.1.0 #
Caution
This release has breaking changes. See the Migration Guide for upgrade instructions. Migration guides: new factories and multi-modal
0.0.2+2 #
0.0.2 #
- FEAT: Support new models API functionality (#203). (33ebe746)
- FEAT: Support new images API functionality (#202). (fcf21daf)
- FEAT: Support new fine-tuning API functionality (#201). (f5f44ad8)
- FEAT: Support new embeddings API functionality (#200). (9b43d85b)
- FEAT: Support new completion API functionality (#199). (f12f6f57)
- FEAT: Support new chat completion API functionality (#198). (01820d69)
- FIX: Handle nullable function call fields when streaming (#191). (8f23cf16)
0.0.1 #
0.0.1-dev.1 #
- Bootstrap project