Skip to main content

Crate ai_agents

Crate ai_agents 

Source
Expand description

§AI Agents Framework

One YAML = Any Agent. A Rust framework for building AI agents from a single YAML specification. No code required for common use cases.

§Quick Start

§From YAML

use ai_agents::{Agent, AgentBuilder};

#[tokio::main]
async fn main() -> ai_agents::Result<()> {
    let agent = AgentBuilder::from_yaml_file("agent.yaml")?
        .auto_configure_llms()?
        .build()?;

    let response = agent.chat("Hello!").await?;
    println!("{}", response.content);
    Ok(())
}

§From Rust API

use ai_agents::{Agent, AgentBuilder, UnifiedLLMProvider, ProviderType};
use std::sync::Arc;

#[tokio::main]
async fn main() -> ai_agents::Result<()> {
    let llm = UnifiedLLMProvider::from_env(ProviderType::OpenAI, "gpt-4.1-nano")?;

    let agent = AgentBuilder::new()
        .system_prompt("You are a helpful assistant.")
        .llm(Arc::new(llm))
        .build()?;

    let response = agent.chat("Hello!").await?;
    println!("{}", response.content);
    Ok(())
}

§Modules

ModuleDescription
agentAgent builder, runtime, streaming, and response types
llmLLM providers and registry
memoryConversation memory with compression and token budgeting
toolsBuilt-in tools and extensible tool registry
stateHierarchical state machine with LLM-evaluated transitions
contextDynamic context injection from multiple sources
skillReusable workflows with LLM-based intent routing
hitlHuman-in-the-loop approval system
reasoningChain-of-thought, ReAct, plan-and-execute modes
disambiguationIntent ambiguity detection and clarification
persistenceSQLite, Redis, and file storage backends
processInput/output processing pipeline
recoveryError recovery with retry and fallback strategies
hooksLifecycle event hooks for logging, metrics, monitoring
specYAML agent specification types
templateTemplate loading with Jinja2 rendering and inheritance
spawnerDynamic agent spawning, registry, and inter-agent messaging

§Feature Flags

FlagDescription
sqliteSQLite storage backend
redis-storageRedis storage backend
http-contextHTTP context source for dynamic context injection
full-storageAll storage backends (sqlite + redis-storage)
fullAll optional features enabled

Re-exports§

pub use memory::create_memory;
pub use memory::create_memory_from_config;
pub use memory::create_memory_from_config_with_llm;
pub use template::TemplateLoader;
pub use persistence::create_storage;

Modules§

agent
context
disambiguation
dot_path
error
hitl
hooks
llm
mcp
MCP (Model Context Protocol) integration types.
memory
orchestration
persistence
persona
process
reasoning
recovery
skill
spawner
Dynamic agent spawning, registry, and inter-agent messaging.
spec
state
template
tool_security
tools

Structs§

