Skip to content

Cookbook

Every example below lives in the Rig v0.44.0 examples directory and is a complete, runnable program that Rig’s CI compiles. Use this page to find a starting point, then read the source for the details. Each example’s src/main.rs opens with a comment saying what it shows and which keys it needs.

Each example is its own workspace package. Clone the repo at the release tag, set the API key(s) the example needs, and run it by package name:

Terminal window
git clone --branch v0.44.0 https://github.com/0xPlaygrounds/rig
cd rig
export OPENAI_API_KEY=...
# export ANTHROPIC_API_KEY=... GEMINI_API_KEY=... COHERE_API_KEY=...
cargo run -p agent

Two short, complete programs you can copy and run. Both are compile-checked against Rig v0.44.0. Set OPENAI_API_KEY before running.

Demonstrates: Agents, Tools. The model decides when to call your Rust function and Rig runs the tool loop for you.

use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize)]
struct AddArgs {
a: i32,
b: i32,
}
#[derive(Debug, thiserror::Error)]
#[error("math error")]
struct MathError;
struct Adder;
impl Tool for Adder {
const NAME: &'static str = "add";
type Error = MathError;
type Args = AddArgs;
type Output = i32;
fn description(&self) -> String {
"Add two integers together".to_string()
}
fn parameters(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": { "a": { "type": "number" }, "b": { "type": "number" } },
"required": ["a", "b"]
})
}
async fn call(&self, _ctx: &mut ToolContext, args: Self::Args) -> Result<i32, MathError> {
Ok(args.a + args.b)
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let agent = AgentBuilder::new(OpenAI::from_env()?.completion(openai::GPT_5_5))
.preamble("Use the add tool for arithmetic.")
.tool(Adder)
.default_max_turns(2) // one turn to call the tool, one to answer
.build();
let answer = agent.prompt("What is 21 + 21?").await?.output();
println!("{answer}");
Ok(())
}
21 + 21 = 42.

Demonstrates: Structured Output. Define a struct, get it back filled in, with no manual JSON parsing.

use rig::extractor::ExtractorBuilder;
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct Person {
name: String,
/// The person's age in years, if stated.
age: Option<u8>,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let model = OpenAI::from_env()?.completion(openai::GPT_5_5);
let extractor = ExtractorBuilder::<Person>::new(model).build();
let person = extractor
.extract("Marie Curie was 66 years old when she passed away.")
.await?
.output;
println!("{person:?}");
Ok(())
}
Person { name: "Marie Curie", age: Some(66) }

The smallest useful programs for the core building blocks. Concepts: Agents, Completions, Structured Output.

ExampleWhat it shows
agentThe provider → model → agent → prompt flow end to end.
extractorTyped extraction into a struct, with and without usage metadata.
sentiment_classifierThe smallest typed extractor, used to classify a sentence into an enum.
multi_extractSeveral extractions of one text in parallel with futures::try_join!.
agent_with_contextStatic context documents attached to an agent (Cohere).
agent_with_loadersLoading files from disk into an agent’s context with FileLoader.
frozen_apiEight short programs (cargo run -p frozen_api --example p1_one_prompt, …): one prompt, streaming, an erased model, tools, local and HTTP operations, an OpenAI-compatible vendor, a custom transport.

Provider-specific features, local models, and non-text modalities. See Model Providers for configuring any provider.

ExampleWhat it shows
openai_agent_completions_api_otelUsing OpenAI’s Chat Completions API instead of the default Responses API.
openai_streaming_per_call_usagePer-model-call token usage inside a streamed agent run.
gemini_video_understandingGemini video input with provider-specific request parameters.
gemini_default_api_recoveryRecovering when Gemini emits a legacy default_api tool name.
gemini_stream_kill_token_countGetting a token-count estimate when a stream is cut off mid-response.
gemini_deep_researchRunning a Gemini Deep Research agent through the Gemini extension API.
gemini_nanobanana_image_generationImage generation with Gemini, written to a file.
cohere_image_embeddingsEmbedding an image with Cohere Embed v3.
transcriptionAudio transcription with OpenAI, Gemini, Groq and Mistral.
candle_localA local chat model on Candle, from downloaded Hugging Face weights.
candle_poseHuman pose estimation with a YOLOv8 checkpoint on Candle.
candle_wasm_chatBrowser chat backed by SmolLM2 compiled to WebAssembly.
typesafeai_triageTyped yes/no decisions about a support ticket with the TypesafeAI provider.
typesafeai_chatInteractive TypesafeAI decisions, optionally followed by an ordinary agent.

