AutoAgents LLM Agent SDK
This example integrates AutoAgents — a Rust-native framework for building multi-agent systems — with Zart’s durable execution. The workflow takes a natural language query like “Find breweries in Portland, Oregon”, uses an LLM agent to extract the location, fetches brewery data from an API, and generates a conversational summary.
Because the task needs an LLM provider as a dependency, this example uses the manual DurableExecution trait instead of the #[zart_durable] macro. This lets us define a struct with fields and inject the provider at construction time.
Features demonstrated: Manual DurableExecution trait with dependency injection, AutoAgents BasicAgent + AgentOutput structured outputs, LLMProvider::chat summarization, #[zart_step], mixed AI + API workflows.
Data types
Section titled “Data types”#[derive(Debug, Clone, Serialize, Deserialize)]struct AgentInput { query: String,}
#[derive(Debug, Clone, Serialize, Deserialize)]struct ExtractedLocation { city: String, state: String,}
#[derive(Debug, Clone, Serialize, Deserialize)]struct BreweryInfo { name: String, brewery_type: String, city: String, state: String,}
#[derive(Debug, Clone, Serialize, Deserialize)]struct AgentOutput { query: String, location: ExtractedLocation, breweries: Vec<BreweryInfo>, summary: String, generated_at: String,}LLM schema and agent types
Section titled “LLM schema and agent types”AutoAgents uses #[derive(AgentOutput)] and #[agent(...)] to drive structured outputs. The LLM populates this type directly via BasicAgent:
#[derive(Debug, Default, Clone, Serialize, Deserialize, AgentOutput)]struct LocationExtraction { #[output(description = "City name extracted from the query")] city: String, #[output(description = "State or region name extracted from the query")] state: String,}
#[agent( name = "location_extractor", description = "You are a location extraction assistant. Always return valid JSON with city and state fields.", output = LocationExtraction,)]#[derive(Default, Clone, AgentHooks)]struct LocationExtractor {}
impl From<BasicAgentOutput> for LocationExtraction { fn from(output: BasicAgentOutput) -> Self { output.try_parse().unwrap_or_default() }}The Durable Execution struct
Section titled “The Durable Execution struct”Instead of using #[zart_durable], we define the struct manually. The LLM provider is stored as Arc<dyn LLMProvider> so it can be cloned into each step and any AutoAgents backend can be injected:
use autoagents::llm::LLMProvider;use std::sync::Arc;
struct AutoAgentsAgent { llm: Arc<dyn LLMProvider>,}Step functions use #[zart_step] to receive the LLM as a parameter:
#[zart_step("extract-location", retry = "exponential(3, 2s)")]async fn extract_location( llm: Arc<dyn LLMProvider>, query: &str,) -> Result<ExtractedLocation, StepError> { println!("[extract-location] Attempt {}", zart::context().current_attempt + 1);
let agent_handle = AgentBuilder::<_, DirectAgent>::new(BasicAgent::new(LocationExtractor {})) .llm(llm) .build() .await .map_err(|e| StepError::Failed { step: "extract-location".into(), reason: format!("failed to build agent: {e}"), })?;
let prompt = format!( r#"Extract the city and state from this query. Return valid JSON.
Query: "{query}"
Respond with only a JSON object with "city" and "state" fields."# );
let result = agent_handle .agent .run(Task::new(&prompt)) .await .map_err(|e| StepError::Failed { step: "extract-location".into(), reason: format!("LLM extraction failed: {e}"), })?;
if result.city.trim().is_empty() || result.state.trim().is_empty() { return Err(StepError::Failed { step: "extract-location".into(), reason: format!( "LLM returned incomplete location: city='{}', state='{}'", result.city, result.state ), }); }
Ok(ExtractedLocation { city: result.city, state: result.state })}
#[zart_step("find-breweries", retry = "exponential(3, 1s)")]async fn find_breweries(city: &str) -> Result<Vec<BreweryRaw>, StepError> { println!("[find-breweries] Attempt {}", zart::context().current_attempt + 1); let client = reqwest::Client::new(); client .get("https://api.openbrewerydb.org/v1/breweries") .query(&[("by_city", city)]) .send().await .map_err(|e| StepError::Failed { step: "find-breweries".into(), reason: e.to_string() })? .json::<Vec<BreweryRaw>>().await .map_err(|e| StepError::Failed { step: "find-breweries".into(), reason: format!("failed to parse response: {e}"), })}
#[zart_step("transform-results")]async fn transform_results( raw: Vec<BreweryRaw>, city: &str, state: &str,) -> Result<Vec<BreweryInfo>, StepError> { Ok(raw.into_iter().map(|b| BreweryInfo { name: b.name, brewery_type: b.brewery_type.unwrap_or_else(|| "unknown".into()), city: b.city.unwrap_or_else(|| city.to_string()), state: b.state.unwrap_or_else(|| state.to_string()), }).collect())}
#[zart_step("generate-summary", retry = "exponential(3, 2s)")]async fn generate_summary( llm: Arc<dyn LLMProvider>, query: &str, location: &ExtractedLocation, breweries: &[BreweryInfo],) -> Result<String, StepError> { println!("[generate-summary] Attempt {}", zart::context().current_attempt + 1);
let brewery_list = breweries.iter().take(5) .map(|b| format!("- {} ({})", b.name, b.brewery_type)) .collect::<Vec<_>>().join("\n");
let prompt = format!( "You're a friendly beer enthusiast. Write a short summary about: {query}\n\ Found {} breweries in {}, {}.\n{brewery_list}", breweries.len(), location.city, location.state );
let messages = vec![ChatMessage::user().content(&prompt).build()]; let response = llm .chat(&messages, None) .await .map_err(|e| StepError::Failed { step: "generate-summary".into(), reason: format!("LLM summary generation failed: {e}"), })?;
Ok(response.text().unwrap_or_default())}The DurableExecution impl composes steps by calling them directly:
#[async_trait::async_trait]impl DurableExecution for AutoAgentsAgent { type Data = AgentInput; type Output = AgentOutput;
async fn run(&self, data: Self::Data) -> Result<Self::Output, TaskError> { let location = extract_location(self.llm.clone(), &data.query).await?;
let raw_breweries: Vec<BreweryRaw> = find_breweries(&location.city).await?;
let breweries: Vec<BreweryInfo> = transform_results( raw_breweries, &location.city, &location.state, ).await?;
let summary = generate_summary( self.llm.clone(), &data.query, &location, &breweries, ).await?;
Ok(AgentOutput { query: data.query, location, breweries, summary, generated_at: Utc::now().to_rfc3339(), }) }}Registering and running
Section titled “Registering and running”let api_key = std::env::var("GEMINI_API_KEY") .or_else(|_| std::env::var("GOOGLE_API_KEY")) .expect("GEMINI_API_KEY or GOOGLE_API_KEY must be set");let model = std::env::var("GEMINI_MODEL").unwrap_or_else(|_| "gemini-2.5-flash".to_string());
let llm: Arc<dyn LLMProvider> = LLMBuilder::<Google>::new() .api_key(api_key) .model(model) .build()?;
let durable = DurableScheduler::from_backend(&pg);durable .start_for::<AutoAgentsAgent>(&execution_id, "autoagents-agent", &AgentInput { query: "Find breweries in Portland, Oregon".to_string(), }) .await?;Running the example
Section titled “Running the example”# Ensure PostgreSQL is runningjust up
# Set your Gemini API keyexport GEMINI_API_KEY="your-key-here"
# Run the examplejust example-autoagents-agentWhat you’ll see
Section titled “What you’ll see”=== Zart AutoAgents Agent Example ===
Starting execution 'autoagents-demo-...'... Query: Find breweries in Portland, Oregon
Initial execution status: Pending
Waiting for execution to complete...
[extract-location] Attempt 1 Extracted location: Portland, Oregon[find-breweries] Attempt 1 Found 20 raw brewery results[generate-summary] Attempt 1
Execution completed! Query: Find breweries in Portland, Oregon Location: Portland, Oregon Breweries: 20
Summary: Portland is a craft beer paradise with 20 fantastic breweries to explore! ...
Breweries found: 1. Breakside Brewery (micro) — Portland, Oregon 2. Cascade Brewing (brewpub) — Portland, Oregon ...Key concepts
Section titled “Key concepts”Manual DurableExecution for dependency injection — When a task needs external dependencies (like an LLM provider), implementing DurableExecution manually lets you define struct fields. The #[zart_durable] macro generates a unit struct with no fields.
Arc<dyn LLMProvider> for shareable providers — AutoAgents’ LLMBuilder::<Backend>::new().build() returns Arc<Backend>, which coerces to Arc<dyn LLMProvider> so it can be cloned into steps and passed to AgentBuilder or used directly via chat().
BasicAgent + AgentOutput for structured output — Derive AgentOutput from autoagents::prelude and annotate the agent struct with #[agent(..., output = LocationExtraction)]. BasicAgentOutput::try_parse() deserializes the structured JSON response automatically.
LLMProvider::chat for free-form text — For steps that return a plain String, call llm.chat(&[ChatMessage::user().content(&prompt).build()], None) and extract text via .text().
Mixed durable workflows — AI steps (LLM calls) and traditional steps (HTTP APIs, data transformations) coexist in the same durable workflow. Each step is independently persisted and retried.
Retry strategy — LLM steps use retry = "exponential(3, 2s)" since they’re prone to transient failures. The deterministic transform_results step needs no retry.
Changing the LLM provider
Section titled “Changing the LLM provider”Because the struct stores Arc<dyn LLMProvider>, swapping providers only requires changing the LLMBuilder type parameter:
use autoagents::llm::backends::openai::OpenAI;use autoagents::llm::backends::anthropic::Anthropic;
// OpenAIlet llm: Arc<dyn LLMProvider> = LLMBuilder::<OpenAI>::new() .api_key(std::env::var("OPENAI_API_KEY")?) .model("gpt-4o") .build()?;let worker = zart::WorkerBuilder::from_backend(&pg) .register_durable_task("autoagents-agent", AutoAgentsAgent { llm }) .build();
// Anthropiclet llm: Arc<dyn LLMProvider> = LLMBuilder::<Anthropic>::new() .api_key(std::env::var("ANTHROPIC_API_KEY")?) .model("claude-sonnet-4-5-20250929") .build()?;let worker = zart::WorkerBuilder::from_backend(&pg) .register_durable_task("autoagents-agent", AutoAgentsAgent { llm }) .build();