### Full Usage Example Source: https://github.com/csells/dartantic/wiki/Chat-Architecture A complete example showing the setup of the API key and the instantiation of the AgentChatView. ```dart 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'); runApp(const App()); } // In widget: AgentChatView( provider: DartanticProvider( agent: Agent.gemini( model: 'gemini-3-flash-preview', apiKey: _apiKey, ), ), ) ``` -------------------------------- ### Quick Start with LoggingOptions Source: https://github.com/csells/dartantic/wiki/Logging-Architecture Enable default logging for agents and operations with a simple setup. This is the recommended approach for most use cases. ```dart import 'package:dartantic_ai/dartantic_ai.dart'; void main() async { // Simple setup - just enable logging with defaults Agent.loggingOptions = LoggingOptions(); // Create agent - will generate logs final agent = Agent('openai:gpt-4o'); // Run conversation - will generate detailed logs final result = await agent.send('Hello!'); // Embeddings operations also generate logs final embedding = await agent.embedQuery('search text'); } ``` -------------------------------- ### Run Example App Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-chat/getting-started.mdx Navigate to the example directory and run the application with the required API key. ```bash cd packages/dartantic_chat/example flutter run --dart-define=GEMINI_API_KEY=your-api-key-here ``` -------------------------------- ### Manual Production Logging Setup Source: https://github.com/csells/dartantic/wiki/Logging-Architecture Manually configure the root logger for production environments. This example captures severe errors for monitoring and sends other logs to a structured logger. ```dart Logger.root.level = Level.INFO; Logger.root.onRecord.listen((record) { if (record.level >= Level.WARNING) { errorMonitoring.captureException(record.message); } structuredLogger.log({ 'level': record.level.name, 'logger': record.loggerName, 'message': record.message, 'timestamp': record.time.toIso8601String(), }); }); ``` -------------------------------- ### Dartantic AI Quick Start Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_ai/README.md Demonstrates basic agent creation, text generation, and typed output retrieval using Dartantic AI. Requires API key setup for the chosen provider. ```dart import 'package:dartantic_ai/dartantic_ai.dart'; void main() async { // Create an agent with your preferred provider final agent = Agent.forProvider(OpenAIProvider(apiKey: apiKey)); // Generate text final result = await agent.send( 'Explain quantum computing in simple terms', history: [ChatMessage.system('You are a helpful assistant.')], ); print(result.output); // Use typed outputs with json_schema_builder final location = await agent.sendFor( 'The windy city in the US', outputSchema: S.object( properties: { 'town': S.string(), 'country': S.string(), }, required: ['town', 'country'], ), outputFromJson: TownAndCountry.fromJson, ); print('${location.output.town}, ${location.output.country}'); } class TownAndCountry { final String town; final String country; TownAndCountry({required this.town, required this.country}); factory TownAndCountry.fromJson(Map json) => TownAndCountry( town: json['town'] as String, country: json['country'] as String, ); } ``` -------------------------------- ### Install Chatarang Dependencies Source: https://github.com/csells/dartantic/blob/main/docs/chatarang.mdx Navigate to the Chatarang sample directory and install its dependencies using Dart's package manager. ```bash cd samples/chatarang dart pub get ``` -------------------------------- ### Installation of Flutter Library Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_chat/example/windows/CMakeLists.txt Installs the main Flutter library file to the installation prefix. This is a core component required for the Flutter engine to run. ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Installation Target for Executable Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_chat/example/windows/CMakeLists.txt Installs the main application executable to the specified runtime destination. This ensures the binary is placed correctly for execution. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Agent and Settings Configuration Source: https://github.com/csells/dartantic/wiki/Dartantic-CLI-Spec Examples of invoking specific agents, setting temperatures, and using custom configuration files. ```bash dartantic -a extractor -p "John Smith works at Acme Corp as a software engineer." ``` ```bash dartantic -t 0.9 -p "Write a creative story opening" ``` ```bash dartantic -v -p "Hello" ``` ```bash dartantic -a pirate -p "What is your favorite food?" ``` ```bash cat > /tmp/custom-settings.yaml << 'EOF' default_agent: custom agents: custom: model: google system: Always respond with exactly one word. EOF dartantic -s /tmp/custom-settings.yaml -p "How are you?" ``` ```bash dartantic --no-color -a openai-responses:o1 -p "Think about 2+2" ``` -------------------------------- ### Example Usage: Image Generation with Previews Source: https://github.com/csells/dartantic/wiki/Server-Side-Tools-Tech-Design Example of generating images with previews and handling final DataParts. ```APIDOC ### Image Generation with Previews ```dart await for (final chunk in agent.sendStream('Generate a logo')) { final imageEvents = chunk.metadata['image_generation'] as List?; if (imageEvents != null) { for (final event in imageEvents) { // Save partial images if (event['partial_image_b64'] != null) { final bytes = base64Decode(event['partial_image_b64']); savePreview(bytes, event['partial_image_index']); } } } // Final image as DataPart for (final msg in chunk.messages) { for (final part in msg.parts) { if (part is DataPart && part.mimeType.startsWith('image/')) { saveFinal(part.bytes); } } } } ``` ``` -------------------------------- ### Run Tool Calling Example Source: https://github.com/csells/dartantic/blob/main/CLAUDE.md Execute the tool calling example from the dartantic_ai package. This demonstrates how the framework can integrate with external tools. ```bash cd packages/dartantic_ai && dart run example/bin/tool_calling.dart ``` -------------------------------- ### DotPrompt Template Example Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-cli.mdx This example defines a reusable prompt template named `math.prompt`. It includes YAML frontmatter for configuration (model, input defaults) and Mustache syntax for variable placeholders. ```yaml # math.prompt --- model: google input: default: operation: add --- Calculate: What is 5 {{operation}} 3? ``` -------------------------------- ### Install Dartantic CLI Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-cli.mdx Navigate to the Dartantic CLI samples directory and install dependencies using Dart's package manager. ```bash cd samples/dartantic_cli dart pub get ``` -------------------------------- ### Multi-Step Tool Calling Example Source: https://github.com/csells/dartantic/blob/main/docs/chatarang.mdx Demonstrates the agentic flow of chaining location lookup and weather tools to answer a user query. ```text 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. ``` -------------------------------- ### Get Weather Information using Tool Source: https://github.com/csells/dartantic/blob/main/docs/chatarang.mdx Example of the AI using the 'weather' tool with a US zipcode to retrieve and report weather conditions. The tool requires a 'zipcode' parameter. ```text 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. ``` -------------------------------- ### Run All CLI Example Scripts Source: https://github.com/csells/dartantic/blob/main/CLAUDE.md Execute all example scripts located in the samples/dartantic_cli/example directory. This provides a comprehensive demonstration of the CLI's capabilities. ```bash cd samples/dartantic_cli && bash example/run_all.sh ``` -------------------------------- ### Run Single CLI Example Script Source: https://github.com/csells/dartantic/blob/main/CLAUDE.md Execute a specific example script for the Dartantic command-line interface, such as 'simple_chat.sh'. ```bash cd samples/dartantic_cli && bash example/basic/simple_chat.sh ``` -------------------------------- ### Multi-Step Tool Use Example Source: https://github.com/csells/dartantic/blob/main/samples/chatarang/README.md Shows the agent performing a location lookup followed by a weather query to answer a complex question. ```text You: what's the weather at the moda center in portland, or? Tool.call: location-lookup({ "location": "Moda Center, Portland, OR" }) Tool.result: location-lookup: { "result": [ { "place_id": 301178490, "licence": "Data © OpenStreetMap contributors, ODbL 1.0. http://osm.org/copyright", "osm_type": "way", "osm_id": 24635906, "lat": "45.5315787", "lon": "-122.6668337", "address": { "postcode": "97240", ... }, ... } ] } Tool.call: weather({ "zipcode": "97240" }) Tool.result: weather: { "result": { "current_condition": [ { "FeelsLikeF": "53", "humidity": "89", ... } ] } } google:gemini-2.0-flash: The weather at the Moda Center in Portland, OR is currently 55°F with light rain and mist. The wind is from the south at 9 mph. The UV index is 1. ``` -------------------------------- ### Install Dependencies Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_firebase_ai/example/README.md Command to fetch project dependencies defined in pubspec.yaml. ```bash flutter pub get ``` -------------------------------- ### Install dependencies Source: https://github.com/csells/dartantic/blob/main/docs/contributing.mdx Fetches required packages for the Dart project. ```bash dart pub get ``` -------------------------------- ### Run Single Turn Chat Example Source: https://github.com/csells/dartantic/blob/main/CLAUDE.md Execute the single-turn chat example from the dartantic_ai package. This demonstrates basic chat functionality. ```bash cd packages/dartantic_ai && dart run example/bin/single_turn_chat.dart ``` -------------------------------- ### Dartantic Full Configuration Example Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-cli.mdx This YAML configuration defines global defaults and specific agent settings, including models, system prompts, and tool configurations. It serves as a comprehensive example for setting up Dartantic. ```yaml # 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 ``` -------------------------------- ### Run Typed Output Example Source: https://github.com/csells/dartantic/blob/main/CLAUDE.md Execute the typed output example from the dartantic_ai package. This showcases how to handle strongly-typed responses from the AI. ```bash cd packages/dartantic_ai && dart run example/bin/typed_output.dart ``` -------------------------------- ### Installation of Bundled Plugin Libraries Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_chat/example/windows/CMakeLists.txt Installs any bundled native libraries required by plugins. This ensures that all necessary plugin dependencies are available at runtime. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Interact with Chatarang REPL Source: https://github.com/csells/dartantic/blob/main/docs/samples.mdx Example of an interactive session showing tool calling and provider responses. ```text 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. ``` -------------------------------- ### Run dartantic_chat Flutter Example with Gemini API Key Source: https://github.com/csells/dartantic/blob/main/CLAUDE.md Run the Flutter chat UI example from the dartantic_chat package. Requires a GEMINI_API_KEY environment variable to be set. ```bash cd packages/dartantic_chat/example && flutter run --dart-define=GEMINI_API_KEY=$GEMINI_API_KEY ``` -------------------------------- ### Anthropic Web Fetch Example Source: https://github.com/csells/dartantic/wiki/Server-Side-Tools-Tech-Design Set up an agent for Anthropic's web fetch tool. Stream content from a URL and identify DataParts for fetched documents. ```dart final agent = Agent( 'anthropic', chatModelOptions: const AnthropicChatOptions( serverSideTools: {AnthropicServerSideTool.webFetch}, ), ); final history = []; await for (final chunk in agent.sendStream( 'Retrieve https://example.com and summarize its content', )) { stdout.write(chunk.output); history.addAll(chunk.messages); } // Fetched document bytes appear as DataParts for (final msg in history) { for (final part in msg.parts) { if (part is DataPart) { print('Fetched: ${part.name} (${part.mimeType})'); // Save or process the fetched document bytes } } } ``` -------------------------------- ### Run Dartantic Example with Warning Logging Source: https://github.com/csells/dartantic/wiki/Logging-Architecture Execute a Dartantic example script that focuses on errors by setting the DARTANTIC_LOG_LEVEL environment variable to WARNING. ```bash DARTANTIC_LOG_LEVEL=WARNING dart run example/bin/tool_calling.dart ``` -------------------------------- ### Installation of Flutter Assets Directory Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_chat/example/windows/CMakeLists.txt Installs the Flutter assets directory, which contains resources like images and fonts. The directory is re-copied on each build to prevent stale files. ```cmake set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Manual Logging Setup Source: https://github.com/csells/dartantic/wiki/Logging-Architecture Manually configure the root logger for complete control over logging behavior. This is for advanced users who need fine-grained control. ```dart import 'package:logging/logging.dart'; import 'package:dartantic_ai/dartantic_ai.dart'; void main() async { // Manual setup for full control Logger.root.level = Level.ALL; Logger.root.onRecord.listen((record) { print('[${record.loggerName}] ${record.level}: ${record.message}'); }); final agent = Agent('openai:gpt-4o'); } ``` -------------------------------- ### Run Dartantic CLI Source: https://github.com/csells/dartantic/blob/main/CLAUDE.md Execute the Dartantic command-line interface tool from the samples/dartantic_cli directory. This example sends a 'Hello' message. ```bash cd samples/dartantic_cli && dart run bin/dartantic.dart -p "Hello" ``` -------------------------------- ### Sample Chatarang Session Source: https://github.com/csells/dartantic/blob/main/docs/chatarang.mdx A full walkthrough of a CLI session including model listing, tool usage, model switching, and exiting. ```text $ 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! ``` -------------------------------- ### Get Current Time using Tool Source: https://github.com/csells/dartantic/blob/main/docs/chatarang.mdx Example of the AI using the 'current-time' tool to retrieve and report the current time. The tool returns an ISO 8601 timestamp. ```text 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. ``` -------------------------------- ### Initialize and Use Agents Source: https://github.com/csells/dartantic/blob/main/wiki/Home.md Demonstrates basic agent instantiation, model selection, tool integration, and embedding generation. ```dart // Simple usage with defaults final agent = Agent('openai'); await agent.send('Hello!'); // Specific models final agent = Agent('openai?chat=gpt-4&embeddings=ada'); // With tools final agent = Agent('anthropic', tools: [weatherTool]); await agent.sendStream('What is the weather?'); // Embeddings final embedding = await agent.embedQuery('search text'); ``` -------------------------------- ### Example Usage: Web Search Source: https://github.com/csells/dartantic/wiki/Server-Side-Tools-Tech-Design Example of how to stream and process web search results. ```APIDOC ## Example Usage ### Web Search ```dart await for (final chunk in agent.sendStream('What are the latest Dart news?')) { final webSearchEvents = chunk.metadata['web_search'] as List?; if (webSearchEvents != null) { for (final event in webSearchEvents) { print('Stage: ${event['type']}'); } } } ``` ``` -------------------------------- ### Setup Vector Store for File Search Source: https://github.com/csells/dartantic/blob/main/docs/server-side-tools/openai-file-search.mdx Upload wiki documents and create a reusable vector store using the `setupVectorStore` helper function. This function takes a list of file paths as input and returns the ID of the created vector store. ```dart final vectorStoreId = await setupVectorStore([ '../../../wiki/Server-Side-Tools-Tech-Design.md', '../../../wiki/Message-Handling-Architecture.md', ]); ``` -------------------------------- ### Instantiate Agents with Different Providers and Models Source: https://github.com/csells/dartantic/blob/main/docs/providers.mdx Demonstrates how to create Agent instances for various AI providers and models, including specifying chat and embedding models, enabling extended thinking, and using server-side tools. ```dart // 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); ``` -------------------------------- ### Installation of Native Assets Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_chat/example/windows/CMakeLists.txt Installs native assets provided by build.dart from all packages. These assets are typically required for the application's functionality. ```cmake set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Clone the repository Source: https://github.com/csells/dartantic/blob/main/docs/contributing.mdx Initial step to obtain a local copy of the project. ```bash git clone https://github.com/csells/dartantic_ai.git cd dartantic_ai ``` -------------------------------- ### Installation of ICU Data File Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_chat/example/windows/CMakeLists.txt Installs the ICU data file, which is necessary for internationalization and localization, to the data directory next to the executable. ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Run Dartantic Example with Logging Disabled Source: https://github.com/csells/dartantic/wiki/Logging-Architecture Execute a Dartantic example script with all logging disabled by setting the DARTANTIC_LOG_LEVEL environment variable to OFF. ```bash DARTANTIC_LOG_LEVEL=OFF dart run example/bin/typed_output.dart ``` -------------------------------- ### Configure via environment variables Source: https://github.com/csells/dartantic/wiki/CLI-Spec Setting behavior and credentials using environment variables. ```bash DARTANTIC_AGENT=anthropic dartantic -p "Hello" ``` ```bash DARTANTIC_LOG_LEVEL=FINE dartantic -p "Hello" 2>&1 | grep -q "\[" && echo "PASS: Logging detected" ``` ```bash OPENAI_API_KEY=sk-test dartantic -a openai -p "Hello" 2>&1 || true ``` ```bash export TEST_TOKEN="my-secret-token" cat > /tmp/env-settings.yaml << 'EOF' agents: test: model: google headers: Authorization: "Bearer ${TEST_TOKEN}" EOF dartantic -s /tmp/env-settings.yaml -a test -p "Hello" ``` -------------------------------- ### Configure OpenAI Reasoning Source: https://github.com/csells/dartantic/wiki/Thinking Demonstrates simple and advanced configuration for enabling thinking in OpenAI models. ```dart import 'package:dartantic_ai/dartantic_ai.dart'; // Simple configuration - enable thinking with default settings final agent = Agent( 'openai-responses:gpt-5', enableThinking: true, // Automatically uses reasoningSummary: detailed ); // Advanced configuration - customize reasoning options final agentAdvanced = Agent( 'openai-responses:gpt-5', enableThinking: true, chatModelOptions: const OpenAIResponsesChatModelOptions( reasoningSummary: OpenAIReasoningSummary.brief, // Override default reasoningEffort: OpenAIReasoningEffort.high, ), ); ``` -------------------------------- ### Installation of AOT Library Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_chat/example/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compilation library on non-Debug builds (Profile and Release). This library is used for performance optimization. ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Agent Usage Examples Source: https://github.com/csells/dartantic/wiki/Home Demonstrates basic and advanced usage patterns for the Agent class, including default instantiation, specifying models via URI, integrating tools, and generating embeddings. ```dart final agent = Agent('openai'); await agent.send('Hello!'); ``` ```dart final agent = Agent('openai?chat=gpt-4&embeddings=ada'); ``` ```dart final agent = Agent('anthropic', tools: [weatherTool]); await agent.sendStream('What is the weather?'); ``` ```dart final embedding = await agent.embedQuery('search text'); ``` -------------------------------- ### Initialize Dartantic Agent Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-chat/getting-started.mdx Set up the agent in your main entry point using the provided API key. ```dart 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()); } ``` -------------------------------- ### Custom Chat History Provider Implementation Example Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-chat/custom-providers.mdx An example implementation of a custom chat history provider. This class extends ChatHistoryProvider and ChangeNotifier, demonstrating how to manage chat history, handle user prompts, and integrate with a hypothetical LLM for generating responses. ```dart 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'; } } ``` -------------------------------- ### Discover and Create AI Providers Source: https://github.com/csells/dartantic/blob/main/docs/providers.mdx Shows how to list all available providers and create a specific provider instance by name. Use `Provider.listModels()` for runtime capability discovery. ```dart // 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}'); } ``` -------------------------------- ### Define and Use Tools Source: https://github.com/csells/dartantic/blob/main/docs/index.mdx Create a tool with a schema and callback, then pass it to the agent for autonomous execution. ```dart 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?"); ``` -------------------------------- ### Execute multimedia input Source: https://github.com/csells/dartantic/wiki/CLI-Spec Include a file reference in a prompt. ```bash dartantic -p "Describe @photo.jpg" ``` -------------------------------- ### Install Dartantic AI Source: https://github.com/csells/dartantic/blob/main/docs/index.mdx Add the package dependency to your pubspec.yaml file. ```yaml dependencies: dartantic_ai: ^VERSION ``` -------------------------------- ### Install Dartantic Chat Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-chat/getting-started.mdx Add the dependency to your project using the Flutter CLI. ```sh $ flutter pub add dartantic_chat ``` -------------------------------- ### Initialize StreamingState Source: https://github.com/csells/dartantic/wiki/State-Management-Architecture Resets the state to ensure a clean starting point for new messages. ```dart // In StreamingOrchestrator.initialize() @override void initialize(StreamingState state) { _logger.fine('Initializing orchestrator with state'); state.resetForNewMessage(); // Ensure clean starting state } ``` -------------------------------- ### Initialize Agents with Model Strings Source: https://github.com/csells/dartantic/wiki/Model-String-Format Shows how to instantiate Agent objects using different model string configurations. ```dart // Simple provider final agent1 = Agent('openai'); // Uses default chat, embeddings, and media models // Specific chat model final agent2 = Agent('openai:gpt-4o'); // Uses gpt-4o for chat, defaults for embeddings and media // Different models for each operation final agent3 = Agent('openai?chat=gpt-4o&embeddings=text-embedding-3-large&media=dall-e-3'); // Explicit models for all operations ``` -------------------------------- ### Generate media with Google Source: https://github.com/csells/dartantic/wiki/Dartantic-CLI-Spec Generate media using the Google provider. ```bash dartantic generate -a google --mime image/png -p "..." ``` -------------------------------- ### Configure Firebase CLI Source: https://github.com/csells/dartantic/blob/main/packages/dartantic_firebase_ai/example/README.md Commands to install the FlutterFire CLI and configure the Firebase project environment. ```bash # Install FlutterFire CLI dart pub global activate flutterfire_cli # Configure Firebase for your project flutterfire configure ``` -------------------------------- ### Execute with usage tracking Source: https://github.com/csells/dartantic/wiki/CLI-Spec Run a command with verbose output for usage tracking. ```bash dartantic -v -p "..." ``` -------------------------------- ### Model String Formats Source: https://github.com/csells/dartantic/blob/main/wiki/Model-Configuration-Spec.md Examples of generated model strings based on the available model types for a provider. ```text openai?chat=gpt-4o&embeddings=text-embedding-3-small&media=dall-e-3 ``` ```text openai?chat=gpt-4o&embeddings=text-embedding-3-small ``` ```text openai:gpt-4o ``` -------------------------------- ### Execute dotprompt Source: https://github.com/csells/dartantic/wiki/CLI-Spec Run a prompt file with parameters. ```bash dartantic -p @story.prompt length=5 ``` -------------------------------- ### Disable server-side tools via CLI Source: https://github.com/csells/dartantic/wiki/Dartantic-CLI-Spec Example command demonstrating how to exclude specific server-side tools for a provider. ```bash dartantic -a anthropic --no-server-tool webSearch,codeInterpreter -p "Hello" ``` -------------------------------- ### Example JSON Output for Audio Transcription Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-cli.mdx Demonstrates the structure of the JSON output when requesting word-level timestamps for audio transcription. ```json { "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} ] } ``` -------------------------------- ### Using Model Strings and Provider Configurations Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-cli.mdx Specify exact models or configure providers with specific parameters like embeddings for advanced usage. ```bash # 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" ``` -------------------------------- ### Quick Agent Configuration (Thinking Disabled) Source: https://github.com/csells/dartantic/blob/main/wiki/CLI-Spec.md Sets up a 'quick' agent with thinking disabled for concise and direct responses. ```yaml # Agent with thinking disabled quick: model: google:gemini-2.5-flash system: Be concise and direct. thinking: false ``` -------------------------------- ### Dartantic Model Stream Processing Logging Source: https://github.com/csells/dartantic/wiki/Logging-Architecture Log the start and completion of model stream processing, and the consolidation of message parts. ```dart _logger.fine('Starting model stream processing'); ``` ```dart _logger.fine('Stream closed. Consolidated message has ${consolidatedMessage.parts.length} parts'); ``` -------------------------------- ### Enable Default Logging Source: https://github.com/csells/dartantic/blob/main/wiki/Logging-Architecture.md Enables default logging for all Dartantic AI operations. No specific setup is required beyond this assignment. ```dart import 'package:dartantic_ai/dartantic_ai.dart'; // Enable default logging Agent.loggingOptions = LoggingOptions(); ``` -------------------------------- ### Configure Alternative LLM Providers Source: https://github.com/csells/dartantic/blob/main/docs/dartantic-chat/getting-started.mdx Initialize agents for different providers like OpenAI, Anthropic, or Ollama. ```dart // 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'); ``` -------------------------------- ### Provider: Implement createMediaModel Source: https://github.com/csells/dartantic/wiki/Provider-Implementation-Guide Providers that support media generation must implement `createMediaModel` or throw an `UnsupportedError`. ```dart createMediaModel ```