Open Agent SDK (Rust)
Build AI agents in Rust, over OpenAI chat completions or Anthropic messages
What you can build:
- Copy editors that analyze manuscripts and track writing patterns
- Git commit generators that write meaningful commit messages
- Market analyzers that research competitors and summarize findings
- Code reviewers, data analysts, research assistants, and more
Why this SDK?
- Two protocols - one API over OpenAI chat completions or Anthropic messages, chosen per endpoint
- Local or hosted - run on your own hardware at no API cost and with no data leaving the machine, or point it at a vendor
- Control - pick your model (Qwen, Llama, Mistral, Claude, etc.)
How fast? From zero to working agent in under 5 minutes. Rust-native performance (zero-cost abstractions, no GC), fearless concurrency, with 569 active tests.
Overview
Open Agent SDK (Rust) provides a clean, streaming API for working with local and cloud model servers over two wire protocols: OpenAI chat completions and Anthropic messages, selected per endpoint. 100% feature parity with the Python SDK—complete with transport-boundary-safe SSE streaming, tool call aggregation, hooks, and automatic tool execution—built on Tokio for high-performance async I/O.
Streaming is tolerant of real-world servers. SSE events are buffered across arbitrary HTTP
transport chunk boundaries, and anything still held is flushed when the stream ends — including
when a server closes the connection or sends data: [DONE] without ever setting
finish_reason, which llama.cpp, vLLM, and several local gateways do. Content is never
silently dropped.
Every stream reports why it ended. The stream from query() terminates with exactly one
StreamEvent::Finish carrying a FinishReason, so a response cut off at the token cap
(Length) is distinguishable from one the model chose to end (Stop) and from a server that
never said (Unspecified) — three cases that look identical from the content alone. On
Client, the same information is available from client.finish_reason().
Supported Providers
The protocol is a property of the endpoint, set with .protocol(..) and defaulting to
ApiProtocol::OpenAiChat.
ApiProtocol::OpenAiChat — POST {base_url}/chat/completions, bearer auth
- LM Studio -
http://localhost:1234/v1 - Ollama -
http://localhost:11434/v1 - llama.cpp server - OpenAI-compatible mode
- vLLM - OpenAI-compatible API
- Text Generation WebUI - OpenAI extension
- Any OpenAI-compatible local endpoint
- Cloud vendors - OpenAI, OpenRouter, z.ai (
https://api.z.ai/api/coding/paas/v4) - Local gateways proxying cloud models - e.g., Ollama or custom gateways that route to cloud providers
Note on LM Studio: LM Studio is particularly well-tested with this SDK and provides reliable OpenAI-compatible API support. If you're looking for a user-friendly local model server with excellent compatibility, LM Studio is highly recommended.
ApiProtocol::Anthropic — POST {base_url}/messages, x-api-key + anthropic-version
- Anthropic
- Moonshot Kimi for Coding -
https://api.kimi.com/coding/v1 - MiniMax -
https://api.minimax.io/anthropic/v1
Extended thinking arrives on the existing reasoning channel (StreamEvent::Reasoning, opt in
with .include_reasoning(true)), and tool calls as ordinary ContentBlock::ToolUse blocks.
Third-party Anthropic-compatible endpoints are not uniform, and the SDK invents nothing on
their behalf: api.kimi.com/coding/v1 requires max_tokens and answers a bare
invalid_request_error 400 without it, and accepts no temperature but 1. Set both
explicitly when an endpoint asks for them.
Not Supported (Use Official SDKs)
- Cloud provider SDKs - Bedrock, Vertex, Azure, etc. (proxied via local gateway is fine)
Quick Start
Installation
[]
= "0.10.0"
= { = "1", = ["full"] }
= "0.3"
= "1.0"
For development:
Upgrading from 0.9.x
v0.10.0 has one breaking change, and the compiler does not catch it: the types are unchanged, only how many events carry the same text.
Text and reasoning arrive fragment by fragment. A response that used to arrive as one
ContentBlock::Text at the end of the stream now arrives as one block per delta, in order,
while the stream is still open — which is what the SDK has always claimed streaming meant.
Code that concatenates what it receives needs no change. Code that read the first text block
as the whole answer now reads a prefix of it:
// Before: happened to work, because there was only ever one text block.
if let Some = stream.next.await.transpose?
// After: join the fragments, printing them as they land.
let mut answer = Stringnew;
while let Some = stream.next.await
If you already collect blocks and want the old shape back, coalesce_text_blocks is the join
the SDK applies internally, now exported:
use coalesce_text_blocks;
let whole = coalesce_text_blocks; // adjacent text joined, tool calls untouched
Conversation history is unaffected — the fragments are joined before the assistant turn is written, so the next request replays exactly what 0.9.x replayed. Tool calls are unaffected: their arguments are only valid JSON once the last fragment lands, so they still emit whole at the end of the stream, in ascending index order.
Upgrading from 0.8.x
v0.9.0 has one breaking change, and the compiler catches it.
AgentOptions::temperature() returns Option<f32>, and unset now means unset. It used
to default to 0.7 and was always sent. A growing number of models reject the parameter
outright — Anthropic's range stops at 1.0, and Moonshot's k3 answers
only temperature 1 is allowed for this model with a 400 — so a client-invented default
turns a working request into a hard error. None omits the field and the server decides,
exactly as max_tokens has behaved since 0.7.0. The builder is unchanged:
.temperature(0.2) still sets one. Callers that relied on the old default now pass it
explicitly.
Reaching an Anthropic messages endpoint is additive:
let options = builder
.model
.base_url
.api_key
.protocol
.max_tokens // this endpoint requires it
.build?;
Upgrading from 0.7.x
v0.8.0 had one breaking change, and the compiler caught it.
query() yields StreamEvent instead of ContentBlock. The stream needed room for
something that is not content: the reason generation stopped. Every stream now ends with
exactly one StreamEvent::Finish.
// Before (0.7.x)
while let Some = stream.next.await
// After (0.8.0) — smallest possible edit
while let Some = stream.next.await
If you parse structured output, the reason you upgraded is the Finish event — match it
rather than discarding it:
use ;
let mut answer = Stringnew;
while let Some = stream.next.await
ContentStream was renamed EventStream. ToolCallAggregator was renamed StreamAccumulator
— if you imported it directly, update the import; the API is otherwise unchanged. ContentBlock
is unchanged — no new variant and no wire-shape change, so exhaustive matches over it and its
serde representation still work.
Client is unaffected. client.receive() still yields ContentBlock; the finish reason
is recorded on the client instead:
client.send.await?;
while let Some = client.receive.await?
if client.finish_reason.is_some_and
New in 0.8.0, with no action required: reasoning-model side channels
(reasoning_content on DeepSeek, reasoning on OpenRouter) are now explicitly parsed and
routed away from assistant text rather than dropped as unknown fields, so deliberation prose
can never be spliced into a response you parse as JSON. Opt into seeing it with
.include_reasoning(true), which surfaces it as StreamEvent::Reasoning and
client.reasoning().
Upgrading from 0.6.x
v0.7.0 has two breaking changes. Most projects need no edits at all; the compiler catches the first, and the second is a behaviour change with no compile error.
1. Error::Api carries the HTTP status. It changed from a tuple variant to a struct
variant, so any pattern match must be updated:
// Before (0.6.x)
if let Api = &err
// After (0.7.0)
if let Api = &err
Constructing errors is unchanged — Error::api(msg) still works and yields status: None.
Use the new Error::api_status(status, msg) when you have a status code, because
is_retryable_error classifies on the status and treats a statusless API error as permanent.
2. max_tokens is no longer defaulted to 4096. Leaving .max_tokens() unset now omits
the field from the request so the server applies its own limit. This is a silent behaviour
change: if you relied on the implicit cap, set it explicitly.
let options = builder
.model
.base_url
.max_tokens // add this to keep the old behaviour
.build?;
Leaving it unset is recommended for long-context and reasoning models, which a 4096-token client-side cap truncates mid-response.
Also fixed in 0.7.0, with no action required: streamed content is no longer discarded when a
server ends its stream without ever sending finish_reason (llama.cpp, vLLM, and several
local gateways do this), and 429 is now correctly treated as retryable.
Simple Query (LM Studio)
use ;
use StreamExt;
async
Multi-Turn Conversation (Ollama)
use ;
async
Function Calling with Tools
Define tools using the builder pattern for clean, type-safe function calling:
use ;
use json;
async
Advanced: Manual Tool Execution
For custom execution logic or result interception:
// Disable auto-execution
let options = builder
.system_prompt
.model
.base_url
.tool
.auto_execute_tools // Manual mode
.build?;
let mut client = new?;
client.send.await?;
while let Some = client.receive.await?
Key Features:
- Automatic execution - Tools run automatically with safety limits
- Type-safe schemas - Automatic JSON schema generation from parameters
- Both protocols - The same tool definitions serve OpenAI function calling and Anthropic tool use
- Clean builder API - Fluent API for tool definition
- Hook integration - PreToolUse/PostToolUse hooks work in both modes
See examples/calculator_tools.rs and examples/auto_execution_demo.rs for complete examples.
Multimodal Vision Support
Send images alongside text to vision-capable models like llava, qwen-vl, or minicpm-v. The SDK formats images for whichever protocol the endpoint speaks.
Simple Image + Text
use ;
// From URL
let msg = user_with_image?;
client.send_message.await?;
// From local file path (NEW!)
let msg = new;
client.send_message.await?;
// From base64 data
let msg = user_with_base64_image?;
client.send_message.await?;
// Control detail level for token costs
let msg = user_with_image_detail?;
client.send_message.await?;
Supported Image Sources:
ImageBlock::from_url(url)- HTTPS/HTTP URLs or data URIs (e.g.,data:image/png;base64,...)ImageBlock::from_file_path(path)- Local filesystem (automatically encodes as base64)- Supports:
.jpg,.jpeg,.png,.gif,.webp,.bmp,.svg - MIME type inferred from file extension
- File is read and encoded automatically
- Supports:
ImageBlock::from_base64(data, mime)- Manual base64 with explicit MIME type
Token Cost Management
Control image processing costs using ImageDetail levels:
ImageDetail::Low- Lower resolution (typically more cost-effective)ImageDetail::High- Higher resolution (typically more detailed analysis)ImageDetail::Auto- Model decides (balanced default)
⚠️ Token Costs Vary by Model:
OpenAI's Vision API uses ~85 tokens (Low) and variable tokens based on dimensions (High), but local models may have completely different token costs—or no token costs for images at all. The ImageDetail setting may even be ignored by some models.
Always benchmark your specific model instead of relying on OpenAI's published values for capacity planning.
Complex Multi-Image Messages
use ;
let msg = new;
Key Features:
send_message()API - Send pre-built messages with images viaclient.send_message(msg).await?- Automatic serialization - Images converted to OpenAI Vision or Anthropic image blocks (
ImageDetailhas no Anthropic equivalent and is dropped there) - Multiple sources - URLs, local file paths, or base64 data
- Backward compatible - Text-only messages still work with
send("text") - Data URIs supported - Base64-encoded images transmitted seamlessly
- Token cost control - Choose detail level based on use case
See examples/vision_example.rs for comprehensive working examples including local file paths.
Context Management
Local models have fixed context windows (typically 8k-32k tokens). The SDK provides utilities for manual history management—no silent mutations, you stay in control.
Token Estimation & Truncation
use ;
let mut client = new?;
// Long conversation...
for i in 0..50
// Check token usage
let tokens = estimate_tokens;
println!;
// Check if approaching limit (margin = 0.8 means warn at 80% of limit)
if is_approaching_limit
// Manually truncate when needed
if tokens > 28000
Recommended Patterns
1. Stateless Agents (Best for single-task agents):
// Process each task independently - no history accumulation
for task in tasks
2. Manual Truncation (At natural breakpoints):
use truncate_messages;
let mut client = new?;
for task in tasks
3. External Memory (RAG-lite for research agents):
// Store important facts in database, keep conversation context small
let mut database = new;
let mut client = new?;
client.send.await?;
// Save response to database
database.insert;
// Clear history, query database when needed
let truncated = truncate_messages;
*client.history_mut = truncated;
Why Manual?
The SDK intentionally does not auto-compact history because:
- Domain-specific needs: Copy editors need different strategies than research agents
- Token accuracy varies: Each model family has different tokenizers
- Risk of breaking context: Silently removing messages could break tool chains
- Natural limits exist: Compaction doesn't bypass model context windows
See examples/context_management.rs for complete patterns and usage.
Lifecycle Hooks
Monitor and control agent behavior at key execution points with zero-cost Rust hooks.
Quick Example
use ;
// Security gate - block dangerous operations
let hooks = new
.add_pre_tool_use
.add_post_tool_use;
// Register hooks in AgentOptions
let options = builder
.system_prompt
.model
.base_url
.hooks
.build?;
let mut client = new?;
Hook Types
PreToolUse - Fires before tool execution
- Block operations: Return
Some(HookDecision::block(reason)) - Modify inputs: Return
Some(HookDecision::modify_input(json!({}), reason)) - Allow: Return
Some(HookDecision::continue_())
PostToolUse - Fires after the tool completes and before the final result is committed
- Observational (tool already executed)
- Use for audit logging, metrics, result validation
- Return
NoneorSome(HookDecision::...)
Every hook event exposes history as Vec<serde_json::Value>, with one structured
JSON object per internal Message (role plus typed content blocks). Prompt and
pre-tool snapshots contain history up to that lifecycle point; post-tool snapshots
also include the completed tool call and its unmodified result.
UserPromptSubmit - Fires before sending prompt to API
- Block prompts: Return
Some(HookDecision::block(reason)) - Modify prompts: Return
Some(HookDecision::modify_prompt(text, reason)) - Allow: Return
Some(HookDecision::continue_())
Common Patterns
Pattern 1: Redirect to Sandbox
hooks.add_pre_tool_use
Pattern 2: Compliance Audit Log
let audit_log = new;
let log_clone = audit_log.clone;
// Note: add_post_tool_use consumes and returns Hooks (builder pattern) — always rebind
let hooks = hooks.add_post_tool_use;
Hook Execution Flow
- Hooks run sequentially in the order registered
- First non-None decision wins (short-circuit behavior)
- Hooks run inline on async runtime (spawn tasks for heavy work)
- Works with both Client and query() function
See examples/hooks_example.rs and examples/multi_tool_agent.rs for comprehensive patterns.
Interrupt Capability
Cancel long-running operations cleanly without corrupting client state. Perfect for timeouts, user cancellations, or conditional interruptions.
Interrupt Quick Example
use ;
use ;
async
Common Interrupt Patterns
1. Conditional Interruption
let mut full_text = Stringnew;
while let Some = client.receive.await?
2. Concurrent Cancellation
use Ordering;
let interrupt_handle = client.interrupt_handle;
let cancel_task = spawn;
while let Some = client.receive.await?
cancel_task.await?;
How It Works
When you call client.interrupt():
- Atomic signal - A thread-safe flag tells the receive loop to stop
- Stream cleanup -
receive()observes the flag, drops the active stream, and returnsOk(None) - Clean history - Partial manual responses are discarded instead of committing incomplete assistant messages
- Idempotent - Safe to call multiple times
- Cross-task safe -
interrupt_handle()lets another task cancel without locking theClient
See examples/interrupt_demo.rs for comprehensive patterns.
Practical Examples
Example agents demonstrating real-world usage:
Git Commit Agent
Analyzes your staged git changes and writes professional commit messages following conventional commit format.
# Stage your changes
# Run the agent
# Output:
# Found staged changes in 3 file(s)
# Analyzing changes and generating commit message...
#
# Suggested commit message:
# feat(auth): Add OAuth2 integration with refresh tokens
#
# - Implement token refresh mechanism
# - Add secure cookie storage for tokens
# - Update login flow to support OAuth2 providers
Features:
- Analyzes diff to determine commit type (feat/fix/docs/etc)
- Writes clear, descriptive commit messages
- Follows conventional commit standards
Log Analyzer Agent
examples/log_analyzer_agent.rs
Intelligently analyzes application logs to identify patterns, errors, and provide actionable insights.
# Analyze a log file
Features:
- Automatic error pattern detection
- Time-based analysis (peak error times)
- Root cause suggestions
- Supports multiple log formats
Why These Examples?
These agents demonstrate:
- Practical Value: Solve real problems developers face daily
- Tool Integration: Show how to integrate with system commands (git, file I/O)
- Structured Output: Parse and format LLM responses for actionable results
- Privacy-First: Keep your code and logs local while getting AI assistance
Why Not Just Use OpenAI Client?
Without open-agent-sdk (raw reqwest):
use Client;
let client = new;
let response = client
.post
.json
.send
.await?;
// Complex parsing of SSE chunks
// Extract delta content
// Handle tool calls manually
// Track conversation state yourself
With open-agent-sdk:
use ;
let options = builder
.system_prompt
.model
.base_url
.build?;
let mut stream = query.await?;
// Clean message types (TextBlock, ToolUseBlock)
// Automatic streaming and tool call handling
// Terminating StreamEvent::Finish tells you why generation stopped
Value: Familiar patterns + Less boilerplate + Rust performance
Why Rust?
Performance: Zero-cost abstractions mean no runtime overhead. Streaming responses with Tokio delivers throughput comparable to C/C++ while maintaining memory safety.
Safety: Compile-time guarantees prevent data races, null pointer dereferences, and buffer overflows. Your agents won't crash from memory issues.
Concurrency: Fearless concurrency with async/await lets you run multiple agents or handle hundreds of concurrent requests without fear of race conditions.
Production Ready: Strong type system catches bugs at compile time. Comprehensive error handling with Result types. No surprises in production.
Small Binaries: Standalone executables under 10MB. Deploy anywhere without runtime dependencies.
API Reference
AgentOptions
builder
.system_prompt // System prompt
.model // Model name (required)
.base_url // Endpoint URL; the path comes from .protocol() (required)
.tool // Add a single tool for function calling
.tools // Add multiple tools at once
.hooks // Lifecycle hooks for monitoring/control
.auto_execute_tools // Enable automatic tool execution
.max_tool_iterations // Max tool calls per query in auto mode
.max_tokens // Tokens to generate (unset: omitted, server decides); getter returns Option<u32>
.max_turns // Max conversation turns (default: 1)
.temperature // Sampling temperature (unset: omitted, server decides)
.protocol // Wire protocol (default: ApiProtocol::OpenAiChat)
.timeout // Request timeout in seconds (default: 60)
.api_key // API key (default: "not-needed")
.include_reasoning // Surface reasoning as StreamEvent::Reasoning (default: false)
.build?
query()
Simple single-turn query function.
pub async pub type EventStream = ;
Returns a stream yielding StreamEvent items. Use futures::StreamExt to iterate.
StreamEvent and FinishReason
Both are #[non_exhaustive]; match with a _ arm. StreamEvent provides as_block(),
into_block(), as_text(), as_reasoning(), and finish_reason(). FinishReason provides
from_wire(), as_str(), is_truncated(), and Display.
Unspecified is not an error — it is the normal behaviour of llama.cpp, vLLM, and several
local gateways, which stream content and then close without setting finish_reason. It is
kept distinct from Stop because "the model finished" and "the SDK has no information" call
for different handling.
MaxToolIterations is the one variant that does not come from a server: in auto-execution
mode the SDK, not the model, ends the run when it hits max_tool_iterations. It is reported
only by client.finish_reason() and never appears in a StreamEvent::Finish.
Client
Multi-turn conversation client with tool monitoring.
let mut client = new?;
client.send.await?;
while let Some = client.receive.await?
Additional Client methods:
// Send a pre-built Message (e.g., with images)
client.send_message.await?;
// Access the AgentOptions this client was created with
let opts = client.options;
// Clear conversation history (resets to system prompt only)
client.clear_history;
// Look up a registered tool by name
if let Some = client.get_tool
// Obtain a shareable interrupt handle (Arc<AtomicBool>) for use across tasks
let handle = client.interrupt_handle;
// Why the most recent stream stopped; None until one completes, reset on the next send()
if let Some = client.finish_reason
// Reasoning captured from the most recent turn (requires .include_reasoning(true));
// accumulates across every round of an auto-execution tool loop
if let Some = client.reasoning
MessageRole
Who sent a message. Used when constructing Message values directly.
use MessageRole;
System // Establishes context and instructions
User // Input from the human or calling application
Assistant // Response from the AI model
Tool // Results from tool/function execution
Message
Pre-built message values (for client.send_message()). Convenience constructors:
use ;
// Build a message manually (any role)
new // Convenience constructors — all return Self (infallible):
user // Vision constructors — return Result<Self>:
user_with_image
Message Types
ContentBlock::Text(TextBlock)- Text content from modelContentBlock::Image(ImageBlock)- Image content (for vision models)ContentBlock::ToolUse(ToolUseBlock)- Tool calls from modelContentBlock::ToolResult(ToolResultBlock)- Tool execution results
Tool System
use tool;
let my_tool = tool
.param
.build;
For full JSON Schema control, use .schema() instead of chaining .param() calls:
let my_tool = tool
.schema
.build;
ToolBuilder
The tool() function returns a ToolBuilder for fluent construction of tool definitions:
use ;
let t: Tool = tool
.param
.build;
Provider Configuration
Helper types and functions for mapping provider names to their default endpoints:
use ;
// get_base_url(provider: Option<Provider>, fallback: Option<&str>) -> String
let url = get_base_url; // http://localhost:1234/v1
let url_with_fallback = get_base_url;
// get_model(fallback: Option<&str>, prefer_env: bool) -> Option<String>
let model = get_model; // use provided model
let env_model = get_model; // prefer OPEN_AGENT_MODEL env var
Wire Types
Low-level serialization types matching each protocol's request and streaming format, exported for callers that need to name what goes over the wire:
// OpenAI chat completions
use ;
// Anthropic messages
use ;
AnthropicRequest::from_openai takes an OpenAIRequest, which is why the OpenAI request half is exported alongside the Anthropic types. anthropic_finish_reason maps Anthropic stop reasons onto FinishReason, and query()/Client apply it for you.
Error and Result Types
use ;
Error is the SDK's unified error type; Result<T> is an alias for std::result::Result<T, Error>.
| Variant | Meaning |
|---|---|
Http(reqwest::Error) |
Transport failure — connection refused, DNS, TLS, network timeout |
Json(serde_json::Error) |
Serialization or deserialization failure |
Config(String) |
Invalid configuration caught by AgentOptions::build() |
Api { status: Option<u16>, message: String } |
Error response from the model server |
Stream(String) |
SSE parsing or stream processing failure |
Tool(String) |
Tool execution or registration failure |
InvalidInput(String) |
User-provided input failed validation |
Timeout |
Request exceeded the configured timeout |
Other(String) |
Anything else |
Api carries the HTTP status as structured data so retry logic never has to parse the
message text:
use Error;
// From an HTTP error response — this is what the client constructs internally
let err = api_status;
assert_eq!;
assert_eq!;
// Without a status
let err = api;
assert_eq!;
status_code() returns None for every non-Api variant, so it is safe to call on any error.
Newtype Wrappers
Strong-typed wrappers used internally by AgentOptions and exported for external use:
use ;
Retry Module
Exponential-backoff retry utilities, exported as a public module:
use ;
// Configure retry behavior (builder pattern)
let config = default // 3 attempts, exponential backoff
.max_attempts
.initial_delay_ms
.max_delay_ms
.backoff_multiplier;
// Retry any async operation
let result = retry_with_backoff.await?;
// Retry only transient failures; anything else fails on the first attempt
let result = retry_with_backoff_conditional.await?;
// Check if an SDK error is worth retrying
let retryable = is_retryable_error;
is_retryable_error treats network errors, timeouts, and stream errors as transient. API
errors are classified on Error::status_code(), which reads the status Error::Api carries as
structured data; the retryable set is 408, 429, 500, 502, 503, 504, 529. Everything else —
including API errors raised without a status — is non-retryable, so a 400 Bad Request fails
immediately rather than burning the full attempt budget.
A mid-stream Anthropic error event arrives on a response that already returned 200, so it
carries no status of its own. The SDK maps the two transient kinds onto the statuses they
would have had earlier — overloaded_error to 529 and rate_limit_error to 429, with
api_error to 500 — which is what lets retry_with_backoff see them as retryable.
use Error;
let err = api_status; // status: Some(429)
assert_eq!;
let err = api; // status: None
assert_eq!;
Prelude Import
For convenience, import the most commonly used types at once:
use *;
Hook Name Constants
String constants for hook event types are exported for use in custom registries:
use ;
Context Utilities
use ;
// Estimate tokens in message history (character-based approximation)
let tokens = estimate_tokens;
// Check if approaching a context limit (margin=0.8 means 80% of limit)
let near_limit = is_approaching_limit;
// Truncate history, keeping the last N messages (preserve_system=true keeps system prompt)
let truncated = truncate_messages;
Recommended Models
Local models (LM Studio, Ollama, llama.cpp):
- GPT-OSS-120B - Best in class for speed and quality
- Qwen 3 30B - Excellent instruction following, good for most tasks
- GPT-OSS-20B - Solid all-around performance
- Mistral 7B - Fast and efficient for simple agents
Cloud-proxied via local gateway:
- kimi-k2:1t-cloud - Tested and working via Ollama gateway
- deepseek-v3.1:671b-cloud - High-quality reasoning model
- qwen3-coder:480b-cloud - Code-focused models
Project Structure
open-agent-sdk-rust/
├── src/
│ ├── client.rs # Public client module docs/imports and fragment orchestration
│ ├── client/ # Query, send, send_message, setup, streaming, receive, history, state, and tests
│ ├── config.rs # Provider helpers (Provider, get_base_url, get_model)
│ ├── context.rs # Token estimation and truncation
│ ├── error.rs # Error types
│ ├── hooks.rs # Public lifecycle-hook module orchestration
│ ├── hooks/ # Hook events, decisions, handlers, registry, and tests
│ ├── lib.rs # Public exports and prelude module
│ ├── retry.rs # Retry logic with exponential backoff
│ ├── retry/ # Retry unit tests
│ ├── tools.rs # Public tool module orchestration
│ ├── tools/ # Tool, schema, builder, handler, factory, and tests
│ ├── types.rs # Public core-type module orchestration
│ ├── types/ # Options, messages, images, OpenAI + Anthropic wire types, ApiProtocol
│ ├── utils.rs # SSE parsing, stream accumulation, and the shared stream driver
│ └── utils/ # accumulator.rs + anthropic_accumulator.rs (wire decoding),
│ # buffers.rs (the shared drain), coalesce.rs (text joining for
│ # history), driver.rs, sse.rs
├── examples/
│ ├── simple_query.rs # Basic streaming query
│ ├── anthropic_query.rs # Anthropic messages endpoint via ApiProtocol
│ ├── calculator_tools.rs # Function calling (manual mode)
│ ├── auto_execution_demo.rs # Automatic tool execution
│ ├── multi_tool_agent.rs # Production agent with 5 tools and hooks
│ ├── hooks_example.rs # Lifecycle hooks patterns
│ ├── context_management.rs # Context management patterns
│ ├── interrupt_demo.rs # Interrupt capability patterns
│ ├── git_commit_agent.rs # Production: Git commit generator
│ ├── log_analyzer_agent.rs # Production: Log analyzer
│ ├── advanced_patterns.rs # Retry logic and concurrent requests
│ ├── vision_example.rs # Multimodal: URLs, local files, base64
│ ├── vision_api_demo.rs # Vision API walkthrough
│ └── test_tool_serialization.rs # Tool call serialization verification
├── benches/
│ └── performance.rs # Criterion benchmarks (token estimation, history ops)
├── tests/
│ ├── integration_tests.rs # Core integration tests
│ ├── regression_incremental_streaming_test.rs # Per-fragment delivery; joined history
│ ├── advanced_integration_test.rs
│ ├── anthropic_protocol_test.rs # Path, headers, body, and event vocabulary per protocol
│ ├── auto_execution_test.rs
│ ├── backward_compatibility_test.rs
│ ├── ci_workflow_policy_test.rs # GitHub CI runner, coverage, mutation, and security guards
│ ├── client_image_serialization_test.rs
│ ├── config_env_test.rs # get_model env resolution (own process: mutates env)
│ ├── context_estimation_test.rs # Token arithmetic and truncation boundaries
│ ├── debug_logging_test.rs
│ ├── defensive_validation_test.rs
│ ├── edge_cases_test.rs
│ ├── hooks_history_snapshot_test.rs
│ ├── hooks_integration_test.rs
│ ├── image_serialization_test.rs
│ ├── package_manifest_test.rs # Package exclusion coverage
│ ├── regression_finish_reason_test.rs
│ ├── regression_max_tokens_test.rs
│ ├── regression_reasoning_channel_test.rs
│ ├── regression_retry_classification_test.rs
│ ├── regression_stream_flush_test.rs
│ ├── security_bypass_test.rs
│ ├── send_message_test.rs # Manual-mode history regression (v0.6.2)
│ ├── source_file_size_test.rs # Repository Rust hard-limit guard
│ ├── tool_call_content_test.rs # Tool call serialization tests
│ └── common/mod.rs # Shared wiremock SSE harness and block helpers
├── scripts/
│ ├── mutants-common.sh # The one definition of the results directory
│ ├── mutants-run.sh # Owns the verdict (missed.txt); called by the hook and CI
│ ├── mutants-remote.sh # rsync + ssh to a build host, falls back loudly
│ └── mutants-staged.sh # Staged-diff scope, through mutants-remote.sh
├── .githooks/
│ └── pre-commit # fmt, clippy, tests, and a --in-diff cargo-mutants sweep
├── .github/
│ ├── dependabot.yml # Grouped weekly Cargo dependency updates
│ └── workflows/
│ ├── ci.yml # GitHub CI (fmt, clippy, MSRV, Linux/macOS stable + beta matrix, security audit, mutation sweep, docs, LLVM Tarpaulin coverage, benchmarks)
│ └── scheduled-audit.yml # Scheduled dependency audit
├── .markdownlint.json # Markdown lint rules (disable MD013, allow duplicate sibling headings)
├── Cargo.toml
├── Cargo.lock
├── CHANGELOG.md
└── README.md
Examples
Production Agents
git_commit_agent.rs– Analyzes git diffs and writes professional commit messageslog_analyzer_agent.rs– Parses logs, finds patterns, suggests fixesmulti_tool_agent.rs– Complete production setup with 5 tools, hooks, and auto-execution
Core SDK Usage
simple_query.rs– Minimal streaming query (simplest quickstart)anthropic_query.rs– Same query against an Anthropic messages endpoint viaApiProtocolcalculator_tools.rs– Manual tool execution patternauto_execution_demo.rs– Automatic tool execution patternvision_example.rs– Multimodal image support (URLs, local files, base64)vision_api_demo.rs– Vision API walkthrough with token cost noteshooks_example.rs– Lifecycle hooks patterns (security gates, audit logging)context_management.rs– Manual history management patternsinterrupt_demo.rs– Interrupt capability patterns (timeout, conditional, concurrent)advanced_patterns.rs– Retry logic and concurrent request handlingtest_tool_serialization.rs– Verifies tool call serialization (seeexamples/test_tool_serialization.rs)
Documentation
- API Documentation
- Python SDK - Reference implementation
- Examples - Comprehensive usage examples
Testing
# Run all tests
# Run with output
# Run specific test
# Mutation sweep (must report zero survivors)
Test Coverage:
- 248 unit tests (lib)
- 157 active integration tests across 26 test files
- 164 active doctests
Total: 569 active unit, integration, and documentation tests
Mutation testing is part of the gate, not an optional extra: a green suite proves the tests ran, not that they would notice if the code were wrong. CI runs the full sweep on every push. To run the same check before each commit:
The hook runs cargo fmt --check, cargo clippy --all-targets -- -D warnings, cargo test,
and a cargo mutants --in-diff sweep scoped to the staged Rust changes. Both the hook and CI
reach their verdict through scripts/mutants-run.sh, which reads missed.txt rather than the
exit code — cargo-mutants reports a timeout in preference to a survivor, so a run with one of
each would otherwise look like a timeout. The current sweep is 231 mutants, 0 missed.
Requirements
- Rust 1.85+
- Tokio 1.50+ (async runtime)
- serde, serde_json (serialization)
- reqwest (HTTP client)
- futures, tokio-stream (async streams)
- eventsource-stream (SSE parsing)
- async-trait (async trait support)
- thiserror 2.0 + anyhow 1.0.103+ (error handling)
- log 0.4.29+ (logging)
- base64 0.23 (multimodal image encoding)
- wiremock 0.6 (dev-only: HTTP mocking for streaming and wire-format tests)
- cargo-mutants 27.1.0 (dev-only: mutation testing gate)
- rand (retry jitter)
License
MIT License - see LICENSE for details.
Acknowledgments
- Rust port of open-agent-sdk Python library
- API design inspired by claude-agent-sdk
- Built for local/open-source LLM enthusiasts
Repository Hosting
GitHub is the canonical repository and CI/release host. Any family Gitea copy is a passive Git mirror and does not run a separate required Actions pipeline.
Status: v0.10.0 - Incremental text and reasoning delivery, plus from v0.9.0 the Anthropic messages protocol alongside OpenAI chat completions selected per endpoint with ApiProtocol, extended thinking on the existing reasoning channel, omittable temperature, plus from v0.8.0 finish reasons surfaced on every stream, explicit reasoning-channel separation, end-of-stream flushing for servers that omit finish_reason, structured Error::Api with status-based retry classification, no implicit max_tokens cap, a mandatory mutation-testing gate, plus transport-boundary-safe SSE streaming, complete structured hook history, source-size architecture guards, Rust 1.85-compatible dependencies, GitHub-hosted Linux/macOS CI, non-locking cancellation, and multimodal image support
Star this repo if you're building AI agents with local models in Rust!