AgentBuilder
AgentInfo
AgentResponse
AgentSnapshot
Snapshot of agent state for persistence
AgentSpec
AmbiguityDetectionResult
Result of ambiguity detection
AmbiguityDetector
LLM-based detector for ambiguous user inputs
ApprovalCondition
ApprovalRequest
AutoApproveHandler
BuiltinProviderConfig
ByRoleFilter
CacheConfig
Cache configuration for disambiguation results
CalculatorTool
This Tool is for development purposes only. It evaluates mathematical expressions. It is not intended for production use.
ChatMessage
ClarificationConfig
Clarification configuration - how to ask for clarity
ClarificationGenerator
LLM-based generator for clarification questions
ClarificationOption
An option for clarification
ClarificationQuestion
Generated clarification question
CompactingMemory
CompactingMemoryConfig
CompositeHooks
CompressionEvent
ConditionEvaluator
ContextConfig
Context configuration - what information helps disambiguation
ContextExtractor
Extract structured data from conversation into context via LLM.
ContextManager
ConversationContext
CriterionResult
DateTimeTool
DetectionConfig
Detection configuration - how to identify ambiguous inputs
DisambiguationConfig
Main disambiguation configuration
DisambiguationContext
Context for disambiguation evaluation
DisambiguationManager
Manager orchestrating the full disambiguation flow
EchoTool
ErrorRecoveryConfig
Top-level error recovery configuration for an agent. Controls retry, LLM failure handling, tool failure handling, and parse error handling.
EvaluationContext
EvaluationResult
FactExtractedEvent
FileStorage
FileStorageConfig
FileTool
GuardOnlyEvaluator
HITLConfig
HITLEngine
HookTimer
HttpTool
InMemoryStore
JsonTool
KeepRecentFilter
LLMConfig
Configuration for LLM provider
LLMRegistry
LLMResponse
LLMSelector
LLMSummarizer
LLMTransitionEvaluator
LlmGenerateConfig
LocalizedHandler
LoggingHooks
MathTool
MemoryBudgetEvent
MemoryBudgetState
MemoryCompressEvent
MemoryConfig
MemoryEvictEvent
MemorySnapshot
Snapshot of memory state for persistence
MemoryTokenBudget
MessageLanguageConfig
MessageResolver
NoopHooks
NoopSummarizer
ParallelToolsConfig
Plan
PlanAvailableActions
PlanReflectionConfig
PlanStep
PlanningConfig
ProcessConfig
ProcessData
ProcessProcessor
ProviderPolicyConfig
Policy configuration for a provider
ProviderSecurityConfig
ProvidersConfig
RandomTool
ReasoningConfig
ReasoningMetadata
RecoveryManager
RedisStorageConfig
ReflectionAttempt
ReflectionConfig
ReflectionMetadata
RejectAllHandler
RuntimeAgent
SessionInfo
SessionMetadata
SessionQuery
SimpleLLMGetter
SkillDefinition
SkillDisambiguationOverride
Skill-level disambiguation override
SkillExecutor
SkillLoader
SkillRouter
SkipPatternFilter
SpawnedAgentEntry
Minimal record of a spawned agent for session persistence.
SpecToolPolicyConfig
Policy configuration for a tool within a provider
SqliteStorageConfig
StateApprovalConfig
StateConfig
StateDefinition
StateDisambiguationOverride
State-level disambiguation override
StateMachine
StateMachineSnapshot
StateMatcher
StateTransitionEvent
StreamingConfig
Configuration for streaming behavior
TemplateRenderer
TemplateTool
TextTool
TimeMatcher
TokenAllocation
ToolAliases
ToolAliasesConfig
Global tool aliases configuration
ToolApprovalConfig
ToolCallRecord
ToolContext
ToolDescriptor
ToolMetadata
ToolPolicyConfig
ToolRegistry
ToolResult
ToolSecurityConfig
ToolSecurityEngine
Transition
TransitionContext
UnifiedLLMProvider
YamlProviderConfig
YamlToolConfig

Enums§

AgentError
Main error type for the framework
AmbiguityAspect
Aspects of ambiguity to detect
AmbiguityType
Type of ambiguity detected
ApprovalMessage
ApprovalResult
ApprovalTrigger
BuiltinSource
ClarificationParseResult
Result of parsing user’s clarification response
ClarificationStyle
Style of clarification questions
CompareOp
CompressResult
ContextMatcher
ContextSource
DisambiguationResult
Disambiguation processing result
EvictionReason
FilterConfig
Selects which messages are passed to the summarizer during context compression.
GuardConditions
HITLCheckResult
LLMProviderType
Provider type enum
MaxAttemptsAction
Action to take when max clarification attempts reached
MessageLanguageStrategy
OverflowStrategy
PlanAction
PlanStatus
PromptMode
ProviderHealth
ProviderType
Provider type enum
ReasoningMode
ReasoningOutput
ReflectionMode
RefreshPolicy
Role
SecurityCheckResult
SessionOrderBy
SkillRef
SkillStep
SkipCondition
Conditions when to skip disambiguation
StateAction
StateApprovalTrigger
StepFailureAction
StepStatus
StorageConfig
Storage configuration using tagged enum for type safety and extensibility
StreamChunk
Represents a chunk of streamed response from the agent
StringOrList
TimeoutAction
ToolCondition
ToolProviderError
ToolProviderType
ToolRef
TransitionGuard
TrustLevel

Traits§

Agent
AgentHooks
AgentStorage
Core storage trait for persisting agent state.
ApprovalHandler
Handler for human-in-the-loop approval requests.
ContextProvider
LLMGetter
LLMProvider
Core LLM provider trait.
Memory
Extended memory trait that preserves the original interface.
MessageFilter
Summarizer
Summarizes conversation messages for memory compression.
Tool
Core tool trait for external capabilities.
ToolProvider
TransitionEvaluator

Functions§

create_builtin_registry
create_handler
create_localized_handler
estimate_message_tokens
estimate_tokens
Language-aware token estimation for multi-language support
resolve_best_language
resolve_tool_message

Type Aliases§

Result
Result type alias for agent operations
ToolConfig
Backward compatibility alias — existing code using ToolConfig keeps working.