Skip to content

Examples

gemini-rs ships 30 runnable cookbook examples plus interactive web demos. The cookbook is organized around the higher-order, governed-agent capabilities — the powerful primitives this SDK is built on — with the composition foundations beneath them.


Governed Agents — the higher-order capabilities

Section titled “Governed Agents — the higher-order capabilities”

These primitives make an agent governed: a declarative control DAG, deterministic fact extraction, agent orchestration, and the safety/connection capabilities around them. They compose multiplicatively (see the Governed Agents synthesis and the Flow / Extraction-kit / Orchestration RFCs in docs/plans/). Start here.

CapabilityExampleWhat it shows
Flow — governed conversation/tool DAG37_governed_flowone DAG gates tools, projects postures, enforces order, once/never…until, mermaid (debt collection)
Extract — deterministic facts (no LLM)38_extractionCPU recognizers fill State → drive a Flow guard with no model in the control loop
Orchestrationcall/dispatch/background19_agent_tool, 26_dispatch_join, 27_race_timeoutinvoke sub-agents sync/async; results land in State
Tool governanceconfirm/timeout/cached34_tool_policiesper-tool policies + ConfirmationProvider enforcement; commit-tool safety
Session persistence35_session_persistencesnapshot/resume + the session store
MCP tools36_mcp_toolsstdio/SSE MCP integration
Capstones (combine all three lenses)39_booking, 40_screeningFlow × Extract × Orchestration on real use cases
Terminal window
cargo run -p example-cookbook --bin 37-governed-flow
cargo run -p example-cookbook --bin 38-extraction
cargo run -p example-cookbook --bin 34-tool-policies

Composition foundations (examples/cookbook/)

Section titled “Composition foundations (examples/cookbook/)”

The building blocks the governed capabilities compose: the builder API, the S·C·T·P·M·A operator algebra, and the text-agent combinators — a structured Crawl → Walk → Run path. Each example is a self-contained binary with detailed doc comments.

Terminal window
cargo run -p example-cookbook --bin 01-foundations
cargo run -p example-cookbook --bin 21-full-algebra

The core builder API and composition primitives, grouped into three combined examples. No async runtime required — they are construction-only and run without credentials.

#BinaryWhat it covers
0101_foundationsAgentBuilder (model, sampling, thinking, copy-on-write, data contracts); SimpleTool/TypedTool/ToolDispatcher + built-in tools; M:: callbacks/middleware (model/tool hooks, taps, resilience)
0202_combinators>> sequential pipelines, | parallel fan-out, * N / * until(pred) loops; review_loop/fan_out_merge/supervised; check_contracts
0303_compositionThe operator algebra: S:: state transforms (>>), P:: prompt sections (+), T:: tools (|), G:: output guards (|)

Compound agent topologies, evaluation, artifacts, and advanced state management.

#BinaryWhat it covers
1111_route_branchingRouteTextAgent, FnTextAgent, RouteRule, S::is_true, S::eq — deterministic state-driven routing
1212_fallback_chain/ operator: graceful degradation, FallbackTextAgent, primary/secondary chains
1313_review_loopReviewer + writer feedback cycle, * until(predicate) convergence, inter-agent state sharing
1414_map_overMapOverTextAgent: parallel item-level processing, collecting and aggregating results
1515_middleware_stackM::cache, M::dedup, M::metrics, M::fallback_model — composing middleware with |
1616_context_engineeringC::window, C::user_only, C::model_only, C::summarize, C::priority, C::exclude_tools, C::dedup
1717_evaluation_suiteE::suite, E::response_match, E::contains_match, E::trajectory, E::safety, E::semantic_match, E::hallucination, E::custom, E::persona
1818_artifactsA::json_output, A::text_output, A::publish, A::save, A::load, A::version — artifact I/O schemas
1919_agent_toolTextAgentTool: wrapping a TextAgent as a callable tool; agent-as-tool dispatch
2020_supervisedHuman-in-the-loop approval: TapTextAgent, approval callbacks, blocking and resuming pipelines

Full-system compositions covering real-world architectures and every SDK capability.

#BinaryWhat it covers
2121_full_algebraAll operators together (>>, |, *, /, * until), all six composition namespaces
2222_contract_testingSchema validation, JSON contract tests, A::json_output with schema enforcement
2323_deep_researchMulti-source research pipeline with T::google_search, synthesis agent, and result merging
2424_customer_supportRouting, escalation state machine, RouteTextAgent, multi-phase support flow
2525_code_reviewAutomated code review: linting agent, security agent, summary agent in a >> pipeline
2626_dispatch_joinDispatchTextAgent + JoinTextAgent: fire-and-forget dispatch with join synchronization
2727_race_timeoutRaceTextAgent: first-to-finish wins; TimeoutTextAgent: deadline enforcement
2828_a2a_remoteAgent-to-agent protocol: RemoteAgent, A2aServer, A2aRegistry, remote agents behind local proxy tools
2929_live_voiceFull Live::builder() API: phases, tools, extraction, watchers, steering, repair, persistence
3030_production_pipelineEnd-to-end production pipeline: telemetry, middleware, evaluation, artifact publishing

