gemini_adk_rs/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![warn(unreachable_pub)]
3#![cfg_attr(not(test), forbid(unsafe_code))]
4#![cfg_attr(test, deny(unsafe_code))]
5#![warn(missing_docs)]
6//! # gemini-adk-rs
7//!
8//! The agent **runtime** for Gemini Live — layer 1 of a three-crate stack.
9//! Below it, [`gemini_genai_rs`] speaks the wire protocol. Above it,
10//! [`gemini-adk-fluent-rs`](https://docs.rs/gemini-adk-fluent-rs) wraps this
11//! crate in the builder API most applications should start from. Come here
12//! when you are building a custom processor, a tool backend, a persistence
13//! layer, or an evaluation harness — or when you want to see what the fluent
14//! builder actually assembles.
15//!
16//! ## What lives here
17//!
18//! | Concern | Start at |
19//! |---------|----------|
20//! | A Live session and its three-lane processor | [`live::LiveSessionBuilder`], [`live::LiveHandle`] |
21//! | Tools the model can call | [`tool::ToolFunction`], [`tool::SimpleTool`], [`tool::TypedTool`], [`tool::ToolDispatcher`] |
22//! | Concurrent typed state with prefix scopes | [`state::State`], [`state::StateKey`] |
23//! | Text agents and combinators | [`text::LlmTextAgent`] and the `*TextAgent` family in [`text`] |
24//! | Declarative conversation phases | [`live::PhaseMachine`], [`live::Phase`] |
25//! | Governed flows enforced while the model speaks | [`flow::Flow`], [`flow::FlowMonitor`] |
26//! | Turn extraction, watchers, temporal patterns | [`live::TurnExtractor`], [`live::watcher`], [`live::temporal`] |
27//! | Session persistence and telemetry | [`live::persistence`], [`live::SessionTelemetry`] |
28//!
29//! Anything behind a Cargo feature is marked on its page — `vertex-ai-sessions`,
30//! `database-sessions`, `templates`, `otel`, and the rest — and the full list is
31//! in this crate's `Cargo.toml`.
32//!
33//! ## The shape of the runtime
34//!
35//! Every Live session runs one **router** and two lanes. The *fast lane* is
36//! synchronous and handles audio, text deltas and transcripts in under a
37//! millisecond per event; the *control lane* is async and runs tool calls,
38//! phase transitions, extractors and watchers. A third, independent
39//! *telemetry lane* observes both. The callback you register decides which
40//! lane it runs on, and the rule is written once at the top of
41//! [`live::callbacks`].
42//!
43//! ## A first taste
44//!
45//! [`state::State`] is the piece every layer shares — tools write it,
46//! guards read it, extractors fill it — so it is the smallest thing worth
47//! showing on its own:
48//!
49//! ```
50//! use gemini_adk_rs::state::{State, StateKey};
51//!
52//! const TURNS: StateKey<u32> = StateKey::new("session:turn_count");
53//!
54//! let state = State::new();
55//! state.set("user:name", "Alice");
56//! state.modify("session:turn_count", 0u32, |n| n + 1);
57//!
58//! assert_eq!(state.get::<String>("user:name").as_deref(), Some("Alice"));
59//! assert_eq!(state.get_key(&TURNS), Some(1));
60//! ```
61//!
62//! For a running session, see the `examples/` directory of the repository or
63//! the `Live::builder()` walkthrough in the fluent crate's documentation.
64
65// The proc macros expand to `::gemini_adk_rs::…`; this makes that path valid
66// inside the crate itself (its own tests and doctests included).
67extern crate self as gemini_adk_rs;
68
69pub mod a2a;
70pub mod agent;
71pub mod agent_config;
72pub mod agent_session;
73pub mod agent_tool;
74pub mod agents;
75pub mod artifacts;
76pub mod auth;
77pub mod code_executors;
78pub mod confirmation;
79pub mod context;
80pub mod credentials;
81pub mod error;
82pub mod evaluation;
83pub mod events;
84pub mod expr;
85pub mod extract;
86pub mod flow;
87pub mod frame;
88pub mod instruction;
89pub mod live;
90pub mod llm;
91pub mod llm_agent;
92pub mod memory;
93pub mod middleware;
94pub mod optimization;
95pub mod orchestration;
96pub mod planners;
97pub mod plugin;
98pub mod primitives;
99pub mod processors;
100pub mod router;
101pub mod run_config;
102pub mod runner;
103pub mod session;
104pub mod skills;
105pub mod state;
106pub mod telemetry;
107pub mod text;
108pub mod text_agent_tool;
109pub mod text_runner;
110pub mod tool;
111pub mod tools;
112pub mod toolset;
113pub mod utils;
114pub mod workflow;
115
116#[cfg(test)]
117pub(crate) mod test_helpers;
118
119// ── Shared closure shapes ─────────────────────────────────────────────────
120// Named once here so every module (phases, workflows, watchers, temporal
121// patterns, callbacks, resolvers) spells the same shape the same way.
122
123/// A boxed, sendable, `'static` future — the return type of every async
124/// callback and hook in the runtime.
125pub type BoxFuture<T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send + 'static>>;
126
127/// A synchronous predicate over shared [`State`]: `true` admits (a phase
128/// transition, a workflow node, a guard).
129pub type StatePredicate = std::sync::Arc<dyn Fn(&State) -> bool + Send + Sync>;
130
131/// An async source of a JSON value — the seam for a tool call, an HTTP fetch,
132/// an MCP request, or a workflow function node. `In` is what the source is
133/// bound from: the whole [`State`] by default, or a pre-bound args
134/// [`Value`](serde_json::Value) for extraction-kit field resolvers.
135///
136/// The `Err(String)` payload is a human-readable reason; it lands in
137/// `{name}:error` state keys and in extraction diagnostics.
138pub type AsyncSourceFn<In = State> = std::sync::Arc<
139    dyn Fn(
140            In,
141        ) -> std::pin::Pin<
142            Box<dyn std::future::Future<Output = Result<serde_json::Value, String>> + Send>,
143        > + Send
144        + Sync,
145>;
146
147// Ergonomic re-exports — existing
148pub use a2a::{A2aMessage, A2aPart, to_a2a_message, to_a2a_parts, to_adk_event, to_genai_parts};
149pub use agent::Agent;
150pub use agent_tool::AgentTool;
151pub use agents::{LoopAgent, ParallelAgent, SequentialAgent};
152#[cfg(feature = "gcs-artifacts")]
153pub use artifacts::GcsArtifactService;
154pub use artifacts::{Artifact, ArtifactService, FileArtifactService, InMemoryArtifactService};
155pub use auth::{
156    AuthConfig, AuthHandler, AuthScheme, CredentialExchanger, CredentialExchangerRegistry,
157    OAuthGrantType,
158};
159pub use code_executors::{
160    BuiltInCodeExecutor, CodeExecutionInput, CodeExecutionResult, CodeExecutor, CodeFile,
161};
162pub use confirmation::{
163    ConfirmationProvider, ConfirmationRequest, StaticConfirmation, ToolConfirmation,
164};
165pub use context::{AgentEvent, CallbackContext, InvocationContext, ToolContext};
166pub use credentials::{
167    AuthCredential, CredentialError, CredentialService, InMemoryCredentialService,
168};
169pub use error::{AgentError, AgentResult, ConfigError, ToolError};
170pub use events::{Event, EventActions, EventType, StructuredEvent};
171pub use extract::{Extract, Recognizer, RecordExtractor};
172pub use flow::{
173    CompiledFlow, Enforcement, Flow, FlowError, FlowErrors, FlowExplanation, FlowMonitor, Guard,
174    SharedFlowMonitor, StepAction, ToolSurface, Verdict, Violation, on_enter,
175};
176pub use frame::{ConfirmPolicy, Frame, FrameSpec, SlotRecognizer, SlotSpec, SlotValidator};
177/// Re-exports the `#[tool]`/`#[derive(..)]` macros route their generated code
178/// through, so downstream crates don't need the upstream crate names
179/// (`serde`/`schemars`/`async_trait`/`serde_json`) in scope or under those exact
180/// names. Not public API.
181#[doc(hidden)]
182pub mod __macros {
183    pub use async_trait;
184    pub use schemars;
185    pub use serde;
186    pub use serde_json;
187}
188
189/// The `#[derive(Extract)]` macro — builds an [`extract::Extract`] record from a
190/// struct's `#[recognize(..)]` fields. Shares the name `Extract` with the
191/// struct (macro vs type namespace), so both can be imported together.
192///
193/// See the [`gemini_adk_macros_rs::Extract`](macro@gemini_adk_macros_rs::Extract)
194/// documentation for details.
195pub use gemini_adk_macros_rs::Extract;
196/// Derive macro that generates a [`frame::Frame`] impl from a struct's
197/// `#[slot(..)]` fields. Shares the name `Frame` with the trait (macro vs type
198/// namespace), so both can be imported together.
199pub use gemini_adk_macros_rs::Frame;
200/// The `#[tool]` attribute macro — turns an `async fn` into a registrable Gemini tool.
201///
202/// See the [`gemini_adk_macros_rs::tool`] documentation for details.
203pub use gemini_adk_macros_rs::tool;
204pub use instruction::inject_session_state;
205pub use live::{
206    EventCallbacks, ExecutionMode, LiveHandle, LiveSessionBuilder, LlmExtractor, PersistenceError,
207    SessionHook, ToolCallSummary, TranscriptBuffer, TranscriptTurn, TurnExtractor,
208};
209pub use llm::{BaseLlm, GeminiLlm, GeminiLlmParams, LlmRegistry, LlmRequest, LlmResponse};
210pub use llm_agent::{LlmAgent, LlmAgentBuilder};
211pub use memory::{InMemoryMemoryService, MemoryEntry, MemoryService};
212pub use middleware::{Middleware, MiddlewareChain};
213pub use orchestration::{AgentMode, Resolver, call_agent, provenance};
214pub use plugin::{Plugin, PluginManager, PluginResult};
215pub use processors::{
216    ContentFilter, InstructionInserter, RequestProcessor, RequestProcessorChain, ResponseProcessor,
217    ResponseProcessorChain,
218};
219pub use router::AgentRegistry;
220pub use run_config::{RunConfig, StreamingMode};
221pub use runner::Runner;
222#[cfg(feature = "database-sessions")]
223pub use session::DatabaseSessionService;
224pub use session::{InMemorySessionService, Session, SessionId, SessionService, db_schema};
225pub use state::{FileJournalSink, JournalSink, MemoryJournalSink};
226pub use state::{PrefixedState, ReadOnlyPrefixedState, StateError};
227pub use state::{SlotEvidence, State, StateMutation, StateMutationOrigin};
228pub use text::{
229    DispatchTextAgent, FallbackTextAgent, FnTextAgent, JoinTextAgent, LlmTextAgent, LoopTextAgent,
230    MapOverTextAgent, ParallelTextAgent, RaceTextAgent, RouteRule, RouteTextAgent,
231    SequentialTextAgent, TapTextAgent, TaskRegistry, TextAgent, TimeoutTextAgent,
232};
233pub use text_agent_tool::TextAgentTool;
234pub use text_runner::{RunEvent, TextRunner};
235pub use tool::{SimpleTool, ToolDispatcher, ToolFunction, ToolPolicy, TypedTool};
236pub use tools::GoogleSearchTool;
237pub use tools::long_running::LongRunningFunctionTool;
238pub use tools::mcp::{McpConnectionParams, McpTool, McpToolset};
239pub use toolset::{StaticToolset, Toolset};
240pub use utils::model_name::{extract_model_name, is_gemini_model, is_gemini2_or_above};
241pub use utils::variant::{GoogleLlmVariant, get_google_llm_variant};
242
243// New re-exports — A2A
244pub use a2a::{AgentCard, AgentSkill, RemoteA2aAgent, RemoteA2aAgentConfig};
245
246// New re-exports — Evaluation
247pub use evaluation::{
248    EvalCase, EvalMetric, EvalResult, EvalSet, Evaluator, Invocation, LlmAsJudge,
249    PerInvocationResult, ResponseEvaluator, TrajectoryEvaluator,
250};
251
252// New re-exports — Planners
253pub use planners::{BuiltInPlanner, PlanReActPlanner, Planner, PlannerError};
254
255// New re-exports — Optimization
256pub use optimization::{
257    AgentOptimizer, EvalSample, OptimizerError, OptimizerResult, Sampler, SimplePromptOptimizer,
258    SimplePromptOptimizerConfig,
259};
260
261// New re-exports — Code Executors
262pub use code_executors::{
263    ContainerCodeExecutor, ContainerCodeExecutorConfig, UnsafeLocalCodeExecutor,
264};
265#[cfg(feature = "vertex-ai-code-executor")]
266pub use code_executors::{VertexAiCodeExecutor, VertexAiCodeExecutorConfig};
267
268// New re-exports — Plugins
269pub use plugin::{ContextFilterPlugin, GlobalInstructionPlugin, ReflectRetryToolPlugin};
270
271// New re-exports — Memory
272pub use memory::{VertexAiMemoryBankConfig, VertexAiMemoryBankService};
273#[cfg(feature = "vertex-ai-rag")]
274pub use memory::{VertexAiRagMemoryConfig, VertexAiRagMemoryService};
275
276// New re-exports — Sessions
277#[cfg(feature = "postgres-sessions")]
278pub use session::{PostgresSessionConfig, PostgresSessionService};
279pub use session::{SqliteSessionConfig, SqliteSessionService};
280#[cfg(feature = "vertex-ai-sessions")]
281pub use session::{VertexAiSessionConfig, VertexAiSessionService};
282
283// New re-exports — Tools
284pub use tools::retrieval::{BaseRetrievalTool, FilesRetrievalTool, RetrievalResult};
285#[cfg(feature = "vertex-ai-rag")]
286pub use tools::retrieval::{VertexAiRagConfig, VertexAiRagRetrievalTool};
287pub use tools::{
288    BashToolPolicy, DiscoveryEngineSearchTool, Example, ExampleTool, ExecuteBashTool, ExitLoopTool,
289    GetUserChoiceTool, LoadMemoryTool, PreloadMemoryTool, TransferToAgentTool, UrlContextTool,
290    VertexAiSearchConfig, VertexAiSearchTool,
291};
292
293// New re-exports — Agent Config
294pub use agent_config::{
295    AgentConfig, AgentConfigError, ToolConfig as AgentToolConfig, discover_agent_configs,
296};
297
298// Wire re-export
299pub use gemini_genai_rs;