Expand description
§SerdesAI - Type-Safe AI Agent Framework for Rust
SerdesAI is a comprehensive Rust library for building AI agents that interact with large language models (LLMs). It is a complete port of pydantic-ai to Rust, providing type-safe, ergonomic APIs for creating intelligent agents.
§Quick Start
ⓘ
use serdes_ai::prelude::*;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let agent = Agent::builder()
.model("openai:gpt-4o")
.system_prompt("You are a helpful assistant.")
.build()?;
let result = agent.run("What is the capital of France?", ()).await?;
println!("{}", result.output());
Ok(())
}§Key Features
- Type-safe agents with generic dependencies and output types
- Multiple LLM providers (OpenAI, Anthropic, Google, Groq, Mistral, Ollama, Bedrock)
- Tool/function calling with automatic JSON schema generation
- Streaming responses with real-time text updates
- Structured outputs with JSON Schema validation
- MCP protocol support for Model Context Protocol servers
- Embeddings for semantic search and RAG applications
- Graph-based workflows for complex multi-step tasks
- Evaluation framework for testing and benchmarking agents
- Retry strategies with exponential backoff
- OpenTelemetry integration for observability
§Feature Flags
| Feature | Description | Default |
|---|---|---|
openai | OpenAI GPT models | ✅ |
anthropic | Anthropic Claude models | ✅ |
gemini | Google Gemini models | ❌ |
groq | Groq fast inference | ❌ |
mistral | Mistral AI models | ❌ |
ollama | Local Ollama models | ❌ |
bedrock | AWS Bedrock | ❌ |
mcp | MCP protocol support | ❌ |
embeddings | Embedding models | ❌ |
graph | Graph execution engine | ❌ |
evals | Evaluation framework | ❌ |
macros | Proc macros | ✅ |
otel | OpenTelemetry | ❌ |
full | All features | ❌ |
§Architecture
SerdesAI is organized as a workspace of focused crates:
serdes_ai_core- Core types, messages, and errorsserdes_ai_agent- Agent implementation and builderserdes_ai_models- Model trait and implementationsserdes_ai_tools- Tool system and schema generationserdes_ai_toolsets- Toolset abstractionsserdes_ai_output- Output schema validationserdes_ai_streaming- Streaming supportserdes_ai_retries- Retry strategiesserdes_ai_mcp- MCP protocol (optional)serdes_ai_embeddings- Embeddings (optional)serdes_ai_graph- Graph execution (optional)serdes_ai_evals- Evaluation framework (optional)serdes_ai_macros- Procedural macros
§Examples
§Simple Chat
ⓘ
use serdes_ai::prelude::*;
let agent = Agent::builder()
.model("openai:gpt-4o")
.system_prompt("You are helpful.")
.build()?;
let result = agent.run("Hello!", ()).await?;§With Tools
ⓘ
use serdes_ai::prelude::*;
#[tool(description = "Get weather for a city")]
async fn get_weather(ctx: &RunContext<()>, city: String) -> ToolResult<String> {
Ok(format!("Weather in {}: 22°C, sunny", city))
}
let agent = Agent::builder()
.model("openai:gpt-4o")
.tool(get_weather)
.build()?;§Structured Output
ⓘ
use serdes_ai::prelude::*;
use serde::Deserialize;
#[derive(Deserialize, OutputSchema)]
struct Person {
name: String,
age: u32,
}
let agent = Agent::builder()
.model("openai:gpt-4o")
.output_type::<Person>()
.build()?;
let result: Person = agent.run("Extract: John is 30 years old", ()).await?.into_output();§Streaming
ⓘ
use serdes_ai::prelude::*;
use futures::StreamExt;
let mut stream = agent.run_stream("Tell me a story", ()).await?;
while let Some(event) = stream.next().await {
if let AgentStreamEvent::Text { delta } = event? {
print!("{}", delta);
}
}Re-exports§
pub use direct::model_request;pub use direct::model_request_stream;pub use direct::model_request_stream_sync;pub use direct::model_request_sync;pub use direct::DirectError;pub use direct::ModelSpec;pub use direct::StreamedResponseSync;pub use serdes_ai_core as core;pub use serdes_ai_agent as agent;pub use serdes_ai_models as models;pub use serdes_ai_providers as providers;pub use serdes_ai_tools as tools;pub use serdes_ai_toolsets as toolsets;pub use serdes_ai_output as output;pub use serdes_ai_streaming as streaming;pub use serdes_ai_retries as retries;pub use serdes_ai_mcp as mcp;mcppub use serdes_ai_embeddings as embeddings;embeddingspub use serdes_ai_graph as graph;graphpub use serdes_ai_evals as evals;evals
Modules§
- direct
- Direct model request functions for imperative API access.
- prelude
- Convenient prelude for common imports.
Structs§
- Agent
- The main agent type.
- Agent
Builder - Builder for creating agents.
- Agent
Run - Active agent run that can be iterated.
- Agent
RunResult - Result of an agent run.
- Agent
Stream - Streaming agent execution.
- Anthropic
Model anthropic - Anthropic Claude model.
- Approval
Required Toolset - Requires approval for tool calls.
- Bedrock
Model bedrock - AWS Bedrock model client.
- Binary
Content - Binary content container for file data.
- Builtin
Tool Call Part - A builtin tool call from a model (web search, code execution, etc.).
- Builtin
Tool Return Part - Return from a builtin tool with structured content.
- Case
evals - A single evaluation test case.
- Code
Execution Result - Result from code execution.
- Combined
Toolset - Combines multiple toolsets into one.
- Contains
Scorer evals - Evaluator that checks if output contains a substring.
- Conversation
Id - Type-safe wrapper for a conversation ID.
- Dataset
evals - A collection of test cases.
- Dynamic
Toolset - Toolset that can have tools added/removed at runtime.
- Edge
graph - An edge between two nodes with an optional condition.
- End
graph - End marker with result value.
- Eval
Case evals - Legacy eval case for backward compatibility.
- Eval
Runner evals - Evaluation runner.
- Eval
Suite evals - A collection of evaluation test cases.
- Evaluation
Report evals - Full evaluation report.
- Exact
Match Scorer evals - Evaluator that checks for exact string match.
- Exponential
Backoff - Exponential backoff with optional jitter.
- Extended
Model Config - Extended configuration options for model building.
- External
Toolset - Toolset for externally-executed tools.
- File
Part - A file response from a model.
- File
Search Result - A single file search result.
- File
Search Results - File search results from a builtin file search tool.
- Filtered
Toolset - Filters tools from a toolset based on a predicate.
- Fixed
Delay - Fixed delay between retries.
- Function
Toolset - A toolset backed by function-based tools.
- Gemini
Model gemini - Google AI / Vertex AI model.
- Graph
graph - A graph for multi-agent workflows.
- Graph
Executor graph - Graph executor with optional persistence and instrumentation.
- Graph
RunContext graph - Context passed to nodes during execution.
- Graph
RunResult graph - Result of a graph run.
- Groq
Model groq - Groq model client.
- Linear
Backoff - Linear backoff.
- McpClient
mcp - MCP client for connecting to servers.
- McpToolset
mcp - Toolset that wraps an MCP server’s tools.
- Mistral
Model mistral - Mistral AI model client.
- Model
Config - Configuration for creating a model from a string spec.
- Model
Request - A complete model request containing multiple parts.
- Model
Response - A complete model response containing multiple parts.
- Model
Settings - Settings for model generation.
- Object
Json Schema - JSON Schema for an object type (tool parameters).
- Ollama
Model ollama - Ollama model client.
- OpenAI
Chat Model openai - OpenAI Chat Completions model.
- Part
Delta Event - Event containing a delta update for a part.
- Part
EndEvent - Event indicating a part has ended.
- Part
Start Event - Event indicating a new part has started.
- Prefixed
Toolset - Adds a prefix to all tool names.
- Prepared
Toolset - Prepares/modifies tool definitions at runtime.
- Renamed
Toolset - Renames specific tools in a toolset.
- Request
Usage - Token usage for a single request.
- Response
Stream - Stream that filters to complete responses.
- Retry
Config - Configuration for retry behavior.
- RunContext
- Context for an agent run.
- RunId
- Type-safe wrapper for a run ID.
- RunOptions
- Options for a run.
- RunUsage
- Accumulated usage for an entire run.
- Schema
Builder - Schema builder for manual schema construction.
- Structured
Output Schema - Schema for structured output using serde.
- System
Prompt Part - System prompt part.
- Text
Output Schema - Schema for plain text output.
- Text
Part - Text content part.
- Thinking
Part - Thinking/reasoning content part.
- Tool
Call Id - Type-safe wrapper for a tool call ID.
- Tool
Call Part - Tool call part.
- Tool
Definition - Complete tool definition sent to the model.
- Tool
Registry - Registry of tools that can be called by an agent.
- Tool
Return Part - Tool return part.
- Toolset
Info - Information about a toolset for serialization.
- Toolset
Tool - A tool that belongs to a toolset.
- Usage
Limits - Usage limits for a run.
- WebSearch
Result - A single web search result.
- WebSearch
Results - Web search results from a builtin search tool.
- Wrapper
Toolset - Wrapper that allows custom pre/post processing.
- XmlFormat
Options - Options for XML formatting.
Enums§
- Agent
Stream Event - Events emitted during streaming.
- Builtin
Tool Return Content - Content returned from builtin tools.
- EndStrategy
- Strategy for handling tool calls when output is ready.
- Evaluation
Result evals - Result of an evaluation.
- Finish
Reason - Reason why the model stopped generating.
- Graph
Error graph - Errors that can occur during graph execution.
- Model
Request Part - Individual parts of a model request.
- Model
Response Part - Individual parts of a model response.
- Model
Response Part Delta - Delta content for different part types.
- Model
Response Stream Event - Stream event for model responses.
- Node
Result graph - Result of a node execution.
- Response
Delta - Delta types for applying to partial response.
- Serdes
AiError - The main error type for serdes-ai operations.
- Step
Result - Result of a single step.
- User
Content - User message content.
- XmlFormat
Error - Error type for XML formatting operations.
Traits§
- Abstract
Toolset - Abstract toolset trait - collection of tools with shared management.
- Base
Node graph - Base trait for all graph nodes.
- Embedding
Model embeddings - Core trait for embedding models.
- Evaluator
evals - Core evaluator trait.
- Model
- Core model trait.
- Output
Schema - Trait for output schemas that can validate model responses.
- Retry
Strategy - Trait for retry strategies.
- Tool
- Core trait for all tools.
Functions§
- build_
model_ extended - Build a model with extended configuration options.
- build_
model_ with_ config - Build a model with custom configuration.
- format_
as_ xml - Format a serializable value as XML.
- format_
as_ xml_ with_ options - Format with full options control.
- version
- Returns the current version of serdes-ai.
- version_
tuple - Returns version information as a tuple (major, minor, patch).
Type Aliases§
- Boxed
Toolset - Boxed toolset for dynamic dispatch.
- Embedding
Result embeddings - Result type for embedding operations.
- Graph
Result graph - Result type for graph operations.
- Tool
Result - Result of a tool execution.
- Validation
Result - Result type for output validation.
Attribute Macros§
- agent_
macro macros - Attribute macro for agent definitions. Attribute macro for defining agents.
- tool
macros - Attribute macro for tool functions. Attribute macro for creating tools from functions.
Derive Macros§
- Output
Schema macros - Derive macro for output schemas.
Derive macro for implementing the
OutputSchematrait. - Tool
macros - Derive macro for tools.
Derive macro for implementing the
Tooltrait.