Fly (31–38) — Higher-order capabilities

Section titled “Fly (31–38) — Higher-order capabilities”

Connection helpers, callback surfaces, macros, governance, and the governed-agent primitives (see the capability track at the top).

#BinaryWhat it covers
3434_tool_policiesT::cached, T::timeout, T::confirm, nested policies, ConfirmationProvider enforcement
3535_session_persistenceMemoryPersistence, FsPersistence, SessionSnapshot round-trips; InMemorySessionService event log
3636_mcp_toolsMcpConnectionParams::Stdio/Sse, McpSessionManager, McpToolset, T::mcp(), JSON-RPC 2.0 lifecycle
3737_governed_flowFlow — a governed conversation/tool DAG: gate tools, project postures, once/never…until, mermaid
3838_extractionExtract — CPU recognizers (integer/money/one_of/fuzzy/yes_no) fill State and drive a Flow guard, no LLM
3939_bookingCapstone — Flow × Extract × Orchestration on a table-booking scenario
4040_screeningCapstone — governed call screening: spam verdict gates the transfer

Flow Studio cookbooks (SessionSpec as JSON)

Section titled “Flow Studio cookbooks (SessionSpec as JSON)”

Six industry scenarios ship as complete JSON documents in the Flow Studio gallery — mock tools, governance constraints, and embedded conformance tests that replay through the real flow monitor in CI, no API key needed:

CookbookIndustryHighlights
Debt collectionFinancial servicescompliance gates, once payment, declarative extraction
Patient intakeHealthcareconditional emergency edge + any join
Line supportTelecomreset loop — a re-test reopens the diagnostic
Call screeningFront deskspam-verdict-gated transfer
Returns deskE-commerceeligibility-gated single refund
Table bookingHospitalityambient memory, computed state

The documents live in apps/gemini-adk-web-rs/static/examples/flows/; import them into the Studio or feed them to SessionSpec directly.

ExampleWhat it shows
examples/telephonyA phone agent behind Twilio Media Streams: axum TwiML webhook + media WebSocket, G.711 bridged to the voice pump, one Live session per call
examples/sip-agentA carrier-free SIP agent (feature sip): binds UDP 5060, answers INVITEs with SDP + symmetric RTP — dial it from any softphone or PBX

See the Telephony guide.


The interactive multi-app web UI runs at http://localhost:25125 and bundles all demo apps into a single server with a shared DevTools panel.

Terminal window
cargo run -p gemini-adk-web-rs # http://127.0.0.1:25125

For more on the web UI design system, dark/light mode, and DevTools panels, see the ADK Web UI guide.

These run independently outside of gemini-adk-web-rs, each with their own Axum server.

Terminal window
cargo run -p example-text-chat # http://127.0.0.1:3001
cargo run -p example-voice-chat # http://127.0.0.1:3002
cargo run -p example-tool-calling # http://127.0.0.1:3003
cargo run -p example-transcription # http://127.0.0.1:3004
ExampleLayerFeatures
text-chatL0Text-only session, streaming deltas, turn lifecycle
voice-chatL0Bidirectional audio, input/output transcription, VAD events
tool-callingL1TypedTool, ToolDispatcher, NonBlocking behavior, WhenIdle scheduling
transcriptionL0Every Gemini Live config option: VAD, compression, resumption, affective dialog

text-chat — Minimal text session. Live::builder().text_only(), streaming.

voice-chat — Native audio. Modality::Audio, voice selection, transcription.

tool-calling — Three demo tools (get_weather, get_time, calculate). NonBlocking + WhenIdle.

all-config — Configuration playground. Every Gemini Live option exposed as a JSON config: modality, temperature, Google Search, code execution, session resumption, context compression.

guardrails — Policy monitoring with real-time corrective injection. RegexExtractor, .watch(), .instruction_amendment(). Policies: PII (SSN, credit cards), off-topic, negative sentiment.

playbook — 6-phase customer support state machine. .phase(), .transition_with(), .greeting(), .with_context(), RegexExtractor, .watch().

support-assistant — Multi-agent handoff between billing and technical support. 10-phase dual state machine, .computed() derived state, .watch() escalation, cross-agent transitions, telemetry.

call-screening — Incoming call screening with sentiment analysis and smart routing. NonBlocking tools: check_contact_list, check_calendar, take_message, transfer_call, block_caller.

clinic — HIPAA-aware telehealth appointment scheduling. 8 tools with NonBlocking behavior. Patient intake, department routing, insurance check, appointment booking.

restaurant — Reservation assistant with menu context. 6 tools, dietary and occasion tracking.

debt-collection — FDCPA-compliant debt collection. StateKey<T> typed state, compliance watchers, identity verification, cease-and-desist handling.


All examples work with both Google AI (API key) and Vertex AI (project/location).

FeatureGoogle AIVertex AI
Async tool calling (NonBlocking)✓ SupportedStripped automatically
Response scheduling (WhenIdle / Silent)✓ SupportedStripped automatically
WebSocket framesTextBinary (handled automatically)
Thinking config✓ SupportedStripped automatically

The SDK detects your authentication method and strips unsupported wire fields transparently — no code changes needed when switching platforms.