Module prelude

Module prelude 

Source
Expand description

The kernel prelude — the ~40 types a typical application touches.

Deliberately a kernel, not an everything-glob. Anything not here lives in a focused submodule and is one import away:

NeedImport
Full Live control plane (persistence, repair, steering, transcripts, contracts)use gemini_adk_fluent_rs::live::*;
Text-agent runtime detailsuse gemini_adk_fluent_rs::text::*;
Toolsets, confirmation, framesuse gemini_adk_fluent_rs::tools::*;
State prefixes / SlotEvidenceuse gemini_adk_fluent_rs::state::*;
Full flow vocabulary (CompiledFlow, StepAction, Violation, …)use gemini_adk_fluent_rs::flow::*;
Agent trait + operator/pattern internalsuse gemini_adk_fluent_rs::agents::*;
Conversation compiler (Conversation, ConversationSpec, …)use gemini_adk_fluent_rs::conversation::*;
A2A, motifs, policy, simulation, testing, orchestration, credentials, run_configthe same-named module, e.g. use gemini_adk_fluent_rs::simulation::*;
Raw L0 wire typesuse gemini_adk_fluent_rs::wire::*;

Re-exports§

pub use crate::voice::Talk;
pub use crate::compose::A;
pub use crate::compose::C;
pub use crate::compose::Ctx;
pub use crate::compose::E;
pub use crate::compose::G;
pub use crate::compose::M;
pub use crate::compose::P;
pub use crate::compose::S;
pub use crate::compose::T;
pub use crate::live::Live;
pub use crate::testing::AgentHarness;
pub use crate::testing::ContractViolation;
pub use crate::testing::DataFlowEdge;
pub use crate::testing::LiveViolation;
pub use crate::testing::check_contracts;
pub use crate::testing::check_live;
pub use crate::testing::diagnose;
pub use crate::testing::infer_data_flow;
pub use crate::builder::*;
pub use crate::operators::*;
pub use crate::patterns::*;

Modules§

tool
Tool dispatch — regular, streaming, and input-streaming tools.
tool_media
Tool media returns — the ADK pattern where a function response carries images or other media to the model alongside its JSON payload, so vision tools (screenshots, chart renderers, document croppers) feed the model something it can actually look at.

Structs§

