adk_rust/lib.rs
1//! # Agent Development Kit (ADK) for Rust
2//!
3//! [](https://crates.io/crates/adk-rust)
4//! [](https://docs.rs/adk-rust)
5//! [](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//! ```ignore
16//! use adk_rust::prelude::*;
17//! use adk_rust::Launcher;
18//! use std::sync::Arc;
19//!
20//! #[tokio::main]
21//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
22//! let api_key = std::env::var("GOOGLE_API_KEY")?;
23//! let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;
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 = "2.2.0"
44//! tokio = { version = "1.40", features = ["full"] }
45//! dotenvy = "0.15" # For loading .env files
46//! ```
47//!
48//! ### Feature Presets
49//!
50//! ```toml
51//! # Minimal (default) — agents, Gemini, runner, sessions (fastest build)
52//! adk-rust = "2.2.0"
53//!
54//! # Standard — minimal + tools, memory, OpenAI, Anthropic, server, auth,
55//! # graph, eval, guardrails, skills, plugins, artifacts, telemetry
56//! adk-rust = { version = "2.2.0", features = ["standard"] }
57//!
58//! # Enterprise — standard + realtime, browser, rag, payments, awp
59//! adk-rust = { version = "2.2.0", features = ["enterprise"] }
60//!
61//! # Full — enterprise + experimental crates (audio, code, sandbox)
62//! adk-rust = { version = "2.2.0", features = ["full"] }
63//!
64//! # Custom — pick exactly what you need
65//! adk-rust = { version = "2.2.0", default-features = false, features = [
66//! "agents", "gemini", "tools", "sessions", "openai", "openrouter"
67//! ] }
68//! ```
69//!
70//! ## Agent Types
71//!
72//! ADK-Rust provides several agent types for different use cases:
73//!
74//! ### LlmAgent - AI-Powered Reasoning
75//!
76//! The core agent type that uses Large Language Models for intelligent
77//! reasoning. `GoogleSearchTool` below requires the `tools` feature (included in
78//! `standard` and above); the agent itself needs only the default tier:
79//!
80//! ```no_run
81//! use adk_rust::prelude::*;
82//! use std::sync::Arc;
83//!
84//! # async fn example() -> Result<()> {
85//! let api_key = std::env::var("GOOGLE_API_KEY").map_err(|e| AdkError::config(e.to_string()))?;
86//! let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;
87//!
88//! let agent = LlmAgentBuilder::new("researcher")
89//! .description("Research assistant with web search")
90//! .instruction("Search for information and provide detailed summaries.")
91//! .model(Arc::new(model))
92//! .tool(Arc::new(GoogleSearchTool::new())) // Add tools
93//! .build()?;
94//! # Ok(())
95//! # }
96//! ```
97//!
98//! ### Workflow Agents - Deterministic Pipelines
99//!
100//! For predictable, multi-step workflows:
101//!
102//! ```no_run
103//! use adk_rust::prelude::*;
104//! use std::sync::Arc;
105//!
106//! # async fn example() -> Result<()> {
107//! # let researcher: Arc<dyn Agent> = todo!();
108//! # let writer: Arc<dyn Agent> = todo!();
109//! # let reviewer: Arc<dyn Agent> = todo!();
110//! // Sequential: Execute agents in order
111//! let pipeline = SequentialAgent::new(
112//! "content_pipeline",
113//! vec![researcher, writer, reviewer]
114//! );
115//!
116//! // Parallel: Execute agents concurrently
117//! # let analyst1: Arc<dyn Agent> = todo!();
118//! # let analyst2: Arc<dyn Agent> = todo!();
119//! let parallel = ParallelAgent::new(
120//! "multi_analysis",
121//! vec![analyst1, analyst2]
122//! );
123//!
124//! // Loop: Iterate until condition met
125//! # let refiner: Arc<dyn Agent> = todo!();
126//! let loop_agent = LoopAgent::new("iterative_refiner", vec![refiner])
127//! .with_max_iterations(5);
128//! # Ok(())
129//! # }
130//! ```
131//!
132//! ### Multi-Agent Systems
133//!
134//! Build hierarchical agent systems with automatic delegation:
135//!
136//! ```no_run
137//! use adk_rust::prelude::*;
138//! use std::sync::Arc;
139//!
140//! # async fn example() -> Result<()> {
141//! # let model: Arc<dyn Llm> = todo!();
142//! # let code_agent: Arc<dyn Agent> = todo!();
143//! # let test_agent: Arc<dyn Agent> = todo!();
144//! let coordinator = LlmAgentBuilder::new("coordinator")
145//! .description("Development team coordinator")
146//! .instruction("Delegate coding tasks to specialists.")
147//! .model(model)
148//! .sub_agent(code_agent) // Delegate to sub-agents
149//! .sub_agent(test_agent)
150//! .build()?;
151//! # Ok(())
152//! # }
153//! ```
154//!
155//! ## Tools
156//!
157//! Give your agents capabilities beyond conversation. The tool types below
158//! require the `tools` feature (included in `standard` and above):
159//!
160//! ### Function Tools - Custom Operations
161//!
162//! Convert any async function into a tool:
163//!
164//! ```no_run
165//! use adk_rust::prelude::*;
166//! use adk_rust::serde_json::{json, Value};
167//! use std::sync::Arc;
168//!
169//! async fn get_weather(_ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
170//! let city = args["city"].as_str().unwrap_or("Unknown");
171//! // Your weather API call here
172//! Ok(json!({
173//! "temperature": 72.0,
174//! "conditions": "Sunny",
175//! "city": city
176//! }))
177//! }
178//!
179//! # fn example() -> Result<()> {
180//! let weather_tool = FunctionTool::new(
181//! "get_weather",
182//! "Get current weather for a city",
183//! get_weather,
184//! );
185//! # Ok(())
186//! # }
187//! ```
188//!
189//! ### Built-in Tools
190//!
191//! Ready-to-use tools included with ADK:
192//!
193//! - `GoogleSearchTool` - Web search via Google
194//! - `ExitLoopTool` - Control loop termination
195//! - `LoadArtifactsTool` - Access stored artifacts
196//!
197//! ### MCP Tools - External Integrations
198//!
199//! Connect to Model Context Protocol servers using the `rmcp` crate:
200//!
201//! ```ignore
202//! use adk_rust::prelude::*;
203//! use adk_rust::tool::McpToolset;
204//! use rmcp::{ServiceExt, transport::TokioChildProcess};
205//! use tokio::process::Command;
206//!
207//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
208//! // Connect to an MCP server (e.g., filesystem, database)
209//! let client = ().serve(TokioChildProcess::new(
210//! Command::new("npx")
211//! .arg("-y")
212//! .arg("@anthropic/mcp-server-filesystem")
213//! .arg("/path/to/dir")
214//! )?).await?;
215//!
216//! let mcp_tools = McpToolset::new(client);
217//!
218//! // Add all MCP tools to your agent
219//! # let builder: LlmAgentBuilder = todo!();
220//! let agent = builder.toolset(Arc::new(mcp_tools)).build()?;
221//! # Ok(())
222//! # }
223//! ```
224//!
225//! ## Sessions & State
226//!
227//! Manage conversation context and working memory:
228//!
229//! ```no_run
230//! use adk_rust::prelude::*;
231//! use adk_rust::session::{SessionService, CreateRequest};
232//! use adk_rust::serde_json::json;
233//! use std::collections::HashMap;
234//!
235//! # async fn example() -> Result<()> {
236//! let session_service = InMemorySessionService::new();
237//!
238//! // Create a session
239//! let session = session_service.create(CreateRequest {
240//! app_name: "my_app".to_string(),
241//! user_id: "user_123".to_string(),
242//! session_id: None,
243//! state: HashMap::new(),
244//! }).await?;
245//!
246//! // Read state (State trait provides read access)
247//! let state = session.state();
248//! let config = state.get("app:config"); // Returns Option<Value>
249//! # Ok(())
250//! # }
251//! ```
252//!
253//! ## Callbacks
254//!
255//! Intercept and customize agent behavior:
256//!
257//! ```no_run
258//! use adk_rust::prelude::*;
259//! use std::sync::Arc;
260//!
261//! # async fn example() -> Result<()> {
262//! # let model: Arc<dyn Llm> = todo!();
263//! let agent = LlmAgentBuilder::new("monitored_agent")
264//! .model(model)
265//! // Modify or inspect model responses
266//! .after_model_callback(Box::new(|_ctx, response| {
267//! Box::pin(async move {
268//! println!("Model responded");
269//! Ok(Some(response)) // Return modified response or None to keep original
270//! })
271//! }))
272//! // Track tool usage
273//! .before_tool_callback(Box::new(|_ctx| {
274//! Box::pin(async move {
275//! println!("Tool about to be called");
276//! Ok(None) // Continue execution
277//! })
278//! }))
279//! .build()?;
280//! # Ok(())
281//! # }
282//! ```
283//!
284//! ## Artifacts
285//!
286//! Store and retrieve binary data (images, files, etc.). Requires the
287//! `artifacts` feature (included in `standard` and above):
288//!
289//! ```no_run
290//! use adk_rust::prelude::*;
291//! use adk_rust::artifact::{ArtifactService, SaveRequest, LoadRequest};
292//!
293//! # async fn example() -> Result<()> {
294//! let artifact_service = InMemoryArtifactService::new();
295//!
296//! // Save an artifact
297//! let response = artifact_service.save(SaveRequest {
298//! app_name: "my_app".to_string(),
299//! user_id: "user_123".to_string(),
300//! session_id: "session_456".to_string(),
301//! file_name: "sales_chart.png".to_string(),
302//! part: Part::Text { text: "chart data".to_string() },
303//! version: None,
304//! }).await?;
305//!
306//! // Load an artifact
307//! let loaded = artifact_service.load(LoadRequest {
308//! app_name: "my_app".to_string(),
309//! user_id: "user_123".to_string(),
310//! session_id: "session_456".to_string(),
311//! file_name: "sales_chart.png".to_string(),
312//! version: None,
313//! }).await?;
314//! # Ok(())
315//! # }
316//! ```
317//!
318//! ## Deployment Options
319//!
320//! ### Console Mode (Interactive CLI)
321//!
322//! ```no_run
323//! use adk_rust::prelude::*;
324//! use adk_rust::Launcher;
325//! use std::sync::Arc;
326//!
327//! # async fn example() -> Result<()> {
328//! # let agent: Arc<dyn Agent> = todo!();
329//! // Interactive chat in terminal
330//! Launcher::new(agent).run().await?;
331//! # Ok(())
332//! # }
333//! ```
334//!
335//! ### Server Mode (REST API)
336//!
337//! ```bash
338//! # Run your agent as a web server
339//! cargo run -- serve --port 8080
340//! ```
341//!
342//! Provides endpoints:
343//! - `POST /chat` - Send messages
344//! - `GET /sessions` - List sessions
345//! - `GET /health` - Health check
346//!
347//! ### Agent-to-Agent (A2A) Protocol
348//!
349//! Expose your agent for inter-agent communication. Requires the `server`
350//! feature (included in `standard` and above):
351//!
352//! ```no_run
353//! use adk_rust::server::{create_app_with_a2a, ServerConfig};
354//! use adk_rust::AgentLoader;
355//!
356//! # async fn example() -> adk_rust::Result<()> {
357//! # let agent_loader: std::sync::Arc<dyn AgentLoader> = todo!();
358//! # let session_service: std::sync::Arc<dyn adk_rust::session::SessionService> = todo!();
359//! // Create server with A2A protocol support
360//! let config = ServerConfig::new(agent_loader, session_service);
361//! let app = create_app_with_a2a(config, Some("http://localhost:8080"));
362//!
363//! // Run the server (requires axum dependency)
364//! // let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
365//! // axum::serve(listener, app).await?;
366//! # Ok(())
367//! # }
368//! ```
369//!
370//! ## Observability
371//!
372//! Built-in OpenTelemetry support for production monitoring. Requires the
373//! `telemetry` feature (included in `standard` and above); OTLP export adds
374//! `telemetry-otlp`:
375//!
376//! ```no_run
377//! use adk_rust::telemetry::init_telemetry;
378//!
379//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
380//! // Basic telemetry with console logging
381//! init_telemetry("my-agent-service")?;
382//!
383//! // With `features = ["telemetry-otlp"]`, export spans to a collector instead:
384//! // adk_rust::telemetry::init_with_otlp("my-agent-service", "http://localhost:4317")?;
385//!
386//! // All agent operations now emit traces and metrics
387//! # Ok(())
388//! # }
389//! ```
390//!
391//! ## Architecture
392//!
393//! ADK-Rust uses a layered architecture for modularity:
394//!
395//! ```text
396//! ┌─────────────────────────────────────────────────────────────┐
397//! │ Application Layer │
398//! │ Launcher • REST Server • A2A │
399//! ├─────────────────────────────────────────────────────────────┤
400//! │ Runner Layer │
401//! │ Agent Execution • Event Streaming │
402//! ├─────────────────────────────────────────────────────────────┤
403//! │ Agent Layer │
404//! │ LlmAgent • CustomAgent • Sequential • Parallel • Loop │
405//! ├─────────────────────────────────────────────────────────────┤
406//! │ Service Layer │
407//! │ Models • Tools • Sessions • Artifacts • Memory │
408//! └─────────────────────────────────────────────────────────────┘
409//! ```
410//!
411//! ## Feature Flags
412//!
413//! | Feature | Description | Preset |
414//! |---------|-------------|--------|
415//! | `agents` | Agent implementations | minimal (default) |
416//! | `models` | Model integrations | minimal (default) |
417//! | `gemini` | Gemini model support | minimal (default) |
418//! | `runner` | Execution runtime | minimal (default) |
419//! | `sessions` | Session management | minimal (default) |
420//! | `tools` | Tool system | standard |
421//! | `skills` | Skill discovery | standard |
422//! | `artifacts` | Artifact storage | standard |
423//! | `memory` | Semantic memory | standard |
424//! | `telemetry` | OpenTelemetry | standard |
425//! | `guardrail` | Input/output validation | standard |
426//! | `auth` | Access control | standard |
427//! | `plugin` | Plugin system | standard |
428//! | `server` | HTTP server + A2A | standard |
429//! | `graph` | Graph workflows | standard |
430//! | `eval` | Agent evaluation | standard |
431//! | `openai` | OpenAI model support | standard |
432//! | `anthropic` | Anthropic model support | standard |
433//! | `realtime` | Voice/audio streaming | enterprise |
434//! | `browser` | Browser automation | enterprise |
435//! | `rag` | RAG pipeline | enterprise |
436//! | `payments` | Agentic commerce (ACP/AP2) | enterprise |
437//! | `awp` | Agentic Web Protocol | enterprise |
438//! | `code` | Code execution | full (experimental) |
439//! | `sandbox` | Sandboxed execution | full (experimental) |
440//! | `audio` | Audio processing | full (experimental) |
441//! | `cli` | CLI launcher | (opt-in, any preset) |
442//! | `agent-engine` | Agent Engine runtime contract: dispatch endpoints + `serve_agent_engine` entrypoint | (opt-in, any preset) |
443//! | `example-store` | Vertex AI Example Store client + few-shot retrieval provider | (opt-in, any preset) |
444//! | `vertex-sandbox` | Vertex AI Agent Engine managed code-execution sandbox (adk-code) | (opt-in, any preset) |
445//! | `vertex-eval` | Gen AI Evaluation Service bridge (adk-eval) | (opt-in, any preset) |
446//! | `vertex-rag` | Vertex AI RAG Engine retrieval client + tool (adk-rag) | (opt-in, any preset) |
447//! | `agent-retrieval` | Agent Retrieval (Vector Search 2.0) store backend (adk-rag) | (opt-in, any preset) |
448//! | `vertex-agent-registry` | Agent Registry client + discovery tool (adk-tool) | (opt-in, any preset) |
449//! | `vertex-skill-registry` | Skill Registry read client + remote skills (adk-skill) | (opt-in, any preset) |
450//! | `vertex-remote-engine` | Remote ReasoningEngine agent invocation (adk-server) | (opt-in, any preset) |
451//! | `gemini-agent-platform` | Gemini Enterprise Agent Platform integrations (Vertex model backend, managed Sessions, GCP Secret Manager, GCS artifacts, Cloud telemetry, Agent Engine runtime contract, Example Store, code-execution Sandbox); excludes realtime transports and host-side deploy tooling | (opt-in, any preset) |
452//! | `vertex-memory` | Vertex AI Memory Bank backend for adk-memory | (opt-in, any preset) |
453//! | `gcp-deploy` | Agent Engine deployment client (host-side; not part of `gemini-agent-platform`) | (opt-in, any preset) |
454//! | `gemini-agent-platform` | Gemini Enterprise Agent Platform integrations (Vertex model backend, managed Sessions, GCP Secret Manager, GCS artifacts, Cloud telemetry, Agent Engine runtime contract, Memory Bank); excludes realtime transports and host-side deploy tooling | (opt-in, any preset) |
455//! | `gemini-agent-platform-full` | `gemini-agent-platform` + Vertex AI Live API (realtime stack) | (opt-in, any preset) |
456//!
457//! ## Examples
458//!
459//! The [examples directory](https://github.com/zavora-ai/adk-rust/tree/main/examples)
460//! contains working examples for every feature:
461//!
462//! - **Agents**: LLM agent, workflow agents, multi-agent systems
463//! - **Tools**: Function tools, Google Search, MCP integration
464//! - **Sessions**: State management, conversation history
465//! - **Callbacks**: Logging, guardrails, caching
466//! - **Deployment**: Console, server, A2A protocol
467//!
468//! ## Related Crates
469//!
470//! ADK-Rust is composed of modular crates that can be used independently:
471//!
472//! - [`adk-core`](https://docs.rs/adk-core) - Core traits and types
473//! - [`adk-agent`](https://docs.rs/adk-agent) - Agent implementations
474//! - [`adk-model`](https://docs.rs/adk-model) - LLM integrations
475//! - [`adk-tool`](https://docs.rs/adk-tool) - Tool system
476//! - [`adk-session`](https://docs.rs/adk-session) - Session management
477//! - [`adk-artifact`](https://docs.rs/adk-artifact) - Artifact storage
478//! - [`adk-runner`](https://docs.rs/adk-runner) - Execution runtime
479//! - [`adk-server`](https://docs.rs/adk-server) - HTTP server
480//! - [`adk-telemetry`](https://docs.rs/adk-telemetry) - Observability
481
482#![warn(missing_docs)]
483#![cfg_attr(docsrs, feature(doc_cfg))]
484
485// ============================================================================
486// Core (always available)
487// ============================================================================
488
489/// Core traits and types.
490///
491/// Always available regardless of feature flags. Includes:
492/// - [`Agent`] - The fundamental trait for all agents
493/// - [`Tool`] / [`Toolset`] - For extending agents with capabilities
494/// - [`Session`] / [`State`] - For managing conversation context
495/// - [`Event`] - For streaming agent responses
496/// - [`AdkError`] / [`Result`] - Unified error handling
497pub use adk_core::*;
498
499// Re-export common dependencies for convenience
500pub use anyhow;
501pub use async_trait::async_trait;
502pub use futures;
503pub use serde;
504pub use serde_json;
505pub use tokio;
506
507// ============================================================================
508// Component Modules (feature-gated)
509// ============================================================================
510
511/// Agent implementations (LLM, Custom, Workflow agents).
512///
513/// Provides the core agent types:
514/// - [`LlmAgent`](agent::LlmAgent) - AI-powered agent using LLMs
515/// - [`CustomAgent`](agent::CustomAgent) - Implement custom agent logic
516/// - [`SequentialAgent`](agent::SequentialAgent) - Execute agents in sequence
517/// - [`ParallelAgent`](agent::ParallelAgent) - Execute agents concurrently
518/// - [`LoopAgent`](agent::LoopAgent) - Iterative execution until condition met
519///
520/// Available with feature: `agents`
521#[cfg(feature = "agents")]
522#[cfg_attr(docsrs, doc(cfg(feature = "agents")))]
523pub mod agent {
524 pub use adk_agent::*;
525}
526
527/// Model integrations (Gemini, etc.).
528///
529/// Provides LLM implementations:
530/// - [`GeminiModel`](model::GeminiModel) - Google's Gemini models
531///
532/// ADK is model-agnostic - implement the [`Llm`] trait for other providers.
533///
534/// Available with feature: `models`
535#[cfg(feature = "models")]
536#[cfg_attr(docsrs, doc(cfg(feature = "models")))]
537pub mod model {
538 pub use adk_model::*;
539}
540
541/// Tool system and built-in tools.
542///
543/// Give agents capabilities beyond conversation:
544/// - `FunctionTool` - Wrap async functions as tools
545/// - `GoogleSearchTool` - Web search
546/// - `ExitLoopTool` - Control loop agents
547/// - `McpToolset` - MCP server integration with the `mcp` feature
548/// - `CodeTool` / `PythonCodeTool` / `JavaScriptCodeTool` / `MontyPythonCodeTool` -
549/// Code execution with the `code-tools` feature (included in `full`); the
550/// embedded live paths need `code-embedded-js` / `code-embedded-python`
551///
552/// Available with feature: `tools`
553#[cfg(feature = "tools")]
554#[cfg_attr(docsrs, doc(cfg(feature = "tools")))]
555pub mod tool {
556 pub use adk_tool::*;
557}
558
559/// AgentSkills parsing, indexing, and runtime injection helpers.
560///
561/// Provides:
562/// - Skill file discovery from `.skills/`
563/// - Frontmatter validation (`name`, `description`)
564/// - Lexical skill selection
565/// - Runner plugin helper for skill injection
566///
567/// Available with feature: `skills`
568#[cfg(feature = "skills")]
569#[cfg_attr(docsrs, doc(cfg(feature = "skills")))]
570pub mod skill {
571 pub use adk_skill::*;
572}
573
574/// Session management.
575///
576/// Manage conversation context and state:
577/// - [`InMemorySessionService`](session::InMemorySessionService) - In-memory sessions
578/// - Session creation, retrieval, and lifecycle
579/// - State management with scoped prefixes
580///
581/// Available with feature: `sessions`
582#[cfg(feature = "sessions")]
583#[cfg_attr(docsrs, doc(cfg(feature = "sessions")))]
584pub mod session {
585 pub use adk_session::*;
586}
587
588/// Artifact storage.
589///
590/// Store and retrieve binary data:
591/// - [`InMemoryArtifactService`](artifact::InMemoryArtifactService) - In-memory storage
592/// - Version tracking for artifacts
593/// - Namespace scoping
594///
595/// Available with feature: `artifacts`
596#[cfg(feature = "artifacts")]
597#[cfg_attr(docsrs, doc(cfg(feature = "artifacts")))]
598pub mod artifact {
599 pub use adk_artifact::*;
600}
601
602/// Memory system with semantic search.
603///
604/// Long-term memory for agents:
605/// - [`InMemoryMemoryService`](memory::InMemoryMemoryService) - In-memory storage
606/// - Semantic search capabilities
607/// - Memory retrieval and updates
608///
609/// Available with feature: `memory`
610#[cfg(feature = "memory")]
611#[cfg_attr(docsrs, doc(cfg(feature = "memory")))]
612pub mod memory {
613 pub use adk_memory::*;
614}
615
616/// Agent execution runtime.
617///
618/// The engine that manages agent execution:
619/// - [`Runner`](runner::Runner) - Executes agents with full context
620/// - [`RunnerConfig`](runner::RunnerConfig) - Configuration options
621/// - Event streaming and tool coordination
622///
623/// Available with feature: `runner`
624#[cfg(feature = "runner")]
625#[cfg_attr(docsrs, doc(cfg(feature = "runner")))]
626pub mod runner {
627 pub use adk_runner::*;
628}
629
630/// HTTP server (REST + A2A).
631///
632/// Deploy agents as web services:
633/// - REST API for chat interactions
634/// - A2A (Agent-to-Agent) protocol support
635/// - Web UI integration
636///
637/// Available with feature: `server`
638#[cfg(feature = "server")]
639#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
640pub mod server {
641 pub use adk_server::*;
642}
643
644/// Telemetry (OpenTelemetry integration).
645///
646/// Production observability:
647/// - Distributed tracing
648/// - Metrics collection
649/// - Log correlation
650///
651/// Available with feature: `telemetry`
652#[cfg(feature = "telemetry")]
653#[cfg_attr(docsrs, doc(cfg(feature = "telemetry")))]
654pub mod telemetry {
655 pub use adk_telemetry::*;
656}
657
658/// Deployment tooling (Agent Engine BYOC deployment client).
659///
660/// Host-side utilities for deploying agents:
661/// - `deploy::gcp` — create, poll, get, and delete ReasoningEngines
662///
663/// Available with feature: `gcp-deploy`
664#[cfg(feature = "gcp-deploy")]
665#[cfg_attr(docsrs, doc(cfg(feature = "gcp-deploy")))]
666pub mod deploy {
667 pub use adk_deploy::*;
668}
669
670/// Graph-based workflow engine (LangGraph-inspired).
671///
672/// Build complex agent workflows with:
673/// - [`StateGraph`](graph::StateGraph) - Graph builder with nodes and edges
674/// - [`GraphAgent`](graph::GraphAgent) - ADK Agent integration
675/// - [`Checkpointer`](graph::Checkpointer) - Persistent state for human-in-the-loop
676/// - [`Router`](graph::Router) - Conditional edge routing helpers
677/// - Cycle support with recursion limits
678/// - Streaming execution modes
679///
680/// Available with feature: `graph`
681#[cfg(feature = "graph")]
682#[cfg_attr(docsrs, doc(cfg(feature = "graph")))]
683pub mod graph {
684 pub use adk_graph::*;
685}
686
687/// Graph, auth, and v8 wire contracts for safe computer-use orchestration.
688///
689/// Available with feature: `computer-use` (included in `standard`).
690#[cfg(feature = "computer-use")]
691#[cfg_attr(docsrs, doc(cfg(feature = "computer-use")))]
692pub mod computer_use {
693 pub use adk_computer_use::*;
694}
695
696/// Code execution substrate (experimental — `full` preset).
697///
698/// First-class code execution for agents, Studio, and generated projects:
699/// - [`CodeExecutor`](code::CodeExecutor) - Backend trait for execution
700/// - [`ExecutionRequest`](code::ExecutionRequest) - Typed execution request
701/// - [`ExecutionResult`](code::ExecutionResult) - Structured execution result
702/// - [`SandboxPolicy`](code::SandboxPolicy) - Sandbox capability model
703/// - [`Workspace`](code::Workspace) - Collaborative project context
704///
705/// Available with feature: `code`
706#[cfg(feature = "code")]
707#[cfg_attr(docsrs, doc(cfg(feature = "code")))]
708pub mod code {
709 pub use adk_code::*;
710}
711
712/// Python `CodeRuntime` for the CodeActAgent, backed by the Monty interpreter
713/// (experimental).
714///
715/// Lets a [`CodeActAgent`](agent::codeact::CodeActAgent) act by writing Python:
716/// - [`MontyRuntime`](codeact_monty::MontyRuntime) - The `CodeRuntime` implementation
717/// - [`OsAccess`](codeact_monty::OsAccess) - Host-granted filesystem/environment/clock policy
718/// - [`PathAccess`](codeact_monty::PathAccess) - Read-only / read-write mount modes
719///
720/// Available with feature: `codeact-monty` (implies `codeact`)
721#[cfg(feature = "codeact-monty")]
722#[cfg_attr(docsrs, doc(cfg(feature = "codeact-monty")))]
723pub mod codeact_monty {
724 pub use adk_codeact_monty::*;
725}
726
727/// Isolated code execution runtime (experimental — `full` preset).
728///
729/// Provides the [`SandboxBackend`](sandbox::SandboxBackend) trait and built-in backends:
730/// - [`ProcessBackend`](sandbox::ProcessBackend) - Subprocess execution with timeout and env isolation
731/// - `WasmBackend` - In-process WASM execution via wasmtime (requires `wasm` feature)
732/// - [`SandboxTool`](sandbox::SandboxTool) - Tool trait implementation for agent integration
733///
734/// Available with feature: `sandbox`
735#[cfg(feature = "sandbox")]
736#[cfg_attr(docsrs, doc(cfg(feature = "sandbox")))]
737pub mod sandbox {
738 pub use adk_sandbox::*;
739}
740
741/// Lightweight console launcher — always available with the `runner` feature.
742///
743/// When the `cli` feature is enabled, this is replaced by the full-featured
744/// `adk_cli::Launcher` with `--serve` mode, readline history, and thinking
745/// block rendering.
746#[cfg(all(feature = "runner", not(feature = "cli")))]
747#[cfg_attr(docsrs, doc(cfg(feature = "runner")))]
748pub use adk_runner::Launcher;
749
750/// Full-featured CLI launcher with console and serve modes.
751///
752/// Requires the `cli` feature (included in `standard` tier).
753/// Provides `--serve` mode, `rustyline` history, and `clap` CLI parsing.
754#[cfg(feature = "cli")]
755#[cfg_attr(docsrs, doc(cfg(feature = "cli")))]
756pub use adk_cli::Launcher;
757
758/// Real-time bidirectional streaming (voice, video).
759///
760/// Provides real-time audio/video streaming for voice-enabled agents:
761/// - [`RealtimeAgent`](realtime::RealtimeAgent) - Agent with voice capabilities
762/// - [`RealtimeRunner`](realtime::RealtimeRunner) - Session management and tool execution
763/// - Multiple providers: OpenAI Realtime, Gemini Live
764///
765/// Available with feature: `realtime`
766#[cfg(feature = "realtime")]
767#[cfg_attr(docsrs, doc(cfg(feature = "realtime")))]
768pub mod realtime {
769 pub use adk_realtime::*;
770}
771
772/// Browser automation (WebDriver).
773///
774/// Provides browser automation tools for agents:
775/// - [`BrowserSession`](browser::BrowserSession) - WebDriver session management
776/// - [`BrowserToolset`](browser::BrowserToolset) - Browser tools for agents
777///
778/// Available with feature: `browser`
779#[cfg(feature = "browser")]
780#[cfg_attr(docsrs, doc(cfg(feature = "browser")))]
781pub mod browser {
782 pub use adk_browser::*;
783}
784
785/// Agent evaluation framework.
786///
787/// Test and validate agent behavior:
788/// - [`Evaluator`](eval::Evaluator) - Run evaluation suites
789/// - [`EvaluationConfig`](eval::EvaluationConfig) - Configure evaluation parameters
790///
791/// Available with feature: `eval`
792#[cfg(feature = "eval")]
793#[cfg_attr(docsrs, doc(cfg(feature = "eval")))]
794pub mod eval {
795 pub use adk_eval::*;
796}
797
798/// Guardrails for safety and policy enforcement.
799///
800/// Validate agent inputs and outputs:
801/// - [`GuardrailSet`](guardrail::GuardrailSet) - Collection of guardrails
802/// - [`ContentFilter`](guardrail::ContentFilter) - Content safety filtering
803///
804/// Available with feature: `guardrail`
805#[cfg(feature = "guardrail")]
806#[cfg_attr(docsrs, doc(cfg(feature = "guardrail")))]
807pub mod guardrail {
808 pub use adk_guardrail::*;
809}
810
811/// Authentication and access control.
812///
813/// Manage agent permissions and identity:
814/// - [`Permission`](auth::Permission) - Permission definitions
815/// - [`AccessControl`](auth::AccessControl) - Access control enforcement
816///
817/// Available with feature: `auth`
818#[cfg(feature = "auth")]
819#[cfg_attr(docsrs, doc(cfg(feature = "auth")))]
820pub mod auth {
821 pub use adk_auth::*;
822}
823
824/// Agentic commerce and payment orchestration.
825///
826/// Provides protocol-neutral payment primitives and adapters for:
827/// - ACP stable `2026-01-30`
828/// - ACP experimental surfaces behind `acp-experimental`
829/// - AP2 `v0.1-alpha` as of `2026-03-22`
830///
831/// Available with feature: `payments`
832#[cfg(feature = "payments")]
833#[cfg_attr(docsrs, doc(cfg(feature = "payments")))]
834pub mod payment {
835 pub use adk_payments::*;
836}
837
838/// Plugin system for extending agent behavior.
839///
840/// Extensible callback architecture for agent lifecycle hooks:
841/// - Plugin registration and discovery
842/// - Before/after hooks for agent operations
843///
844/// Available with feature: `plugin`
845#[cfg(feature = "plugin")]
846#[cfg_attr(docsrs, doc(cfg(feature = "plugin")))]
847pub mod plugin {
848 pub use adk_plugin::*;
849}
850
851/// Audio processing pipeline (experimental — `full` preset).
852///
853/// Provides audio capabilities for agents:
854/// - [`TtsProvider`](audio::TtsProvider) - Text-to-speech synthesis
855/// - [`SttProvider`](audio::SttProvider) - Speech-to-text transcription
856/// - [`AudioProcessor`](audio::AudioProcessor) - Audio effects processing
857/// - `AudioPipeline` - Composable audio pipelines
858/// - Cloud providers: ElevenLabs, OpenAI, Gemini, Cartesia, Deepgram, AssemblyAI
859/// - Local inference: MLX (Apple Silicon), ONNX Runtime
860///
861/// Available with feature: `audio`
862#[cfg(feature = "audio")]
863#[cfg_attr(docsrs, doc(cfg(feature = "audio")))]
864pub mod audio {
865 pub use adk_audio::*;
866}
867
868/// Retrieval-Augmented Generation (RAG) pipeline.
869///
870/// Modular RAG system with trait-based components:
871/// - [`RagPipeline`](rag::RagPipeline) - Orchestrates ingest and query workflows
872/// - [`RagTool`](rag::RagTool) - Agentic retrieval via `Tool` trait
873/// - [`InMemoryVectorStore`](rag::InMemoryVectorStore) - Zero-dependency vector store
874/// - Chunking strategies: fixed-size, recursive, markdown-aware
875/// - Feature-gated backends: Gemini, OpenAI, Qdrant, LanceDB, pgvector
876///
877/// Available with feature: `rag`
878#[cfg(feature = "rag")]
879#[cfg_attr(docsrs, doc(cfg(feature = "rag")))]
880pub mod rag {
881 pub use adk_rag::*;
882}
883
884/// Shared action node types for graph workflows.
885///
886/// Provides the type definitions for all 14 action node types:
887/// - Trigger nodes (manual, webhook, schedule, event)
888/// - Data nodes (HTTP, Set, Transform)
889/// - Control flow nodes (Switch, Loop, Merge, Wait)
890/// - Compute nodes (Code)
891/// - Infrastructure nodes (Database)
892/// - Communication nodes (Email, Notification, RSS, File)
893///
894/// Available with feature: `action`
895#[cfg(feature = "action")]
896#[cfg_attr(docsrs, doc(cfg(feature = "action")))]
897pub use adk_action;
898
899/// Anthropic API client types and HTTP client.
900///
901/// Direct access to the `adk-anthropic` crate for low-level Anthropic API usage:
902/// - [`Anthropic`](anthropic_client::Anthropic) - HTTP client struct
903/// - Wire types: `MessageCreateParams`, `Message`, `ContentBlock`, etc.
904/// - Streaming: `MessageStreamEvent`, `ContentBlockDelta`
905/// - Error handling: `Error` enum with typed variants
906///
907/// For high-level agent usage, prefer `adk-model`'s `AnthropicClient` instead.
908///
909/// Available with feature: `anthropic-client`
910#[cfg(feature = "anthropic-client")]
911#[cfg_attr(docsrs, doc(cfg(feature = "anthropic-client")))]
912pub mod anthropic_client {
913 pub use adk_anthropic::*;
914}
915
916// ============================================================================
917// v0.7.0 Competitive Parity Feature Re-exports (opt-in only)
918// ============================================================================
919
920// --- adk-server features ---
921
922/// YAML agent configuration loader and hot reload watcher.
923///
924/// Declaratively define agents in YAML files with hot reload support:
925/// - [`YamlAgentDefinition`](server::yaml_agent::YamlAgentDefinition) - YAML schema types
926/// - [`AgentConfigLoader`](server::yaml_agent::AgentConfigLoader) - Load and validate YAML agent files
927/// - [`HotReloadWatcher`](server::yaml_agent::HotReloadWatcher) - Watch for file changes and reload agents
928///
929/// Available with feature: `yaml-agent`
930#[cfg(feature = "yaml-agent")]
931#[cfg_attr(docsrs, doc(cfg(feature = "yaml-agent")))]
932pub mod yaml_agent {
933 pub use adk_server::yaml_agent::*;
934}
935
936/// Agent Registry REST API for agent discovery and management.
937///
938/// Register, discover, and manage agents through a REST API:
939/// - [`AgentCard`](server::registry::AgentCard) - Agent metadata
940/// - [`AgentRegistryStore`](server::registry::AgentRegistryStore) - Storage backend trait
941/// - [`InMemoryAgentRegistryStore`](server::registry::InMemoryAgentRegistryStore) - In-memory storage
942/// - [`registry_router`](server::registry::registry_router) - Axum router for registry endpoints
943///
944/// Available with feature: `agent-registry`
945#[cfg(feature = "agent-registry")]
946#[cfg_attr(docsrs, doc(cfg(feature = "agent-registry")))]
947pub mod registry {
948 pub use adk_server::registry::*;
949}
950
951// --- adk-tool features ---
952
953/// MCP sampling callback support.
954///
955/// Handle `sampling/createMessage` requests from MCP servers:
956/// - [`SamplingHandler`](tool::sampling::SamplingHandler) - Trait for handling sampling requests
957/// - [`LlmSamplingHandler`](tool::sampling::LlmSamplingHandler) - Default handler routing to agent's LLM
958/// - [`SamplingRequest`](tool::sampling::SamplingRequest) / [`SamplingResponse`](tool::sampling::SamplingResponse) - Wire types
959///
960/// Available with feature: `mcp-sampling`
961#[cfg(feature = "mcp-sampling")]
962#[cfg_attr(docsrs, doc(cfg(feature = "mcp-sampling")))]
963pub mod sampling {
964 pub use adk_tool::sampling::*;
965}
966
967/// Native Slack toolset for agent-driven Slack interactions.
968///
969/// Built-in Slack tools for agents:
970/// - [`SlackToolset`](tool::slack::SlackToolset) - Toolset implementing `adk_core::Toolset`
971/// - Tools: `slack_send_message`, `slack_read_channel`, `slack_add_reaction`, `slack_list_threads`
972///
973/// Available with feature: `slack`
974#[cfg(feature = "slack")]
975#[cfg_attr(docsrs, doc(cfg(feature = "slack")))]
976pub mod slack {
977 pub use adk_tool::slack::*;
978}
979
980/// Native BigQuery toolset for data-analysis agents.
981///
982/// Built-in BigQuery tools for agents:
983/// - [`BigQueryToolset`](tool::bigquery::BigQueryToolset) - Toolset implementing `adk_core::Toolset`
984/// - Tools: `bigquery_execute_sql`, `bigquery_get_table_schema`, `bigquery_list_datasets`, `bigquery_list_tables`
985///
986/// Available with feature: `bigquery`
987#[cfg(feature = "bigquery")]
988#[cfg_attr(docsrs, doc(cfg(feature = "bigquery")))]
989pub mod bigquery {
990 pub use adk_tool::bigquery::*;
991}
992
993/// Native Spanner toolset for Cloud Spanner interactions.
994///
995/// Built-in Spanner tools for agents:
996/// - [`SpannerToolset`](tool::spanner::SpannerToolset) - Toolset implementing `adk_core::Toolset`
997/// - Tools: `spanner_execute_sql`, `spanner_get_table_schema`, `spanner_list_tables`
998///
999/// Available with feature: `spanner`
1000#[cfg(feature = "spanner")]
1001#[cfg_attr(docsrs, doc(cfg(feature = "spanner")))]
1002pub mod spanner {
1003 pub use adk_tool::spanner::*;
1004}
1005
1006// --- adk-eval features ---
1007
1008/// User personas for evaluation.
1009///
1010/// Define simulated user personas for realistic multi-turn test conversations:
1011/// - [`PersonaProfile`](eval::personas::PersonaProfile) - Persona definition
1012/// - [`UserSimulator`](eval::personas::UserSimulator) - Generate persona-driven messages
1013/// - [`PersonaRegistry`](eval::personas::PersonaRegistry) - Load personas from directory
1014///
1015/// Available with feature: `personas`
1016#[cfg(feature = "personas")]
1017#[cfg_attr(docsrs, doc(cfg(feature = "personas")))]
1018pub mod personas {
1019 pub use adk_eval::personas::*;
1020}
1021
1022// --- adk-realtime features ---
1023
1024/// Video avatar configuration for realtime sessions.
1025///
1026/// Attach a video avatar to realtime voice agents:
1027/// - [`AvatarConfig`](realtime::avatar::AvatarConfig) - Avatar source, lip-sync, and rendering settings
1028/// - [`LipSyncConfig`](realtime::avatar::LipSyncConfig) - Lip-sync configuration
1029/// - [`RenderingConfig`](realtime::avatar::RenderingConfig) - Rendering parameters
1030///
1031/// Available with feature: `video-avatar`
1032#[cfg(feature = "video-avatar")]
1033#[cfg_attr(docsrs, doc(cfg(feature = "video-avatar")))]
1034pub mod avatar {
1035 pub use adk_realtime::avatar::*;
1036}
1037
1038// ============================================================================
1039// Managed Agent Runtime (feature-gated, experimental)
1040// ============================================================================
1041
1042/// Managed agent runtime — durable, resumable, provider-neutral agent execution.
1043///
1044/// Provides the `ManagedAgentRuntime` trait and `DefaultManagedAgentRuntime`:
1045/// - [`ManagedAgentRuntime`](managed::ManagedAgentRuntime) - Central lifecycle trait
1046/// - [`DefaultManagedAgentRuntime`](managed::DefaultManagedAgentRuntime) - Default implementation
1047/// - [`ManagedAgentDef`](managed::types::ManagedAgentDef) - Declarative agent definition
1048/// - [`SessionEvent`](managed::types::SessionEvent) - Provider-neutral event stream
1049/// - [`UserEvent`](managed::types::UserEvent) - Client-to-agent events
1050/// - [`ModelResolver`](managed::ModelResolver) - ModelRef → Arc<dyn Llm> resolution
1051/// - [`ScriptedLlm`](managed::ScriptedLlm) - Deterministic testing double
1052///
1053/// STABILITY: Experimental, additive, feature-gated. No breaking changes to
1054/// existing `Runner`/`LlmAgent` APIs when this feature is disabled.
1055///
1056/// Available with feature: `managed-runtime`
1057#[cfg(feature = "managed-runtime")]
1058#[cfg_attr(docsrs, doc(cfg(feature = "managed-runtime")))]
1059pub mod managed {
1060 pub use adk_managed::*;
1061}
1062
1063// ============================================================================
1064// Enterprise Client SDK (feature-gated, experimental)
1065// ============================================================================
1066
1067/// Enterprise client SDK — native Rust client for the ADK-Rust Enterprise
1068/// Managed Agent Service.
1069///
1070/// Provides `EnterpriseClient` for interacting with the platform over HTTP/SSE:
1071/// - [`EnterpriseClient`](enterprise::EnterpriseClient) - Primary API client
1072/// - [`ClientConfig`](enterprise::ClientConfig) - Client configuration
1073/// - Agent, Environment, and Session CRUD
1074/// - SSE event streaming with auto-reconnect
1075/// - Vault and Memory management (beta)
1076///
1077/// This crate has zero dependency on `adk-model`, `adk-runner`, or `adk-agent` —
1078/// it communicates exclusively via HTTP with the managed agent platform.
1079///
1080/// STABILITY: Experimental, additive, feature-gated.
1081///
1082/// Available with feature: `enterprise-client`
1083#[cfg(feature = "enterprise-client")]
1084#[cfg_attr(docsrs, doc(cfg(feature = "enterprise-client")))]
1085pub use adk_enterprise;
1086
1087// ============================================================================
1088// Convenience Functions
1089// ============================================================================
1090
1091/// Detect LLM provider from environment variables.
1092///
1093/// Checks environment variables in precedence order and returns the first
1094/// matching provider that was compiled through Cargo features. The default
1095/// `minimal` tier detects Gemini via `GOOGLE_API_KEY`; add `openai` or
1096/// `anthropic` to widen detection.
1097///
1098/// 1. `GOOGLE_GENAI_USE_ENTERPRISE` / `GOOGLE_GENAI_USE_VERTEXAI` truthy
1099/// (`1` or case-insensitive `true`) → Gemini on Vertex AI via Application
1100/// Default Credentials, using `GOOGLE_CLOUD_PROJECT` and
1101/// `GOOGLE_CLOUD_LOCATION` (requires the `gemini-vertex` feature;
1102/// `GOOGLE_GENAI_USE_ENTERPRISE` takes precedence when both are set)
1103/// 2. `ANTHROPIC_API_KEY` → Anthropic (Claude)
1104/// 3. `OPENAI_API_KEY` → OpenAI
1105/// 4. `GOOGLE_API_KEY` → Gemini
1106///
1107/// When a Vertex flag is truthy but the `gemini-vertex` feature is not
1108/// compiled, a `tracing` warning is emitted and detection falls through to
1109/// the API-key steps, which may select the Gemini Studio endpoint
1110/// (`generativelanguage.googleapis.com`).
1111///
1112/// # Errors
1113///
1114/// Returns [`AdkError`] when no supported environment variable is set, or
1115/// when a Vertex flag is truthy but `GOOGLE_CLOUD_PROJECT` /
1116/// `GOOGLE_CLOUD_LOCATION` is missing.
1117///
1118/// # Example
1119///
1120/// ```rust,ignore
1121/// use adk_rust::provider_from_env;
1122/// use std::sync::Arc;
1123///
1124/// let model: Arc<dyn adk_rust::Llm> = provider_from_env()?;
1125/// ```
1126pub fn provider_from_env() -> Result<std::sync::Arc<dyn Llm>> {
1127 // The Vertex opt-in flags come before any API-key sniffing so a
1128 // deployment pinned to Vertex AI can never be diverted to the Studio
1129 // endpoint by a stray API key.
1130 #[cfg(feature = "gemini")]
1131 {
1132 if model::gemini::vertex_env_requested() {
1133 #[cfg(feature = "gemini-vertex")]
1134 {
1135 return Ok(std::sync::Arc::new(model::GeminiModel::from_env(
1136 model::catalog::GEMINI_DEFAULT,
1137 )?));
1138 }
1139 #[cfg(not(feature = "gemini-vertex"))]
1140 tracing::warn!(
1141 env.flags = "GOOGLE_GENAI_USE_ENTERPRISE/GOOGLE_GENAI_USE_VERTEXAI",
1142 "vertex backend requested via environment but the gemini-vertex feature is not compiled; api-key detection may select the gemini studio endpoint (generativelanguage.googleapis.com)"
1143 );
1144 }
1145 }
1146
1147 #[cfg(feature = "anthropic")]
1148 {
1149 if let Ok(key) = std::env::var("ANTHROPIC_API_KEY") {
1150 return Ok(std::sync::Arc::new(model::anthropic::AnthropicClient::from_api_key(key)?));
1151 }
1152 }
1153
1154 #[cfg(feature = "openai")]
1155 {
1156 if let Ok(key) = std::env::var("OPENAI_API_KEY") {
1157 let config = model::openai::OpenAIConfig::new(key, model::catalog::OPENAI_DEFAULT);
1158 return Ok(std::sync::Arc::new(model::openai::OpenAIClient::new(config)?));
1159 }
1160 }
1161
1162 #[cfg(feature = "gemini")]
1163 {
1164 if let Ok(key) = std::env::var("GOOGLE_API_KEY") {
1165 return Ok(std::sync::Arc::new(model::GeminiModel::new(
1166 key,
1167 model::catalog::GEMINI_DEFAULT,
1168 )?));
1169 }
1170 }
1171
1172 Err(AdkError::config(
1173 "No LLM provider detected. Set one of: ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_API_KEY",
1174 ))
1175}
1176
1177/// High-level single-turn agent invocation.
1178///
1179/// Creates an agent with the given instructions, sends the input, and returns
1180/// the text response. Uses [`provider_from_env`] to auto-detect the LLM provider.
1181///
1182/// This is the fastest way to get started with ADK — a single function call
1183/// that handles provider selection, session creation, agent building, and
1184/// execution.
1185///
1186/// # Arguments
1187///
1188/// * `instructions` - System instructions for the agent
1189/// * `input` - User input to send to the agent
1190///
1191/// # Returns
1192///
1193/// The agent's text response as a `String`.
1194///
1195/// # Errors
1196///
1197/// Returns [`AdkError`] when no supported environment variable is set, or
1198/// when agent execution fails.
1199///
1200/// # Example
1201///
1202/// ```rust,ignore
1203/// use adk_rust::run;
1204///
1205/// let response = run("You are a helpful assistant.", "What is 2 + 2?").await?;
1206/// println!("{response}");
1207/// ```
1208#[cfg(all(feature = "agents", feature = "sessions", feature = "runner"))]
1209pub async fn run(instructions: &str, input: &str) -> Result<String> {
1210 use futures::StreamExt;
1211 use std::collections::HashMap;
1212 use std::sync::Arc;
1213
1214 type ProviderPair = (Arc<dyn Llm>, Option<Arc<dyn CacheCapable>>);
1215
1216 let (model, cache_capable): ProviderPair = {
1217 #[allow(unused_assignments)]
1218 let mut result: Option<ProviderPair> = None;
1219
1220 #[cfg(feature = "anthropic")]
1221 {
1222 if result.is_none()
1223 && let Ok(key) = std::env::var("ANTHROPIC_API_KEY")
1224 {
1225 let m = model::anthropic::AnthropicClient::from_api_key(key)?;
1226 result = Some((Arc::new(m), None));
1227 }
1228 }
1229
1230 #[cfg(feature = "openai")]
1231 {
1232 if result.is_none()
1233 && let Ok(key) = std::env::var("OPENAI_API_KEY")
1234 {
1235 let config = model::openai::OpenAIConfig::new(key, model::catalog::OPENAI_DEFAULT);
1236 let m = model::openai::OpenAIClient::new(config)?;
1237 result = Some((Arc::new(m), None));
1238 }
1239 }
1240
1241 #[cfg(feature = "gemini")]
1242 {
1243 if result.is_none()
1244 && let Ok(key) = std::env::var("GOOGLE_API_KEY")
1245 {
1246 let m = Arc::new(model::GeminiModel::new(key, model::catalog::GEMINI_DEFAULT)?);
1247 let cc: Arc<dyn CacheCapable> = m.clone();
1248 result = Some((m, Some(cc)));
1249 }
1250 }
1251
1252 result.ok_or_else(|| {
1253 AdkError::config(
1254 "No LLM provider detected. Set one of: ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_API_KEY",
1255 )
1256 })?
1257 };
1258
1259 let agent =
1260 agent::LlmAgentBuilder::new("adk_run").instruction(instructions).model(model).build()?;
1261
1262 let session_service: Arc<dyn adk_session::SessionService> =
1263 Arc::new(session::InMemorySessionService::new());
1264
1265 let session_id = SessionId::generate();
1266
1267 session_service
1268 .create(session::CreateRequest {
1269 app_name: "adk_run".into(),
1270 user_id: "user".into(),
1271 session_id: Some(session_id.to_string()),
1272 state: HashMap::new(),
1273 })
1274 .await?;
1275
1276 let mut runner_builder = runner::Runner::builder()
1277 .app_name("adk_run")
1278 .agent(Arc::new(agent))
1279 .session_service(session_service);
1280 if let Some(cache_capable) = cache_capable {
1281 runner_builder = runner_builder.cache_capable(cache_capable);
1282 }
1283 let runner = runner_builder.build()?;
1284
1285 let content = Content::new("user").with_text(input);
1286 let mut stream = runner.run(UserId::new("user")?, session_id, content).await?;
1287
1288 let mut result = String::new();
1289 while let Some(event) = stream.next().await {
1290 let event = event?;
1291 if let Some(content) = &event.llm_response.content {
1292 for part in &content.parts {
1293 if let Some(text) = part.text() {
1294 result.push_str(text);
1295 }
1296 }
1297 }
1298 }
1299
1300 Ok(result)
1301}
1302
1303// ============================================================================
1304// Prelude
1305// ============================================================================
1306
1307/// Convenience prelude for common imports.
1308///
1309/// Import everything you need with a single line:
1310///
1311/// ```
1312/// use adk_rust::prelude::*;
1313/// ```
1314///
1315/// This includes:
1316/// - Core traits: `Agent`, `Tool`, `Llm`, `Session`
1317/// - Agent builders: `LlmAgentBuilder`, `CustomAgentBuilder`
1318/// - Workflow agents: `SequentialAgent`, `ParallelAgent`, `LoopAgent`
1319/// - Models: `GeminiModel`
1320/// - Tools: `FunctionTool`, `GoogleSearchTool`, `McpToolset`
1321/// - Services: `InMemorySessionService`, `InMemoryArtifactService`
1322/// - Runtime: `Runner`, `RunnerConfig`
1323/// - Common types: `Arc`, `Result`, `Content`, `Event`
1324pub mod prelude {
1325 // Core types (always available)
1326 pub use crate::{
1327 AdkError, Agent, BeforeModelResult, Content, Event, EventStream, InvocationContext, Llm,
1328 LlmRequest, LlmResponse, Part, Result, RunConfig, RunConfigBuilder, Session, State, Tool,
1329 ToolContext, Toolset,
1330 };
1331
1332 // Agents
1333 #[cfg(feature = "agents")]
1334 pub use crate::agent::{
1335 ConditionalAgent, CustomAgent, CustomAgentBuilder, LlmAgent, LlmAgentBuilder,
1336 LlmConditionalAgent, LlmConditionalAgentBuilder, LoopAgent, ParallelAgent, SequentialAgent,
1337 };
1338
1339 // Models
1340 #[cfg(feature = "gemini")]
1341 pub use crate::model::GeminiModel;
1342
1343 // Model providers (when specific features are enabled)
1344 #[cfg(feature = "openai")]
1345 pub use crate::model::openai::{OpenAIClient, OpenAIConfig};
1346
1347 #[cfg(feature = "openrouter")]
1348 pub use crate::model::openrouter::{
1349 OpenRouterApiMode, OpenRouterClient, OpenRouterConfig, OpenRouterPlugin,
1350 OpenRouterProviderPreferences, OpenRouterReasoningConfig, OpenRouterRequestOptions,
1351 OpenRouterResponseTool,
1352 };
1353
1354 #[cfg(feature = "anthropic")]
1355 pub use crate::model::anthropic::{AnthropicClient, AnthropicConfig, Effort, ThinkingMode};
1356
1357 #[cfg(feature = "deepseek")]
1358 pub use crate::model::deepseek::{DeepSeekClient, DeepSeekConfig};
1359
1360 #[cfg(feature = "groq")]
1361 pub use crate::model::groq::{GroqClient, GroqConfig};
1362
1363 #[cfg(feature = "ollama")]
1364 pub use crate::model::ollama::{OllamaConfig, OllamaModel};
1365
1366 // OpenAI-compatible providers: use OpenAICompatible with provider presets
1367 // e.g. OpenAICompatibleConfig::fireworks(api_key, model)
1368 #[cfg(feature = "openai")]
1369 pub use crate::model::openai_compatible::{OpenAICompatible, OpenAICompatibleConfig};
1370
1371 #[cfg(feature = "bedrock")]
1372 pub use crate::model::bedrock::{BedrockClient, BedrockConfig};
1373
1374 #[cfg(feature = "azure-ai")]
1375 pub use crate::model::azure_ai::{AzureAIClient, AzureAIConfig};
1376
1377 // Tools
1378 #[cfg(feature = "mcp")]
1379 pub use crate::tool::McpToolset;
1380 #[cfg(feature = "tools")]
1381 pub use crate::tool::{
1382 BasicToolset, ExitLoopTool, FunctionTool, GoogleSearchTool, LoadArtifactsTool,
1383 UrlContextTool, WebSearchTool,
1384 };
1385
1386 // Skills
1387 #[cfg(feature = "skills")]
1388 pub use crate::skill::{SelectionPolicy, SkillInjector, SkillInjectorConfig, load_skill_index};
1389 #[cfg(feature = "skills-progressive-disclosure")]
1390 pub use crate::skill::{SkillToolset, SkillToolsetConfig};
1391
1392 // Sessions
1393 #[cfg(feature = "sessions")]
1394 pub use crate::session::InMemorySessionService;
1395
1396 // Artifacts
1397 #[cfg(feature = "artifacts")]
1398 pub use crate::artifact::InMemoryArtifactService;
1399
1400 // Memory
1401 #[cfg(feature = "memory")]
1402 pub use crate::memory::InMemoryMemoryService;
1403
1404 // Runner
1405 #[cfg(feature = "runner")]
1406 pub use crate::runner::{Runner, RunnerConfig};
1407
1408 // Graph workflows
1409 #[cfg(feature = "graph")]
1410 pub use crate::graph::{END, GraphAgent, NodeOutput, Router, START, StateGraph};
1411
1412 // Realtime
1413 #[cfg(feature = "realtime")]
1414 pub use crate::realtime::{
1415 RealtimeAgent, RealtimeAgentBuilder, RealtimeConfig, RealtimeModel, RealtimeRunner,
1416 RealtimeSession,
1417 };
1418
1419 // Common re-exports
1420 pub use crate::anyhow::Result as AnyhowResult;
1421 pub use crate::async_trait;
1422 pub use std::sync::Arc;
1423
1424 // Convenience functions
1425 pub use crate::provider_from_env;
1426 #[cfg(all(feature = "agents", feature = "sessions", feature = "runner"))]
1427 pub use crate::run;
1428}