dart_openai 包为 Dart 应用程序提供了集成 OpenAI 高级 AI 模型(包括 GPT-3 和 DALL-E)的 Dart SDK。它支持与 OpenAI API 的无缝通信,使开发者能够生成文本、创建图像并实现对话式 AI 功能。该包支持 Android、iOS、macOS、Windows 和 Linux 等多个平台,非常适合跨平台应用。通过简单直接的 API 访问和清晰的文档,它简化了在 Flutter 及其他基于 Dart 的项目中集成生成式 AI 能力的过程。
适合场景
使用 GPT-3 进行文本生成
使用 DALL-E 创建图像
构建人工智能驱动的聊天机器人
将人工智能集成到移动和桌面应用程序中
创建内容自动化工具
主要特点
支持 GPT-3 和 DALL-E API
跨平台兼容性
简单直观的 Dart 接口
实时 API 交互
全面的错误处理
适合对象
Flutter 开发者
AI应用创作者
全栈开发人员
初创公司正在构建人工智能功能
教育或原型项目
使用建议
需要一个 OpenAI API 密钥
基于订阅应用速率限制
需要网络连接
API 响应中的潜在延迟
超出免费层级的使用成本
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
dart_openai
Unofficial Dart/Flutter SDK for the OpenAI API. Typed clients for every major API surface: Responses, Chat Completions, Realtime, Videos, Batch, Fine-tuning, Vector Stores, Evals, Administration and more. Compiles and runs on every platform: Android, iOS, macOS, Linux, Windows, web, and server-side Dart.
Every OpenAIClient owns its configuration. Run several accounts, Azure resources, or OpenAI-compatible providers side by side without global state:
final production = OpenAIClient(apiKey: 'sk-prod');
final deepseek = OpenAIClient(
apiKey: 'ds-...',
baseUrl: 'https://api.deepseek.com',
);
final localLlama = OpenAIClient(
apiKey: 'not-needed',
baseUrl: 'http://localhost:1234/v1',
);
Works with any provider that implements the OpenAI wire format: DeepSeek, LM Studio, Ollama, Groq, Together, Azure OpenAI gateways, and others.
Streaming
One SSE engine backs every streaming endpoint. It closes on [DONE], never duplicates events, and surfaces errors as exceptions instead of swallowing them.
Responses API events:
final events = client.responses.createStream(
model: 'gpt-4o',
input: 'Write a haiku about databases.',
);
awaitfor (final event in events) {
if (event['type'] == 'response.output_text.delta') {
stdout.write(event['delta']);
}
}
Chat Completions deltas:
final chunks = client.chat.createStream(model: 'gpt-4o', messages: messages);
awaitfor (final chunk in chunks) {
stdout.write(chunk.choices.first.delta?.content);
}
Images emit partial results as they render (createStream), and stored completions support retrieval and listing.
Not planned: Assistants v1 and Threads (superseded by the Responses API), ChatKit.
Resilience
Requests retry automatically on transient failures (connection errors, HTTP 408/429/5xx). GET requests always retry; POST retries only on rate limits and server errors. Backoff is exponential with jitter and the server's Retry-After header takes precedence.
Streaming has an idle watchdog: a connection that stops delivering bytes fails with StreamTimedOutException after the request timeout instead of hanging forever. After any call, quota is observable:
final azure = OpenAIClient(
apiKey: '<azure-key>',
azure: constOpenAIAzure(
resource: 'my-resource',
apiVersion: '2024-10-21',
deployments: {'gpt-4o': 'gpt4o-prod'},
),
);
// model is rewritten to your deployment automatically:await azure.chat.create(model: 'gpt-4o', messages: messages);
Files on every platform
Upload APIs take a platform-neutral file type — no dart:io, so the same code runs on web:
// From disk (native):final file = awaitloadOpenAIFile('training.jsonl');
await client.file.upload(file: file, purpose: 'fine-tune');
// From memory (anywhere, including web):await client.file.uploadBytes(
bytes: utf8.encode(jsonl),
fileName: 'training.jsonl',
purpose: 'fine-tune',
);
Error handling
All failures throw typed exceptions you can catch precisely:
try {
await client.chat.create(model: 'gpt-4o', messages: messages);
} onRequestFailedExceptioncatch (e) {
// Non-2xx from the API: e.message, e.statusCode
} onMissingApiKeyExceptioncatch (e) {
// No key configured for this client
} onOpenAIUnexpectedExceptioncatch (e) {
// Malformed response that is not an API error payload
}
Error payloads are normalized across providers. Whether a provider returns {"error": {"message": ...}}, a bare string error, or an HTML error page, you get a RequestFailedException with the body preserved.
Global facade equivalents: OpenAI.apiKey, OpenAI.organization, OpenAI.baseUrl, OpenAI.requestsTimeOut, plus OpenAI.showLogs and OpenAI.showResponsesLogs for request debugging.
Reasoning models (o-series, GPT-5 family): pass reasoningEffort: 'low' and use maxTokens, which maps to max_completion_tokens. Incompatible sampling parameters are rejected by the API; use extraParams to pass anything not yet modeled.
Migrating from 6.x / 7.x
Nothing breaks if you used the global facade. To adopt per-client instances, replace global configuration with construction:
8.0.0 replaces dart:io File parameters with the platform-neutral OpenAIFile type (await loadOpenAIFile(path) on native, OpenAIFile(bytes:, fileName:) anywhere), and audio.createSpeech now returns bytes.
The suite runs entirely against mocked HTTP — request shapes, SSE decoding, malformed-payload fuzzing, retry behavior. No API keys required:
dart test
Live integration tests run only when OPEN_AI_API_KEY is present in the environment.
Contributing
Bug reports and feature requests go through GitHub Issues. Pull requests welcome: keep diffs focused, add or update tests for changed behavior, and follow the existing module layout (lib/src/instance/<module>/ with models under lib/src/core/models/<module>/). Commit messages use Conventional Commits.