Retrieval-augmented generation and vector stores. Concepts: Vector Stores & RAG, Embeddings; full walkthrough in Build a RAG system; backends in Vector Stores.

ExampleWhat it shows
ragEmbed documents, attach the index to an agent as dynamic context, answer.
chainRetrieval by hand: look up context, fold it into the prompt, then prompt.
rag_ollamaThe same RAG flow against a local Ollama model.
vector_searchAn in-memory vector index with OpenAI embeddings: top_n vs top_n_ids.
vector_search_cohereSeparate Cohere document and query embeddings.
vector_search_ollamaVector search with a local Ollama embedding model.
rag_dynamic_toolsTools picked per prompt by vector search over their descriptions.
rag_dynamic_tools_multi_turnDynamic tool retrieval across a multi-turn run.
pdf_agentLoad and chunk PDFs, embed with Ollama, answer questions over them.
gemini_extractor_with_ragA typed extractor fed by retrieval, on Gemini.
custom_vector_storeImplementing VectorStoreIndex for your own backend.

Callable tools, tool streaming, and MCP. Concept: Tools; MCP: Model Context Protocol.

ExampleWhat it shows
agent_with_toolsRuntime-defined DynamicTools registered on an agent.
calculator_chatbotAn interactive terminal chatbot (ChatBotBuilder) with arithmetic tools.
agent_with_default_max_turnsRaising the agent’s turn budget for tool-heavy prompts.
manual_tool_callsHandling tool calls yourself with a raw model request, no agent loop.
agent_tool_call_streamingTool-call arguments streaming in as the provider sends them.
tool_result_outcomesTools that classify their failures as structured facts; hooks apply policy.
force_tool_first_turnForcing a tool call on the first turn only, with a request patch.
rmcpUsing MCP server tools from an agent via rmcp (package rmcp_example).
agent_with_echochambersAn agent driving a third-party HTTP API through several tools.

Multi-turn runs, multi-agent patterns, memory, streaming, and control over the agent loop. Concepts: Agents, AgentRunner, Hooks, Streaming, Memory, Workflows; guide: Multi-agent systems.

ExampleWhat it shows
multi_turn_agentA run that takes several tool-calling turns to finish.
complex_agentic_loop_claudeA Claude orchestrator delegating to research, analysis and recommendation agents.
reasoning_loopA chain-of-thought agent that reasons before calling tools.
agent_stream_chatA streamed run that continues prior conversation history.
agent_with_memoryRig-managed conversation memory with an in-memory backend.
agent_with_memory_streamingThe same memory setup with streamed responses.
agent_with_agent_toolOne agent used as a tool by another (Agent::into_tool).
multi_agentA translator agent wrapped in a hand-written tool for a main agent.
agent_orchestratorAn orchestrator agent that splits a task and dispatches it to workers.
agent_routingA classifier agent choosing which follow-up prompt runs.
agent_prompt_chainingTwo agents in sequence, the second transforming the first’s output.
agent_parallelizationSeveral agents scoring one input in parallel.
agent_evaluator_optimizerA generator and an evaluator agent iterating on an answer.
agent_autonomousAn extractor loop that feeds its own output back in until a stop condition.
debateTwo agents on different providers debating each other.
enum_dispatchChoosing between agents on different providers by name at runtime.
request_hookStacking several AgentHooks that all run on every model call.
agent_with_retry_hookRetrying a model turn from a hook within the run’s turn budget.
agent_with_human_in_the_loopAsking a human to approve each side-effecting tool call.
agent_with_approval_policyApproval rules decided up front and applied by a hook, no human prompt.
agent_with_durable_approvalPausing a run, serializing it, and resuming after out-of-process approval.
agent_run_steppingDriving the loop by hand with AgentRun, compared with AgentRunner.
agent_no_tokioRunning an agent on bevy_tasks instead of tokio.

Running agents as services, observability and HTTP concerns. Guides: Discord bot, Deploy to AWS Lambda, Deploy with LanceDB; concept: Observability.

ExampleWhat it shows
discord_botA Rig agent behind a Discord slash command, with per-thread history.
agent_with_tools_otelA tool-using agent exporting traces to an OpenTelemetry collector.
openai_streaming_with_tools_otelThe same, for a streamed run. The collector config is in otel/.
http_middlewareHTTP middleware on a provider call: add headers, log bodies, read rate-limit headers.
reqwest_middlewareBinding a provider to your own reqwest client with retry middleware.