# Agentic Behavior Source: https://docs.dartantic.ai/agentic-behavior What makes an agent an agent is the ability to chain multiple tool calls. What makes an agent an agent is the ability to chain multiple tool calls to solve more complex problems. The dartantic `Agent` calls your tools for you automatically. You create an agent with a set of tools -- which themselves each have a callback -- and the Agent will handle the tool calls from the model and map them to the callbacks on your tools. ## Multi-Step Reasoning As an example, here's an agent defined with two tools: ```dart theme={null} // Tools that work together final tools = [ Tool( name: 'get_current_time', description: 'Get the current date and time', onCall: (_) async => {'time': '2025-01-27T10:00:00Z'}, ), Tool( name: 'find_events', description: 'Find events for a date', inputSchema: S.object(properties: { 'date': S.string(), }), onCall: (args) async => { 'events': ['Team Meeting at 11am', 'Lunch at 12pm'], }, ), ]; // Agent chains tools automatically final agent = Agent('openai', tools: tools); final result = await agent.send( 'What events do I have today? Find the current date first.' ); // Agent will: // 1. Call get_current_time → gets "2025-01-27" // 2. Extract date from response // 3. Call find_events with that date // 4. Return final answer with events ``` We're asking the agent to call both two in succession here, one to find out the current date and another to find the events associated with that date. That's multiple round trips between the agent and the model, but the ultimate response comes back from the model after it's done calling tools and has the data it needs. ## Complex Workflows Here's another example where we're configuring the agent with multiple tools that the model can choose to call or not: ```dart theme={null} // Weather + activity planning final tools = [ weatherTool, // Gets weather activityTool, // Suggests activities based on weather bookingTool, // Books the activity ]; final result = await agent.send( 'Plan an outdoor activity for tomorrow in Seattle' ); // Agent chains: weather → activity → booking ``` Here the agent calls the tools it decides it needs, potentially using the results of one to form calls to another. ## Loop Behavior Often we don't know how many tooling round-trips are going to happen, but the `Agent` implementation will keep looping until the model is done calling tools and provides its final response. ## Examples * [Agent with tools](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/agent.dart) * [Multi-tool calling](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/multi_tool_call.dart) ## Next Steps * [Tool Calling](/tool-calling) - Define custom tools * [Multi-turn Chat](/multi-turn-chat) - Maintain context * [System Messages](/system-messages) - Guide agent behavior * [Server-Side Tools](/server-side-tools) - Combine intrinsic and custom tools # Automatic Retry Source: https://docs.dartantic.ai/automatic-retry Built-in retry logic handles temporary rate limits and failures. Model provider endpoints can be busy places; sometimes an LLM request will time out. When that happens, dartantic will invoke its built-in retry logic to handle temporary rate limits and failures. ## Zero Configuration The HTTP 429 "Too Many Requests" client error response status code indicates that the client has sent too many requests within a given time period. This mechanism, known as "rate limiting," is employed by servers to prevent overload, ensure fair resource usage, and mitigate potential abuse or denial-of-service attacks. When dartantic gets a 429 response, it will retry automatically without you having to do anything: ```dart theme={null} final agent = Agent('openai'); // Automatically retries on 429 errors final result = await agent.send('Hello!'); ``` ## Timing Strategy Dartantic will use an incremental backoff algorithm along with a random "jitter" to see if it can get a response to go through. ``` Attempt 1: Immediate Attempt 2: 1s + jitter Attempt 3: 2s + jitter Attempt 4: 4s + jitter ``` ## Next Steps * [Usage Tracking](/usage-tracking) - Monitor retry costs * [Providers](/providers) - Provider-specific limits # Chatarang Source: https://docs.dartantic.ai/chatarang Interactive REPL chat application with tool calling. An interactive REPL chat application with multi-provider support and tool calling. Perfect for exploring what AI can do when given real capabilities. ## Installation ```bash theme={null} cd samples/chatarang dart pub get ``` ## Quick Start ```bash theme={null} dart run ``` ## Features * **Multi-Provider**: Switch between Google, OpenAI, and OpenRouter mid-conversation * **Tool Calling**: Built-in tools the AI can use to answer questions * **Conversation Memory**: Context persists across provider switches * **Slash Commands**: Control the app without leaving the chat ## Slash Commands | Command | Arguments | Description | | ----------- | ---------- | --------------------------------------------- | | `/help` | | Show available commands | | `/model` | `[name]` | View current model or switch to new model | | `/models` | `[filter]` | List available models (optionally filtered) | | `/tools` | | Show all available tools | | `/messages` | | Display full conversation history | | `/clear` | | Clear conversation and reset to system prompt | | `/exit` | | Quit the application | ### Model Switching Switch providers or models at any time: ``` You: /model openai:gpt-4o Model set to: openai:gpt-4o You: /model google:gemini-2.0-flash Model set to: google:gemini-2.0-flash You: /model anthropic Model set to: anthropic ``` Model formats: * `provider` - Uses provider's default model * `provider:model` - Specific model * `provider/model` - Alternative notation ### Filtering Models ``` You: /models gpt openai:gpt-4o openai:gpt-4o-mini openai:gpt-4 You: /models gemini flash google:gemini-2.0-flash google:gemini-1.5-flash ``` ### Viewing History The `/messages` command shows the full conversation including tool interactions: ``` You: /messages SYSTEM: You are a helpful assistant... You: What's the weather in Portland? google:gemini-2.0-flash: Tool.call: location-lookup({"location": "Portland, OR"}) Tool.result: location-lookup: {"postcode": "97240", ...} Tool.call: weather({"zipcode": "97240"}) Tool.result: weather: {"FeelsLikeF": "53", ...} The weather in Portland is currently 55°F with light rain. ``` ## Built-in Tools The AI can autonomously use these tools to answer your questions: ### current-time Get the current time. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | *(none)* | | | | **Returns:** ISO 8601 timestamp ``` You: What time is it? Tool.call: current-time({}) Tool.result: current-time: 2024-12-14T15:30:00.000Z google:gemini-2.0-flash: It's currently 3:30 PM. ``` ### current-date Get the current date. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | *(none)* | | | | **Returns:** ISO 8601 timestamp ``` You: What's today's date? Tool.call: current-date({}) Tool.result: current-date: 2024-12-14T00:00:00.000Z google:gemini-2.0-flash: Today is December 14th, 2024. ``` ### weather Get weather information for a US zipcode. | Parameter | Type | Required | Description | | --------- | ------ | -------- | ----------- | | `zipcode` | string | Yes | US zipcode | **Returns:** JSON with current conditions, temperature, humidity, wind, UV index **Data source:** wttr.in API ``` You: What's the weather in 97201? Tool.call: weather({"zipcode": "97201"}) Tool.result: weather: {"current_condition": [{"FeelsLikeF": "53", "humidity": "89", ...}]} google:gemini-2.0-flash: In Portland (97201), it's currently 55°F and feels like 53°F with 89% humidity. ``` ### location-lookup Get geographic data for any location query. | Parameter | Type | Required | Description | | ---------- | ------ | -------- | ---------------------- | | `location` | string | Yes | Location to search for | **Returns:** Array of location objects with coordinates, address details, place IDs **Data source:** OpenStreetMap Nominatim API ``` You: Where is the Eiffel Tower? Tool.call: location-lookup({"location": "Eiffel Tower, Paris"}) Tool.result: location-lookup: [{"lat": "48.8584", "lon": "2.2945", "display_name": "..."}] google:gemini-2.0-flash: The Eiffel Tower is located at coordinates 48.8584°N, 2.2945°E in Paris, France. ``` ### surf-web Fetch the content of a web page. | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------- | | `link` | string | Yes | URL of the web page | **Returns:** HTML content of the page ``` You: What's on example.com? Tool.call: surf-web({"link": "https://example.com"}) Tool.result: surf-web: ... google:gemini-2.0-flash: Example.com is a simple domain used for documentation examples... ``` ## Multi-Step Tool Calling Watch the AI chain tools together to solve complex questions: ``` You: what's the weather at the moda center in portland, or? Tool.call: location-lookup({ "location": "Moda Center, Portland, OR" }) Tool.result: { "postcode": "97240", ... } Tool.call: weather({ "zipcode": "97240" }) Tool.result: { "FeelsLikeF": "53", "humidity": "89", ... } google:gemini-2.0-flash: The weather at the Moda Center is currently 55°F with light rain. Wind from the south at 9 mph. ``` The AI figured out it needed to: 1. Look up the Moda Center's location to get a zipcode 2. Use that zipcode to fetch the weather 3. Synthesize the results into a natural response That's agentic behavior in action. ## Conversation Memory Context persists across the entire session, including model switches: ``` You: my name is chris google:gemini-2.0-flash: Okay, Chris. How can I help you today? You: /model openai:gpt-4o Model set to: openai:gpt-4o You: say my name openai:gpt-4o: Your name is Chris. How can I assist you further? ``` ## Environment Setup Create a `.env` file in the chatarang directory or set environment variables: ```bash theme={null} GEMINI_API_KEY=your_google_api_key OPENAI_API_KEY=your_openai_api_key OPENROUTER_API_KEY=your_openrouter_api_key ``` ### Required Keys | Provider | Environment Variable | Required | | ---------- | -------------------- | --------------------- | | Google | `GEMINI_API_KEY` | For Google models | | OpenAI | `OPENAI_API_KEY` | For OpenAI models | | OpenRouter | `OPENROUTER_API_KEY` | For OpenRouter models | You only need keys for the providers you plan to use. ## Supported Providers ### Google (Gemini) Default provider. Models include: * `google:gemini-2.0-flash` (default) * `google:gemini-1.5-pro` * `google:gemini-1.5-flash` ### OpenAI GPT models: * `openai:gpt-4o` * `openai:gpt-4o-mini` * `openai:gpt-4` ### OpenRouter Access to various models through OpenRouter: * `openrouter:anthropic/claude-3-opus` * `openrouter:meta-llama/llama-3-70b` * And many more ## Output Colors Chatarang uses colors to distinguish message types: | Color | Meaning | | ------- | ------------------- | | Blue | Your input (`You:`) | | Yellow | Model response | | Magenta | Tool calls | | Cyan | Tool results | | Red | System messages | ## Sample Session ``` $ dart run Welcome to Chatarang! Type /help for available commands. Found 42 models across 3 providers. You: /models gemini google:gemini-2.0-flash google:gemini-1.5-pro google:gemini-1.5-flash You: What can you help me with? google:gemini-2.0-flash: I can help you with a variety of tasks! I have access to several tools that let me: - Tell you the current time and date - Look up weather for any US location - Find geographic information about places - Fetch and read web pages What would you like to know? You: What's the weather like in Seattle right now? Tool.call: location-lookup({"location": "Seattle, WA"}) Tool.result: location-lookup: {"postcode": "98101", ...} Tool.call: weather({"zipcode": "98101"}) Tool.result: weather: {"current_condition": [...]} google:gemini-2.0-flash: In Seattle (98101), it's currently 48°F with overcast skies and a light drizzle. Humidity is at 82%. You: /model openai:gpt-4o Model set to: openai:gpt-4o You: What about Portland? Tool.call: location-lookup({"location": "Portland, OR"}) Tool.result: location-lookup: {"postcode": "97201", ...} Tool.call: weather({"zipcode": "97201"}) Tool.result: weather: {"current_condition": [...]} openai:gpt-4o: Portland is a bit warmer at 52°F, also with overcast conditions but no rain at the moment. You: /exit Goodbye! ``` ## Adding Custom Tools To add your own tools, edit `lib/tools.dart`: ```dart theme={null} final myTool = Tool( name: 'my-tool', description: 'Description of what the tool does', inputSchema: S.object(properties: { 'param1': S.string(description: 'First parameter'), 'param2': S.integer(description: 'Optional param'), }, required: ['param1']), onCall: (args) async { final param1 = args['param1'] as String; // Do something... return 'Result'; }, ); ``` Then add it to the `tools` list in the same file. # Contributing to dartantic_ai Source: https://docs.dartantic.ai/contributing Your contributions to dartantic_ai are welcome! Got an issue? Let's hear it. A feature request? Send it in! A PR? Even better!! ## How to Contribute an Issue If you have found a bug or have a feature request, please open an issue on the [GitHub repository](https://github.com/csells/dartantic_ai/issues). ## How to Contribute a PR ### 1. Fork and Clone 1. Fork the repository on GitHub 2. Clone your fork locally: ```bash theme={null} git clone https://github.com/csells/dartantic_ai.git cd dartantic_ai ``` ### 2. Set Up Your Development Environment Before making changes, ensure you can run the existing test suite successfully. #### Install Dependencies ```bash theme={null} dart pub get ``` #### Set Up API Keys for Testing To run the full test suite, you'll need API keys for various providers. Set these environment variables: ```bash theme={null} export OPENAI_API_KEY="your-openai-key" export ANTHROPIC_API_KEY="your-anthropic-key" export GEMINI_API_KEY="your-google-gemini-key" export MISTRAL_API_KEY="your-mistral-key" export COHERE_API_KEY="your-cohere-key" export OPENROUTER_API_KEY="your-openrouter-key" export TOGETHER_API_KEY="your-together-key" export XAI_API_KEY="your-xai-key" ``` **Note**: Ollama providers run locally and don't require API keys. ### 3. Run Tests Verify your setup by running the existing tests: ```bash theme={null} # Run all tests dart test # Run a specific test file dart test test/specific_test_file.dart # Run tests with timeout for long-running suites dart test --timeout=10m ``` All tests should pass before you make any changes. ### 4. Make Your Changes 1. Create a new branch for your feature: ```bash theme={null} git checkout -b feature/your-feature-name ``` 2. Make your changes following the existing code style and patterns 3. **Add tests for your new feature** - This is critical! ### 5. Testing Your Changes #### Test Requirements * **Every new feature must have tests** * Follow the testing philosophy in test files (no defensive programming) * Test both success cases and edge cases * Ensure your tests work across all applicable providers #### Testing Best Practices 1. **No Exception Hiding**: Let exceptions bubble up for diagnosis 2. **Provider Filtering**: Only filter by test capabilities (e.g., `ProviderTestCaps` in `run_provider_test.dart`) 3. **80/20 Rule**: Test common cases across all providers, edge cases on Google only 4. **No Duplication**: Each functionality should be tested in ONE file only ### 6. Verify Your Changes Before submitting: 1. **Run all tests** and ensure they pass: ```bash theme={null} dart test ``` 2. **Format your code**: ```bash theme={null} dart format . ``` 3. **Analyze your code**: ```bash theme={null} dart analyze ``` ### 7. Submit Your Pull Request 1. Commit your changes with a clear message: ```bash theme={null} git commit -m "feat: add support for new feature X" ``` 2. Push to your fork: ```bash theme={null} git push origin feature/your-feature-name ``` 3. Open a Pull Request on GitHub with: * Clear description of what you've added/changed * Reference to any related issues * Confirmation that all tests pass * Description of the tests you've added ## Code Style Guidelines * Follow Dart conventions and the existing code style * Use meaningful variable and function names * Add documentation comments for public APIs * Keep functions focused and single-purpose ## Need Help? If you have questions: 1. Check existing issues and discussions 2. Review the test files for examples 3. Open an issue for clarification Thank you for contributing to dartantic\_ai! # Custom Providers Source: https://docs.dartantic.ai/custom-providers Create your own providers and use them like the built-in providers. Your provider can expose a `ChatModel`, an `EmbeddingsModel` or both. ## Dependencies You do not need to depend on the `dartantic_ai` package to create a custom provider. The `dartantic_interface` package is all you need. ```yaml theme={null} dependencies: dartantic_interface: ^VERSION ``` ## Creating a Custom Provider Here's a simple example of a custom provider that exposes a `ChatModel`: ```dart theme={null} class EchoProvider extends Provider< ChatModelOptions, EmbeddingsModelOptions, MediaGenerationModelOptions > { EchoProvider() : super( name: 'echo', displayName: 'Echo', defaultModelNames: {ModelKind.chat: 'echo'}, ); @override ChatModel createChatModel({ String? name, List>? tools, double? temperature, ChatModelOptions? options, }) => EchoChatModel( name: name ?? defaultModelNames[ModelKind.chat]!, defaultOptions: options, ); @override MediaGenerationModel createMediaModel({ String? name, List? tools, MediaGenerationModelOptions? options, }) => throw UnsupportedError('Media generation not supported'); // ... other required methods } ``` ## Custom Model Here's a minimal chat model example: ```dart theme={null} class EchoChatModel extends ChatModel { EchoChatModel({required super.name, ChatModelOptions? defaultOptions}) : super(defaultOptions: defaultOptions ?? const ChatModelOptions()); @override Stream> sendStream( List messages, { ChatModelOptions? options, Schema? outputSchema, }) { // Echo back the last user message return Stream.fromIterable([ ChatResult( output: ChatMessage.fromJson( messages.last.toJson()..['role'] = 'model', ), ), ]); } } ``` With your custom provider, you can use it with an agent directly: ```dart theme={null} final agent = Agent.forProvider(EchoProvider()); final result = await agent.send('Hello!'); print(result.output); ``` ## Dynamic Provider Registration If you'd like to participate in the named lookup of providers, you can add your custom provider to the factory registry: ```dart theme={null} // Add your custom provider factory to the registry Agent.providerFactories['echo'] = EchoProvider.new; // Use it like any built-in provider final agent = Agent('echo'); final result = await agent.send('Hello!'); print(result.output); ``` Note: The registry maps provider names to factory functions (`Provider Function()`), not instances. Each time a provider is requested, a fresh instance is created. ## Examples * [Custom Provider](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/custom_provider.dart) ## Next Steps * [Providers](/providers) - Current built-in providers * [Environment Setup](/environment-setup) - Configure API keys # Custom History Providers Source: https://docs.dartantic.ai/dartantic-chat/custom-providers Build your own LLM provider for the chat widget The `ChatHistoryProvider` interface connects any LLM to `AgentChatView`: ```dart theme={null} abstract class ChatHistoryProvider implements Listenable { Stream transcribeAudio(XFile audioFile); Stream sendMessageStream(String prompt, {Iterable attachments}); Iterable get history; set history(Iterable history); } ``` Built-in providers: * **DartanticProvider**: Wraps dartantic\_ai for multi-provider support * **EchoProvider**: Minimal example, useful for testing ## Implementation Guide To build your own provider: 1. **Configuration**: Allow model creation as a parameter 2. **History**: Manage history, notify listeners, support serialization 3. **Messages**: Map `ChatMessage` and `Part` types to your LLM format 4. **LLM calls**: Implement `sendMessageStream` and `transcribeAudio` Example structure: ```dart theme={null} class MyProvider extends ChatHistoryProvider with ChangeNotifier { MyProvider({ required MyLlmModel model, Iterable? history, }) : _model = model, _history = history?.toList() ?? []; final MyLlmModel _model; final List _history; @override Stream sendMessageStream( String prompt, { Iterable attachments = const [], }) async* { final userMessage = ChatMessage.user(prompt); _history.add(userMessage); // Call your LLM here and stream the response final response = await _model.generate(prompt); _history.add(ChatMessage.model(response)); yield response; notifyListeners(); } @override Iterable get history => _history; @override set history(Iterable history) { _history.clear(); _history.addAll(history); notifyListeners(); } @override Stream transcribeAudio(XFile audioFile) async* { // Implement audio transcription yield 'Transcribed text'; } } ``` See the [EchoProvider implementation](https://github.com/csells/dartantic/tree/main/packages/dartantic_chat/blob/main/lib/src/providers/implementations/echo_provider.dart) for a complete example. # Feature Integration Source: https://docs.dartantic.ai/dartantic-chat/feature-integration Customize and extend the chat experience ## Welcome Messages Display an initial greeting: ```dart theme={null} AgentChatView( welcomeMessage: 'Hello and welcome to Dartantic Chat!', provider: DartanticProvider( agent: Agent('gemini'), ), ) ``` ## Suggested Prompts Show predefined prompts (only when no history exists): ```dart theme={null} AgentChatView( suggestions: [ 'I\'m a Star Wars fan. What should I wear for Halloween?', 'I\'m allergic to peanuts. What candy should I avoid at Halloween?', 'What\'s the difference between a pumpkin and a squash?', ], provider: DartanticProvider( agent: Agent('gemini'), ), ) ``` ## Disable Attachments and Audio Input ```dart theme={null} AgentChatView( provider: DartanticProvider(agent: Agent('gemini')), enableAttachments: false, enableVoiceNotes: false, ) ``` ## Custom Speech-to-Text Provide your own implementation: ```dart theme={null} AgentChatView( provider: DartanticProvider(agent: Agent('gemini')), speechToText: MyCustomSpeechToText(), ) ``` ## Cancel and Error Behavior Override default cancel/error handling: ```dart theme={null} AgentChatView( provider: DartanticProvider(agent: Agent('gemini')), onCancelCallback: (context) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Chat cancelled')), ); }, cancelMessage: 'Request cancelled', ) ``` ## Manage History Access and modify history via the provider: ```dart theme={null} void _clearHistory() => _provider.history = []; ``` ## Chat Serialization/Deserialization Save history: ```dart theme={null} Future _saveHistory() async { final history = _provider.history.toList(); for (var i = 0; i != history.length; ++i) { final file = await _messageFile(i); if (file.existsSync()) continue; final map = history[i].toJson(); final json = JsonEncoder.withIndent(' ').convert(map); await file.writeAsString(json); } } ``` Restore history: ```dart theme={null} Future _loadHistory() async { final history = []; for (var i = 0;; ++i) { final file = await _messageFile(i); if (!file.existsSync()) break; final map = jsonDecode(await file.readAsString()); history.add(ChatMessage.fromJson(map)); } _provider.history = history; } ``` ## Custom Response Widgets Replace default Markdown rendering: ```dart theme={null} AgentChatView( provider: _provider, welcomeMessage: _welcomeMessage, responseBuilder: (context, response) => RecipeResponseView(response), ) ``` ## Custom Styling Fully customize the appearance: ```dart theme={null} AgentChatView( provider: DartanticProvider(agent: Agent('gemini')), style: ChatViewStyle(...), ) ``` See the [styles example](https://github.com/csells/dartantic/tree/main/packages/dartantic_chat/blob/main/example/lib/styles/styles.dart) for complete options. ## Drag and Drop On desktop and web platforms, users can drag and drop files directly into the chat to attach them. The drop zone overlay can be customized: ```dart theme={null} AgentChatView( provider: DartanticProvider(agent: Agent('gemini')), style: ChatViewStyle( fileDropOverlayStyle: FileDropOverlayStyle( iconSize: 64.0, iconColor: Colors.blue, backgroundColor: Colors.blue.withOpacity(0.1), text: 'Drop files here', textStyle: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500), ), ), ) ``` Drag and drop is automatically enabled when `enableAttachments` is true (the default). It's not available on mobile platforms (Android/iOS) where users should use the attachment buttons instead. ## Rerouting Prompts Debug, log, or manipulate the connection: ```dart theme={null} AgentChatView( provider: _provider, messageSender: _logMessage, ) Stream _logMessage( String prompt, { required Iterable attachments, }) async* { debugPrint('# Sending Message'); debugPrint('## Prompt\n$prompt'); final response = _provider.sendMessageStream(prompt, attachments: attachments); final text = await response.join(); debugPrint('## Response\n$text'); yield text; } ``` # Getting Started Source: https://docs.dartantic.ai/dartantic-chat/getting-started Installation, configuration, and device permissions ## Installation Add the following dependencies to your `pubspec.yaml` file: ```sh theme={null} $ flutter pub add dartantic_chat ``` ## Configuration Get your API key from the [Google AI Studio](https://aistudio.google.com/apikey) or your preferred LLM provider. Run your app with the API key: ```bash theme={null} flutter run --dart-define=GEMINI_API_KEY=your-api-key-here ``` In your Dart code, initialize the agent: ```dart theme={null} import 'package:dartantic_ai/dartantic_ai.dart'; import 'package:dartantic_chat/dartantic_chat.dart'; const _apiKey = String.fromEnvironment('GEMINI_API_KEY'); void main() { assert(_apiKey.isNotEmpty, 'GEMINI_API_KEY not provided via --dart-define'); Agent.environment['GEMINI_API_KEY'] = _apiKey; runApp(const App()); } ``` Then create your chat interface: ```dart theme={null} class ChatPage extends StatelessWidget { const ChatPage({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('Chat')), body: AgentChatView( provider: DartanticProvider( agent: Agent('gemini'), ), ), ); } ``` For a complete usage example, check out the [`gemini.dart` sample](https://github.com/csells/dartantic/tree/main/packages/dartantic_chat/blob/main/example/lib/gemini/gemini.dart). ## Using Other LLM Providers dartantic\_ai supports multiple providers. Set the appropriate API key and configure the Agent: ```dart theme={null} // OpenAI Agent.environment['OPENAI_API_KEY'] = openaiKey; final agent = Agent('openai-responses:gpt-4o'); // Anthropic Agent.environment['ANTHROPIC_API_KEY'] = anthropicKey; final agent = Agent('anthropic:claude-3-5-sonnet'); // Ollama (local, no API key needed) final agent = Agent('ollama:llama3.2'); ``` ## Device Permissions To enable your users to take advantage of features like voice input and media attachments, ensure that your app has the necessary permissions: ### Network Access On macOS, add the following to your `*.entitlements` files: ```xml theme={null} ... com.apple.security.network.client ``` On Android, ensure your `AndroidManifest.xml` contains: ```xml theme={null} ... ``` ### Clipboard Access To enable copying and pasting images and other custom data to and from the Android clipboard, add the following content provider to your `AndroidManifest.xml` inside the `` tag: ```xml theme={null} ... ... ``` Be sure to replace `` with your actual package name (e.g., `com.example.myapp`). ### Other Permissions * **Microphone access:** To enable voice input, update configs according to the [permission and setup instructions](https://pub.dev/packages/record#setup-permissions-and-others) for `package:record`. * **File selection:** To enable file attachments, follow the [usage instructions](https://pub.dev/packages/file_selector#usage) for `package:file_selector`. * **Image selection:** To enable taking or selecting pictures, refer to the [installation instructions](https://pub.dev/packages/image_picker#installation) for `package:image_picker`. ## Running Examples Provide your API key via `--dart-define`: ```bash theme={null} cd packages/dartantic_chat/example flutter run --dart-define=GEMINI_API_KEY=your-api-key-here ``` See the [example apps](https://github.com/csells/dartantic/tree/main/packages/dartantic_chat/tree/main/example/lib). # Overview Source: https://docs.dartantic.ai/dartantic-chat/index Flutter chat UI widgets for AI applications The dartantic\_chat package provides the widgets to make it easy to add an AI chat window to your Flutter app. The package is organized around an abstract chat history provider API that makes it easy to swap out the agentic SDK or REST endpoint that you'd like your chat widget to use. Out of the box, it comes with support for [dartantic\_ai](https://pub.dev/packages/dartantic_ai), which provides access to multiple LLM providers including Google Gemini, OpenAI, Anthropic, Mistral, Cohere, Ollama, OpenRouter, and xAI (Grok). On Flutter you can also use [`dartantic_firebase_ai`](https://pub.dev/packages/dartantic_firebase_ai) for Gemini through Firebase AI Logic. Dartantic Chat Screenshot ## Key Features * **Multi-turn chat:** Maintains context across multiple interactions. * **Streaming responses:** Displays AI responses in real-time as they're generated. * **Rich text display:** Supports formatted text in chat messages. * **Voice input:** Allows users to input prompts using speech. * **Multimedia attachments:** Enables sending and receiving various media types. * **Drag and drop:** Drop files directly into the chat on desktop and web platforms. * **Custom styling:** Offers extensive customization to match your app's design. * **Chat serialization/deserialization:** Store and retrieve conversations between app sessions. * **Custom response widgets:** Introduce specialized UI components to present LLM responses. * **Pluggable LLM support:** Implement a simple interface to plug in your own LLM. * **Cross-platform support:** Compatible with Android, iOS, web, and macOS platforms. * **Slash commands:** Define custom commands triggered by typing `/` in the chat input, with filtering and keyboard navigation. * **Function calling/Tools:** Support for LLM function calling via dartantic\_ai tools. # User Experience Source: https://docs.dartantic.ai/dartantic-chat/user-experience Built-in chat features and interactions The `AgentChatView` widget is the entry point for the interactive chat experience. Hosting an instance enables these features automatically: * **Multiline text input**: Paste long text or insert new lines * **Voice input**: Input prompts using speech * **Multimedia input**: Take pictures, send images, attach files and URLs * **Image zoom**: Tap thumbnails to zoom * **Copy to clipboard**: Copy message text * **Paste from clipboard**: Paste text or images from the clipboard * **Message editing**: Edit the most recent message * **Material and Cupertino**: Adapts to both design languages ## Multiline Text Input Submitting prompts: * **Mobile**: Tap the **Submit** button * **Web/Desktop**: Press **Enter** or tap the **Submit** button Embedding newlines: * **Mobile**: Tap Return key on the virtual keyboard * **Web/Desktop**: Press `Shift+Enter` ## Voice Input Tap the **Mic** button (visible when no text entered) to start recording. Select **Stop** to translate voice input to text, which can then be edited and submitted. ## Multimedia Input Select the **Plus** button to choose from **Take Photo**, **Image Gallery**, **Attach File**, and **Attach Link** options. ## Image Zoom Tap an image thumbnail to zoom. Press **Esc** or tap outside to dismiss. ## Copy to Clipboard On desktop/web, select text to copy, or use the **Copy** button on hover. On mobile, long-tap a message and choose Copy. ## Pasting from Clipboard Users can paste content using standard keyboard shortcuts or context menus: * **Text**: Paste formatted or plain text * **Images**: Paste images (PNG, JPEG, GIF, WebP, etc.) The input field automatically detects content type and adds images/files as attachments. On some platforms, you may need to grant clipboard access permissions for paste functionality to work with certain content types. See the [clipboard access](/dartantic-chat/getting-started#clipboard-access) section for more information. ## Message Editing On desktop, tap the **Edit** button alongside **Copy** for your most recent prompt. On mobile, long-tap and select **Edit**. ## Material and Cupertino `AgentChatView` supports both Material and Cupertino apps. Theming is controlled via the `style` property. # Dartantic CLI Source: https://docs.dartantic.ai/dartantic-cli Command-line interface for the Dartantic framework. A full-featured command-line interface for the Dartantic framework. Think of it as `curl` for AI: scriptable, composable, and ready for shell pipelines. ## Installation ```bash theme={null} cd samples/dartantic_cli dart pub get ``` ## Quick Start ```bash theme={null} # Simple question dartantic -p "What is 2+2?" # Use a specific provider dartantic -a anthropic -p "Explain recursion in one sentence" # Pipe input echo "Summarize this: Dart is a client-optimized language" | dartantic # Attach files dartantic -p "Describe this image: @photo.jpg" ``` ## Commands | Command | Description | | -------------- | ------------------------------------ | | `chat` | Send a chat prompt (default) | | `generate` | Generate media (images, PDFs, CSVs) | | `embed create` | Create embeddings from documents | | `embed search` | Semantic search over embeddings | | `models` | List available models for a provider | ## Global Options Global options must be placed **before** the command name: ```bash theme={null} dartantic [global-options] [command] [command-options] ``` | Option | Short | Type | Default | Description | | ------------------ | ----- | ------ | --------------------------- | ------------------------------------ | | `--agent` | `-a` | string | google | Agent name or model string | | `--settings` | `-s` | string | \~/.dartantic/settings.yaml | Path to settings file | | `--cwd` | `-d` | string | current directory | Working directory for relative paths | | `--output-dir` | `-o` | string | cwd | Output directory for generated files | | `--verbose` | `-v` | flag | false | Show token usage stats | | `--no-thinking` | | flag | false | Disable extended thinking | | `--no-server-tool` | | multi | | Disable server-side tools by name | | `--no-color` | | flag | false | Disable colored output | | `--version` | | flag | | Show CLI version | | `--help` | `-h` | flag | | Show help text | **Important**: Global options must come before the command: ```bash theme={null} # Correct dartantic -a openai -p "Hello" dartantic -v chat -p "Hello" # Incorrect - causes errors dartantic chat -a openai -p "Hello" ``` ## Chat Command Send a prompt to an AI agent and receive a streaming response. This is the default command. ### Options | Option | Short | Type | Description | | ----------------- | ----- | ------ | --------------------------------- | | `--prompt` | `-p` | string | Prompt text or @filename | | `--output-schema` | | string | JSON Schema for structured output | | `--temperature` | `-t` | float | Model temperature (0.0-1.0) | ### Examples ```bash theme={null} # Basic chat (google is the default provider) dartantic -p "What is the capital of France?" # Different providers dartantic -a openai -p "Hello from GPT-4o" dartantic -a anthropic -p "Hello from Claude" dartantic -a ollama -p "Hello from local Llama" # Model strings for specific models dartantic -a "google:gemini-2.5-flash" -p "Quick response please" dartantic -a "openai?chat=gpt-4o&embeddings=text-embedding-3-small" -p "Hi" # File attachments dartantic -p "Summarize this: @document.txt" dartantic -p "Compare these: @file1.txt and @file2.txt" dartantic -p "What's in this image? @screenshot.png" # Structured JSON output dartantic -p "List 3 colors" --output-schema '{"type":"array","items":{"type":"string"}}' # Control temperature dartantic -t 0.9 -p "Write a creative story opening" # Verbose mode (shows token usage) dartantic -v -p "Hello" # From stdin echo "Your prompt" | dartantic cat prompt.txt | dartantic ``` ### Audio Transcription Google agents support audio transcription natively. Attach an audio file with `@filename` syntax and request transcription in your prompt. **Plain text transcription:** ```bash theme={null} # Transcribe audio to text dartantic -a google chat \ -p "Transcribe this audio file: @audio.m4a" ``` **JSON transcription with word-level timestamps:** ```bash theme={null} # Get structured transcription with timing data dartantic -a google chat \ --output-schema '{ "type": "object", "properties": { "transcript": {"type": "string"}, "words": { "type": "array", "items": { "type": "object", "properties": { "word": {"type": "string"}, "start_time": {"type": "number"}, "end_time": {"type": "number"} } } } } }' \ -p "Transcribe this audio with word-level timestamps: @audio.m4a" ``` **Example output:** ```json theme={null} { "transcript": "Hello and welcome to Dartantic.", "words": [ {"word": "Hello", "start_time": 0.0, "end_time": 0.55}, {"word": "and", "start_time": 0.6, "end_time": 0.7}, {"word": "welcome", "start_time": 0.7, "end_time": 1.25}, {"word": "to", "start_time": 1.25, "end_time": 1.45}, {"word": "Dartantic", "start_time": 1.7, "end_time": 2.4} ] } ``` **Note:** Audio transcription is currently only supported by Google Gemini models. ### OCR (Optical Character Recognition) Google agents support OCR for extracting text from images. Attach an image containing text with `@filename` syntax and request text extraction in your prompt. **Text extraction from images:** ```bash theme={null} # Extract text from an image dartantic -a google chat \ -p "Extract all text from this image. Preserve the formatting: @document.png" ``` **Example output:** ``` Dartantic Overview Welcome to Dartantic! The dartantic_ai package is an agent framework inspired by pydantic-ai... ``` **Use cases:** * Extract text from scanned documents * Read text from screenshots * Process forms and receipts * Analyze documents with complex layouts **Note:** OCR is supported by Google Gemini, OpenAI, and Anthropic vision models. For specialized OCR with extremely high accuracy, Mistral offers a dedicated OCR model (`mistral-ocr-3-25-12`) which will be supported once the SDK adds vision capabilities. ## Generate Command Generate media content (images, PDFs) based on a prompt. Supports native image editing by passing existing images as attachments. ### Options | Option | Short | Type | Required | Description | | ---------- | ----- | ------ | -------- | ---------------------------------- | | `--prompt` | `-p` | string | No | Prompt text or @filename | | `--mime` | | multi | Yes | MIME type to generate (repeatable) | ### Examples ```bash theme={null} # Generate an image dartantic generate --mime image/png -p "A minimalist robot logo" # Generate to a specific directory dartantic generate --mime image/png -p "A sunset" -o ./images/ # Edit an existing image (native image editing with Google Imagen) dartantic generate -a google --mime image/png \ -p "Colorize this black and white drawing. Make it vibrant. @robot_bw.png" # Generate a PDF dartantic generate -a openai-responses --mime application/pdf \ -p "Create a one-page report about AI trends" # Generate CSV data dartantic generate -a openai-responses --mime text/csv \ -p "Sample user data with name, email, age columns" # Generate multiple formats dartantic generate -p @prompt.txt --mime image/jpeg --mime image/png ``` **Note:** Image editing works by attaching an existing image to the prompt using `@filename` syntax. Google uses native Imagen editing, while OpenAI and Anthropic use code execution to process the image. ## Embeddings Commands ### embed create Create embeddings from text files. ```bash theme={null} dartantic embed create [options] ``` | Option | Type | Default | Description | | ----------------- | ---- | ------- | ------------------------ | | `--chunk-size` | int | 512 | Chunk size in characters | | `--chunk-overlap` | int | 100 | Overlap between chunks | ```bash theme={null} # Create embeddings dartantic embed create doc1.txt doc2.txt > embeddings.json # Custom chunk settings dartantic embed create --chunk-size 256 --chunk-overlap 50 *.txt > small-chunks.json ``` **Output format:** ```json theme={null} { "model": "google", "created": "2024-12-14T15:30:00Z", "chunk_size": 512, "chunk_overlap": 100, "documents": [ { "file": "doc.txt", "chunks": [ { "text": "chunk content", "vector": [0.1, 0.2, ...], "offset": 0 } ] } ] } ``` ### embed search Semantic search over embeddings. ```bash theme={null} dartantic embed search -q ``` | Option | Short | Type | Required | Description | | --------- | ----- | ------ | -------- | ------------ | | `--query` | `-q` | string | Yes | Search query | ```bash theme={null} # Semantic search dartantic embed search -q "machine learning concepts" embeddings.json # Search with scores dartantic -v embed search -q "neural networks" embeddings.json # Search directory of JSON files dartantic embed search -q "API usage" ./embeddings/ ``` **Output format:** ```json theme={null} { "query": "search term", "results": [ { "file": "doc.txt", "text": "matching text...", "offset": 125, "similarity": 0.87 } ] } ``` ## Models Command List available models for a provider. ```bash theme={null} # Default provider (google) dartantic models # Specific provider dartantic -a openai models dartantic -a anthropic models ``` **Output:** ``` Provider: Google (google) Chat Models: gemini-2.5-flash gemini-1.5-pro Embeddings Models: text-embedding-004 Media Models: imagen-3 ``` ## Settings File Create `~/.dartantic/settings.yaml` to define custom agents and defaults. ### Schema **Root level:** | Field | Type | Default | Description | | --------------- | ------- | -------------------- | --------------------------------- | | `default_agent` | string | google | Default agent if none specified | | `thinking` | boolean | false | Enable extended thinking globally | | `server_tools` | boolean | true | Enable server-side tools | | `chunk_size` | int | 512 | Default chunk size for embeddings | | `chunk_overlap` | int | 100 | Default overlap between chunks | | `agents` | map | Agent configurations | | **Agent configuration (agents.\):** | Field | Type | Required | Description | | --------------- | ------- | -------- | ------------------------------------ | | `model` | string | Yes | Model string (e.g., `openai:gpt-4o`) | | `system` | string | No | System prompt | | `thinking` | boolean | No | Enable extended thinking | | `server_tools` | boolean | No | Enable server-side tools | | `output_schema` | object | No | JSON Schema for structured output | | `api_key_name` | string | No | Environment variable for API key | | `base_url` | string | No | Override provider's base URL | | `headers` | map | No | Custom HTTP headers | | `mcp_servers` | list | No | MCP server configurations | **MCP server configuration:** | Field | Type | Use | Description | | ------------------- | ------ | ------ | --------------------- | | `name` | string | Both | Server identifier | | `url` | string | Remote | HTTP server URL | | `headers` | map | Remote | Custom HTTP headers | | `command` | string | Local | Command to execute | | `args` | list | Local | Command arguments | | `environment` | map | Local | Environment variables | | `working_directory` | string | Local | Working directory | ### Full Example ```yaml theme={null} # Global defaults default_agent: coder thinking: true server_tools: true chunk_size: 512 chunk_overlap: 100 agents: # Simple agent with just model default: model: google # Coding assistant coder: model: anthropic:claude-sonnet-4-20250514 system: | You are an expert software engineer. Write clean, well-documented code. # Fast responses quick: model: google:gemini-2.5-flash thinking: false # Entity extraction with structured output extractor: model: openai:gpt-4o output_schema: type: object properties: entities: type: array items: type: object properties: name: { type: string } type: { type: string } required: [entities] # Research agent with MCP tools (remote) research: model: anthropic:claude-sonnet-4-20250514 mcp_servers: - name: context7 url: https://mcp.context7.com/mcp headers: CONTEXT7_API_KEY: "${CONTEXT7_API_KEY}" # Agent with local MCP server filesystem: model: google mcp_servers: - name: filesystem command: npx args: ["-y", "@anthropic/mcp-server-filesystem", "/tmp"] # Custom provider endpoint custom: model: openai:gpt-4o-mini base_url: https://api.custom-provider.com/v1 headers: X-Custom-Header: value ``` Then use them: ```bash theme={null} dartantic -a coder -p "Write a binary search in Rust" dartantic -a extractor -p "John Smith works at Acme Corp" dartantic -a research -p "Find documentation about hooks" ``` ### Environment Variable Substitution Use `${VAR_NAME}` syntax for environment variables: ```yaml theme={null} agents: custom: model: openai headers: Authorization: "Bearer ${MY_API_KEY}" ``` ## Model String Formats | Format | Example | Description | | -------------- | ------------------------------------------------------ | ----------------------------- | | Provider only | `openai` | Uses provider's default model | | Provider:model | `openai:gpt-4o` | Legacy colon notation | | Provider/model | `openai/gpt-4o` | Slash notation | | URI params | `openai?chat=gpt-4o&embeddings=text-embedding-3-small` | Multiple models | | Agent name | `coder` | Lookup in settings file | ## DotPrompt Templates Use `.prompt` files for reusable templates with variable substitution: ```yaml theme={null} # math.prompt --- model: google input: default: operation: add --- Calculate: What is 5 {{operation}} 3? ``` ```bash theme={null} # Uses default (add) dartantic -p @math.prompt # Override variable dartantic -p @math.prompt operation=multiply ``` ### Template Features * YAML frontmatter with `---` delimiters * `model:` field overrides the agent's model * `input:` section defines variable defaults * `{{variable}}` placeholders use Mustache syntax * Variables passed via CLI: `name=value` ## Exit Codes | Code | Name | Meaning | | ---- | ------------------ | ------------------------------------ | | 0 | success | Command executed successfully | | 1 | generalError | General execution error | | 2 | invalidArguments | Invalid arguments or missing options | | 3 | configurationError | Settings file error | | 4 | apiError | Provider API error | | 5 | networkError | Network connectivity error | ## Environment Variables ```bash theme={null} # Set default agent export DARTANTIC_AGENT=anthropic # Enable debug logging export DARTANTIC_LOG_LEVEL=FINE # API keys (standard pattern) export OPENAI_API_KEY="sk-..." export ANTHROPIC_API_KEY="sk-ant-..." export GEMINI_API_KEY="..." ``` ## Agent Resolution Order 1. CLI `--agent` flag (highest priority) 2. Environment variable `DARTANTIC_AGENT` 3. Settings file `default_agent` field 4. Direct provider name (google, openai, etc.) 5. 'google' (final default) # Embeddings Source: https://docs.dartantic.ai/embeddings Some providers produce embeddings as well as chat responses. An AI embedding is a numerical vector representation of data (like text, images, or audio) that captures its meaning and context, allowing AI models to understand and work with complex, unstructured information. By converting diverse data types into numbers, embeddings place similar items close together in a high-dimensional space, making it easier for algorithms to find patterns, perform searches, and group information based on semantic relationships rather than just keyword matches. Dartantic has full support for creating embeddings using providers that expose embeddings models. ## Basic Usage You can turn a string into a embedding using one of the `embedXxx` methods. The `embedQuery` method works on a single string and is generally meant for lookups (which we'll see later). The `embedDocuments` method works on a batch of strings. ```dart theme={null} final agent = Agent('openai'); // Single text final result = await agent.embedQuery('Hello world'); print(result.embeddings.length); // 1536 // Multiple texts final responsesAgent = Agent('openai-responses'); final results = await responsesAgent.embedDocuments([ 'Machine learning', 'Deep learning', 'Neural networks' ]); ``` Strings for embeddings are length-limited as per the underlying model, so you'll have to split larger strings according to the requirements for that model. ## Similarity There are several ways to do searches with embeddings, many of the advanced ones beyond the scope of this documentation, but one simple, built-in way is via cosine similarity. Cosine similarity is a metric that measures the angle between two non-zero vectors to determine their similarity, with a score of 1 meaning they point in the same direction, 0 meaning they are unrelated, and -1 meaning they point in opposite directions. What this means for embeddings is cosine similarity useful for doing searches: the higher the number, the closer the match. ```dart theme={null} // Compare two texts final embed1 = await agent.embedQuery('cat'); final embed2 = await agent.embedQuery('dog'); final similarity = EmbeddingsModel.cosineSimilarity( embed1.embeddings, embed2.embeddings, ); print(similarity); // 0.8234 ``` ## Search Example It's pretty typical to use `embedDocuments` to calculate embeddings for documents to be searched against via `embedQuery` like so: ```dart theme={null} // Find most similar final query = await agent.embedQuery('programming'); final docs = await agent.embedDocuments([ 'Dart language', 'Cooking recipes', 'Python coding' ]); // Get similarities final sims = docs.embeddings.map((e) => EmbeddingsModel.cosineSimilarity(query.embeddings, e) ).toList(); // Find best match final best = sims.indexOf(sims.reduce(max)); print('Best match: index $best'); ``` Some embedding models have the same underlying implementation for calculating query vs. documentation embeddings, but following this pattern will always get you to the right place. ## Configuration Different embedding models from different providers have different options, e.g. it's common to be able to change the default size of the calculated embeddings vector. ```dart theme={null} // Custom model Agent('openai?embeddings=text-embedding-3-large'); // Reduce dimensions (OpenAI / OpenAI Responses) final agent = Agent( 'openai-responses', embeddingsModelOptions: OpenAIEmbeddingsModelOptions( dimensions: 256, // Smaller vectors ), ); // Reduce dimensions (Mistral) // Note: Custom dimensions require a compatible model like codestral-embed-2505 // The default mistral-embed model does not support custom dimensions final mistralAgent = Agent( 'mistral?embeddings=codestral-embed-2505', embeddingsModelOptions: MistralEmbeddingsModelOptions( dimensions: 256, // Smaller vectors ), ); ``` It takes longer to calculate more dimensions but a larger vector gives more accurate comparison results. Note that not all embedding models support custom dimensions - check your provider's documentation for model-specific capabilities. ## Vectors are Provider-Specific Even though the concept of embeddings and how to use them is the same across providers and many providers calculate embeddings that are the same size, an embedding calculated with one providers, e.g. Google, is NOT compatible with an embedding calcuated with another providers, e.g. OpenAI. You'll need to track the source and maintain integrity yourself per the requirements of your applications. ## Examples * [Embeddings](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/embeddings.dart) ## Next Steps * [Providers](/providers) - Embeddings support by provider # Environment Setup Source: https://docs.dartantic.ai/environment-setup Set API keys via environment variables and the providers automatically discover them. While you can configure providers with API keys manually, I wouldn't recommend it. It's much easier to just use the conventionally API key name and let your provider grab it from the environment. ## Quick Start You can just set up the API key values in your environment and let dartantic find them automatically: ```bash theme={null} # Set your API keys export OPENAI_API_KEY="sk-..." export ANTHROPIC_API_KEY="sk-ant-..." export GEMINI_API_KEY="AI..." # Use without configuration dart run ``` ```dart theme={null} // Keys are auto-discovered final agent = Agent('openai'); final result = await agent.send('Hello!'); ``` ## Provider Variable Names | Provider | Variable | Required | | ------------------- | -------------------- | -------- | | OpenAI | `OPENAI_API_KEY` | ✅ | | Anthropic | `ANTHROPIC_API_KEY` | ✅ | | Google | `GEMINI_API_KEY` | ✅ | | Mistral | `MISTRAL_API_KEY` | ✅ | | Cohere | `COHERE_API_KEY` | ✅ | | OpenRouter | `OPENROUTER_API_KEY` | ✅ | | xAI / xAI Responses | `XAI_API_KEY` | ✅ | | Ollama | None (local) | ❌ | The optional **Firebase AI** add-on ([`dartantic_firebase_ai`](https://pub.dev/packages/dartantic_firebase_ai)) does not use these environment variables; it relies on Firebase configuration, and the Google AI backend uses API keys configured in the Firebase project. ## Agent Environment The environment provided by your platform is a fall-back mechanism and it's not always available, e.g. when you're running dartantic in your Flutter web app. The first place that dartantic looks is the environment supplied by the `Agent` class itself: ```dart theme={null} // Set programmatically Agent.environment['OPENAI_API_KEY'] = 'sk-...'; Agent.environment['ANTHROPIC_API_KEY'] = 'sk-ant-...'; ``` The agent's environment is the default place for providers to look for API keys and it's available on all platforms. It's useful for loading from .env files, your cloud vendor's secrets database, [Flutter's compile-time constant mechanism](https://dart.dev/language/variables#final-and-const) or wherever fine API keys are grown. Only if the provider's key isn't found there will your platforms's environment be checked (if your platform has an environment, that is). ## Examples * [Environment setup](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/chat.dart) ## Next Steps * [Quick Start](/quick-start) - Start building * [Providers](/providers) - Available providers # Dartantic Overview Source: https://docs.dartantic.ai/index Welcome to Dartantic! The [dartantic\_ai package](https://pub.dev/packages/dartantic_ai) is an agent framework inspired by pydantic-ai and designed to make building client and server-side apps in Dart with generative AI easier and more fun! ## Why Dartantic? Dartantic was born out of frustration with not being able to easily use generative AI in my Dart and Flutter apps without doing things in a very different way based on the model I chose and the type of app I was building, i.e. GUI, CLI or server-side. It's all Dart -- why can't I use all the models with a single API across all the apps? As an example of the kinds of apps that I wanted to build, consider [CalPal](https://github.com/csells/calpal), a Flutter app that uses Dartantic to build an agentic workflow for managing a user's calendar. Check out this screenshot: CalPal screenshot *CalPal in action* In about \~300 LOC, CalPal is able to figure out the events in my schedule based on an English phrase. To do this, it first has to figure out the local date and time to understand what "today" means anyway and then uses the result of that against the Zapier MCP server connected to my Google Calendar. That multi-step tool usage is all built into Dartantic and it's what makes it an "agentic" framework. Oh, and then just for fun, I asked CalPal to add a calendar event to my calendar based on a picture of the events at my local pool. I can't imagine the person-years of effort that would've been required to build this without generative AI, but I couldn't rest until I had that kind of power for all my Dart and Flutter apps. Combine that with [pydantic-ai](https://ai.pydantic.dev/) for inspiration and Dartantic was born. Enjoy! ## What is Dartantic AI? One API, multiple provider configurations out of the box: * **Agentic behavior with multi-step tool calling:** Let your AI agents autonomously chain tool calls together to solve multi-step problems without human intervention. * **Multiple Providers Out of the Box** - OpenAI, OpenAI Responses, Google, Anthropic, Mistral, Cohere, Ollama, OpenRouter, xAI (Grok), xAI Responses, and more; optional [`dartantic_firebase_ai`](https://pub.dev/packages/dartantic_firebase_ai) for Gemini via Firebase on Flutter * **OpenAI-Compatibility** - Access to literally thousands of providers via the OpenAI API that nearly every single modern LLM provider implements * **Streaming Output** - Real-time response generation * **Typed Outputs and Tool Calling** - Uses Dart types and JSON serialization * **Multimedia Input** - Process text, images, and files * **Media Generation** - Stream images, PDFs, and other artifacts from OpenAI Responses, xAI Responses (Grok Imagine), Google Gemini (Nana Banana), and Anthropic code execution * **Embeddings** - Vector generation and semantic search * **Model Reasoning ("Thinking")** - Extended reasoning support across OpenAI Responses, xAI Responses, Anthropic, and Google * **Provider-Hosted Server-Side Tools** - Web search, file search, image generation, and code interpreter via OpenAI Responses, xAI Responses, Anthropic, and Google * **MCP Support** - Model Context Protocol server integration * **Provider Switching** - Switch between AI providers mid-conversation * **Production Ready**: Built-in logging, error handling, and retry handling * **Extensible**: Easy to add custom providers as well as tools of your own or from your favorite MCP servers Switch providers with one line of code. All models. Single API. Enjoy! ## Installation ```yaml theme={null} dependencies: dartantic_ai: ^VERSION ``` ## Quick Examples ### Basic Chat ```dart theme={null} import 'package:dartantic_ai/dartantic_ai.dart'; final agent = Agent('claude'); // or 'openai', 'gemini', etc. final result = await agent.send('Hello!'); print(result.output); ``` ### Streaming ```dart theme={null} await for (final chunk in agent.sendStream('Tell me a story')) { stdout.write(chunk.output); } ``` ### Tools ```dart theme={null} final weatherTool = Tool( name: 'get_weather', description: 'Get weather for a location', inputSchema: S.object(properties: { 'location': S.string(), }), onCall: (args) async => {'temp': 72, 'condition': 'sunny'}, ); final agent = Agent('openai', tools: [weatherTool]); final result = await agent.send("Weather in Seattle?"); ``` ### Embeddings ```dart theme={null} final agent = Agent('openai'); final embed = await agent.embedQuery('Hello world'); print(embed.embeddings.length); // 1536 ``` ### Multi-Provider Conversations ```dart theme={null} final history = []; // Start with Gemini final gemini = Agent('google'); final result1 = await gemini.send('Hi, I\'m Alice', history: history); history.addAll(result1.messages); // Switch to Claude final claude = Agent('anthropic'); final result2 = await claude.send('What\'s my name?', history: history); print(result2.output); // "Your name is Alice" ``` ## Examples See complete working examples: * [Basic chat](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/chat.dart) * [Multi-turn conversations](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/multi_turn_chat.dart) * [Tool calling](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/single_tool_call.dart) * [Multi-provider chat](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/multi_provider.dart) * [Agent with tools](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/agent.dart) ## Next Steps * [Quick Start Guide](/quick-start) * [Providers](/providers) - Available providers and capabilities * [Extended Thinking](/thinking) - Surface model reasoning alongside responses * [Server-Side Tools](/server-side-tools) - Built-in provider tools # Logging Source: https://docs.dartantic.ai/logging Show, filter and shape logging from the agent, providers, models and mappers. The dartantic\_ai package implements a comprehensive logging system using the `logging` package. All logging follows a hierarchical naming convention to provide clear operational visibility and debugging capabilities. ## Basic Usage By default, dartantic logging is disabled. You can enable logging by setting the `loggingOptions` property of the `Agent` class to an instance of the `LoggingOptions` class: ```dart theme={null} // Enable logging Agent.loggingOptions = const LoggingOptions(); final agent = Agent('openai'); await agent.send('Hello!'); // See formatted logs in console ``` ## Logging Levels The `loggingOptions` property of the `Agent` class can be set to a `LoggingOptions` object to configure the logging level. ```dart theme={null} import 'package:logging/logging.dart'; // Development - verbose output Agent.loggingOptions = LoggingOptions(level: Level.FINE); // Production - minimal output Agent.loggingOptions = LoggingOptions(level: Level.WARNING); ``` | Level | Use Case | Output | | --------------- | ----------- | -------- | | `Level.FINE` | Development | Verbose | | `Level.INFO` | General | Moderate | | `Level.WARNING` | Production | Minimal | ## Filter by String You can filter logging by a string by setting the `filter` property of the `LoggingOptions` class to a string that matches the logging output: ```dart theme={null} // Only OpenAI logs Agent.loggingOptions = LoggingOptions( filter: 'openai', onRecord: (record) => print('OpenAI: ${record.message}'), ); // Only HTTP retry logs Agent.loggingOptions = LoggingOptions(filter: 'http'); ``` ## Environment Variable Set logging without touching code by exporting `DARTANTIC_LOG_LEVEL` before you run your app. Any value accepted by `package:logging` works (`INFO`, `FINE`, `WARNING`, `OFF`, etc.): ```bash theme={null} DARTANTIC_LOG_LEVEL=FINE dart run packages/dartantic_ai/example/bin/logging.dart ``` At startup `Agent.loggingOptions` reads this environment variable and adopts the requested logging level automatically. You can still override it in code if you need more granular control. ## Examples * [Logging](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/logging.dart) ## Next Steps * [Automatic Retry](/automatic-retry) - Handle rate limits * [Usage Tracking](/usage-tracking) - Monitor costs # MCP Server Support Source: https://docs.dartantic.ai/mcp-support Connect to MCP servers running in the cloud or local processes on your machine. An MCP server (aka Model Context Protocol server), is an external service that provides data, capabilities, or tools to a Large Language Model (LLM). These servers enable LLMs to interact with other systems like databases, the internet, or local files, allowing them to perform actions, fetch information, and integrate into larger workflows by presenting their functions as tools the LLM can use. Dartantic has built-in support for mapping the tools from an MCP server, whether it's local or running in the cloud, via a built-in `McpClient` class. ## Remote MCP Servers Connect to MCP servers running in the cloud: ```dart theme={null} // Connect to remote MCP server final huggingFace = McpClient.remote( 'huggingface', url: Uri.parse('https://hf.co/mcp'), ); // Get tools from the server final tools = await huggingFace.listTools(); // Use with your agent final agent = Agent('google', tools: tools); final result = await agent.send('Who is hugging face?'); ``` ## Local MCP Servers Connect to local processes running on your machine: ```dart theme={null} final calculator = McpClient.local( 'calculator', command: 'npx', args: ['-y', '@modelcontextprotocol/server-calculator'], ); final tools = await calculator.listTools(); final agent = Agent('anthropic', tools: [...tools]); await agent.send('What is 15 multiplied by 27?'); ``` ## Combining Multiple Sources Mix local tools, MCP servers, and custom tools: ```dart theme={null} // Local tool final timeTool = Tool( name: 'local_time', description: 'Get current time', onCall: (_) async => {'time': DateTime.now().toIso8601String()}, ); // MCP servers final wiki = McpClient.remote('wiki', url: wikiUrl); final hf = McpClient.remote('hf', url: hfUrl); // Combine everything final agent = Agent('google', tools: [ timeTool, ...await wiki.listTools(), ...await hf.listTools(), ]); await agent.send('What time is it and who is hugging face?'); ``` ## Examples * [MCP Servers](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/mcp_servers.dart) ## Next Steps * [Tool Calling](/tool-calling) - Create custom tools # Media Generation Source: https://docs.dartantic.ai/media-generation Generate images, PDFs, and files using a unified API across providers. Dartantic provides a unified `generateMedia()` API that works across multiple providers. Each provider uses its own underlying mechanism (native image generation, code execution, etc.) but the API surface is consistent. ## Provider Support | Provider | Images | PDFs | CSV/Files | Mechanism | | -------------------- | ------------- | ---- | --------- | --------------------------------------------------------------- | | **OpenAI Responses** | Native + Code | Code | Code | DALL-E + Code Interpreter | | **Google** | Native + Code | Code | Code | Nano Banana Pro (`gemini-3-pro-image-preview`) + Code Execution | | **Anthropic** | Code | Code | Code | Code Interpreter (matplotlib, reportlab) | When you request an image, Dartantic routes to the provider's native image model (DALL-E for OpenAI, Nano Banana Pro for Google). For other file types, it uses each provider's code execution environment. ## Basic Usage ```dart theme={null} final agent = Agent('google'); // or 'openai-responses', 'anthropic' final result = await agent.generateMedia( 'Create a minimalist robot mascot for a developer conference.', mimeTypes: const ['image/png'], ); // Access generated assets for (final asset in result.assets) { if (asset is DataPart) { print('Generated: ${asset.name} (${asset.mimeType})'); File('output/${asset.name}').writeAsBytesSync(asset.bytes); } } ``` ## Image Editing with Attachments All providers support image editing by providing an input image as an attachment. Google uses native Imagen for high-quality editing, while OpenAI and Anthropic use code execution (PIL/Pillow): ```dart theme={null} import 'package:cross_file/cross_file.dart'; final agent = Agent('google'); // or 'openai-responses', 'anthropic' // Load the input image const imagePath = 'input/robot_bw.png'; final imageFile = XFile.fromData( await File(imagePath).readAsBytes(), path: imagePath, mimeType: 'image/png', ); final imagePart = await DataPart.fromFile(imageFile); // Edit the image final result = await agent.generateMedia( 'Colorize this black and white robot drawing. ' 'Make the robot body blue, the eyes bright green, and add ' 'orange/yellow accents.', mimeTypes: const ['image/png'], attachments: [imagePart], ); // Save the edited image for (final asset in result.assets) { if (asset is DataPart) { File('output/${asset.name}').writeAsBytesSync(asset.bytes); } } ``` **Common image editing use cases:** * **Colorization**: Add color to black and white images * **Style Transfer**: Apply artistic styles to existing images * **Object Removal**: Remove unwanted objects (inpainting) * **Background Replacement**: Change backgrounds while preserving subjects * **Enhancement**: Improve quality, lighting, or resolution ## Example MIME Types The `mimeTypes` parameter tells the provider what kind of output you want, e.g. * `image/png`, `image/jpeg` - Images * `application/pdf` - PDF documents * `text/csv` - CSV files * Other file types depend on provider code execution capabilities ## Streaming Generation Use `generateMediaStream()` to receive incremental updates: ```dart theme={null} final agent = Agent('openai-responses'); await for (final chunk in agent.generateMediaStream( 'Create a colorful abstract art piece.', mimeTypes: const ['image/png'], )) { // Check for partial/preview images in metadata final previews = chunk.metadata['image_generation'] as List?; if (previews != null) { for (final preview in previews) { final b64 = preview['partial_image_b64'] as String?; if (b64 != null) { print('Preview available at index ${preview['partial_image_index']}'); } } } // Check for completed assets if (chunk.isComplete) { for (final asset in chunk.assets) { if (asset is DataPart) { File('final.png').writeAsBytesSync(asset.bytes); } } } } ``` ## Specifying Media Models Use the model string to specify which media model to use: ```dart theme={null} // Use Nano Banana Pro explicitly for Google image generation final agent = Agent('google?media=gemini-3-pro-image-preview'); // Or combine with a chat model final agent = Agent('google?chat=gemini-3-pro-preview&media=gemini-3-pro-image-preview'); ``` The model string is passed through to the provider's API, so you can use new models as soon as they're available without waiting for a Dartantic update. ## Provider-Specific Options Each provider accepts options for customization: ### OpenAI Responses ```dart theme={null} final agent = Agent( 'openai-responses', mediaModelOptions: OpenAIResponsesMediaGenerationModelOptions( imageModel: 'gpt-image-1', // Specific image model ), ); ``` ### Google ```dart theme={null} final agent = Agent( 'google?media=gemini-3-pro-image-preview', // Use Nano Banana Pro mediaModelOptions: GoogleMediaGenerationModelOptions( aspectRatio: '16:9', // Image aspect ratio ), ); ``` ### Anthropic ```dart theme={null} final agent = Agent( 'anthropic', mediaModelOptions: AnthropicMediaGenerationModelOptions( // Uses code interpreter for all generation ), ); ``` ## Result Structure `MediaGenerationResult` contains: * `assets` - List of `Part` objects (typically `DataPart` with bytes) * `links` - List of `LinkPart` for hosted URLs (if applicable) * `messages` - Conversation messages generated during the run * `metadata` - Provider-specific metadata (previews, progress, etc.) * `isComplete` - Whether generation is finished (for streaming) ## Examples * [OpenAI Media Generation](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/media_gen/media_gen_openai.dart) * [Google Media Generation](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/media_gen/media_gen_google.dart) * [Anthropic Media Generation](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/media_gen/media_gen_anthropic.dart) ## Related Topics * [Server-Side Tools](/server-side-tools) - Lower-level access to code interpreters * [Multimedia Input](/attachments) - Send images and files to models # Migration Guide Source: https://docs.dartantic.ai/migration-guide ## Migrating from 2.x to 3.0.0 ### Thinking API Change Thinking is also stored as `ThinkingPart` in the consolidated message for history. ```dart theme={null} // Non-streaming - use result.thinking final result = await agent.send(prompt); if (result.thinking != null) { print('[[${result.thinking}]]'); } print(result.output); // Streaming - use chunk.thinking for real-time display await for (final chunk in agent.sendStream(prompt)) { if (chunk.thinking != null) stdout.write(chunk.thinking); stdout.write(chunk.output); history.addAll(chunk.messages); } ``` ### Schema API Change The `JsonSchema` class has been replaced with `Schema`: ```dart theme={null} // OLD import 'package:json_schema/json_schema.dart'; final schema = JsonSchema.create({ 'type': 'object', 'properties': { 'city': {'type': 'string'}, }, 'required': ['city'], }); // Or with builder methods: final schema = JsonSchema.object({ 'location': JsonSchema.string(description: 'The location'), 'count': JsonSchema.integer(description: 'The count'), }, required: ['location']); // NEW import 'package:dartantic_ai/dartantic_ai.dart'; // Schema is re-exported final schema = Schema.fromMap({ 'type': 'object', 'properties': { 'city': {'type': 'string'}, }, 'required': ['city'], }); // Or with builder methods (using S shorthand): final schema = S.object(properties: { 'location': S.string(description: 'The location'), 'count': S.integer(description: 'The count'), }, required: ['location']); ``` Key changes: * `JsonSchema.create({...})` becomes `Schema.fromMap({...})` * `JsonSchema.object({...})` becomes `S.object(properties: {...})` * `JsonSchema.string(...)` becomes `S.string(...)` * `JsonSchema.integer(...)` becomes `S.integer(...)` * No need to import `json_schema` package; `Schema` is re-exported from `dartantic_ai` ## Migrating from 1.x to 2.0.0 ### Exposing dartantic\_interface directly from dartantic\_ai It's no longer necessary to manually include the dartantic\_interface package. ```dart theme={null} // OLD - had to import both packages import 'package:dartantic_ai/dartantic_ai.dart'; import 'package:dartantic_interface/dartantic_interface.dart'; // NEW - one import does it all import 'package:dartantic_ai/dartantic_ai.dart'; ``` ### Provider Factory Registry Provider lookup has been moved from the `Providers` class to `Agent` static methods. Providers are now created via factory functions not cached instances. ```dart theme={null} // OLD final provider = Providers.get('openai'); final allProviders = Providers.all; Providers.providerMap['custom'] = MyProvider(); final provider2 = Providers.openai; // NEW final provider = Agent.getProvider('openai'); final allProviders = Agent.allProviders; Agent.providerFactories['custom'] = MyProvider.new; final provider2 = OpenAIProvider(); ``` ### Moved OpenAI-compat providers to example (except OpenRouter) Removed the following intrinsic providers from dartantic to the `openai_compat.dart` example: * `google-openai` * `together` * `ollama-openai` The `openrouter` OpenAI-compatible provider remains as an intrinsic provider. ### Simplified Thinking API Extended thinking (chain-of-thought reasoning) is now a first-class feature in Dartantic with a simplified, unified API across all providers that support thinking: ```dart theme={null} // OLD final agent = Agent( 'openai-responses:gpt5', chatModelOptions: OpenAIResponsesChatModelOptions( reasoningSummary: OpenAIReasoningSummary.detailed, ), ); final thinking = result.metadata['thinking'] as String?; // NEW final agent = Agent('openai-responses:gpt5', enableThinking: true); final thinking = result.thinking; ``` * Provider-specific fine-tuning options remain for advanced use cases: * `GoogleChatModelOptions.thinkingBudgetTokens` * `AnthropicChatOptions.thinkingBudgetTokens` * `OpenAIResponsesChatModelOptions.reasoningSummary` ### Removed `ProviderCaps` The `ProviderCaps` type was removed from the provider implementation and moved to a helper function in the tests. ```dart theme={null} // OLD final visionProviders = Providers.allWith({ProviderCaps.chatVision}); // NEW // use Provider.listModels() and choose via ModelInfo instead ``` ## Migrating from 0.9.7 to 1.0.0 This release went through a major refactoring to support many more providers for both chat and embeddings, as well as to support more features. The API is different in a lot of tiny ways, but the core concepts remain largely the same. This is a list of changes (some of them breaking) to help you migrate. And as long as this list is, I'm sure I've missed some. If you find something that's not here, please let me know! ### Dynamic => Static Provider factories Provider access has moved to `Agent` static methods: ```dart theme={null} // OLD (0.9.7) final provider = OpenAiProvider(); final providerFactory = Agent.providers['google']; final providerFactoryByAlias = Agent.providers['gemini']; // NEW (2.0.0) final provider1 = Agent.createProvider('openai'); final provider2 = Agent.createProvider('google'); final provider3 = Agent.createProvider('gemini'); ``` If you'd like to extend the list of providers dynamically at runtime, you can use the `providerFactories` map on the `Agent` class: ```dart theme={null} Agent.providerFactories['my-provider'] = MyProvider.new; ``` ### Agent.runXxx => Agent.sendXxx The `Agent.runXxx` methods have been renamed for consistency with chat models and the new `Chat` class: ```dart theme={null} // OLD final result = await agent.run('Hello'); final typedResult = await agent.runFor('Hello', outputSchema: schema); await for (final chunk in agent.runStream('Hello')) {...} // NEW final result = await agent.send('Hello'); final typedResult = await agent.sendFor('Hello', outputSchema: schema); await for (final chunk in agent.sendStream('Hello')) {...} ``` Also, when you're sending a prompt to the agent, instead of passing a list of messages via the messages parameter, you can pass it via the history parameter: ```dart theme={null} // OLD final result = await agent.run('Hello', messages: messages); // NEW final result = await agent.send('Hello', history: history); ``` The subtle difference is that the history is a list of previous messages before the prompt + optional attachments, which forms the new message. Love it or don't, but it made sense to me at the time... ### Agent.provider => Agent.forProvider The `Agent.provider` constructor has been renamed to `Agent.forProvider` for clarity: ```dart theme={null} // OLD final agent = Agent.provider(OpenAiProvider()); // NEW final agent = Agent.forProvider(Agent.createProvider('anthropic')); ``` ### Message => ChatMessage The `Message` type has been renamed to `ChatMessage` for consistency with chat models: ```dart theme={null} // OLD var messages = []; final response = await agent.run('Hello', messages: messages); messages = response.messages.toList(); // NEW var history = []; final response = await agent.send('Hello', history: history); history.addAll(response.messages); ``` ### toSchema => JsonSchema.create The `toSchema` method has been dropped in favor of the built-in `JsonSchema.create` method for simplicity: ```dart theme={null} // OLD final schema = { 'type': 'object', 'properties': { 'town': {'type': 'string'}, 'country': {'type': 'string'}, }, 'required': ['town', 'country'], }.toSchema(); // NEW final schema = JsonSchema.create({ 'type': 'object', 'properties': { 'town': {'type': 'string', 'description': 'Name of the town'}, 'country': {'type': 'string', 'description': 'Name of the country'}, }, 'required': ['town', 'country'], }); ``` ### systemPrompt + Message.system() => ChatMessage.system() The `systemPrompt` parameter has been removed from Agent and model constructors. It was confusing to have both a system prompt and a system message, so I've simplified the implementation to use just an optional `ChatMessage.system()` instead. In practice, you'll want to keep the system message in the history anyway, so think of this as a "pit of success" thing: ```dart theme={null} // OLD final agent = Agent( 'openai', systemPrompt: 'You are a helpful assistant.', ); final result = await agent.send('Hello'); // NEW final agent = Agent('openai'); final result = await agent.send( 'Hello', history: [ const ChatMessage.system('You are a helpful assistant.'), ], ); ``` ### Agent chat and streaming The agent now streams new messages as they're created along with the output: ```dart theme={null} final agent = Agent('openai'); final history = []; await for (final chunk in agent.sendStream('Hello', history: history)) { // collect text and messages as they're created print(chunk.output); history.addAll(chunk.messages); } ``` If you'd prefer not to collect and track the message history manually, you can use the `Chat` class to collect messages for you: ```dart theme={null} final chat = Chat(Agent('openai')); await for (final chunk in chat.sendStream('Hello')) { print(chunk.output); } // chat.history is a list of ChatMessage objects ``` ### DataPart.file(File) => DataPart.fromFile(XFile) The `DataPart.file` constructor has been replaced with `DataPart.fromFile` to support cross-platform file handling, i.e. the web: ```dart theme={null} // OLD import 'dart:io'; final part = await DataPart.file(File('bio.txt')); // NEW import 'package:cross_file/cross_file.dart'; final file = XFile.fromData( await File('bio.txt').readAsBytes(), path: 'bio.txt', ); final part = await DataPart.fromFile(file); ``` ### Model String Format Enhanced The model string format has been enhanced to support chat, embeddings and other model names using custom relative URI. This was important to be able to specify the model for chat and embeddings separately: ```dart theme={null} // OLD Agent('openai'); Agent('openai:gpt-4o'); Agent('openai/gpt-4o'); // NEW - all of the above still work plus: Agent('openai?chat=gpt-4o&embeddings=text-embedding-3-large'); ``` ### Agent.embedXxx The agent gets new `Agent.embedXxx` methods for creating embeddings for documents and queries: ```dart theme={null} final agent = Agent('openai'); final embedding = await agent.embedQuery('Hello world'); final results = await agent.embedDocuments(['Text 1', 'Text 2']); final similarity = EmbeddingsModel.cosineSimilarity(e1, e2); ``` Also, the `cosineSimilarity` method has been moved to the `EmbeddingsModel`. ### Automatic Retry The agent now supports automatic retry for rate limits and failures: ```dart theme={null} final agent = Agent('openai'); final result = await agent.send('Hello!'); // Automatically retries on 429 ``` ### Agent\(outputSchema) => sendForXxx\(outputSchema) Instead of putting the output schema on the `Agent` class, it's now on the `sendForXxx` method: ```dart theme={null} // OLD final agent = Agent>('openai', outputSchema: ...); final result = await agent.send('Hello'); // NEW final agent = Agent('openai'); final result = await agent.sendFor>('Hello', outputSchema: ...); ``` This allows you to be more flexible from message to message. ### `AgentResponse` to `ChatResult` The `AgentResponse` type has been renamed to `ChatResult`. ### DotPrompt Support Removed The dependency on [the dotprompt\_dart package](https://pub.dev/packages/dotprompt_dart) has been removed from dartantic\_ai. However, you can still use the `DotPrompt` class to parse `.prompt` files: ```dart theme={null} import 'package:dotprompt_dart/dotprompt_dart.dart'; final dotPrompt = DotPrompt(...); final prompt = dotPrompt.render(); final agent = Agent(dotPrompt.frontMatter.model!); await agent.send(prompt); ``` ### Tool Calls with Typed Output The `Agent.sendForXxx` method now supports specifying the output type of the tool call: ```dart theme={null} final provider = Agent.createProvider('openai'); // Note: ProviderCaps removed - capabilities are now model-specific // tools final agent = Agent.forProvider( provider, tools: [currentDateTimeTool, temperatureTool, recipeLookupTool], ); // typed output final result = await agent.sendFor( 'What is the time and temperature in Portland, OR?', outputSchema: TimeAndTemperature.schema, outputFromJson: TimeAndTemperature.fromJson, ); // magic! print('time: ${result.output.time}'); print('temperature: ${result.output.temperature}'); ``` Unfortunately, not all providers support this feature. You can check the provider's capabilities to see if it does. ### ChatMessage Part Helpers The `ChatMessage` class has been enhanced with helpers for extracting specific types of parts from a list: ```dart theme={null} final message = ChatMessage.system('You are a helpful assistant.'); final text = message.text; // "You are a helpful assistant." final toolCalls = message.toolCalls; // [] final toolResults = message.toolResults; // [] ``` ### Usage Tracking The agent now supports usage tracking: ```dart theme={null} final result = await agent.send('Hello'); print('Tokens used: ${result.usage.totalTokens}'); ``` ### Logging The agent now supports logging: ```dart theme={null} Agent.loggingOptions = const LoggingOptions(level: LogLevel.ALL); ``` ## Migrating from 0.9.6 to 0.9.7 ### Breaking Change: DataPart.file → DataPart.stream The `DataPart.file` constructor has been **removed** and replaced with `DataPart.stream` for file and image attachments. This change was made to enable compatibility with web and WASM platforms, where direct file access is not available. ### What you need to do * **Replace** all usages of `DataPart.file(File(...))` with `await DataPart.stream(file.openRead(), name: file.path)`. * Always provide a `name` argument for best results (especially for web/WASM). ### Before (0.9.6 and earlier) ```dart theme={null} final file = File('bio.txt'); final part = await DataPart.file(file); ``` ### After (0.9.7 and later) ```dart theme={null} final file = File('bio.txt'); final part = await DataPart.stream(file.openRead(), name: file.path); ``` ### Why? * This approach works on all Dart platforms, including web and WASM, by using streams instead of direct file APIs. * It also makes it easier to support file uploads from sources other than the local filesystem. # Multimedia Input Source: https://docs.dartantic.ai/multi-media-input Because sometimes words aren't enough—your AI needs to see what's in your fridge too. Dartantic supports multi-modal input, including text, images, PDFs and other binary attachments. You can attach local files, download files from URLs, attach raw bytes, attach links, or mix and match all of the above. ## Local Files You can attach local files to prompts you send to your agent: ```dart theme={null} // Using cross_file for cross-platform support import 'package:cross_file/cross_file.dart'; final agent = Agent('openai'); // Text file final bioFile = XFile.fromData( await File('bio.txt').readAsBytes(), path: 'bio.txt', ); final result = await agent.send( 'Can you summarize the attached file?', attachments: [await DataPart.fromFile(bioFile)], ); // Image file (the moment of truth) final fridgeFile = XFile.fromData( await File('fridge.png').readAsBytes(), path: 'fridge.png', ); final result = await agent.send( 'What food do I have on hand?', attachments: [await DataPart.fromFile(fridgeFile)], ); // "I see leftover pizza, expired milk, and... is that a science experiment?" // Responses API can request richer vision detail final responsesAgent = Agent( 'openai-responses', chatModelOptions: const OpenAIResponsesChatModelOptions( imageDetail: ImageDetail.high, ), ); await responsesAgent.send( 'Describe the fridge image with extra detail', attachments: [await DataPart.fromFile(fridgeFile)], ); ``` ## Download from URL You can download data from links: ```dart theme={null} // Download and include file from URL final urlData = await DataPart.url( Uri.parse('https://example.com/document.pdf'), ); final result = await agent.send( 'Summarize this document', attachments: [urlData], ); ``` ## Raw Bytes You can attach bytes you've already got in memory: ```dart theme={null} // Include raw bytes with mime type final bytes = Uint8List.fromList([/* your data */]); final rawData = DataPart( bytes: bytes, mimeType: 'application/pdf', ); final result = await agent.send( 'Process this data', attachments: [rawData], ); ``` ## Web URLs You an attach links w/o downloading: ```dart theme={null} // Direct URL reference (OpenAI) final result = await agent.send( 'Describe this image', attachments: [ LinkPart(Uri.parse('https://example.com/image.jpg')), ], ); ``` ## Mix and Match Attachments You can mix and match: ```dart theme={null} // Mix text and images final result = await agent.send( 'Based on the bio and fridge contents, suggest a meal', attachments: [ await DataPart.fromFile(bioFile), await DataPart.fromFile(fridgeFile), ], ); ``` ## Audio Transcription Google Gemini models support audio transcription natively through the chat interface. Simply attach an audio file and request transcription in your prompt. ### Text Transcription For simple text transcription, attach an audio file and request the transcription: ```dart theme={null} import 'dart:io'; import 'package:dartantic_ai/dartantic_ai.dart'; final agent = Agent('google'); final audioBytes = await File('audio.m4a').readAsBytes(); final result = await agent.send( 'Transcribe this audio file word for word.', attachments: [ DataPart(audioBytes, mimeType: 'audio/mp4', name: 'audio.m4a'), ], ); // Get transcription text final transcription = result.messages .expand((m) => m.parts) .whereType() .map((p) => p.text) .join('\n'); print(transcription); ``` ### Transcription with Timestamps For word-level timestamps and structured output, use typed responses with a JSON schema: ```dart theme={null} import 'dart:io'; import 'package:dartantic_ai/dartantic_ai.dart'; final agent = Agent('google'); final audioBytes = await File('audio.m4a').readAsBytes(); final schema = Schema.fromMap({ 'type': 'object', 'properties': { 'transcript': {'type': 'string'}, 'words': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'word': {'type': 'string'}, 'start_time': {'type': 'number'}, 'end_time': {'type': 'number'}, }, }, }, }, }); final result = await agent.sendFor>( 'Transcribe this audio with word-level timestamps (in seconds).', outputSchema: schema, attachments: [ DataPart(audioBytes, mimeType: 'audio/mp4', name: 'audio.m4a'), ], ); final transcription = result.output; print('Transcript: ${transcription['transcript']}'); // Access word-level timestamps for (final word in transcription['words'] as List) { final w = word as Map; print('${w['start_time']}s - ${w['end_time']}s: ${w['word']}'); } ``` ### Provider Support | Provider | Audio Transcription | Timestamps | | ---------------- | ------------------- | ------------ | | Google | ✅ Native support | ✅ Word-level | | OpenAI Responses | ❌ Not supported | ❌ | | Anthropic | ❌ Not supported | ❌ | Note: Only Google Gemini models currently support audio transcription through the chat interface. ## OCR (Optical Character Recognition) Google Gemini models support OCR for extracting text from images. Simply attach an image containing text and request extraction in your prompt. ### Text Extraction Extract text from images while preserving formatting and structure: ```dart theme={null} import 'dart:io'; import 'package:cross_file/cross_file.dart'; import 'package:dartantic_ai/dartantic_ai.dart'; final agent = Agent('google'); const imagePath = 'document.png'; final imageFile = XFile.fromData( await File(imagePath).readAsBytes(), path: imagePath, ); final result = await agent.send( 'Extract all text from this image. Preserve the formatting and structure.', attachments: [await DataPart.fromFile(imageFile)], history: [ChatMessage.system('Be precise and preserve formatting.')], ); print(result.output); // Extracted text with formatting preserved ``` ### Use Cases OCR is useful for: * Extracting text from scanned documents * Reading text from screenshots * Processing forms and receipts * Analyzing documents with complex layouts * Converting images of text to editable format ### Provider Support | Provider | OCR Support | Complex Layouts | | ---------------- | ---------------- | ---------------------- | | Google | ✅ Native support | ✅ Tables, multi-column | | OpenAI Responses | ✅ Vision models | ✅ General layout | | Anthropic | ✅ Vision models | ✅ General layout | Note: For specialized OCR tasks requiring extremely high accuracy or specific document types, consider using dedicated OCR services. Mistral also offers a specialized OCR model (`mistral-ocr-3-25-12`) for document processing, which will be supported once the SDK adds vision capabilities. ## Examples * [Multimedia chat](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/multimedia_input.dart) - includes audio transcription and OCR examples ## Next Steps * [Providers](/providers) - Check multimedia support * [Streaming Output](/streaming-output) - Stream with attachments # Multi-turn Chat Source: https://docs.dartantic.ai/multi-turn-chat Build conversations that remember context. An agent contains configuration information for what provider and model you'd like to use, what settings you want to use, what tools, etc. However, an agent has no context (aka memory) to bring from one prompt to the next. That context comes from the message history, which you manage and send to each agent along with each prompt. ## Basic Example Each response from an `Agent.sendXxx` method includes a list of new messages, which you can accumulate into the history of the conversation. ```dart theme={null} final agent = Agent('openai'); final history = []; // First turn var result = await agent.send('My name is Alice', history: history); history.addAll(result.messages); // Second turn - remembers result = await agent.send("What's my name?", history: history); history.addAll(result.messages); print(result.output); // "Your name is Alice" ``` ## Streaming Example When using streaming, you can accumulate the messages as they arrive. ```dart theme={null} final agent = Agent('openai'); final history = []; const prompt1 = 'My name is Alice.'; await for (final chunk in agent.sendStream(prompt1, history: history)) { stdout.write(chunk.output); history.addAll(chunk.messages); } stdout.writeln(); const prompt2 = 'What is my name?'; await for (final chunk in agent.sendStream(prompt2, history: history)) { stdout.write(chunk.output); history.addAll(chunk.messages); } stdout.writeln(); ``` ## Multi-Provider Chat You can pass a shared history to multiple agents, even across providers. ```dart theme={null} final history = []; final gemini = Agent('google'); var r = await gemini.send('Summarize...', history: history); print('Gemini: ${r.output}'); history.addAll(r.messages); final claude = Agent('anthropic'); r = await claude.send('Analyze...', history: history); print('Claude: ${r.output}'); history.addAll(r.messages); ``` ## With Tools When you use tools in a chat, the results are included in the history and provide context for the next request. ```dart theme={null} final agent = Agent('openai', tools: [weatherTool]); final history = []; // Tools persist across turns var r = await agent.send('Weather in NYC?', history: history); print(r.output); history.addAll(r.messages); r = await agent.send('How about LA?', history: history); print(r.output); history.addAll(r.messages); ``` ## Prompt Caching with Provider Sessions The OpenAI Responses provider attaches metadata to each response message it providers so that you do not need to pass the history around; you only need to send the new messages since the last response. This provides prompt caching and saves on network traffic. You still send messages around as normal, so your code doesn't change. Moreover, this works across multiple providers; the OpenAI Responses provider can send along all of the messages since the last response, even the request/response pairs from other providers. You can control this behavior with the `store` parameter to the `OpenAIResponsesChatModelOptions` class. ```dart theme={null} final agent = Agent( 'openai-responses', chatModelOptions: const OpenAIResponsesChatModelOptions(store: true), ); ``` When `store` is `true` (the default), the provider caches the entire conversation server-side. You can manually set `store: false` to force stateless behavior. ## Examples * [Multi-turn chat](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/multi_turn_chat.dart) * [Multi-provider conversation](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/multi_provider.dart) * [Chat with tools and history](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/chat.dart) ## Next Steps * [Tool Calling](/tool-calling) - Using tools in conversations * [Streaming Output](/streaming-output) - Real-time responses # Notes On AI Codegen Source: https://docs.dartantic.ai/notes-on-ai-codegen It is the dawn of a new age. Much of the implementation of Dartantic was written by AI. That has its upsides and downsides. The major upside is that I can produce an Agentic framework for Dart quickly and it was needed! (or at least *missing* and I **wanted** it : ). The downside is that not all of the code is what I would have written. I can't tell you how hard that is for me, but it is the dawn of a new age. On the gripping hand, the AI surprises me with things I'd have never thought of, so it feels like a wash from a quality standpoint. The main part I still write by hand is the public API. I want to ensure that dartantic has a great developer experience, mostly because I use it in my daily work building actual agentic apps. That means a great API that gives you the control you need without being too complex, great coverage of samples that shows off that power, and great docs that are easy to understand and use. I also pay close attention to the tests to triple-check that I'm testing the behavior I want to see. That's an excellent way to ensure that the AI is heading down the right path. I figure that if I can get the API, the docs, the samples and the tests right, then I can let the AI write the bulk of the code. That's worth the trade-off in turn-around time on features and bug fixes. Plus, I'm building an agentic framework, so I wanted to eat my own dogfood! If that doesn't work for you, I understand. Change is challenging, especially change of this magnitude. No hard feelings if a package written with the assistance of AI is not what you want. # Providers Source: https://docs.dartantic.ai/providers Providers for chat and embeddings models. The `dartantic_ai` package ships **10 built-in providers**. For **Flutter** apps that use Gemini through [Firebase AI Logic](https://firebase.google.com/docs/ai-logic), add the optional [`dartantic_firebase_ai`](https://pub.dev/packages/dartantic_firebase_ai) package and register it (see [Firebase AI](#firebase-ai-flutter-add-on) below). Additional OpenAI-compatible endpoints are available via the `openai_compat.dart` example. ## Provider Capabilities | Provider | Default Model | Default Embedding Model | Capabilities | Notes | | -------------------- | ----------------------------- | ------------------------ | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------- | | **OpenAI** | `gpt-4o` | `text-embedding-3-small` | Chat, Embeddings, Vision, Tools, Streaming | Full feature support | | **OpenAI Responses** | `gpt-5` | `text-embedding-3-small` | Chat, Embeddings, Vision, Tools, Streaming, Thinking | Includes built-in server-side tools | | **Anthropic** | `claude-sonnet-4-0` | - | Chat, Vision, Tools, Streaming, Thinking | Extended thinking with token budgets | | **Google** | `gemini-2.5-flash` | `text-embedding-004` | Chat, Embeddings, Vision, Tools, Streaming, Thinking | Extended thinking with dynamic budgets | | **Firebase AI** | `gemini-2.5-flash` | - | Chat, Vision, Tools, Streaming, Thinking, Media | Gemini via Firebase SDK (Flutter only) | | **Mistral** | `mistral-small-latest` | `mistral-embed` | Chat, Embeddings, Tools, Streaming | European servers | | **Cohere** | `command-r-08-2024` | `embed-v4.0` | Chat, Embeddings, Tools, Streaming | RAG-optimized | | **Ollama** | `qwen2.5:7b-instruct` | - | Chat, Tools, Streaming | Local models only | | **OpenRouter** | `google/gemini-2.5-flash` | - | Chat, Vision, Tools, Streaming | Multi-model gateway | | **xAI** | `grok-4-1-fast-non-reasoning` | - | Chat, Vision, Tools, Streaming | OpenAI-compatible chat completions; no embeddings or `temperature` in Dartantic | | **xAI Responses** | `grok-4-1-fast-non-reasoning` | - | Chat, Vision, Tools, Streaming, Thinking, Server-side tools, Media | Stateful Responses API; default image `grok-imagine-image`, video `grok-imagine-video` | **Note**: Together AI, Google-OpenAI, and Ollama-OpenAI have been moved to the `openai_compat.dart` example. You can still use them by registering them with `Agent.providerFactories`. ## Provider Configuration | Provider | Provider Prefix | Aliases | API Key | Provider Type | | -------------------- | ------------------ | -------------------- | -------------------- | ------------------------- | | **OpenAI** | `openai` | - | `OPENAI_API_KEY` | `OpenAIProvider` | | **OpenAI Responses** | `openai-responses` | - | `OPENAI_API_KEY` | `OpenAIResponsesProvider` | | **Anthropic** | `anthropic` | `claude` | `ANTHROPIC_API_KEY` | `AnthropicProvider` | | **Google** | `google` | `gemini`, `googleai` | `GEMINI_API_KEY` | `GoogleProvider` | | **Firebase AI** | `firebase` | - | None (Firebase) | `FirebaseAIProvider` | | **Mistral** | `mistral` | - | `MISTRAL_API_KEY` | `MistralProvider` | | **Cohere** | `cohere` | - | `COHERE_API_KEY` | `CohereProvider` | | **Ollama** | `ollama` | - | None (local) | `OllamaProvider` | | **OpenRouter** | `openrouter` | - | `OPENROUTER_API_KEY` | `OpenAIProvider` | | **xAI** | `xai` | `grok` | `XAI_API_KEY` | `XAIProvider` | | **xAI Responses** | `xai-responses` | `grok-responses` | `XAI_API_KEY` | `XAIResponsesProvider` | ## Firebase AI (Flutter add-on) Use [`dartantic_firebase_ai`](https://pub.dev/packages/dartantic_firebase_ai) when you want Gemini through the Firebase SDK (Firebase AI Logic), including App Check and Firebase Auth on the Vertex AI path. **Pure Dart** apps should keep using [`GoogleProvider`](/providers) with `GEMINI_API_KEY` instead. Add the package, call `Firebase.initializeApp()`, then register factories for each backend you need. Provider **name** is `firebase_ai`; model strings use the **aliases** below. | Backend | Prefix (alias) | Authentication / setup | | --------------------------------------------- | ----------------- | --------------------------------------------------------- | | Google AI (Gemini Developer API via Firebase) | `firebase-google` | Google AI API key in Firebase console; lighter setup | | Vertex AI (through Firebase) | `firebase-vertex` | Full Firebase project, billing; optional App Check / Auth | ```dart theme={null} import 'package:dartantic_ai/dartantic_ai.dart'; import 'package:dartantic_firebase_ai/dartantic_firebase_ai.dart'; import 'package:firebase_core/firebase_core.dart'; await Firebase.initializeApp(); Agent.providerFactories['firebase-google'] = () => FirebaseAIProvider(backend: FirebaseAIBackend.googleAI); Agent.providerFactories['firebase-vertex'] = () => FirebaseAIProvider(backend: FirebaseAIBackend.vertexAI); final dev = Agent('firebase-google:gemini-2.5-flash'); final prod = Agent('firebase-vertex:gemini-2.5-flash'); ``` **Platforms:** iOS, Android, macOS, and Web (Flutter only). Supports chat, streaming, tools, thinking, structured output, and media generation; **no** embeddings model. See the [`dartantic_firebase_ai` README](https://pub.dev/packages/dartantic_firebase_ai) for dependency versions and setup. ## Setup ```bash theme={null} # Set API keys export OPENAI_API_KEY="sk-..." export ANTHROPIC_API_KEY="sk-ant-..." export GEMINI_API_KEY="..." export XAI_API_KEY="..." ``` ## Usage ```dart theme={null} // Basic Agent('openai'); // With model Agent('anthropic:claude-3-5-sonnet'); // Chat + embeddings Agent('openai?chat=gpt-4o&embeddings=text-embedding-3-large'); // Extended thinking (OpenAI Responses, xAI Responses, Anthropic, Google) Agent('anthropic:claude-sonnet-4-5', enableThinking: true); // Server-side tools (OpenAI Responses) Agent('openai-responses:gpt-5'); // xAI Grok — OpenAI-compatible chat completions Agent('xai'); Agent('grok:grok-4-1-fast-non-reasoning'); // xAI Grok — Responses API (thinking, server-side tools, media models) Agent('xai-responses'); Agent('xai-responses:grok-4-1-fast-reasoning', enableThinking: true); ``` ## Find Providers ```dart theme={null} // All providers Agent.allProviders // By name (returns fresh instance) Agent.createProvider('claude') // → anthropic provider // For runtime capability discovery, use Provider.listModels() final provider = Agent.createProvider('openai'); await for (final model in provider.listModels()) { print('${model.name}: ${model.kinds}'); // Shows chat, embeddings, media, etc. } ``` ## Custom Config ```dart theme={null} final provider = OpenAIProvider( apiKey: 'key', baseUrl: Uri.parse('https://custom.api.com/v1'), ); Agent.forProvider(provider); ``` ## Custom Headers All providers support custom HTTP headers for enterprise scenarios like authentication proxies, request tracing, or compliance logging: ```dart theme={null} final provider = GoogleProvider( apiKey: apiKey, headers: { 'X-Request-ID': requestId, 'X-Tenant-ID': tenantId, }, ); final agent = Agent.forProvider(provider); ``` Custom headers flow through to all API calls and can override internal headers when needed. This works consistently across OpenAI, Google, Anthropic, Mistral, Ollama, and xAI providers. ## Check Capabilities Use `Provider.listModels()` for runtime capability discovery: ```dart theme={null} // List models and their capabilities final provider = Agent.createProvider('openai'); await for (final model in provider.listModels()) { print('${model.name}: ${model.kinds}'); // Output: gpt-4o: {chat}, text-embedding-3-small: {embeddings} } // Check if a specific model supports embeddings final models = await provider.listModels().toList(); final hasEmbeddings = models.any((m) => m.kinds.contains(ModelKind.embeddings)); if (hasEmbeddings) { final agent = Agent('openai'); final embed = await agent.embedQuery('test'); } else { print('Provider does not support embeddings'); } ``` ### Model Kinds Models are categorized by their kind via `ModelKind` (a model may report multiple kinds): * **`chat`** - Chat / completion models * **`embeddings`** - Text embedding models * **`media`** - Unified media generation (images, documents, audio, etc.) * **`image`** - Image generation or vision models * **`video`** - Video generation models * **`audio`** - Audio processing (e.g. speech-to-text) * **`tts`** - Text-to-speech * **`countTokens`** - Token counting * **`other`** - Other specialized model types ### Typed Output With Tools The `typedOutputWithTools` capability indicates a provider can handle both function calling and structured JSON output in the same request: | Provider | Support | Implementation | | ---------------- | ------- | ---------------------------------------- | | OpenAI | ✅ | Native `response_format` | | OpenAI Responses | ✅ | Native `response_format` | | Anthropic | ✅ | `return_result` tool | | Google | ✅ | Double agent orchestrator | | OpenRouter | ✅ | OpenAI-compatible | | xAI | ✅ | OpenAI-compatible | | xAI Responses | ✅ | Native `response_format` (Responses API) | | Ollama | ❌ | Coming soon | | Cohere | ❌ | API limitation | *Together AI, Google-OpenAI, and Ollama-OpenAI also support typed output with tools when registered via the `openai_compat.dart` example.* **Anthropic's approach** uses the `return_result` tool pattern. This is a special tool that allows the model to return a structured JSON response. This is handled automatically by the Anthropic provider. **Google's approach** uses a transparent two-phase workflow: Phase 1 executes tools, Phase 2 requests structured output. This is handled automatically by the Google provider. ## List Models ```dart theme={null} // List all models from a provider final provider = Agent.createProvider('openai'); await for (final model in provider.listModels()) { final status = model.stable ? 'stable' : 'preview'; print('${model.name}: ${model.displayName} [$status]'); } // Example output: // - openai:gpt-4-0613 (chat) // - openai:gpt-4 (chat) // - openai:gpt-3.5-turbo (chat) ``` ## Examples * [List all provider models](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/provider_models.dart) * [Multi-provider conversations](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/multi_provider.dart) * [Custom providers](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/custom_provider.dart) # Quick Start Source: https://docs.dartantic.ai/quick-start Zero to hero; no PhD required. ## Install ```yaml theme={null} dependencies: dartantic_ai: ^VERSION ``` For **Flutter** apps using **Firebase AI Logic** (Gemini through Firebase), also add [`dartantic_firebase_ai`](https://pub.dev/packages/dartantic_firebase_ai) and register `firebase-google` / `firebase-vertex` on `Agent.providerFactories` (see [Providers](/providers#firebase-ai-flutter-add-on)). ## API Keys Set environment variables for the providers you'll use: ```bash theme={null} # Native providers export OPENAI_API_KEY="sk-..." export ANTHROPIC_API_KEY="sk-ant-..." export GEMINI_API_KEY="..." export MISTRAL_API_KEY="..." # OpenAI-compatible export OPENROUTER_API_KEY="..." export TOGETHER_API_KEY="..." export COHERE_API_KEY="..." export XAI_API_KEY="..." # Ollama runs locally - no key needed # OpenAI Responses reuses OPENAI_API_KEY ``` Prefer to handle API keys server-side. Take special care to not expose them in your client code. See [Providers](/providers) for the complete list. ## Your First Chat The following shows simple agent usage using the `Agent()` constructor, which takes a model string. ```dart theme={null} void main() async { // Create an agent with a model string final agent = Agent( 'openai', // Try 'openai:gpt-4o' or 'gemini:gemini-2.0-flash' ); // Run the agent with a prompt and system message final result = await agent.send( 'Where does "hello world" come from?', history: [ const ChatMessage.system('Be concise, reply with one sentence.'), ], ); print(result.output); // Output: one sentence on the origin of "hello world" } ``` Alternatively, you can use the `Agent.forProvider()` constructor which takes a provider directly: ```dart theme={null} void main() async { // Create an agent with a provider final agent = Agent.forProvider( Agent.createProvider('openai'), ); // Run the agent with a prompt and system message final result = await agent.send( 'Where does "hello world" come from?', history: [ const ChatMessage.system('Be concise, reply with one sentence.'), ], ); print(result.output); // Output: one sentence on the origin of "hello world" } ``` ## Model Strings The model string used by `Agent` can be specified in several ways: * Just the `providerName`, e.g. `openai` → specifies whatever the default chat and embeddings models are for that provider * `providerName:chatModelName`, e.g. `google:gemini-2.0-flash` → specifies a provider and model, separated by a **colon** * `providerName/chatModelName`, e.g. `google/gemini-2.0-flash` → specifies a provider and model, separated by a **slash** * `providerName?chat=chatModelName&embeddings=embeddingsModelName` → `openai?chat=gpt-4&embeddings=text-embedding-ada-002` → uses query format ## Providers A provider is a Dart type like `GoogleProvider` that knows how to expose model objects. When you pass in a model string, you're really looking up a provider object and one or more types of model objects for the agent to do its work. All the providers support a chat model (e.g. `GoogleChatModel`) and several of them also support an embeddings model (e.g. `GoogleEmbeddingsModel`). You can see the list of [Supported Providers](/providers) that Dartantic exposes. And you can build your own [Custom Providers](/custom-providers) if you like. ## Provider Aliases Some providers support multiple provider prefixes. The alias can be used where the provider name is specified, e.g. `gemini:gemini-2.0-flash` → `google:gemini-2.0-flash`. Here's where you can see the list of aliases for each of the [Supported Providers](/providers). ## What's Next? Now that you've tasted power, dive deeper: * [Examples](https://github.com/csells/dartantic_ai/tree/main/packages/dartantic_ai/example/bin) - Pretty much all the things * [Providers](/providers) - Pick your AI overlord * [Tools](/tool-calling) - Give your AI superpowers # Sample Applications Source: https://docs.dartantic.ai/samples Real apps built with Dartantic. The `samples/` folder contains complete applications demonstrating Dartantic in action. These aren't toy examples; they're functional tools you can use and extend. ## [Dartantic CLI](/dartantic-cli) A full-featured command-line interface for the Dartantic framework. Think of it as `curl` for AI: scriptable, composable, and ready for shell pipelines. **Key features:** * Multiple commands: chat, generate, embed, models * Custom agents via settings file * DotPrompt templates with variable substitution * MCP server integration * Structured JSON output with schemas ```bash theme={null} dartantic -p "What is 2+2?" dartantic -a anthropic -p "Explain recursion" dartantic generate --mime image/png -p "A robot logo" dartantic embed create docs/*.txt > index.json ``` ## [Chatarang](/chatarang) An interactive REPL chat application with multi-provider support and tool calling. Perfect for exploring what AI can do when given real capabilities. **Key features:** * Switch providers mid-conversation * Built-in tools: weather, location, web fetch * Slash commands for app control * Conversation history with tool visibility ``` You: what's the weather at the moda center? Tool.call: location-lookup({"location": "Moda Center, Portland"}) Tool.call: weather({"zipcode": "97240"}) google:gemini-2.0-flash: It's currently 55°F with light rain. ``` ## Patterns These samples show two different patterns: * **Dartantic CLI**: Non-interactive, scriptable, single-turn. Great for automation, shell scripts, and CI/CD pipelines. * **Chatarang**: Interactive REPL with multi-turn conversations. Great for exploration and debugging. Both use the same underlying Dartantic framework, so the skills transfer directly to building your own applications. ## Next Steps * [Quick Start](/quick-start) - Get the framework running * [Tool Calling](/tool-calling) - Build your own tools * [MCP Support](/mcp-support) - Connect to external tool servers # Anthropic Code Interpreter Source: https://docs.dartantic.ai/server-side-tools/anthropic-code-interpreter Execute Python code in Anthropic's sandbox environment. Anthropic's code interpreter runs Python in a sandboxed environment. State persists across turns, and generated files are automatically downloaded. ## Enable Code Interpreter ```dart theme={null} final agent = Agent( 'anthropic', chatModelOptions: const AnthropicChatOptions( serverSideTools: {AnthropicServerSideTool.codeInterpreter}, ), ); ``` ## Multi-Turn Execution State persists across conversation turns: ```dart theme={null} final history = []; // Step 1: Calculate data await for (final chunk in agent.sendStream( 'Calculate the first 10 Fibonacci numbers and store them in a variable ' 'called "fib_sequence". Create a CSV file called "fibonacci.csv".', )) { stdout.write(chunk.output); history.addAll(chunk.messages); } // Step 2: Use the data from step 1 await for (final chunk in agent.sendStream( 'Using fib_sequence, create a plot showing the golden ratio convergence. ' 'Save it as "golden_ratio.png".', history: history, )) { stdout.write(chunk.output); history.addAll(chunk.messages); } ``` ## Generated Files Files created during code execution are attached as `DataPart` instances: ```dart theme={null} for (final msg in history) { for (final part in msg.parts) { if (part is DataPart) { print('Generated: ${part.name} (${part.mimeType})'); File('output/${part.name}').writeAsBytesSync(part.bytes); } } } ``` Anthropic's code interpreter supports common Python libraries including matplotlib for plotting, pandas for data manipulation, and reportlab for PDF generation. ## Streaming Code Events Code execution events stream through `metadata['code_interpreter']`: ```dart theme={null} await for (final chunk in agent.sendStream(prompt)) { final events = chunk.metadata['code_interpreter'] as List?; if (events != null) { for (final event in events) { if (event['type'] == 'code_delta') { stdout.write(event['delta']); } } } } ``` ## Example * [Anthropic Code Interpreter demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/server_side_tools_anthropic/server_side_code_interpreter.dart) ## Related Topics * [Server-Side Tools](/server-side-tools) * [Media Generation](/media-generation) * [Anthropic Web Search](/server-side-tools/anthropic-web-search) # Anthropic Web Fetch Source: https://docs.dartantic.ai/server-side-tools/anthropic-web-fetch Fetch and process web pages using Anthropic's server-side tool. Anthropic's web fetch tool retrieves and processes content from specific URLs. Unlike web search, this tool fetches a known URL directly. ## Enable Web Fetch ```dart theme={null} final agent = Agent( 'anthropic', chatModelOptions: const AnthropicChatOptions( serverSideTools: {AnthropicServerSideTool.webFetch}, ), ); ``` ## Usage ```dart theme={null} await for (final chunk in agent.sendStream( 'Retrieve https://dart.dev and summarize the main features.', )) { stdout.write(chunk.output); } ``` ## Fetched Documents Fetched content is attached as `DataPart` instances on the message history: ```dart theme={null} final history = []; await for (final chunk in agent.sendStream(prompt)) { stdout.write(chunk.output); history.addAll(chunk.messages); } // Access fetched documents for (final msg in history) { for (final part in msg.parts) { if (part is DataPart) { print('Fetched: ${part.name} (${part.mimeType})'); File('output/${part.name}').writeAsBytesSync(part.bytes); } } } ``` ## Combined Tools Combine web fetch with other tools for research workflows: ```dart theme={null} final agent = Agent( 'anthropic', chatModelOptions: const AnthropicChatOptions( serverSideTools: { AnthropicServerSideTool.webSearch, AnthropicServerSideTool.webFetch, }, ), ); ``` ## Example * [Anthropic Web Fetch demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/server_side_tools_anthropic/server_side_web_fetch.dart) ## Related Topics * [Server-Side Tools](/server-side-tools) * [Web Search](/server-side-tools/anthropic-web-search) # Anthropic Web Search Source: https://docs.dartantic.ai/server-side-tools/anthropic-web-search Search the web using Anthropic's server-side search tool. Anthropic's web search tool allows Claude to search the web and incorporate real-time information into responses. ## Enable Web Search ```dart theme={null} final agent = Agent( 'anthropic', chatModelOptions: const AnthropicChatOptions( serverSideTools: {AnthropicServerSideTool.webSearch}, ), ); ``` ## Usage ```dart theme={null} await for (final chunk in agent.sendStream( 'Search the web for the three most recent announcements ' 'about the Dart programming language and summarize them.', )) { stdout.write(chunk.output); } ``` The model automatically decides when to search based on the query. Search results are incorporated directly into the response with citations. ## Streaming Metadata Web search events stream through `metadata['web_search']`: ```dart theme={null} await for (final chunk in agent.sendStream(prompt)) { stdout.write(chunk.output); final events = chunk.metadata['web_search'] as List?; if (events != null) { for (final event in events) { stdout.writeln('[search] ${event['type']}'); } } } ``` ## Example * [Anthropic Web Search demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/server_side_tools_anthropic/server_side_web_search.dart) ## Related Topics * [Server-Side Tools](/server-side-tools) * [Web Fetch](/server-side-tools/anthropic-web-fetch) * [Code Interpreter](/server-side-tools/anthropic-code-interpreter) # Google Code Execution Source: https://docs.dartantic.ai/server-side-tools/google-code-execution Execute Python code in Google's sandbox environment. Google's code execution tool runs Python in a sandboxed environment. State persists across turns, allowing multi-step computations and file generation. ## Enable Code Execution ```dart theme={null} final agent = Agent( 'google', chatModelOptions: const GoogleChatModelOptions( serverSideTools: {GoogleServerSideTool.codeExecution}, ), ); ``` ## Multi-Turn Execution State persists across conversation turns, enabling iterative workflows: ```dart theme={null} final history = []; // Step 1: Calculate data await for (final chunk in agent.sendStream( 'Calculate the first 10 Fibonacci numbers and store them in a variable ' 'called "fib_sequence".', )) { stdout.write(chunk.output); history.addAll(chunk.messages); } // Step 2: Use the data from step 1 await for (final chunk in agent.sendStream( 'Using fib_sequence, create a plot showing the golden ratio convergence. ' 'Save it as "golden_ratio.png".', history: history, )) { stdout.write(chunk.output); history.addAll(chunk.messages); } ``` ## Generated Files Files created during code execution (images, CSVs, etc.) are attached as `DataPart` instances on the assistant message: ```dart theme={null} for (final msg in history) { for (final part in msg.parts) { if (part is DataPart) { print('Generated: ${part.name} (${part.mimeType})'); File('output/${part.name}').writeAsBytesSync(part.bytes); } } } ``` ## Combined Tools Enable both search and code execution for research + computation workflows: ```dart theme={null} final agent = Agent( 'google', chatModelOptions: const GoogleChatModelOptions( serverSideTools: { GoogleServerSideTool.googleSearch, GoogleServerSideTool.codeExecution, }, ), ); ``` ## Example * [Code Execution demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/server_side_tools_google/server_side_code_execution.dart) ## Related Topics * [Server-Side Tools](/server-side-tools) * [Google Search](/server-side-tools/google-search) * [Media Generation](/media-generation) # Google Search Source: https://docs.dartantic.ai/server-side-tools/google-search Search the web using Google's Grounding feature. Google's server-side search tool uses Google Search to ground responses in real-time web data. Results are automatically woven into the model's response. ## Enable Google Search ```dart theme={null} final agent = Agent( 'google', chatModelOptions: const GoogleChatModelOptions( serverSideTools: {GoogleServerSideTool.googleSearch}, ), ); ``` ## Usage ```dart theme={null} await for (final chunk in agent.sendStream( 'Search the web for the three most recent announcements ' 'about the Dart programming language and summarize them.', )) { stdout.write(chunk.output); } ``` The model automatically decides when to search based on the query. Search results are incorporated directly into the response. ## Grounding Metadata Google Search results include grounding metadata in the response. Access it via the message metadata to show citations or sources: ```dart theme={null} final history = []; await for (final chunk in agent.sendStream(prompt)) { stdout.write(chunk.output); history.addAll(chunk.messages); } // Check for grounding metadata in the final message for (final msg in history) { final grounding = msg.metadata['grounding']; if (grounding != null) { print('Sources: $grounding'); } } ``` ## Example * [Google Search demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/server_side_tools_google/server_side_google_search.dart) ## Related Topics * [Server-Side Tools](/server-side-tools) * [Code Execution](/server-side-tools/google-code-execution) # Overview Source: https://docs.dartantic.ai/server-side-tools/index Use provider-hosted capabilities such as web search, code execution, and image creation without writing local tool handlers. Server-side tools run entirely on the provider's infrastructure. They stream progress events, produce final deliverables, and keep your application logic focused on orchestration instead of implementation. ## Provider Support | Provider | Tools Available | | -------------------- | ----------------------------------------------------------- | | **OpenAI Responses** | Web Search, File Search, Image Generation, Code Interpreter | | **xAI Responses** | Web Search, X Search, File Search, Code Interpreter, MCP | | **Google** | Google Search, Code Execution | | **Anthropic** | Web Search, Web Fetch, Code Interpreter | ## Enabling Tools Each provider uses its own options class and tool enum: ### OpenAI Responses ```dart theme={null} final agent = Agent( 'openai-responses', chatModelOptions: const OpenAIResponsesChatModelOptions( serverSideTools: { OpenAIServerSideTool.webSearch, OpenAIServerSideTool.codeInterpreter, }, ), ); ``` ### xAI Responses ```dart theme={null} final agent = Agent( 'xai-responses', chatModelOptions: const XAIResponsesChatModelOptions( serverSideTools: { XAIServerSideTool.webSearch, XAIServerSideTool.codeInterpreter, }, ), ); ``` ### Google ```dart theme={null} final agent = Agent( 'google', chatModelOptions: const GoogleChatModelOptions( serverSideTools: { GoogleServerSideTool.googleSearch, GoogleServerSideTool.codeExecution, }, ), ); ``` ### Anthropic ```dart theme={null} final agent = Agent( 'anthropic', chatModelOptions: const AnthropicChatOptions( serverSideTools: { AnthropicServerSideTool.webSearch, AnthropicServerSideTool.codeInterpreter, }, ), ); ``` Pick the tools you want per request. Providers default to their own safe configuration if you omit the set. ## Streaming Metadata Each tool streams structured metadata under a predictable key: | Tool | Metadata key | | ---------------- | ------------------------------ | | Web search | `metadata['web_search']` | | File search | `metadata['file_search']` | | Image generation | `metadata['image_generation']` | | Code interpreter | `metadata['code_interpreter']` | Metadata is delivered on every `ChatResult` during streaming, which you can use to show live progress, log it, or feed it into analytics. ```dart theme={null} await for (final chunk in agent.sendStream('Recent Dart news?')) { final searchEvents = chunk.metadata['web_search'] as List?; if (searchEvents != null) { for (final event in searchEvents) { stdout.writeln('stage: ${event['type']}'); } } } ``` ## Message Content Final deliverables (images, generated files, synthesized summaries) arrive as normal message parts so you can handle them with the usual `ChatMessage` APIs. ## Configuration Blocks Each tool exposes an optional configuration object. Configuration objects are provider-specific: ```dart theme={null} // OpenAI Responses final agent = Agent( 'openai-responses', chatModelOptions: OpenAIResponsesChatModelOptions( serverSideTools: const {OpenAIServerSideTool.webSearch}, webSearchConfig: const WebSearchConfig( contextSize: WebSearchContextSize.high, followupQuestions: true, ), ), ); ``` ## OpenAI Responses Tools * [Web Search](/server-side-tools/web-search) - Search the web and weave results into responses * [File Search](/server-side-tools/file-search) - Search provider-hosted files and vector stores * [Image Generation](/server-side-tools/image-generation) - Generate images with streaming previews * [Code Interpreter](/server-side-tools/code-interpreter) - Execute Python code in a sandbox ## Google Tools * [Google Search](/server-side-tools/google-search) - Search with Google Grounding * [Code Execution](/server-side-tools/google-code-execution) - Execute Python in Google's sandbox ## Anthropic Tools * [Web Search](/server-side-tools/anthropic-web-search) - Search the web via Anthropic * [Web Fetch](/server-side-tools/anthropic-web-fetch) - Fetch and process web pages * [Code Interpreter](/server-side-tools/anthropic-code-interpreter) - Execute Python via Anthropic ## Examples * [OpenAI server-side tools](https://github.com/csells/dartantic_ai/tree/main/packages/dartantic_ai/example/bin/server_side_tools) * [Google server-side tools](https://github.com/csells/dartantic_ai/tree/main/packages/dartantic_ai/example/bin/server_side_tools_google) * [Anthropic server-side tools](https://github.com/csells/dartantic_ai/tree/main/packages/dartantic_ai/example/bin/server_side_tools_anthropic) ## Related Topics * [Media Generation](/media-generation) - Generate images, PDFs, and files across providers * [Thinking Metadata](/thinking) - Combine reasoning output with tool progress * [Tool Calling](/tool-calling) - Define your own local tools # OpenAI Code Interpreter Source: https://docs.dartantic.ai/server-side-tools/openai-code-interpreter Let OpenAI execute Python code for you. The OpenAI Responses provider exposes a code interpreter tool that allows you to execute Python code in a sandboxed container environment hosted by OpenAI. If you'd like to keep state between requests, you can reuse an existing container from a previous request. Any artifacts that are generated by the code interpreter tool can be downloaded by your app. ## Enable Code Interpreter You can enable the code interpreter tool via the `chatModelOptions` parameter of the `Agent` constructor: ```dart theme={null} final agent = Agent( 'openai-responses', chatModelOptions: const OpenAIResponsesChatModelOptions( serverSideTools: {OpenAIServerSideTool.codeInterpreter}, ), ); ``` ## Streaming Execution Code deltas and lifecycle events stream through `metadata['code_interpreter']`: ```dart theme={null} await for (final chunk in agent.sendStream(prompt)) { final events = chunk.metadata['code_interpreter'] as List?; if (events == null) continue; for (final event in events) { switch (event['type']) { case 'response.code_interpreter_call_code.delta': stdout.write(event['delta']); case 'response.output_item.done': stdout.writeln('container: ${event['item']['container_id']}'); } } } ``` Use these events to show live output, capture errors, or record container IDs. ## Container Reuse Containers persist across turns when you supply a `containerId`. The example below captures the ID from the first response and injects it into the second: ```dart theme={null} String? containerId; await for (final chunk in agent.sendStream(prompt)) { containerId ??= containerIdFromMetadata(chunk.metadata); } final agent2 = Agent( 'openai-responses', chatModelOptions: OpenAIResponsesChatModelOptions( serverSideTools: const {OpenAIServerSideTool.codeInterpreter}, codeInterpreterConfig: CodeInterpreterConfig(containerId: containerId), ), ); agent2.sendStream(prompt2)...; // Helper function to extract container ID from metadata String? containerIdFromMetadata(Map metadata) { final ciEvents = metadata['code_interpreter'] as List?; if (ciEvents != null) { for (final event in ciEvents) { // Check for container_id at the top level (older synthetic events) if (event['container_id'] != null) { return event['container_id'] as String; } // Check for container_id nested in item (response.output_item.done // events) final item = event['item']; if (item is Map && item['container_id'] != null) { return item['container_id'] as String; } } } return null; } ``` ## Generated Files When the interpreter saves files (e.g. images, CSVs) they are downloaded automatically and attached as `DataPart` instances on the assistant message. Each `DataPart` includes the actual filename from the interpreter (e.g., `fibonacci.csv`, `plot.png`) for easy identification and saving. ```dart theme={null} final history = []; await for (final chunk in agent.sendStream(prompt)) { history.addAll(chunk.messages); } // Access generated files for (final msg in history) { for (final part in msg.parts) { if (part is DataPart) { print('File: ${part.name}'); // e.g., "fibonacci.csv" print('MIME: ${part.mimeType}'); // e.g., "text/csv" print('Size: ${part.bytes.length} bytes'); // Save to disk with original filename File('output/${part.name}').writeAsBytesSync(part.bytes); } } } ``` ## Example * [Server-side code interpreter demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/server_side_tools/server_side_code_interpreter.dart) ## Related Topics * [Image Generation](/server-side-tools/image-generation) * [Thinking Metadata](/thinking) # OpenAI File Search Source: https://docs.dartantic.ai/server-side-tools/openai-file-search Search provider-hosted files and vector stores without leaving the chat flow. The OpenAI Responses provider exposes a file search tool that allows you to search through files and vector stores hosted by OpenAI. ## Enable File Search The file search tool can be enabled via the `chatModelOptions` parameter of the `Agent` constructor. ```dart theme={null} final agent = Agent( 'openai-responses', chatModelOptions: OpenAIResponsesChatModelOptions( serverSideTools: const {OpenAIServerSideTool.fileSearch}, fileSearchConfig: const FileSearchConfig( maxResults: 5, vectorStoreIds: ['vs_123'], ), ), ); ``` When `fileSearchConfig.vectorStoreIds` is supplied, the provider restricts searches to those stores. You can also omit the list and rely on the provider's defaults. ## Streaming Events Results stream under the `file_search` metadata key: ```dart theme={null} await for (final chunk in agent.sendStream(prompt)) { final events = chunk.metadata['file_search'] as List?; if (events == null) continue; for (final event in events) { switch (event['type']) { case 'response.file_search_call.started': stdout.writeln('🔍 searching ${event['query']}'); case 'response.file_search_call.result': stdout.writeln('- ${event['document']['filename']}'); } } } ``` Typical fields include `query`, `document`, `score`, and provider-specific metadata that you can surface in your UI. ## Vector Store Bootstrap The OpenAI Responses example repo includes a helper that uploads wiki docs and creates a reusable vector store: ```dart theme={null} final vectorStoreId = await setupVectorStore([ '../../../wiki/Server-Side-Tools-Tech-Design.md', '../../../wiki/Message-Handling-Architecture.md', ]); ``` See the sample below for the full workflow, including caching the vector store ID on disk so you do not re-upload files every run. ## Example * [Server-side vector search demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/server_side_tools/server_side_vector_search.dart) ## Related Topics * [Web Search](/server-side-tools/web-search) * [Image Generation](/server-side-tools/image-generation) # OpenAI Image Generation Source: https://docs.dartantic.ai/server-side-tools/openai-image-generation Generate images on the provider and receive both previews and final assets in one streaming response. The OpenAI Responses provider exposes an image generation tool that allows you to generate images on the provider. ## Enable Image Generation The image generation tool can be enabled via the `chatModelOptions` parameter of the `Agent` constructor: ```dart theme={null} final agent = Agent( 'openai-responses', chatModelOptions: const OpenAIResponsesChatModelOptions( serverSideTools: {OpenAIServerSideTool.imageGeneration}, imageGenerationConfig: ImageGenerationConfig( partialImages: 3, quality: ImageGenerationQuality.low, size: ImageGenerationSize.square256, ), ), ); ``` `ImageGenerationConfig` lets you request progressive previews (`partialImages`), choose the quality profile, and select a size. Omit these values to fall back to the provider defaults. ## Streaming Previews Partial renders arrive as base64-encoded bytes inside metadata events: ```dart theme={null} void handleMetadata(Map metadata) { final events = metadata['image_generation'] as List?; if (events == null) return; for (final event in events) { final preview = event['partial_image_b64'] as String?; if (preview != null) { // import 'dart:convert' to use base64Decode final bytes = base64Decode(preview); savePreview(bytes, event['partial_image_index'] as int); } } } ``` Each event also includes the tool stage (`response.image_generation_call.*`) so you can display progress indicators while the image renders. ## Final Image Completed images are attached to the assistant message as `DataPart` instances with an `image/*` MIME type: ```dart theme={null} final result = await agent.send(prompt); for (final msg in result.messages) { for (final part in msg.parts) { if (part is DataPart && part.mimeType.startsWith('image/')) { saveFinalImage(part.bytes); } } } ``` No extra download step is required; Dartantic fetches the file from the provider and hands you the bytes. ## Example * [Server-side image generation demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/server_side_tools/server_side_image_gen.dart) ## Related Topics * [Server-Side Tools](/server-side-tools) * [Code Interpreter](/server-side-tools/code-interpreter) # OpenAI Web Search Source: https://docs.dartantic.ai/server-side-tools/openai-web-search Stream curated search results directly from the provider and weave them into your responses. The OpenAI Responses provider exposes a web search tool that allows you to search the web and weave the results into your responses. ## Enable Web Search The web search tool can be enabled via the `chatModelOptions` parameter of the `Agent` constructor: ```dart theme={null} final agent = Agent( 'openai-responses', chatModelOptions: const OpenAIResponsesChatModelOptions( serverSideTools: {OpenAIServerSideTool.webSearch}, ), ); await for (final chunk in agent.sendStream('Latest Dart language news?')) { stdout.write(chunk.output); dumpWebSearch(chunk.metadata); } void dumpWebSearch(Map metadata) { final events = metadata['web_search'] as List?; if (events == null) return; for (final event in events) { stdout.writeln('[web-search] ${event['type']}'); } } ``` Use `OpenAIServerSideTool.webSearch` to turn the tool on for a request. Each chunk includes the streaming progress events under `metadata['web_search']`. ## Configure Context ```dart theme={null} final options = OpenAIResponsesChatModelOptions( serverSideTools: const {OpenAIServerSideTool.webSearch}, webSearchConfig: const WebSearchConfig( contextSize: WebSearchContextSize.high, followupQuestions: true, location: WebSearchLocation(city: 'Portland', region: 'OR'), ), ); final agent = Agent('openai-responses', chatModelOptions: options); ``` Configuration controls: * `contextSize` tunes how much context the provider should gather (low/medium/ high/other) * `followupQuestions` requests suggested follow-ups in metadata where supported * `location` nudges the search toward a city/region/country/time zone ## Metadata Structure The metadata list contains chronological events streamed by the provider. Each entry includes: * `type`: the event identifier (e.g. `response.web_search_call.started`) * `query`: text of the query that ran * `results`: snippets or URLs when the provider shares them ```dart theme={null} final events = chunk.metadata['web_search'] as List?; if (events != null) { for (final event in events) { if (event['results'] case final List results?) { for (final result in results) { stdout.writeln('- ${result['url']}'); } } } } ``` Use these events to show a progress panel or capture citations. Because they arrive in metadata, they never pollute the chat transcript. ## Example * [Server-side web search demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/server_side_tools/server_side_web_search.dart) ## Related Topics * [Server-Side Tools](/server-side-tools) * [File Search](/server-side-tools/file-search) # Streaming Output Source: https://docs.dartantic.ai/streaming-output Watch your AI think in real-time. It's like watching paint dry, but faster. ## Basic Streaming ```dart theme={null} final agent = Agent('openai'); // Like watching a typist with 200 WPM await for (final chunk in agent.sendStream('Tell me your best joke')) { stdout.write(chunk.output); } // "Why don't scientists trust atoms?" // (dramatic pause as it streams...) // "Because they make up everything!" ``` ## With Messages ```dart theme={null} final agent = Agent('openai'); final history = [ChatMessage.system('You are a comedian.')]; await for (final chunk in agent.sendStream( 'Tell me your best joke', history: history, )) { // Stream the output stdout.write(chunk.output); // Add new messages to the history history.addAll(chunk.messages); } ``` ## With Tools ```dart theme={null} // Tool calls stream alongside text await for (final chunk in agent.sendStream( 'Weather in NYC?', tools: [weatherTool], )) { // Tool results integrated into stream stdout.write(chunk.output); } ``` ## Extended Thinking ```dart theme={null} final agent = Agent( 'anthropic:claude-sonnet-4-5', enableThinking: true, ); final result = await agent.send('Explain quicksort.'); final thinking = result.messages .expand((m) => m.parts) .whereType() .map((p) => p.text) .join(); if (thinking.isNotEmpty) { stdout.write('[[${thinking.trim()}]]'); } stdout.write(result.output); ``` Thinking is available via `ThinkingPart` in message parts so you can show a live "thought bubble" without polluting the message stream. See [Extended Thinking](/thinking) for more options. ## With Typed Output ```dart theme={null} // Stream structured JSON await for (final chunk in agent.sendStream( 'List 3 facts', outputSchema: factsSchema, )) { stdout.write(chunk.output); // Streams JSON chunks } ``` ## Usage Tracking & Tool Metadata ```dart theme={null} var usage = const LanguageModelUsage(); await for (final chunk in agent.sendStream('Story time')) { stdout.write(chunk.output); if (chunk.usage.totalTokens != null) { usage = chunk.usage; // Final chunk contains usage } // Inspect server-side tool events (OpenAI Responses) final web = chunk.metadata['web_search'] as List?; if (web != null) { stdout.writeln('\nSearch stage: ${web.last['type']}'); } } print('\nTokens used: ${usage.totalTokens}'); ``` ## Examples * [Chat with streaming](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/chat.dart) * [Multi-turn streaming](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/multi_turn_chat.dart) * [Agent with streaming](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/agent.dart) ## Next Steps * [Tool Calling](/tool-calling) - Stream with tools * [Usage Tracking](/usage-tracking) - Monitor streaming costs * [Server-Side Tools](/server-side-tools) - Stream provider-hosted tool output # System Prompts Source: https://docs.dartantic.ai/system-messages Set default behavior and personality for your agents. A system message is a message that sets the default behavior and personality for your agents. You can add it to the history as the first message to influence the behavior of the agent. ## Basic Usage ```dart theme={null} final agent = Agent('openai'); // Use default assistant final result1 = await agent.send( 'Hello!', history: [ChatMessage.system('You are a helpful assistant.')], ); // Response: "Hello! How can I help you today?" // Use pirate personality final result2 = await agent.send( 'Hello!', history: [ChatMessage.system('You are a pirate. Speak like one.')], ); // Response: "Ahoy, matey!" ``` ## Examples * [System message usage](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/system_message.dart) ## Next Steps * [Tool Calling](/tool-calling) - Combine prompts with tools * [Agentic Behavior](/agentic-behavior) - Complex agent workflows # Extended Thinking Source: https://docs.dartantic.ai/thinking Surface model reasoning without forcing it into the conversation transcript. Some providers expose a separate "thinking" channel that streams the model's reasoning metadata alongside the normal message output. This lets you display or inspect the model's inner monologue without sending it back to the model or to end users who just want the final answer. **OpenAI Responses**, **Anthropic**, and **Google** all support extended thinking. The generated output is provider-agnostic, so additional providers can adopt it later without requiring any changes to your code. ## Enable Thinking Enable thinking at the Agent level using the `enableThinking` parameter: ```dart theme={null} // Simple configuration - uses provider defaults final agent = Agent( 'anthropic:claude-sonnet-4-5', enableThinking: true, ); final result = await agent.send('In one sentence, how does quicksort work?'); // Access thinking via result.thinking if (result.thinking != null) { print('[[${result.thinking}]]'); } print(result.output); ``` ### Provider-Specific Defaults Each provider has sensible defaults when `enableThinking: true`: * **OpenAI Responses**: Uses `reasoningSummary: detailed` automatically * **Anthropic**: Uses 4096 token budget for extended thinking * **Google**: Uses dynamic token budget (model decides based on task complexity) ### Advanced Configuration For fine-tuning provider-specific behavior, use the options classes: #### OpenAI Responses ```dart theme={null} final agent = Agent( 'openai-responses:gpt-5', enableThinking: true, chatModelOptions: const OpenAIResponsesChatModelOptions( reasoningSummary: OpenAIReasoningSummary.brief, // Override default reasoningEffort: OpenAIReasoningEffort.high, ), ); ``` #### Anthropic ```dart theme={null} final agent = Agent( 'anthropic:claude-sonnet-4-5', enableThinking: true, chatModelOptions: const AnthropicChatOptions( thinkingBudgetTokens: 8192, // Override default 4096 ), ); ``` Anthropic recommends starting with smaller budgets (4k-10k) and scaling up based on task complexity. #### Google ```dart theme={null} final agent = Agent( 'google:gemini-2.5-flash', enableThinking: true, chatModelOptions: const GoogleChatModelOptions( thinkingBudgetTokens: 8192, // Override dynamic default ), ); // Or use explicit dynamic mode final agentDynamic = Agent( 'google:gemini-2.5-flash', enableThinking: true, chatModelOptions: const GoogleChatModelOptions( thinkingBudgetTokens: -1, // Model decides optimal budget ), ); ``` ### Key Points * Access thinking via `result.thinking` for both streaming and non-streaming * Thinking is also stored as `ThinkingPart` in consolidated messages for history * You control where (or if) thinking is displayed * **Important**: When using Anthropic with tool calls, thinking blocks are automatically preserved in conversation history as required by their API. This increases token costs on subsequent turns. ## Streaming Thinking ```dart theme={null} final history = []; var stillThinking = true; stdout.write('[['); await for (final chunk in agent.sendStream( 'In one sentence: how does quicksort work?', )) { // Display thinking in real-time via chunk.thinking field if (chunk.thinking != null) { stdout.write(chunk.thinking); } // Display response text if (chunk.output.isNotEmpty) { if (stillThinking) { stillThinking = false; stdout.writeln(']]\n'); } stdout.write(chunk.output); } history.addAll(chunk.messages); } stdout.writeln('\n'); ``` The stream delivers reasoning deltas incrementally through `chunk.thinking`, so you can render a live "thought bubble" while the model is working. Each chunk may include text output (`chunk.output`), thinking (`chunk.thinking`), or both. ## Examples * [Thinking demo](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/thinking.dart) ## Related Topics * [Streaming Output](/streaming-output) – Combine thinking with live text * [Server-Side Tools](/server-side-tools) – Providers can expose both thinking metadata and intrinsic tools # Tool Calling Source: https://docs.dartantic.ai/tool-calling Give your AI superpowers. Imagine that you'd like to extend the capabilities of your AI Agent with some new abilities. For example, out of the box, an LLM doesn't know what time it is. If you ask it anyway, you're not going to get a very good answer. If you want to teach the LLM to tell the time, you need to give it a tool. ## Basic Example You can define a tool with a name, description, and input schema. The input schema is used to parse the input from the LLM to the tool's input type. The tool's input type is used to parse the output from the tool to the LLM's output type. The `onCall` function is called when the tool is invoked. ```dart theme={null} final timeTool = Tool( name: 'get_time', description: 'Get current time in a location', inputSchema: Schema.fromMap({ 'type': 'object', 'properties': { 'location': {'type': 'string'}, }, 'required': ['location'], }), onCall: (args) async { // NOTE: insert actual timezone magic here return { 'time': '3:42 PM', 'location': args['location'], }; }, ); final agent = Agent('openai', tools: [timeTool]); final result = await agent.send("What time is it in New York?"); print(result.output); // "It's currently 3:42 PM in New York" ``` Tools are passed to the agent constructor and are available to the agent for the duration of the conversation. It's not shown here, but it's best practice for you to also list the tools and their metadata in the agent's system message. See [System Messages](/system-messages) for more information. ## Tools Without Parameters For tools that don't take any input, simply omit the `inputSchema`: ```dart theme={null} final currentTimeTool = Tool( name: 'get_current_time', description: 'Get the current date and time', onCall: (_) => DateTime.now().toIso8601String(), ); final agent = Agent('openai', tools: [currentTimeTool]); final result = await agent.send("What time is it?"); ``` The tool will use a default empty object schema. ## Multiple Tools You can pass multiple tools to the agent constructor. ```dart theme={null} final agent = Agent('anthropic', tools: [ weatherTool, temperatureConverterTool, currentDateTimeTool, ]); // Single request, multiple tool calls final result = await agent.send( "What's the weather in Paris? Convert to Fahrenheit and tell me the time." ); // Agent calls all three tools automatically ``` ## Streaming Tool Calls ```dart theme={null} await for (final chunk in agent.sendStream( "Weather in NYC and Boston?", )) { stdout.write(chunk.output); // Streams response as tools execute } ``` ## Error Handling If you throw an error in a tool, it will be caught and returned to the LLM as an error message so it can handle it gracefully (ideally). ```dart theme={null} final tool = Tool( name: 'divide', description: 'Divide numbers', inputSchema: Schema.fromMap({ 'type': 'object', 'properties': { 'a': {'type': 'number'}, 'b': {'type': 'number'}, }, 'required': ['a', 'b'], }), onCall: (args) async { if (args['b'] == 0) throw 'Cannot divide by zero'; return {'result': args['a'] / args['b']}; }, ); ``` ## Automatic Schema Generation Use `json_serializable` for type-safe tools: ```dart theme={null} @JsonSerializable(createJsonSchema: true) class WeatherInput { WeatherInput({required this.city}); /// The city to get weather for final String city; factory WeatherInput.fromJson(Map json) => _$WeatherInputFromJson(json); static const schemaMap = _$WeatherInputJsonSchema; } // Use the generated schema final weatherTool = Tool( name: 'get_weather', description: 'Get weather for a city', inputSchema: Schema.fromMap(WeatherInput.schemaMap), onCall: (args) async { final input = WeatherInput.fromJson(args); return {'temp': 72, 'city': input.city}; }, ); ``` ## Examples * [Single tool call](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/single_tool_call.dart) * [Multiple tool calls](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/multi_tool_call.dart) * [Agent with tools](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/agent.dart) * [MCP server tools](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/mcp_servers.dart) * [Server-side tools](https://github.com/csells/dartantic_ai/tree/main/packages/dartantic_ai/example/bin/server_side_tools) ## Next Steps * [Typed Output](/typed-output) - Structured responses with tools * [Multi-turn Chat](/multi-turn-chat) - Conversations with tool memory * [Server-Side Tools](/server-side-tools) - Provider-hosted capabilities # Typed Output Source: https://docs.dartantic.ai/typed-output Get more than a string back from your AI. Typed output allows constraining LLM responses to specific JSON schemas. ## Basic JSON You can pass a JSON schema to the `outputSchema` parameter of the `Agent.send` method. The schema is used to constrain the LLM's response to a specific JSON object shape. ```dart theme={null} final result = await agent.send( 'The windy city in the US of A', outputSchema: Schema.fromMap({ 'type': 'object', 'properties': { 'city': {'type': 'string'}, }, 'required': ['city'], }), ); print(result.output); // {"city":"Chicago"} ``` ## Parsed Map You can also pass a type to the `sendFor` method. By default, dartantic already knows how to parse the LLM's response to a `Map`. ```dart theme={null} final result = await agent.sendFor>( 'Name 3 colors that make you happy', outputSchema: Schema.fromMap({ 'type': 'object', 'properties': { 'colors': { 'type': 'array', 'items': {'type': 'string'}, }, }, 'required': ['colors'], }), ); print(result.output['colors']); // ['sunshine yellow', 'ocean blue', 'grass green'] ``` ## Custom Types If you'd like to parse the JSON output to a custom type, you can pass a type to the `sendFor` method along with the `outputFromJson` parameter. ```dart theme={null} class Weather { final String city; final int temp; Weather.fromJson(Map json) : city = json['city'], temp = json['temp']; } final result = await agent.sendFor( 'How hot is it in the Big Apple right now?', outputSchema: Schema.fromMap({ 'type': 'object', 'properties': { 'city': {'type': 'string'}, 'temp': {'type': 'integer'}, }, 'required': ['city', 'temp'], }), outputFromJson: Weather.fromJson, ); print('${result.output.city}: ${result.output.temp}°F'); ``` ## Schema Generation Hand-writing schemas and JSON serialization is a lot of boilerplate. Consider using the `json_serializable` package to automate this: ```dart theme={null} // Generate JSON serialization and JSON Schema from the same model. @JsonSerializable(createJsonSchema: true) class TownAndCountry { final String town; final String country; TownAndCountry({required this.town, required this.country}); factory TownAndCountry.fromJson(Map json) => _$TownAndCountryFromJson(json); static const schemaMap = _$TownAndCountryJsonSchema; } // now we pass the schema and JSON serialization to the agent and magic happens final result = await agent.sendFor( 'What is the capital of France?', outputSchema: Schema.fromMap(TownAndCountry.schemaMap), outputFromJson: TownAndCountry.fromJson, ); print('${result.output.town}, ${result.output.country}'); ``` ## Streaming You can stream structured JSON from the provider by passing the `outputSchema` parameter to the `sendStream` method. ```dart theme={null} // Stream structured JSON await for (final chunk in agent.sendStream( 'List 3 facts', outputSchema: factsSchema, )) { stdout.write(chunk.output); // Streams JSON chunks } ``` This is useful if you'd like to render the JSON progressively as it's streamed. ## With Tools Most providers support both tools and typed output in the same request, allowing you to gather information via tools and return structured results: ```dart theme={null} final weatherTool = Tool( name: 'get_weather', description: 'Get current weather', inputSchema: weatherInputSchema, onCall: (input) => getWeather(input['city']), ); final agent = Agent('openai', tools: [weatherTool]); final result = await agent.sendFor( 'Get weather for Seattle and format as a report', outputSchema: WeatherReport.schema, outputFromJson: WeatherReport.fromJson, ); print(result.output); // WeatherReport with structured data ``` ### Provider Support | Provider | Tools + Typed Output | Method | | ---------- | -------------------- | ------------------------- | | OpenAI | ✅ | Native response\_format | | Anthropic | ✅ | return\_result tool | | Google | ✅ | Double agent orchestrator | | Together | ✅ | OpenAI-compatible | | OpenRouter | ✅ | OpenAI-compatible | | Ollama | ❌ | Coming soon | | Cohere | ❌ | API limitation | **Google's Double Agent Pattern**: Google's API doesn't support tools and typed output in a single call, but dartantic handles this transparently with a two-phase approach: first executing tools, then requesting structured output with the tool results. See the [typed output example](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/typed_output.dart) for working code. ## Examples * [Typed output basics](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/typed_output.dart) * [Chat with typed output](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/chat.dart) ## Next Steps * [Tool Calling](/tool-calling) - Extend with functions * [Multi-turn Chat](/multi-turn-chat) - Structured conversations # Usage Tracking Source: https://docs.dartantic.ai/usage-tracking Track token usage and costs. Every provider supports tracking token usage and costs. ## Basic Usage The `ChatResult` object includes a `usage` property that contains the token usage and costs. ```dart theme={null} final agent = Agent('openai'); final result = await agent.send('Explain AI briefly'); // Access usage print('Input tokens: ${result.usage.promptTokens}'); print('Output tokens: ${result.usage.responseTokens}'); print('Total tokens: ${result.usage.totalTokens}'); ``` ## Embeddings Usage The `EmbeddingsModel` class includes a `usage` property that contains the token usage and costs as well. ```dart theme={null} final agent = Agent('openai'); final result = await agent.embedDocuments([ 'Text 1', 'Text 2', 'Text 3', ]); print('Tokens used: ${result.usage.totalTokens}'); ``` ## Examples * [Usage Tracking](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/usage_tracking.dart) ## Next Steps * [Providers](/providers) - Compare provider costs # Using DotPrompt Source: https://docs.dartantic.ai/using-dotprompt Define your prompts as files that can be executed. Google's [DotPrompt specification](https://google.github.io/dotprompt) allows you to define prompts as files with metadata, templates, and validation. These files can be executed by dartantic. ## Quick Start You can use the `DotPrompt` class to parse `.prompt` files: ```dart theme={null} import 'package:dotprompt_dart/dotprompt_dart.dart'; final dotPrompt = DotPrompt(''' --- model: openai input: default: length: 3 text: "The quick brown fox jumps over the lazy dog." --- Summarize this in {{length}} words: {{text}} '''); // Extract model and render prompt final prompt = dotPrompt.render(); final agent = Agent(dotPrompt.frontMatter.model!); final result = await agent.send(prompt); print(result.output); // "Fox jumps dog." ``` ## With Variables You can pass variables to the `render` method: ```dart theme={null} final dotPrompt = DotPrompt(''' --- model: anthropic --- Translate "{{phrase}}" to {{language}} '''); final prompt = dotPrompt.render({ 'phrase': 'Hello world', 'language': 'Spanish', }); final agent = Agent(dotPrompt.frontMatter.model!); await agent.send(prompt); ``` ## From Files You can also read prompts from files: ```dart theme={null} final file = File('prompts/summarize.prompt'); final content = await file.readAsString(); final dotPrompt = DotPrompt(content); final agent = Agent(dotPrompt.frontMatter.model!); await agent.send(dotPrompt.render()); ``` ## Examples * [DotPrompt example](https://github.com/csells/dartantic_ai/blob/main/packages/dartantic_ai/example/bin/dotprompt.dart) * [DotPrompt package](https://pub.dev/packages/dotprompt_dart) ## Next Steps * [Quick Start](/quick-start) - Agent fundamentals * [System Messages](/system-messages) - Built-in prompt management