AudioJitterBuffer
Adaptive jitter buffer for audio playback.
AutomaticActivityDetection
Automatic activity detection (VAD) settings.
BargeInConfig
Configuration for barge-in behavior.
BargeInDetector
Barge-in detector — checks whether user speech should interrupt model output.
BatchJob
A batch prediction job resource.
BatchJobDestination
Destination configuration for a batch job.
BatchJobSource
Source configuration for a batch job.
Blob
A blob of inline data (audio, image, etc.) sent to or received from Gemini.
CachedContent
Cached content resource.
CachedContentUsageMetadata
Usage metadata for cached content.
CallbackContext
Rich context for callbacks — provides access to state, artifacts, memory, and event actions for mutation.
ChatSession
A stateful chat session that tracks conversation history.
CitationMetadata
Citation metadata for a response.
CitationSource
A single citation source.
CodeExecutionResult
Result of code execution.
ConfigError
A build-time configuration error: one or more problems found while validating user-supplied configuration (a Flow, a PhaseMachine, a ComputedRegistry, …).
ConnectBuilder
Connects a SessionConfig with options: transport tuning, a custom transport or codec, a wire recorder. connect is the same thing with none of them.
Content
A content message containing a role and a sequence of parts.
ContentEmbedding
Embedding vector.
ContextWindowCompressionConfig
Context window compression configuration for long sessions.
CountTokensResponse
Response from countTokens.
CreateBatchJobConfig
Configuration for creating a batch job.
CreateCachedContentConfig
Configuration for creating cached content.
CreateTuningJobConfig
Configuration for creating a tuning job.
DispatchTextAgent
Fire-and-forget background task launcher with global task budget.
EmbedContentConfig
Configuration for embed requests.
EmbedContentResponse
Response from embedContent.
EventCallbacks
Typed callback registry for Live session events.
ExecutableCode
Executable code returned by the model.
Extract
A declarative extraction record: typed fields filled by recognizers and/or async resolvers.
FallbackTextAgent
Tries each child agent in sequence. Returns the first successful result. If all fail, returns the last error.
FileData
Reference to an uploaded file.
Flow
A governed conversation/tool DAG.
FlowMonitor
Observes the session trace, maintains the Marking, answers tool admissibility, and projects active postures.
FnTextAgent
Zero-cost state transform agent — executes a closure, no LLM call.
FsPersistence
File-system persistence (good for development and single-server deployments).
FunctionCall
A function call request from the model.
FunctionCallingConfig
Configuration for function calling behavior.
FunctionDeclaration
Schema for a single function that the model can call.
FunctionResponse
A function call response sent back to the model.
GeminiLlm
Concrete Gemini LLM implementation using gemini-live Client.
GeminiLlmParams
Parameters for constructing a GeminiLlm.
GenerateContentConfig
Configuration for a generateContent request.
GenerateContentResponse
Top-level response from generateContent.
GenerationConfig
Generation config sent in the setup message.
GoogleAIAuth
Google AI API key authentication.
GoogleAITokenAuth
Google AI OAuth2 access token authentication.
GoogleSearch
Google Search tool configuration (empty — presence enables the feature).
GoogleSearchRetrieval
Google Search retrieval tool configuration.
GroundingMetadata
Grounding metadata for server content with search results.
HttpClient
HTTP client wrapping reqwest with retry and telemetry.
HttpConfig
Configuration for the HTTP client.
InputAudioTranscription
Input audio transcription configuration.
JitterConfig
Configuration for the jitter buffer.
JoinTextAgent
Waits for dispatched background tasks and collects their results.
JsonCodec
Default JSON codec — current behavior extracted from connection.rs.
ListBatchJobsResponse
Response from listBatchJobs.
ListCachedContentsResponse
Response from listCachedContents.
ListModelsResponse
Response from list models.
ListTuningJobsResponse
Response from listTuningJobs.
LiveHandle
Handle for interacting with a running Live session.
LlmExtractor
LLM-backed turn extractor that sends transcript windows to an OOB LLM with a structured extraction prompt.
LlmTextAgent
Core text agent — calls BaseLlm::generate(), dispatches tools, loops until the model produces a final text response.
LoopTextAgent
Runs a text agent repeatedly until max iterations or a state predicate.
MapOverTextAgent
Iterates a single agent over each item in a state list. Reads state[list_key], runs agent per item (setting state[item_key]), collects results into state[output_key].
MemoryPersistence
In-memory persistence (good for tests).
MockTransport
Mock transport for unit testing.
ModalityTokenCount
Token count breakdown by modality (text, audio, image, video).
ModelId
A Gemini model identifier, exactly as the API accepts it.
OutputAudioTranscription
Output audio transcription configuration.
ParallelTextAgent
Runs text agents concurrently. All branches share state. Results are collected and joined with newlines.
PrebuiltVoiceConfig
Prebuilt voice selection.
ProactivityConfig
Proactivity configuration — controls whether the model can initiate responses.
RaceTextAgent
Runs agents concurrently, returns the first to complete. Cancels the rest.
RealtimeInputConfig
Server-side VAD configuration for the setup message.
RepairConfig
Configuration for the conversation repair system.
ResumeInfo
Session resumption information from the server.
RouteRule
A routing rule: predicate over state → target agent.
RouteTextAgent
State-driven deterministic branching — evaluates predicates in order, dispatches to the first matching agent. Falls back to default if none match.
SafetyRating
Per-category safety assessment of generated content.
SafetySetting
Per-category safety configuration for content generation.
SequentialTextAgent
Runs text agents sequentially. Each agent sees state mutations from previous agents. The final agent’s output is the pipeline’s output.
SessionConfig
Complete session configuration — the builder entrypoint.
SessionHandle
The public API surface for a Gemini Live session.
SessionResumptionConfig
Session resumption configuration.
SimpleTool
Simple function tool that wraps an async closure.
SlidingWindow
Sliding window configuration for context compression.
SoftTurnDetector
Detects proactive silence — user stopped speaking but model didn’t respond.
SpeechConfig
Speech configuration for audio output.
SpscConsumer
The reading half of an SpscRing.
SpscProducer
The writing half of an SpscRing.
SpscRing
Wait-free single-producer single-consumer ring buffer for audio samples.
State
A concurrent, type-safe state container that agents read from and write to.
StateKey
A compile-time typed state key that eliminates typo bugs and type mismatches.
SupervisedTuningSpec
Supervised tuning specification.
TapTextAgent
Read-only observation agent. Calls a function with the state but cannot mutate it. Returns empty string. No LLM call.
TaskRegistry
Shared registry for dispatched background tasks.
TemplateInstruction
A full template-engine instruction (feature templates) — minijinja (Jinja2 syntax: conditionals, loops, filters) over the session state, mirroring ADK’s use_jinja2 instructions. The whole state is exposed as state (subscript prefixed keys: {{ state["session:turn_count"] }}), and every key that is a bare identifier is also available at top level ({{ name }}). Falls back to the empty string for missing values under Jinja’s default undefined semantics.
ThinkingConfig
Configuration for model thinking/reasoning (Gemini 2.5+).
TimeoutTextAgent
Wraps an agent with a time limit. Returns AgentError::Timeout if exceeded.
Tool
A tool declaration sent in the setup message. Each Tool object can contain one of: function declarations, urlContext, googleSearch, codeExecution, or googleSearchRetrieval.
ToolCodeExecution
Code execution tool configuration (empty — presence enables the feature).
ToolConfig
Controls how and when the model uses tools.
ToolContext
Extended context for tool execution — adds function call ID and confirmation.
ToolDispatcher
Routes function calls to the right tool implementation.
ToolPolicy
Optional per-tool execution policy.
TranscriptBuffer
Accumulates input/output transcripts and segments them by turn boundaries.
TranscriptTurn
A single completed conversation turn with accumulated transcripts.
TransportConfig
Configuration for the transport layer.
TungsteniteTransport
WebSocket transport using tokio-tungstenite.
TuningHyperParameters
Tuning hyperparameters.
TuningJob
A tuning job resource.
TurnDetectionConfig
Configuration for client-side turn detection.
TurnDetector
Client-side turn detector.
TypedTool
Type-safe function tool with auto-generated JSON Schema.
UpdateCachedContentRequest
Updates to apply to a cached content resource.
UrlContext
URL context tool configuration (empty — presence enables the feature).
UrlContextMetadata
URL context metadata for content sourced from URLs.
UsageMetadata
Usage metadata returned by the server on messages.
VadConfig
VAD configuration parameters.
VertexAIAuth
Vertex AI Bearer token authentication.
VertexConfig
Configuration for connecting through Vertex AI.
VoiceActivityDetector
Voice Activity Detector with adaptive noise floor.
VoiceConfig
Voice configuration within speech config.

