Skip to main content

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//! ```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.1.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.1.0"
53//!
54//! # Standard — minimal + tools, memory, OpenAI, Anthropic, server, auth,
55//! # graph, eval, guardrails, skills, plugins, artifacts, telemetry
56//! adk-rust = { version = "2.1.0", features = ["standard"] }
57//!
58//! # Enterprise — standard + realtime, browser, rag, payments, awp
59//! adk-rust = { version = "2.1.0", features = ["enterprise"] }
60//!
61//! # Full — enterprise + experimental crates (audio, code, sandbox)
62//! adk-rust = { version = "2.1.0", features = ["full"] }
63//!
64//! # Custom — pick exactly what you need
65//! adk-rust = { version = "2.1.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//! | `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) |
446//! | `vertex-memory` | Vertex AI Memory Bank backend for adk-memory | (opt-in, any preset) |
447//! | `gcp-deploy` | Agent Engine deployment client (host-side; not part of `gemini-agent-platform`) | (opt-in, any preset) |
448//! | `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) |
449//! | `gemini-agent-platform-full` | `gemini-agent-platform` + Vertex AI Live API (realtime stack) | (opt-in, any preset) |
450//!
451//! ## Examples
452//!
453//! The [examples directory](https://github.com/zavora-ai/adk-rust/tree/main/examples)
454//! contains working examples for every feature:
455//!
456//! - **Agents**: LLM agent, workflow agents, multi-agent systems
457//! - **Tools**: Function tools, Google Search, MCP integration
458//! - **Sessions**: State management, conversation history
459//! - **Callbacks**: Logging, guardrails, caching
460//! - **Deployment**: Console, server, A2A protocol
461//!
462//! ## Related Crates
463//!
464//! ADK-Rust is composed of modular crates that can be used independently:
465//!
466//! - [`adk-core`](https://docs.rs/adk-core) - Core traits and types
467//! - [`adk-agent`](https://docs.rs/adk-agent) - Agent implementations
468//! - [`adk-model`](https://docs.rs/adk-model) - LLM integrations
469//! - [`adk-tool`](https://docs.rs/adk-tool) - Tool system
470//! - [`adk-session`](https://docs.rs/adk-session) - Session management
471//! - [`adk-artifact`](https://docs.rs/adk-artifact) - Artifact storage
472//! - [`adk-runner`](https://docs.rs/adk-runner) - Execution runtime
473//! - [`adk-server`](https://docs.rs/adk-server) - HTTP server
474//! - [`adk-telemetry`](https://docs.rs/adk-telemetry) - Observability
475
476#![warn(missing_docs)]
477#![cfg_attr(docsrs, feature(doc_cfg))]
478
479// ============================================================================
480// Core (always available)
481// ============================================================================
482
483/// Core traits and types.
484///
485/// Always available regardless of feature flags. Includes:
486/// - [`Agent`] - The fundamental trait for all agents
487/// - [`Tool`] / [`Toolset`] - For extending agents with capabilities
488/// - [`Session`] / [`State`] - For managing conversation context
489/// - [`Event`] - For streaming agent responses
490/// - [`AdkError`] / [`Result`] - Unified error handling
491pub use adk_core::*;
492
493// Re-export common dependencies for convenience
494pub use anyhow;
495pub use async_trait::async_trait;
496pub use futures;
497pub use serde;
498pub use serde_json;
499pub use tokio;
500
501// ============================================================================
502// Component Modules (feature-gated)
503// ============================================================================
504
505/// Agent implementations (LLM, Custom, Workflow agents).
506///
507/// Provides the core agent types:
508/// - [`LlmAgent`](agent::LlmAgent) - AI-powered agent using LLMs
509/// - [`CustomAgent`](agent::CustomAgent) - Implement custom agent logic
510/// - [`SequentialAgent`](agent::SequentialAgent) - Execute agents in sequence
511/// - [`ParallelAgent`](agent::ParallelAgent) - Execute agents concurrently
512/// - [`LoopAgent`](agent::LoopAgent) - Iterative execution until condition met
513///
514/// Available with feature: `agents`
515#[cfg(feature = "agents")]
516#[cfg_attr(docsrs, doc(cfg(feature = "agents")))]
517pub mod agent {
518    pub use adk_agent::*;
519}
520
521/// Model integrations (Gemini, etc.).
522///
523/// Provides LLM implementations:
524/// - [`GeminiModel`](model::GeminiModel) - Google's Gemini models
525///
526/// ADK is model-agnostic - implement the [`Llm`] trait for other providers.
527///
528/// Available with feature: `models`
529#[cfg(feature = "models")]
530#[cfg_attr(docsrs, doc(cfg(feature = "models")))]
531pub mod model {
532    pub use adk_model::*;
533}
534
535/// Tool system and built-in tools.
536///
537/// Give agents capabilities beyond conversation:
538/// - `FunctionTool` - Wrap async functions as tools
539/// - `GoogleSearchTool` - Web search
540/// - `ExitLoopTool` - Control loop agents
541/// - `McpToolset` - MCP server integration with the `mcp` feature
542/// - `CodeTool` / `PythonCodeTool` / `JavaScriptCodeTool` / `MontyPythonCodeTool` -
543///   Code execution with the `code-tools` feature (included in `full`); the
544///   embedded live paths need `code-embedded-js` / `code-embedded-python`
545///
546/// Available with feature: `tools`
547#[cfg(feature = "tools")]
548#[cfg_attr(docsrs, doc(cfg(feature = "tools")))]
549pub mod tool {
550    pub use adk_tool::*;
551}
552
553/// AgentSkills parsing, indexing, and runtime injection helpers.
554///
555/// Provides:
556/// - Skill file discovery from `.skills/`
557/// - Frontmatter validation (`name`, `description`)
558/// - Lexical skill selection
559/// - Runner plugin helper for skill injection
560///
561/// Available with feature: `skills`
562#[cfg(feature = "skills")]
563#[cfg_attr(docsrs, doc(cfg(feature = "skills")))]
564pub mod skill {
565    pub use adk_skill::*;
566}
567
568/// Session management.
569///
570/// Manage conversation context and state:
571/// - [`InMemorySessionService`](session::InMemorySessionService) - In-memory sessions
572/// - Session creation, retrieval, and lifecycle
573/// - State management with scoped prefixes
574///
575/// Available with feature: `sessions`
576#[cfg(feature = "sessions")]
577#[cfg_attr(docsrs, doc(cfg(feature = "sessions")))]
578pub mod session {
579    pub use adk_session::*;
580}
581
582/// Artifact storage.
583///
584/// Store and retrieve binary data:
585/// - [`InMemoryArtifactService`](artifact::InMemoryArtifactService) - In-memory storage
586/// - Version tracking for artifacts
587/// - Namespace scoping
588///
589/// Available with feature: `artifacts`
590#[cfg(feature = "artifacts")]
591#[cfg_attr(docsrs, doc(cfg(feature = "artifacts")))]
592pub mod artifact {
593    pub use adk_artifact::*;
594}
595
596/// Memory system with semantic search.
597///
598/// Long-term memory for agents:
599/// - [`InMemoryMemoryService`](memory::InMemoryMemoryService) - In-memory storage
600/// - Semantic search capabilities
601/// - Memory retrieval and updates
602///
603/// Available with feature: `memory`
604#[cfg(feature = "memory")]
605#[cfg_attr(docsrs, doc(cfg(feature = "memory")))]
606pub mod memory {
607    pub use adk_memory::*;
608}
609
610/// Agent execution runtime.
611///
612/// The engine that manages agent execution:
613/// - [`Runner`](runner::Runner) - Executes agents with full context
614/// - [`RunnerConfig`](runner::RunnerConfig) - Configuration options
615/// - Event streaming and tool coordination
616///
617/// Available with feature: `runner`
618#[cfg(feature = "runner")]
619#[cfg_attr(docsrs, doc(cfg(feature = "runner")))]
620pub mod runner {
621    pub use adk_runner::*;
622}
623
624/// HTTP server (REST + A2A).
625///
626/// Deploy agents as web services:
627/// - REST API for chat interactions
628/// - A2A (Agent-to-Agent) protocol support
629/// - Web UI integration
630///
631/// Available with feature: `server`
632#[cfg(feature = "server")]
633#[cfg_attr(docsrs, doc(cfg(feature = "server")))]
634pub mod server {
635    pub use adk_server::*;
636}
637
638/// Telemetry (OpenTelemetry integration).
639///
640/// Production observability:
641/// - Distributed tracing
642/// - Metrics collection
643/// - Log correlation
644///
645/// Available with feature: `telemetry`
646#[cfg(feature = "telemetry")]
647#[cfg_attr(docsrs, doc(cfg(feature = "telemetry")))]
648pub mod telemetry {
649    pub use adk_telemetry::*;
650}
651
652/// Deployment tooling (Agent Engine BYOC deployment client).
653///
654/// Host-side utilities for deploying agents:
655/// - `deploy::gcp` — create, poll, get, and delete ReasoningEngines
656///
657/// Available with feature: `gcp-deploy`
658#[cfg(feature = "gcp-deploy")]
659#[cfg_attr(docsrs, doc(cfg(feature = "gcp-deploy")))]
660pub mod deploy {
661    pub use adk_deploy::*;
662}
663
664/// Graph-based workflow engine (LangGraph-inspired).
665///
666/// Build complex agent workflows with:
667/// - [`StateGraph`](graph::StateGraph) - Graph builder with nodes and edges
668/// - [`GraphAgent`](graph::GraphAgent) - ADK Agent integration
669/// - [`Checkpointer`](graph::Checkpointer) - Persistent state for human-in-the-loop
670/// - [`Router`](graph::Router) - Conditional edge routing helpers
671/// - Cycle support with recursion limits
672/// - Streaming execution modes
673///
674/// Available with feature: `graph`
675#[cfg(feature = "graph")]
676#[cfg_attr(docsrs, doc(cfg(feature = "graph")))]
677pub mod graph {
678    pub use adk_graph::*;
679}
680
681/// Graph, auth, and v8 wire contracts for safe computer-use orchestration.
682///
683/// Available with feature: `computer-use` (included in `standard`).
684#[cfg(feature = "computer-use")]
685#[cfg_attr(docsrs, doc(cfg(feature = "computer-use")))]
686pub mod computer_use {
687    pub use adk_computer_use::*;
688}
689
690/// Code execution substrate (experimental — `full` preset).
691///
692/// First-class code execution for agents, Studio, and generated projects:
693/// - [`CodeExecutor`](code::CodeExecutor) - Backend trait for execution
694/// - [`ExecutionRequest`](code::ExecutionRequest) - Typed execution request
695/// - [`ExecutionResult`](code::ExecutionResult) - Structured execution result
696/// - [`SandboxPolicy`](code::SandboxPolicy) - Sandbox capability model
697/// - [`Workspace`](code::Workspace) - Collaborative project context
698///
699/// Available with feature: `code`
700#[cfg(feature = "code")]
701#[cfg_attr(docsrs, doc(cfg(feature = "code")))]
702pub mod code {
703    pub use adk_code::*;
704}
705
706/// Python `CodeRuntime` for the CodeActAgent, backed by the Monty interpreter
707/// (experimental).
708///
709/// Lets a [`CodeActAgent`](agent::codeact::CodeActAgent) act by writing Python:
710/// - [`MontyRuntime`](codeact_monty::MontyRuntime) - The `CodeRuntime` implementation
711/// - [`OsAccess`](codeact_monty::OsAccess) - Host-granted filesystem/environment/clock policy
712/// - [`PathAccess`](codeact_monty::PathAccess) - Read-only / read-write mount modes
713///
714/// Available with feature: `codeact-monty` (implies `codeact`)
715#[cfg(feature = "codeact-monty")]
716#[cfg_attr(docsrs, doc(cfg(feature = "codeact-monty")))]
717pub mod codeact_monty {
718    pub use adk_codeact_monty::*;
719}
720
721/// Isolated code execution runtime (experimental — `full` preset).
722///
723/// Provides the [`SandboxBackend`](sandbox::SandboxBackend) trait and built-in backends:
724/// - [`ProcessBackend`](sandbox::ProcessBackend) - Subprocess execution with timeout and env isolation
725/// - `WasmBackend` - In-process WASM execution via wasmtime (requires `wasm` feature)
726/// - [`SandboxTool`](sandbox::SandboxTool) - Tool trait implementation for agent integration
727///
728/// Available with feature: `sandbox`
729#[cfg(feature = "sandbox")]
730#[cfg_attr(docsrs, doc(cfg(feature = "sandbox")))]
731pub mod sandbox {
732    pub use adk_sandbox::*;
733}
734
735/// Lightweight console launcher — always available with the `runner` feature.
736///
737/// When the `cli` feature is enabled, this is replaced by the full-featured
738/// `adk_cli::Launcher` with `--serve` mode, readline history, and thinking
739/// block rendering.
740#[cfg(all(feature = "runner", not(feature = "cli")))]
741#[cfg_attr(docsrs, doc(cfg(feature = "runner")))]
742pub use adk_runner::Launcher;
743
744/// Full-featured CLI launcher with console and serve modes.
745///
746/// Requires the `cli` feature (included in `standard` tier).
747/// Provides `--serve` mode, `rustyline` history, and `clap` CLI parsing.
748#[cfg(feature = "cli")]
749#[cfg_attr(docsrs, doc(cfg(feature = "cli")))]
750pub use adk_cli::Launcher;
751
752/// Real-time bidirectional streaming (voice, video).
753///
754/// Provides real-time audio/video streaming for voice-enabled agents:
755/// - [`RealtimeAgent`](realtime::RealtimeAgent) - Agent with voice capabilities
756/// - [`RealtimeRunner`](realtime::RealtimeRunner) - Session management and tool execution
757/// - Multiple providers: OpenAI Realtime, Gemini Live
758///
759/// Available with feature: `realtime`
760#[cfg(feature = "realtime")]
761#[cfg_attr(docsrs, doc(cfg(feature = "realtime")))]
762pub mod realtime {
763    pub use adk_realtime::*;
764}
765
766/// Browser automation (WebDriver).
767///
768/// Provides browser automation tools for agents:
769/// - [`BrowserSession`](browser::BrowserSession) - WebDriver session management
770/// - [`BrowserToolset`](browser::BrowserToolset) - Browser tools for agents
771///
772/// Available with feature: `browser`
773#[cfg(feature = "browser")]
774#[cfg_attr(docsrs, doc(cfg(feature = "browser")))]
775pub mod browser {
776    pub use adk_browser::*;
777}
778
779/// Agent evaluation framework.
780///
781/// Test and validate agent behavior:
782/// - [`Evaluator`](eval::Evaluator) - Run evaluation suites
783/// - [`EvaluationConfig`](eval::EvaluationConfig) - Configure evaluation parameters
784///
785/// Available with feature: `eval`
786#[cfg(feature = "eval")]
787#[cfg_attr(docsrs, doc(cfg(feature = "eval")))]
788pub mod eval {
789    pub use adk_eval::*;
790}
791
792/// Guardrails for safety and policy enforcement.
793///
794/// Validate agent inputs and outputs:
795/// - [`GuardrailSet`](guardrail::GuardrailSet) - Collection of guardrails
796/// - [`ContentFilter`](guardrail::ContentFilter) - Content safety filtering
797///
798/// Available with feature: `guardrail`
799#[cfg(feature = "guardrail")]
800#[cfg_attr(docsrs, doc(cfg(feature = "guardrail")))]
801pub mod guardrail {
802    pub use adk_guardrail::*;
803}
804
805/// Authentication and access control.
806///
807/// Manage agent permissions and identity:
808/// - [`Permission`](auth::Permission) - Permission definitions
809/// - [`AccessControl`](auth::AccessControl) - Access control enforcement
810///
811/// Available with feature: `auth`
812#[cfg(feature = "auth")]
813#[cfg_attr(docsrs, doc(cfg(feature = "auth")))]
814pub mod auth {
815    pub use adk_auth::*;
816}
817
818/// Agentic commerce and payment orchestration.
819///
820/// Provides protocol-neutral payment primitives and adapters for:
821/// - ACP stable `2026-01-30`
822/// - ACP experimental surfaces behind `acp-experimental`
823/// - AP2 `v0.1-alpha` as of `2026-03-22`
824///
825/// Available with feature: `payments`
826#[cfg(feature = "payments")]
827#[cfg_attr(docsrs, doc(cfg(feature = "payments")))]
828pub mod payment {
829    pub use adk_payments::*;
830}
831
832/// Plugin system for extending agent behavior.
833///
834/// Extensible callback architecture for agent lifecycle hooks:
835/// - Plugin registration and discovery
836/// - Before/after hooks for agent operations
837///
838/// Available with feature: `plugin`
839#[cfg(feature = "plugin")]
840#[cfg_attr(docsrs, doc(cfg(feature = "plugin")))]
841pub mod plugin {
842    pub use adk_plugin::*;
843}
844
845/// Audio processing pipeline (experimental — `full` preset).
846///
847/// Provides audio capabilities for agents:
848/// - [`TtsProvider`](audio::TtsProvider) - Text-to-speech synthesis
849/// - [`SttProvider`](audio::SttProvider) - Speech-to-text transcription
850/// - [`AudioProcessor`](audio::AudioProcessor) - Audio effects processing
851/// - `AudioPipeline` - Composable audio pipelines
852/// - Cloud providers: ElevenLabs, OpenAI, Gemini, Cartesia, Deepgram, AssemblyAI
853/// - Local inference: MLX (Apple Silicon), ONNX Runtime
854///
855/// Available with feature: `audio`
856#[cfg(feature = "audio")]
857#[cfg_attr(docsrs, doc(cfg(feature = "audio")))]
858pub mod audio {
859    pub use adk_audio::*;
860}
861
862/// Retrieval-Augmented Generation (RAG) pipeline.
863///
864/// Modular RAG system with trait-based components:
865/// - [`RagPipeline`](rag::RagPipeline) - Orchestrates ingest and query workflows
866/// - [`RagTool`](rag::RagTool) - Agentic retrieval via `Tool` trait
867/// - [`InMemoryVectorStore`](rag::InMemoryVectorStore) - Zero-dependency vector store
868/// - Chunking strategies: fixed-size, recursive, markdown-aware
869/// - Feature-gated backends: Gemini, OpenAI, Qdrant, LanceDB, pgvector
870///
871/// Available with feature: `rag`
872#[cfg(feature = "rag")]
873#[cfg_attr(docsrs, doc(cfg(feature = "rag")))]
874pub mod rag {
875    pub use adk_rag::*;
876}
877
878/// Shared action node types for graph workflows.
879///
880/// Provides the type definitions for all 14 action node types:
881/// - Trigger nodes (manual, webhook, schedule, event)
882/// - Data nodes (HTTP, Set, Transform)
883/// - Control flow nodes (Switch, Loop, Merge, Wait)
884/// - Compute nodes (Code)
885/// - Infrastructure nodes (Database)
886/// - Communication nodes (Email, Notification, RSS, File)
887///
888/// Available with feature: `action`
889#[cfg(feature = "action")]
890#[cfg_attr(docsrs, doc(cfg(feature = "action")))]
891pub use adk_action;
892
893/// Anthropic API client types and HTTP client.
894///
895/// Direct access to the `adk-anthropic` crate for low-level Anthropic API usage:
896/// - [`Anthropic`](anthropic_client::Anthropic) - HTTP client struct
897/// - Wire types: `MessageCreateParams`, `Message`, `ContentBlock`, etc.
898/// - Streaming: `MessageStreamEvent`, `ContentBlockDelta`
899/// - Error handling: `Error` enum with typed variants
900///
901/// For high-level agent usage, prefer `adk-model`'s `AnthropicClient` instead.
902///
903/// Available with feature: `anthropic-client`
904#[cfg(feature = "anthropic-client")]
905#[cfg_attr(docsrs, doc(cfg(feature = "anthropic-client")))]
906pub mod anthropic_client {
907    pub use adk_anthropic::*;
908}
909
910// ============================================================================
911// v0.7.0 Competitive Parity Feature Re-exports (opt-in only)
912// ============================================================================
913
914// --- adk-server features ---
915
916/// YAML agent configuration loader and hot reload watcher.
917///
918/// Declaratively define agents in YAML files with hot reload support:
919/// - [`YamlAgentDefinition`](server::yaml_agent::YamlAgentDefinition) - YAML schema types
920/// - [`AgentConfigLoader`](server::yaml_agent::AgentConfigLoader) - Load and validate YAML agent files
921/// - [`HotReloadWatcher`](server::yaml_agent::HotReloadWatcher) - Watch for file changes and reload agents
922///
923/// Available with feature: `yaml-agent`
924#[cfg(feature = "yaml-agent")]
925#[cfg_attr(docsrs, doc(cfg(feature = "yaml-agent")))]
926pub mod yaml_agent {
927    pub use adk_server::yaml_agent::*;
928}
929
930/// Agent Registry REST API for agent discovery and management.
931///
932/// Register, discover, and manage agents through a REST API:
933/// - [`AgentCard`](server::registry::AgentCard) - Agent metadata
934/// - [`AgentRegistryStore`](server::registry::AgentRegistryStore) - Storage backend trait
935/// - [`InMemoryAgentRegistryStore`](server::registry::InMemoryAgentRegistryStore) - In-memory storage
936/// - [`registry_router`](server::registry::registry_router) - Axum router for registry endpoints
937///
938/// Available with feature: `agent-registry`
939#[cfg(feature = "agent-registry")]
940#[cfg_attr(docsrs, doc(cfg(feature = "agent-registry")))]
941pub mod registry {
942    pub use adk_server::registry::*;
943}
944
945// --- adk-tool features ---
946
947/// MCP sampling callback support.
948///
949/// Handle `sampling/createMessage` requests from MCP servers:
950/// - [`SamplingHandler`](tool::sampling::SamplingHandler) - Trait for handling sampling requests
951/// - [`LlmSamplingHandler`](tool::sampling::LlmSamplingHandler) - Default handler routing to agent's LLM
952/// - [`SamplingRequest`](tool::sampling::SamplingRequest) / [`SamplingResponse`](tool::sampling::SamplingResponse) - Wire types
953///
954/// Available with feature: `mcp-sampling`
955#[cfg(feature = "mcp-sampling")]
956#[cfg_attr(docsrs, doc(cfg(feature = "mcp-sampling")))]
957pub mod sampling {
958    pub use adk_tool::sampling::*;
959}
960
961/// Native Slack toolset for agent-driven Slack interactions.
962///
963/// Built-in Slack tools for agents:
964/// - [`SlackToolset`](tool::slack::SlackToolset) - Toolset implementing `adk_core::Toolset`
965/// - Tools: `slack_send_message`, `slack_read_channel`, `slack_add_reaction`, `slack_list_threads`
966///
967/// Available with feature: `slack`
968#[cfg(feature = "slack")]
969#[cfg_attr(docsrs, doc(cfg(feature = "slack")))]
970pub mod slack {
971    pub use adk_tool::slack::*;
972}
973
974/// Native BigQuery toolset for data-analysis agents.
975///
976/// Built-in BigQuery tools for agents:
977/// - [`BigQueryToolset`](tool::bigquery::BigQueryToolset) - Toolset implementing `adk_core::Toolset`
978/// - Tools: `bigquery_execute_sql`, `bigquery_get_table_schema`, `bigquery_list_datasets`, `bigquery_list_tables`
979///
980/// Available with feature: `bigquery`
981#[cfg(feature = "bigquery")]
982#[cfg_attr(docsrs, doc(cfg(feature = "bigquery")))]
983pub mod bigquery {
984    pub use adk_tool::bigquery::*;
985}
986
987/// Native Spanner toolset for Cloud Spanner interactions.
988///
989/// Built-in Spanner tools for agents:
990/// - [`SpannerToolset`](tool::spanner::SpannerToolset) - Toolset implementing `adk_core::Toolset`
991/// - Tools: `spanner_execute_sql`, `spanner_get_table_schema`, `spanner_list_tables`
992///
993/// Available with feature: `spanner`
994#[cfg(feature = "spanner")]
995#[cfg_attr(docsrs, doc(cfg(feature = "spanner")))]
996pub mod spanner {
997    pub use adk_tool::spanner::*;
998}
999
1000// --- adk-eval features ---
1001
1002/// User personas for evaluation.
1003///
1004/// Define simulated user personas for realistic multi-turn test conversations:
1005/// - [`PersonaProfile`](eval::personas::PersonaProfile) - Persona definition
1006/// - [`UserSimulator`](eval::personas::UserSimulator) - Generate persona-driven messages
1007/// - [`PersonaRegistry`](eval::personas::PersonaRegistry) - Load personas from directory
1008///
1009/// Available with feature: `personas`
1010#[cfg(feature = "personas")]
1011#[cfg_attr(docsrs, doc(cfg(feature = "personas")))]
1012pub mod personas {
1013    pub use adk_eval::personas::*;
1014}
1015
1016// --- adk-realtime features ---
1017
1018/// Video avatar configuration for realtime sessions.
1019///
1020/// Attach a video avatar to realtime voice agents:
1021/// - [`AvatarConfig`](realtime::avatar::AvatarConfig) - Avatar source, lip-sync, and rendering settings
1022/// - [`LipSyncConfig`](realtime::avatar::LipSyncConfig) - Lip-sync configuration
1023/// - [`RenderingConfig`](realtime::avatar::RenderingConfig) - Rendering parameters
1024///
1025/// Available with feature: `video-avatar`
1026#[cfg(feature = "video-avatar")]
1027#[cfg_attr(docsrs, doc(cfg(feature = "video-avatar")))]
1028pub mod avatar {
1029    pub use adk_realtime::avatar::*;
1030}
1031
1032// ============================================================================
1033// Managed Agent Runtime (feature-gated, experimental)
1034// ============================================================================
1035
1036/// Managed agent runtime — durable, resumable, provider-neutral agent execution.
1037///
1038/// Provides the `ManagedAgentRuntime` trait and `DefaultManagedAgentRuntime`:
1039/// - [`ManagedAgentRuntime`](managed::ManagedAgentRuntime) - Central lifecycle trait
1040/// - [`DefaultManagedAgentRuntime`](managed::DefaultManagedAgentRuntime) - Default implementation
1041/// - [`ManagedAgentDef`](managed::types::ManagedAgentDef) - Declarative agent definition
1042/// - [`SessionEvent`](managed::types::SessionEvent) - Provider-neutral event stream
1043/// - [`UserEvent`](managed::types::UserEvent) - Client-to-agent events
1044/// - [`ModelResolver`](managed::ModelResolver) - ModelRef → Arc<dyn Llm> resolution
1045/// - [`ScriptedLlm`](managed::ScriptedLlm) - Deterministic testing double
1046///
1047/// STABILITY: Experimental, additive, feature-gated. No breaking changes to
1048/// existing `Runner`/`LlmAgent` APIs when this feature is disabled.
1049///
1050/// Available with feature: `managed-runtime`
1051#[cfg(feature = "managed-runtime")]
1052#[cfg_attr(docsrs, doc(cfg(feature = "managed-runtime")))]
1053pub mod managed {
1054    pub use adk_managed::*;
1055}
1056
1057// ============================================================================
1058// Enterprise Client SDK (feature-gated, experimental)
1059// ============================================================================
1060
1061/// Enterprise client SDK — native Rust client for the ADK-Rust Enterprise
1062/// Managed Agent Service.
1063///
1064/// Provides `EnterpriseClient` for interacting with the platform over HTTP/SSE:
1065/// - [`EnterpriseClient`](enterprise::EnterpriseClient) - Primary API client
1066/// - [`ClientConfig`](enterprise::ClientConfig) - Client configuration
1067/// - Agent, Environment, and Session CRUD
1068/// - SSE event streaming with auto-reconnect
1069/// - Vault and Memory management (beta)
1070///
1071/// This crate has zero dependency on `adk-model`, `adk-runner`, or `adk-agent` —
1072/// it communicates exclusively via HTTP with the managed agent platform.
1073///
1074/// STABILITY: Experimental, additive, feature-gated.
1075///
1076/// Available with feature: `enterprise-client`
1077#[cfg(feature = "enterprise-client")]
1078#[cfg_attr(docsrs, doc(cfg(feature = "enterprise-client")))]
1079pub use adk_enterprise;
1080
1081// ============================================================================
1082// Convenience Functions
1083// ============================================================================
1084
1085/// Detect LLM provider from environment variables.
1086///
1087/// Checks environment variables in precedence order and returns the first
1088/// matching provider that was compiled through Cargo features. The default
1089/// `minimal` tier detects Gemini via `GOOGLE_API_KEY`; add `openai` or
1090/// `anthropic` to widen detection.
1091///
1092/// 1. `GOOGLE_GENAI_USE_ENTERPRISE` / `GOOGLE_GENAI_USE_VERTEXAI` truthy
1093///    (`1` or case-insensitive `true`) → Gemini on Vertex AI via Application
1094///    Default Credentials, using `GOOGLE_CLOUD_PROJECT` and
1095///    `GOOGLE_CLOUD_LOCATION` (requires the `gemini-vertex` feature;
1096///    `GOOGLE_GENAI_USE_ENTERPRISE` takes precedence when both are set)
1097/// 2. `ANTHROPIC_API_KEY` → Anthropic (Claude)
1098/// 3. `OPENAI_API_KEY` → OpenAI
1099/// 4. `GOOGLE_API_KEY` → Gemini
1100///
1101/// When a Vertex flag is truthy but the `gemini-vertex` feature is not
1102/// compiled, a `tracing` warning is emitted and detection falls through to
1103/// the API-key steps, which may select the Gemini Studio endpoint
1104/// (`generativelanguage.googleapis.com`).
1105///
1106/// # Errors
1107///
1108/// Returns [`AdkError`] when no supported environment variable is set, or
1109/// when a Vertex flag is truthy but `GOOGLE_CLOUD_PROJECT` /
1110/// `GOOGLE_CLOUD_LOCATION` is missing.
1111///
1112/// # Example
1113///
1114/// ```rust,ignore
1115/// use adk_rust::provider_from_env;
1116/// use std::sync::Arc;
1117///
1118/// let model: Arc<dyn adk_rust::Llm> = provider_from_env()?;
1119/// ```
1120pub fn provider_from_env() -> Result<std::sync::Arc<dyn Llm>> {
1121    // The Vertex opt-in flags come before any API-key sniffing so a
1122    // deployment pinned to Vertex AI can never be diverted to the Studio
1123    // endpoint by a stray API key.
1124    #[cfg(feature = "gemini")]
1125    {
1126        if model::gemini::vertex_env_requested() {
1127            #[cfg(feature = "gemini-vertex")]
1128            {
1129                return Ok(std::sync::Arc::new(model::GeminiModel::from_env(
1130                    model::catalog::GEMINI_DEFAULT,
1131                )?));
1132            }
1133            #[cfg(not(feature = "gemini-vertex"))]
1134            tracing::warn!(
1135                env.flags = "GOOGLE_GENAI_USE_ENTERPRISE/GOOGLE_GENAI_USE_VERTEXAI",
1136                "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)"
1137            );
1138        }
1139    }
1140
1141    #[cfg(feature = "anthropic")]
1142    {
1143        if let Ok(key) = std::env::var("ANTHROPIC_API_KEY") {
1144            return Ok(std::sync::Arc::new(model::anthropic::AnthropicClient::from_api_key(key)?));
1145        }
1146    }
1147
1148    #[cfg(feature = "openai")]
1149    {
1150        if let Ok(key) = std::env::var("OPENAI_API_KEY") {
1151            let config = model::openai::OpenAIConfig::new(key, model::catalog::OPENAI_DEFAULT);
1152            return Ok(std::sync::Arc::new(model::openai::OpenAIClient::new(config)?));
1153        }
1154    }
1155
1156    #[cfg(feature = "gemini")]
1157    {
1158        if let Ok(key) = std::env::var("GOOGLE_API_KEY") {
1159            return Ok(std::sync::Arc::new(model::GeminiModel::new(
1160                key,
1161                model::catalog::GEMINI_DEFAULT,
1162            )?));
1163        }
1164    }
1165
1166    Err(AdkError::config(
1167        "No LLM provider detected. Set one of: ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_API_KEY",
1168    ))
1169}
1170
1171/// High-level single-turn agent invocation.
1172///
1173/// Creates an agent with the given instructions, sends the input, and returns
1174/// the text response. Uses [`provider_from_env`] to auto-detect the LLM provider.
1175///
1176/// This is the fastest way to get started with ADK — a single function call
1177/// that handles provider selection, session creation, agent building, and
1178/// execution.
1179///
1180/// # Arguments
1181///
1182/// * `instructions` - System instructions for the agent
1183/// * `input` - User input to send to the agent
1184///
1185/// # Returns
1186///
1187/// The agent's text response as a `String`.
1188///
1189/// # Errors
1190///
1191/// Returns [`AdkError`] when no supported environment variable is set, or
1192/// when agent execution fails.
1193///
1194/// # Example
1195///
1196/// ```rust,ignore
1197/// use adk_rust::run;
1198///
1199/// let response = run("You are a helpful assistant.", "What is 2 + 2?").await?;
1200/// println!("{response}");
1201/// ```
1202#[cfg(all(feature = "agents", feature = "sessions", feature = "runner"))]
1203pub async fn run(instructions: &str, input: &str) -> Result<String> {
1204    use futures::StreamExt;
1205    use std::collections::HashMap;
1206    use std::sync::Arc;
1207
1208    type ProviderPair = (Arc<dyn Llm>, Option<Arc<dyn CacheCapable>>);
1209
1210    let (model, cache_capable): ProviderPair = {
1211        #[allow(unused_assignments)]
1212        let mut result: Option<ProviderPair> = None;
1213
1214        #[cfg(feature = "anthropic")]
1215        {
1216            if result.is_none()
1217                && let Ok(key) = std::env::var("ANTHROPIC_API_KEY")
1218            {
1219                let m = model::anthropic::AnthropicClient::from_api_key(key)?;
1220                result = Some((Arc::new(m), None));
1221            }
1222        }
1223
1224        #[cfg(feature = "openai")]
1225        {
1226            if result.is_none()
1227                && let Ok(key) = std::env::var("OPENAI_API_KEY")
1228            {
1229                let config = model::openai::OpenAIConfig::new(key, model::catalog::OPENAI_DEFAULT);
1230                let m = model::openai::OpenAIClient::new(config)?;
1231                result = Some((Arc::new(m), None));
1232            }
1233        }
1234
1235        #[cfg(feature = "gemini")]
1236        {
1237            if result.is_none()
1238                && let Ok(key) = std::env::var("GOOGLE_API_KEY")
1239            {
1240                let m = Arc::new(model::GeminiModel::new(key, model::catalog::GEMINI_DEFAULT)?);
1241                let cc: Arc<dyn CacheCapable> = m.clone();
1242                result = Some((m, Some(cc)));
1243            }
1244        }
1245
1246        result.ok_or_else(|| {
1247            AdkError::config(
1248                "No LLM provider detected. Set one of: ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_API_KEY",
1249            )
1250        })?
1251    };
1252
1253    let agent =
1254        agent::LlmAgentBuilder::new("adk_run").instruction(instructions).model(model).build()?;
1255
1256    let session_service: Arc<dyn adk_session::SessionService> =
1257        Arc::new(session::InMemorySessionService::new());
1258
1259    let session_id = SessionId::generate();
1260
1261    session_service
1262        .create(session::CreateRequest {
1263            app_name: "adk_run".into(),
1264            user_id: "user".into(),
1265            session_id: Some(session_id.to_string()),
1266            state: HashMap::new(),
1267        })
1268        .await?;
1269
1270    let mut runner_builder = runner::Runner::builder()
1271        .app_name("adk_run")
1272        .agent(Arc::new(agent))
1273        .session_service(session_service);
1274    if let Some(cache_capable) = cache_capable {
1275        runner_builder = runner_builder.cache_capable(cache_capable);
1276    }
1277    let runner = runner_builder.build()?;
1278
1279    let content = Content::new("user").with_text(input);
1280    let mut stream = runner.run(UserId::new("user")?, session_id, content).await?;
1281
1282    let mut result = String::new();
1283    while let Some(event) = stream.next().await {
1284        let event = event?;
1285        if let Some(content) = &event.llm_response.content {
1286            for part in &content.parts {
1287                if let Some(text) = part.text() {
1288                    result.push_str(text);
1289                }
1290            }
1291        }
1292    }
1293
1294    Ok(result)
1295}
1296
1297// ============================================================================
1298// Prelude
1299// ============================================================================
1300
1301/// Convenience prelude for common imports.
1302///
1303/// Import everything you need with a single line:
1304///
1305/// ```
1306/// use adk_rust::prelude::*;
1307/// ```
1308///
1309/// This includes:
1310/// - Core traits: `Agent`, `Tool`, `Llm`, `Session`
1311/// - Agent builders: `LlmAgentBuilder`, `CustomAgentBuilder`
1312/// - Workflow agents: `SequentialAgent`, `ParallelAgent`, `LoopAgent`
1313/// - Models: `GeminiModel`
1314/// - Tools: `FunctionTool`, `GoogleSearchTool`, `McpToolset`
1315/// - Services: `InMemorySessionService`, `InMemoryArtifactService`
1316/// - Runtime: `Runner`, `RunnerConfig`
1317/// - Common types: `Arc`, `Result`, `Content`, `Event`
1318pub mod prelude {
1319    // Core types (always available)
1320    pub use crate::{
1321        AdkError, Agent, BeforeModelResult, Content, Event, EventStream, InvocationContext, Llm,
1322        LlmRequest, LlmResponse, Part, Result, RunConfig, RunConfigBuilder, Session, State, Tool,
1323        ToolContext, Toolset,
1324    };
1325
1326    // Agents
1327    #[cfg(feature = "agents")]
1328    pub use crate::agent::{
1329        ConditionalAgent, CustomAgent, CustomAgentBuilder, LlmAgent, LlmAgentBuilder,
1330        LlmConditionalAgent, LlmConditionalAgentBuilder, LoopAgent, ParallelAgent, SequentialAgent,
1331    };
1332
1333    // Models
1334    #[cfg(feature = "gemini")]
1335    pub use crate::model::GeminiModel;
1336
1337    // Model providers (when specific features are enabled)
1338    #[cfg(feature = "openai")]
1339    pub use crate::model::openai::{OpenAIClient, OpenAIConfig};
1340
1341    #[cfg(feature = "openrouter")]
1342    pub use crate::model::openrouter::{
1343        OpenRouterApiMode, OpenRouterClient, OpenRouterConfig, OpenRouterPlugin,
1344        OpenRouterProviderPreferences, OpenRouterReasoningConfig, OpenRouterRequestOptions,
1345        OpenRouterResponseTool,
1346    };
1347
1348    #[cfg(feature = "anthropic")]
1349    pub use crate::model::anthropic::{AnthropicClient, AnthropicConfig, Effort, ThinkingMode};
1350
1351    #[cfg(feature = "deepseek")]
1352    pub use crate::model::deepseek::{DeepSeekClient, DeepSeekConfig};
1353
1354    #[cfg(feature = "groq")]
1355    pub use crate::model::groq::{GroqClient, GroqConfig};
1356
1357    #[cfg(feature = "ollama")]
1358    pub use crate::model::ollama::{OllamaConfig, OllamaModel};
1359
1360    // OpenAI-compatible providers: use OpenAICompatible with provider presets
1361    // e.g. OpenAICompatibleConfig::fireworks(api_key, model)
1362    #[cfg(feature = "openai")]
1363    pub use crate::model::openai_compatible::{OpenAICompatible, OpenAICompatibleConfig};
1364
1365    #[cfg(feature = "bedrock")]
1366    pub use crate::model::bedrock::{BedrockClient, BedrockConfig};
1367
1368    #[cfg(feature = "azure-ai")]
1369    pub use crate::model::azure_ai::{AzureAIClient, AzureAIConfig};
1370
1371    // Tools
1372    #[cfg(feature = "mcp")]
1373    pub use crate::tool::McpToolset;
1374    #[cfg(feature = "tools")]
1375    pub use crate::tool::{
1376        BasicToolset, ExitLoopTool, FunctionTool, GoogleSearchTool, LoadArtifactsTool,
1377        UrlContextTool, WebSearchTool,
1378    };
1379
1380    // Skills
1381    #[cfg(feature = "skills")]
1382    pub use crate::skill::{SelectionPolicy, SkillInjector, SkillInjectorConfig, load_skill_index};
1383
1384    // Sessions
1385    #[cfg(feature = "sessions")]
1386    pub use crate::session::InMemorySessionService;
1387
1388    // Artifacts
1389    #[cfg(feature = "artifacts")]
1390    pub use crate::artifact::InMemoryArtifactService;
1391
1392    // Memory
1393    #[cfg(feature = "memory")]
1394    pub use crate::memory::InMemoryMemoryService;
1395
1396    // Runner
1397    #[cfg(feature = "runner")]
1398    pub use crate::runner::{Runner, RunnerConfig};
1399
1400    // Graph workflows
1401    #[cfg(feature = "graph")]
1402    pub use crate::graph::{END, GraphAgent, NodeOutput, Router, START, StateGraph};
1403
1404    // Realtime
1405    #[cfg(feature = "realtime")]
1406    pub use crate::realtime::{
1407        RealtimeAgent, RealtimeAgentBuilder, RealtimeConfig, RealtimeModel, RealtimeRunner,
1408        RealtimeSession,
1409    };
1410
1411    // Common re-exports
1412    pub use crate::anyhow::Result as AnyhowResult;
1413    pub use crate::async_trait;
1414    pub use std::sync::Arc;
1415
1416    // Convenience functions
1417    pub use crate::provider_from_env;
1418    #[cfg(all(feature = "agents", feature = "sessions", feature = "runner"))]
1419    pub use crate::run;
1420}