adk_rust/
lib.rs

1//! # Agent Development Kit (ADK) for Rust
2//!
3//! [![Crates.io](https://img.shields.io/crates/v/adk-rust.svg)](https://crates.io/crates/adk-rust)
4//! [![Documentation](https://docs.rs/adk-rust/badge.svg)](https://docs.rs/adk-rust)
5//! [![License](https://img.shields.io/crates/l/adk-rust.svg)](https://github.com/zavora-ai/adk-rust/blob/main/LICENSE)
6//!
7//! A flexible and modular framework for developing and deploying AI agents in Rust.
8//! While optimized for Gemini and the Google ecosystem, ADK is model-agnostic,
9//! deployment-agnostic, and compatible with other frameworks.
10//!
11//! ## Quick Start
12//!
13//! Create your first AI agent in minutes:
14//!
15//! ```no_run
16//! use adk_rust::prelude::*;
17//! use adk_rust::Launcher;
18//! use std::sync::Arc;
19//!
20//! #[tokio::main]
21//! async fn main() -> Result<()> {
22//!     let api_key = std::env::var("GOOGLE_API_KEY")?;
23//!     let model = GeminiModel::new(&api_key, "gemini-2.0-flash-exp")?;
24//!
25//!     let agent = LlmAgentBuilder::new("assistant")
26//!         .description("A helpful AI assistant")
27//!         .instruction("You are a friendly assistant. Answer questions concisely.")
28//!         .model(Arc::new(model))
29//!         .build()?;
30//!
31//!     // Run in interactive console mode
32//!     Launcher::new(Arc::new(agent)).run().await?;
33//!     Ok(())
34//! }
35//! ```
36//!
37//! ## Installation
38//!
39//! Add to your `Cargo.toml`:
40//!
41//! ```toml
42//! [dependencies]
43//! adk-rust = "0.1"
44//! tokio = { version = "1.40", features = ["full"] }
45//! dotenv = "0.15"  # For loading .env files
46//! ```
47//!
48//! ### Feature Presets
49//!
50//! ```toml
51//! # Full (default) - Everything included
52//! adk-rust = "0.1"
53//!
54//! # Minimal - Agents + Gemini + Runner only
55//! adk-rust = { version = "0.1", default-features = false, features = ["minimal"] }
56//!
57//! # Custom - Pick exactly what you need
58//! adk-rust = { version = "0.1", default-features = false, features = [
59//!     "agents", "gemini", "tools", "sessions"
60//! ] }
61//! ```
62//!
63//! ## Agent Types
64//!
65//! ADK-Rust provides several agent types for different use cases:
66//!
67//! ### LlmAgent - AI-Powered Reasoning
68//!
69//! The core agent type that uses Large Language Models for intelligent reasoning:
70//!
71//! ```no_run
72//! use adk_rust::prelude::*;
73//! use std::sync::Arc;
74//!
75//! # async fn example() -> Result<()> {
76//! let api_key = std::env::var("GOOGLE_API_KEY")?;
77//! let model = GeminiModel::new(&api_key, "gemini-2.0-flash-exp")?;
78//!
79//! let agent = LlmAgentBuilder::new("researcher")
80//!     .description("Research assistant with web search")
81//!     .instruction("Search for information and provide detailed summaries.")
82//!     .model(Arc::new(model))
83//!     .tool(Arc::new(GoogleSearchTool::new()))  // Add tools
84//!     .build()?;
85//! # Ok(())
86//! # }
87//! ```
88//!
89//! ### Workflow Agents - Deterministic Pipelines
90//!
91//! For predictable, multi-step workflows:
92//!
93//! ```no_run
94//! use adk_rust::prelude::*;
95//! use std::sync::Arc;
96//!
97//! # async fn example() -> Result<()> {
98//! # let researcher: Arc<dyn Agent> = todo!();
99//! # let writer: Arc<dyn Agent> = todo!();
100//! # let reviewer: Arc<dyn Agent> = todo!();
101//! // Sequential: Execute agents in order
102//! let pipeline = SequentialAgent::new(
103//!     "content_pipeline",
104//!     vec![researcher, writer, reviewer]
105//! );
106//!
107//! // Parallel: Execute agents concurrently
108//! # let analyst1: Arc<dyn Agent> = todo!();
109//! # let analyst2: Arc<dyn Agent> = todo!();
110//! let parallel = ParallelAgent::new(
111//!     "multi_analysis",
112//!     vec![analyst1, analyst2]
113//! );
114//!
115//! // Loop: Iterate until condition met
116//! # let refiner: Arc<dyn Agent> = todo!();
117//! let loop_agent = LoopAgent::new("iterative_refiner", refiner, 5);
118//! # Ok(())
119//! # }
120//! ```
121//!
122//! ### Multi-Agent Systems
123//!
124//! Build hierarchical agent systems with automatic delegation:
125//!
126//! ```no_run
127//! use adk_rust::prelude::*;
128//! use std::sync::Arc;
129//!
130//! # async fn example() -> Result<()> {
131//! # let model: Arc<dyn Llm> = todo!();
132//! # let code_agent: Arc<dyn Agent> = todo!();
133//! # let test_agent: Arc<dyn Agent> = todo!();
134//! let coordinator = LlmAgentBuilder::new("coordinator")
135//!     .description("Development team coordinator")
136//!     .instruction("Delegate coding tasks to specialists.")
137//!     .model(model)
138//!     .sub_agent(code_agent)   // Delegate to sub-agents
139//!     .sub_agent(test_agent)
140//!     .build()?;
141//! # Ok(())
142//! # }
143//! ```
144//!
145//! ## Tools
146//!
147//! Give your agents capabilities beyond conversation:
148//!
149//! ### Function Tools - Custom Operations
150//!
151//! Convert any async function into a tool:
152//!
153//! ```no_run
154//! use adk_rust::prelude::*;
155//! use schemars::JsonSchema;
156//! use serde::{Deserialize, Serialize};
157//!
158//! #[derive(Debug, Deserialize, JsonSchema)]
159//! struct WeatherInput {
160//!     /// City name to get weather for
161//!     city: String,
162//! }
163//!
164//! #[derive(Debug, Serialize)]
165//! struct WeatherOutput {
166//!     temperature: f64,
167//!     conditions: String,
168//! }
169//!
170//! async fn get_weather(_ctx: ToolContext, input: WeatherInput) -> Result<WeatherOutput> {
171//!     // Your weather API call here
172//!     Ok(WeatherOutput {
173//!         temperature: 72.0,
174//!         conditions: "Sunny".to_string(),
175//!     })
176//! }
177//!
178//! # fn example() -> Result<()> {
179//! let weather_tool = FunctionTool::new(
180//!     "get_weather",
181//!     "Get current weather for a city",
182//!     get_weather,
183//! );
184//! # Ok(())
185//! # }
186//! ```
187//!
188//! ### Built-in Tools
189//!
190//! Ready-to-use tools included with ADK:
191//!
192//! - [`GoogleSearchTool`](tool::GoogleSearchTool) - Web search via Google
193//! - [`ExitLoopTool`](tool::ExitLoopTool) - Control loop termination
194//! - [`LoadArtifactsTool`](tool::LoadArtifactsTool) - Access stored artifacts
195//!
196//! ### MCP Tools - External Integrations
197//!
198//! Connect to Model Context Protocol servers:
199//!
200//! ```no_run
201//! use adk_rust::prelude::*;
202//!
203//! # async fn example() -> Result<()> {
204//! // Connect to an MCP server (e.g., filesystem, database)
205//! let mcp_tools = McpToolset::from_command("npx", &[
206//!     "-y", "@anthropic/mcp-server-filesystem", "/path/to/dir"
207//! ]).await?;
208//!
209//! // Add all MCP tools to your agent
210//! # let builder: LlmAgentBuilder = todo!();
211//! let agent = builder.toolset(Arc::new(mcp_tools)).build()?;
212//! # Ok(())
213//! # }
214//! ```
215//!
216//! ## Sessions & State
217//!
218//! Manage conversation context and working memory:
219//!
220//! ```no_run
221//! use adk_rust::prelude::*;
222//!
223//! # async fn example() -> Result<()> {
224//! # let session_service: InMemorySessionService = todo!();
225//! // Create a session
226//! let session = session_service.create("user_123", None).await?;
227//!
228//! // Store state with scoped prefixes
229//! let state = session.state();
230//! state.set("app:config", "production");      // App-level config
231//! state.set("user:preference", "dark_mode");  // User preferences
232//! state.set("temp:cache", "computed_value");  // Temporary data
233//!
234//! // State persists across conversation turns
235//! let config = state.get::<String>("app:config")?;
236//! # Ok(())
237//! # }
238//! ```
239//!
240//! ## Callbacks
241//!
242//! Intercept and customize agent behavior:
243//!
244//! ```no_run
245//! use adk_rust::prelude::*;
246//! use std::sync::Arc;
247//!
248//! # async fn example() -> Result<()> {
249//! # let model: Arc<dyn Llm> = todo!();
250//! let agent = LlmAgentBuilder::new("monitored_agent")
251//!     .model(model)
252//!     // Log all agent invocations
253//!     .before_agent(|ctx| {
254//!         Box::pin(async move {
255//!             println!("Agent starting: {}", ctx.agent_name);
256//!             Ok(None) // Continue execution
257//!         })
258//!     })
259//!     // Modify or cache model responses
260//!     .after_model(|ctx, response| {
261//!         Box::pin(async move {
262//!             println!("Model responded with {} tokens", response.usage.output_tokens);
263//!             Ok(response)
264//!         })
265//!     })
266//!     // Track tool usage
267//!     .before_tool(|ctx, name, args| {
268//!         Box::pin(async move {
269//!             println!("Calling tool: {} with {:?}", name, args);
270//!             Ok(None)
271//!         })
272//!     })
273//!     .build()?;
274//! # Ok(())
275//! # }
276//! ```
277//!
278//! ## Artifacts
279//!
280//! Store and retrieve binary data (images, files, etc.):
281//!
282//! ```no_run
283//! use adk_rust::prelude::*;
284//!
285//! # async fn example() -> Result<()> {
286//! # let artifact_service: InMemoryArtifactService = todo!();
287//! // Save an artifact
288//! let image_data = std::fs::read("chart.png")?;
289//! artifact_service.save(
290//!     "reports",           // namespace
291//!     "sales_chart.png",   // filename
292//!     &image_data,
293//!     "image/png",         // MIME type
294//! ).await?;
295//!
296//! // Load an artifact
297//! let artifact = artifact_service.load("reports", "sales_chart.png", None).await?;
298//! # Ok(())
299//! # }
300//! ```
301//!
302//! ## Deployment Options
303//!
304//! ### Console Mode (Interactive CLI)
305//!
306//! ```no_run
307//! use adk_rust::prelude::*;
308//! use adk_rust::Launcher;
309//! use std::sync::Arc;
310//!
311//! # async fn example() -> Result<()> {
312//! # let agent: Arc<dyn Agent> = todo!();
313//! // Interactive chat in terminal
314//! Launcher::new(agent).run().await?;
315//! # Ok(())
316//! # }
317//! ```
318//!
319//! ### Server Mode (REST API)
320//!
321//! ```bash
322//! # Run your agent as a web server
323//! cargo run -- serve --port 8080
324//! ```
325//!
326//! Provides endpoints:
327//! - `POST /chat` - Send messages
328//! - `GET /sessions` - List sessions
329//! - `GET /health` - Health check
330//!
331//! ### Agent-to-Agent (A2A) Protocol
332//!
333//! Expose your agent for inter-agent communication:
334//!
335//! ```no_run
336//! use adk_rust::server::{A2AServer, AgentCard};
337//!
338//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
339//! # let agent: std::sync::Arc<dyn adk_rust::Agent> = todo!();
340//! # let session_service: std::sync::Arc<adk_rust::session::InMemorySessionService> = todo!();
341//! # let artifact_service: std::sync::Arc<adk_rust::artifact::InMemoryArtifactService> = todo!();
342//! let card = AgentCard::new("my_agent", "https://my-agent.example.com")
343//!     .with_description("A helpful assistant")
344//!     .with_skill("research", "Can search and summarize information");
345//!
346//! let server = A2AServer::new(agent, card, session_service, artifact_service);
347//! server.serve(8080).await?;
348//! # Ok(())
349//! # }
350//! ```
351//!
352//! ## Observability
353//!
354//! Built-in OpenTelemetry support for production monitoring:
355//!
356//! ```no_run
357//! use adk_rust::telemetry::{TelemetryConfig, init_telemetry};
358//!
359//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
360//! let config = TelemetryConfig::new("my-agent-service")
361//!     .with_otlp_endpoint("http://localhost:4317");
362//!
363//! init_telemetry(config)?;
364//! // All agent operations now emit traces and metrics
365//! # Ok(())
366//! # }
367//! ```
368//!
369//! ## Architecture
370//!
371//! ADK-Rust uses a layered architecture for modularity:
372//!
373//! ```text
374//! ┌─────────────────────────────────────────────────────────────┐
375//! │                    Application Layer                        │
376//! │              Launcher • REST Server • A2A                   │
377//! ├─────────────────────────────────────────────────────────────┤
378//! │                      Runner Layer                           │
379//! │           Agent Execution • Event Streaming                 │
380//! ├─────────────────────────────────────────────────────────────┤
381//! │                      Agent Layer                            │
382//! │    LlmAgent • CustomAgent • Sequential • Parallel • Loop    │
383//! ├─────────────────────────────────────────────────────────────┤
384//! │                     Service Layer                           │
385//! │      Models • Tools • Sessions • Artifacts • Memory         │
386//! └─────────────────────────────────────────────────────────────┘
387//! ```
388//!
389//! ## Feature Flags
390//!
391//! | Feature | Description | Default |
392//! |---------|-------------|---------|
393//! | `agents` | Agent implementations | ✅ |
394//! | `models` | Model integrations | ✅ |
395//! | `gemini` | Gemini model support | ✅ |
396//! | `tools` | Tool system | ✅ |
397//! | `mcp` | MCP integration | ✅ |
398//! | `sessions` | Session management | ✅ |
399//! | `artifacts` | Artifact storage | ✅ |
400//! | `memory` | Semantic memory | ✅ |
401//! | `runner` | Execution runtime | ✅ |
402//! | `server` | HTTP server | ✅ |
403//! | `telemetry` | OpenTelemetry | ✅ |
404//! | `cli` | CLI launcher | ✅ |
405//!
406//! ## Examples
407//!
408//! The [examples directory](https://github.com/zavora-ai/adk-rust/tree/main/examples)
409//! contains working examples for every feature:
410//!
411//! - **Agents**: LLM agent, workflow agents, multi-agent systems
412//! - **Tools**: Function tools, Google Search, MCP integration
413//! - **Sessions**: State management, conversation history
414//! - **Callbacks**: Logging, guardrails, caching
415//! - **Deployment**: Console, server, A2A protocol
416//!
417//! ## Related Crates
418//!
419//! ADK-Rust is composed of modular crates that can be used independently:
420//!
421//! - [`adk-core`](https://docs.rs/adk-core) - Core traits and types
422//! - [`adk-agent`](https://docs.rs/adk-agent) - Agent implementations
423//! - [`adk-model`](https://docs.rs/adk-model) - LLM integrations
424//! - [`adk-tool`](https://docs.rs/adk-tool) - Tool system
425//! - [`adk-session`](https://docs.rs/adk-session) - Session management
426//! - [`adk-artifact`](https://docs.rs/adk-artifact) - Artifact storage
427//! - [`adk-runner`](https://docs.rs/adk-runner) - Execution runtime
428//! - [`adk-server`](https://docs.rs/adk-server) - HTTP server
429//! - [`adk-telemetry`](https://docs.rs/adk-telemetry) - Observability
430
431#![warn(missing_docs)]
432#![cfg_attr(docsrs, feature(doc_cfg))]
433
434// ============================================================================
435// Core (always available)
436// ============================================================================
437
438/// Core traits and types.
439///
440/// Always available regardless of feature flags. Includes:
441/// - [`Agent`] - The fundamental trait for all agents
442/// - [`Tool`] / [`Toolset`] - For extending agents with capabilities
443/// - [`Session`] / [`State`] - For managing conversation context
444/// - [`Event`] - For streaming agent responses
445/// - [`AdkError`] / [`Result`] - Unified error handling
446pub use adk_core::*;
447
448// Re-export common dependencies for convenience
449pub use anyhow;
450pub use async_trait::async_trait;
451pub use futures;
452pub use serde;
453pub use serde_json;
454pub use tokio;
455
456// ============================================================================
457// Component Modules (feature-gated)
458// ============================================================================
459
460/// Agent implementations (LLM, Custom, Workflow agents).
461///
462/// Provides the core agent types:
463/// - [`LlmAgent`](agent::LlmAgent) - AI-powered agent using LLMs
464/// - [`CustomAgent`](agent::CustomAgent) - Implement custom agent logic
465/// - [`SequentialAgent`](agent::SequentialAgent) - Execute agents in sequence
466/// - [`ParallelAgent`](agent::ParallelAgent) - Execute agents concurrently
467/// - [`LoopAgent`](agent::LoopAgent) - Iterative execution until condition met
468///
469/// Available with feature: `agents`
470#[cfg(feature = "agents")]
471#[cfg_attr(docsrs, doc(cfg(feature = "agents")))]
472pub mod agent {
473    pub use adk_agent::*;
474}
475
476/// Model integrations (Gemini, etc.).
477///
478/// Provides LLM implementations:
479/// - [`GeminiModel`](model::GeminiModel) - Google's Gemini models
480///
481/// ADK is model-agnostic - implement the [`Llm`] trait for other providers.
482///
483/// Available with feature: `models`
484#[cfg(feature = "models")]
485#[cfg_attr(docsrs, doc(cfg(feature = "models")))]
486pub mod model {
487    pub use adk_model::*;
488}
489
490/// Tool system and built-in tools.
491///
492/// Give agents capabilities beyond conversation:
493/// - [`FunctionTool`](tool::FunctionTool) - Wrap async functions as tools
494/// - [`GoogleSearchTool`](tool::GoogleSearchTool) - Web search
495/// - [`ExitLoopTool`](tool::ExitLoopTool) - Control loop agents
496/// - [`McpToolset`](tool::McpToolset) - MCP server integration
497///
498/// Available with feature: `tools`
499#[cfg(feature = "tools")]
500#[cfg_attr(docsrs, doc(cfg(feature = "tools")))]
501pub mod tool {
502    pub use adk_tool::*;
503}
504
505/// Session management.
506///
507/// Manage conversation context and state:
508/// - [`InMemorySessionService`](session::InMemorySessionService) - In-memory sessions
509/// - Session creation, retrieval, and lifecycle
510/// - State management with scoped prefixes
511///
512/// Available with feature: `sessions`
513#[cfg(feature = "sessions")]
514#[cfg_attr(docsrs, doc(cfg(feature = "sessions")))]
515pub mod session {
516    pub use adk_session::*;
517}
518
519/// Artifact storage.
520///
521/// Store and retrieve binary data:
522/// - [`InMemoryArtifactService`](artifact::InMemoryArtifactService) - In-memory storage
523/// - Version tracking for artifacts
524/// - Namespace scoping
525///
526/// Available with feature: `artifacts`
527#[cfg(feature = "artifacts")]
528#[cfg_attr(docsrs, doc(cfg(feature = "artifacts")))]
529pub mod artifact {
530    pub use adk_artifact::*;
531}
532
533/// Memory system with semantic search.
534///
535/// Long-term memory for agents:
536/// - [`InMemoryMemoryService`](memory::InMemoryMemoryService) - In-memory storage
537/// - Semantic search capabilities
538/// - Memory retrieval and updates
539///
540/// Available with feature: `memory`
541#[cfg(feature = "memory")]
542#[cfg_attr(docsrs, doc(cfg(feature = "memory")))]
543pub mod memory {
544    pub use adk_memory::*;
545}
546
547/// Agent execution runtime.
548///
549/// The engine that manages agent execution:
550/// - [`Runner`](runner::Runner) - Executes agents with full context
551/// - [`RunnerConfig`](runner::RunnerConfig) - Configuration options
552/// - Event streaming and tool coordination
553///
554/// Available with feature: `runner`
555#[cfg(feature = "runner")]
556#[cfg_attr(docsrs, doc(cfg(feature = "runner")))]
557pub mod runner {
558    pub use adk_runner::*;
559}
560
561/// HTTP server (REST + A2A).
562///
563/// Deploy agents as web services:
564/// - REST API for chat interactions
565/// - A2A (Agent-to-Agent) protocol support
566/// - Web UI integration
567///
568/// Available with feature: `server`
569#[cfg(feature = "server")]
570#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
571pub mod server {
572    pub use adk_server::*;
573}
574
575/// Telemetry (OpenTelemetry integration).
576///
577/// Production observability:
578/// - Distributed tracing
579/// - Metrics collection
580/// - Log correlation
581///
582/// Available with feature: `telemetry`
583#[cfg(feature = "telemetry")]
584#[cfg_attr(docsrs, doc(cfg(feature = "telemetry")))]
585pub mod telemetry {
586    pub use adk_telemetry::*;
587}
588
589/// CLI launcher for running agents.
590///
591/// Quick way to run agents in console or server mode:
592/// - [`Launcher`] - Main entry point for CLI apps
593/// - [`SingleAgentLoader`] - Load a single agent
594///
595/// Available with feature: `cli`
596#[cfg(feature = "cli")]
597#[cfg_attr(docsrs, doc(cfg(feature = "cli")))]
598pub use adk_cli::{Launcher, SingleAgentLoader};
599
600// ============================================================================
601// Prelude
602// ============================================================================
603
604/// Convenience prelude for common imports.
605///
606/// Import everything you need with a single line:
607///
608/// ```
609/// use adk_rust::prelude::*;
610/// ```
611///
612/// This includes:
613/// - Core traits: `Agent`, `Tool`, `Llm`, `Session`
614/// - Agent builders: `LlmAgentBuilder`, `CustomAgentBuilder`
615/// - Workflow agents: `SequentialAgent`, `ParallelAgent`, `LoopAgent`
616/// - Models: `GeminiModel`
617/// - Tools: `FunctionTool`, `GoogleSearchTool`, `McpToolset`
618/// - Services: `InMemorySessionService`, `InMemoryArtifactService`
619/// - Runtime: `Runner`, `RunnerConfig`
620/// - Common types: `Arc`, `Result`, `Content`, `Event`
621pub mod prelude {
622    // Core types (always available)
623    pub use crate::{
624        AdkError, Agent, BeforeModelResult, Content, Event, EventStream, InvocationContext, Llm,
625        LlmRequest, LlmResponse, Part, Result, RunConfig, Session, State, Tool, ToolContext,
626        Toolset,
627    };
628
629    // Agents
630    #[cfg(feature = "agents")]
631    pub use crate::agent::{
632        ConditionalAgent, CustomAgent, CustomAgentBuilder, LlmAgent, LlmAgentBuilder, LoopAgent,
633        ParallelAgent, SequentialAgent,
634    };
635
636    // Models
637    #[cfg(feature = "models")]
638    pub use crate::model::GeminiModel;
639
640    // Tools
641    #[cfg(feature = "tools")]
642    pub use crate::tool::{
643        BasicToolset, ExitLoopTool, FunctionTool, GoogleSearchTool, LoadArtifactsTool, McpToolset,
644    };
645
646    // Sessions
647    #[cfg(feature = "sessions")]
648    pub use crate::session::InMemorySessionService;
649
650    // Artifacts
651    #[cfg(feature = "artifacts")]
652    pub use crate::artifact::InMemoryArtifactService;
653
654    // Memory
655    #[cfg(feature = "memory")]
656    pub use crate::memory::InMemoryMemoryService;
657
658    // Runner
659    #[cfg(feature = "runner")]
660    pub use crate::runner::{Runner, RunnerConfig};
661
662    // Common re-exports
663    pub use crate::anyhow::Result as AnyhowResult;
664    pub use crate::async_trait;
665    pub use std::sync::Arc;
666}