Enums§

AccessToken
An OAuth2 access token source.
ActivityHandling
Controls how incoming audio interacts with model output.
AgentError
Errors that can occur during agent execution.
ApiEndpoint
API endpoint selector — Google AI (direct), Google AI with OAuth token, or Vertex AI.
AudioFormat
Audio encoding formats supported by the Gemini Live API.
AuthError
Authentication-specific errors.
BargeInAction
Result of a barge-in check.
BatchJobState
State of a batch job.
BatchesError
Errors from the Batches API.
BufferState
Current state of the jitter buffer.
CachesError
Errors from the Caches API.
CodecError
Error during encoding or decoding.
ContextDelivery
When to deliver model-role context turns to the wire.
EmbedError
Errors from the Embed API.
EndpointEnvError
Error resolving an ApiEndpoint from the environment.
Enforcement
How a FlowMonitor treats off-path activity — enforcement vs observation.
ExtractionTrigger
Controls WHEN an extractor runs.
FinishReason
Why the model stopped generating.
FunctionCallingBehavior
Whether tool calls block model output or run concurrently.
FunctionCallingMode
How the model should decide when to execute tool calls.
FunctionResponseScheduling
Scheduling mode for non-blocking function responses.
GenerateError
Errors specific to the Generate API.
Guard
A boolean predicate over (state, marking) — the only predicate type.
HarmBlockThreshold
Blocking threshold for safety settings.
HarmCategory
Categories of potential harm in model output.
HarmProbability
Probability that content is harmful.
HttpError
Errors from HTTP client operations.
MediaResolution
Media resolution for image/video inputs.
Modality
Output modalities the model can produce.
ModelsError
Errors from the Models API.
Part
A single part of a Content message. Parts are polymorphic — discriminated by field presence, not a type tag.
PersistenceError
Error returned by a SessionPersistence backend.
Role
Role in a conversation.
Sensitivity
Voice activity detection sensitivity level.
ServerMessage
Unified server message enum — parsed from incoming WebSocket text frames.
ServiceEndpoint
Identifies which Gemini API service to connect to.
SessionCommand
Commands sent from application code to the session transport.
SessionError
Errors that can occur during a session.
SessionEvent
Events emitted by the session, consumed by application code.
SessionPhase
The lifecycle phase of a Gemini Live session.
SetupError
Errors during the setup handshake phase.
SteeringMode
How the phase machine steers the model’s behavior.
TokensError
Errors from the Tokens API.
ToolError
Errors that can occur during tool execution.
TungsteniteError
Errors from the TungsteniteTransport.
TuningJobState
State of a tuning job.
TuningsError
Errors from the Tunings API.
TurnCoverage
Controls which input counts toward a user’s conversation turn.
TurnDetectionEvent
Events from the turn detector.
VadEvent
Events emitted by the VAD.
Verdict
The conformance status of a step.
Voice
Available voice presets for Gemini Live audio output.
WebSocketError
WebSocket-level errors with structured detail.

Constants§

LIVE_INPUT_SAMPLE_RATE
The sample rate the Live API takes on the way in.

Traits§

Agent
The fundamental agent trait. Everything that can process a live session implements this — LLM agents, function agents, pipelines, routers.
AuthProvider
Provides authentication credentials and URL construction for Gemini API connections.
BaseLlm
Trait for LLM providers — decouples agents from specific models.
Codec
Encodes client commands into wire bytes and decodes server bytes into messages.
Frame
A typed conversation frame. Implement via #[derive(Frame)].
InstructionProvider
A dynamic instruction source — the ADK “instruction provider” pattern: instead of a string fixed at build time, the instruction is produced from live session state on every model request (persona switching, risk-driven guardrails, multi-tenant instructions without rebuilding the agent). Any Fn(&State) -> String closure is a provider.
SessionPersistence
Trait for persisting session state across process restarts.
SessionReader
Read-side of a session — subscribe to events and observe phase.
SessionWriter
Write-side of a session — send commands without owning the full handle.
TextAgent
A text-based agent that runs via BaseLlm::generate() (request/response).
ToolFunction
A regular tool — called once, returns a result.
ToolProvider
Declares tools for a Gemini session setup message. Implement this trait to provide tools from any source (runtime ToolDispatcher, etc.).
Transport
A bidirectional message transport.
TurnExtractor
Trait for between-turn extraction from transcript windows.

Functions§

bytes_to_i16
Convert raw bytes to i16 PCM samples (zero-copy via bytemuck).
connect
Connect to the Gemini Multimodal Live API with the default transport and return a session handle.
i16_to_bytes
Convert a slice of i16 PCM samples to raw bytes (zero-copy via bytemuck).
into_shared
Wrap raw bytes as a shared Bytes handle for zero-copy fan-out.
recv_event
Receive the next event from a broadcast receiver, handling lag gracefully.

Type Aliases§

AgentResult
Convenience alias for fallible agent-runtime operations.

Attribute Macros§

tool
Turn an async fn into a registrable Gemini tool.

Derive Macros§

Extract
Derive an Extract record builder from a struct’s fields.
Frame
Derive a Frame impl from a struct’s #[slot(..)] fields.