Build an LLM agent
In this tutorial you build a picnic planner. You ask it whether you can have a picnic in a city on a given day. A model checks the weather and looks up parks with two tools, then answers with a typed PicnicPlan. A plain node turns the plan into a message. You run it, stream the model’s text as it arrives, and finally test the whole program with a scripted model that needs no server.
The model runs on your own machine through Ollama, so you need no API key and pay nothing. Use a hosted model instead shows how to switch to OpenAI or Anthropic.
Each step uses one piece that a guide covers in depth: Call a model, Define tools and Build an agent. This tutorial puts the pieces together into one program. The code follows demos 03, 06 and 23 in strata-demos-dotnet and strata-demos-rust.
What you need
Section titled “What you need”-
The .NET 10 SDK or Rust 1.88 or later. See Requirements.
-
Ollama, with a small model that supports tool calls. This tutorial uses
qwen2.5:3b, which is about 1.9 GB:Terminal window ollama pull qwen2.5:3bOr run Ollama in Docker:
Terminal window docker run -d --name ollama -p 11434:11434 ollama/ollama:0.40.4docker exec ollama ollama pull qwen2.5:3bEither way, Ollama answers at
http://localhost:11434. -
You should know what a graph, a node and the state are. The Quickstart covers all three.
1. Create the project
Section titled “1. Create the project”Create a console app. Add Strata and the OpenAI provider for Microsoft.Extensions.AI, which also talks to Ollama:
dotnet new console -n PicnicAgentcd PicnicAgentdotnet add package Datalium.Strata.Hosting --version 0.9.0-preview.2dotnet add package Microsoft.Extensions.AI.OpenAI --version 10.11.0Create a binary crate:
cargo new picnic-agentcd picnic-agentSet its dependencies in Cargo.toml. datalium-strata-ai has the model clients and the agent. futures-util is for the scripted model in step 8.
[dependencies]datalium-strata = "=0.9.0-preview.2"datalium-strata-ai = "=0.9.0-preview.2"datalium-strata-memory = "=0.9.0-preview.2"futures-util = { version = "0.3", default-features = false, features = ["std"] }serde = { version = "1", features = ["derive"] }tokio = { version = "1", features = ["macros", "rt-multi-thread"] }2. Make a chat client
Section titled “2. Make a chat client”A chat client is the object that sends requests to a model. Ollama speaks OpenAI’s Chat Completions API, so the OpenAI client works with it when you give it Ollama’s address.
Any IChatClient works. This helper creates the OpenAI one, pointed at Endpoint. Put it at the end of Program.cs:
static IChatClient CreateClient(string model, string? baseUrl, string? apiKey) => new OpenAI.Chat.ChatClient( model, new ApiKeyCredential(apiKey ?? "not-needed"), new OpenAIClientOptions { RetryPolicy = new ClientRetryPolicy(maxRetries: 0), Endpoint = baseUrl is null ? null : new Uri(baseUrl), }) .AsIChatClient();Then create the client at the top:
using IChatClient chat = CreateClient("qwen2.5:3b", "http://localhost:11434/v1", apiKey: null);Ollama needs no key, but the SDK won’t send an empty one, so the helper sends a placeholder. maxRetries: 0 turns off the SDK’s own retries. The node’s recovery policy, which you add in step 4, does the retrying.
OpenAiOptions::ollama takes Ollama’s address and adds /v1 itself:
let chat: Arc<dyn ChatClient> = Arc::new(OpenAiChatClient::new( OpenAiOptions::ollama("http://localhost:11434").with_model("qwen2.5:3b"),));The client doesn’t retry. The node’s recovery policy, which you add in step 4, does the retrying.
Call a model lists the client options.
3. Define two tools
Section titled “3. Define two tools”A tool is a function that the model can call by name with JSON arguments. These two return fixed data, so every run sees the same weather. Each prints a line when it runs, so you can watch the loop.
Create PicnicTools.cs. The [StrataTool] source generator makes the class a tool provider:
using Datalium.Strata.Tools;
public partial class PicnicTools{ [StrataTool(Name = "weather.forecast", Description = "The weather forecast for a city on a day of the week.")] public static string Forecast(string city, string day) { Console.WriteLine($"[tool] weather.forecast({city}, {day})"); return city.Trim().ToLowerInvariant() switch { "lisbon" => $"{day} in Lisbon: sunny, 24°C, 5% chance of rain", "oslo" => $"{day} in Oslo: heavy rain, 9°C, 90% chance of rain", _ => $"no forecast for {city}", }; }
[StrataTool(Name = "parks.search", Description = "Parks in a city where picnics are allowed.")] public static string Search(string city) { Console.WriteLine($"[tool] parks.search({city})"); return city.Trim().ToLowerInvariant() switch { "lisbon" => "Jardim da Estrela, Parque Eduardo VII", "oslo" => "Frognerparken, St. Hanshaugen", _ => $"no parks known in {city}", }; }}Register them in Program.cs:
var tools = new ToolRegistry().Register(new PicnicTools());Create src/tools.rs. #[strata_tool] turns each function into a tool, with a handle named WeatherForecastTool and ParksSearchTool:
use datalium_strata::prelude::*;use serde::Deserialize;
#[derive(Deserialize, StrataSchema)]pub struct ForecastArgs { city: String, day: String,}
#[strata_tool( name = "weather.forecast", description = "The weather forecast for a city on a day of the week.")]pub async fn weather_forecast(args: ForecastArgs) -> Result<String, StrataError> { println!("[tool] weather.forecast({}, {})", args.city, args.day); Ok(match args.city.trim().to_lowercase().as_str() { "lisbon" => format!("{} in Lisbon: sunny, 24°C, 5% chance of rain", args.day), "oslo" => format!("{} in Oslo: heavy rain, 9°C, 90% chance of rain", args.day), _ => format!("no forecast for {}", args.city), })}
#[derive(Deserialize, StrataSchema)]pub struct ParksArgs { city: String,}
#[strata_tool(name = "parks.search", description = "Parks in a city where picnics are allowed.")]pub async fn parks_search(args: ParksArgs) -> Result<String, StrataError> { println!("[tool] parks.search({})", args.city); Ok(match args.city.trim().to_lowercase().as_str() { "lisbon" => "Jardim da Estrela, Parque Eduardo VII".to_string(), "oslo" => "Frognerparken, St. Hanshaugen".to_string(), _ => format!("no parks known in {}", args.city), })}Register them in src/main.rs:
let mut tools = ToolRegistry::new();tools .register(Box::new(WeatherForecastTool)) .register(Box::new(ParksSearchTool));The agent offers the model every tool in the registry it gets, and nothing else. Define tools covers argument types, the schema the model sees, and failures.
4. Build the agent
Section titled “4. Build the agent”An agent runs a model in a loop. Each turn is one model call. When the model asks for tools, the agent runs them and sends the results back. When the model answers without a tool call, the loop ends and the agent parses the answer into the type you chose.
The answer type
Section titled “The answer type”The answer is a PicnicPlan. A validate function checks what the type can’t: a picnic that goes ahead needs a park. When the answer doesn’t parse or doesn’t validate, the agent sends it back to the model once, with the problems, to be repaired.
public sealed record PicnicPlan(string City, string Day, bool GoAhead, string? Park, string Reason);
static IReadOnlyList<string> Validate(PicnicPlan plan) => plan.GoAhead && string.IsNullOrWhiteSpace(plan.Park) ? ["a picnic that goes ahead needs a park"] : [];Derive StrataSchema and Deserialize. rename_all gives the fields the same JSON names as in C#:
#[derive(Debug, Clone, Serialize, Deserialize, StrataSchema)]#[serde(rename_all = "camelCase")]struct PicnicPlan { city: String, day: String, go_ahead: bool, park: Option<String>, reason: String,}
fn validate(plan: &PicnicPlan) -> Vec<String> { let has_park = plan.park.as_deref().is_some_and(|park| !park.trim().is_empty()); if plan.go_ahead && !has_park { vec!["a picnic that goes ahead needs a park".to_string()] } else { Vec::new() }}The agent
Section titled “The agent”var agent = new StrataAgent<PicnicPlan>(chat, tools, new StrataAgentOptions<PicnicPlan>{ Id = "picnic-planner", Chat = new ChatOptions { Temperature = 0 }, MaxTurns = 4, Validate = Validate, // Ollama holds the model to the response format on every turn that asks for one, so the // model can't call a tool there. Ask for the JSON schema only on a repair turn. ConfigureTurn = (turn, options) => { if (!turn.IsRepair) { options.ResponseFormat = null; } },});let agent = Arc::new(Agent::<PicnicPlan>::new( chat, Arc::new(tools), AgentOptions::new("picnic-planner") .with_temperature(0.0) .with_max_turns(4) .with_validate(validate) // Ollama holds the model to the response format on every turn that asks for one, so // the model can't call a tool there. Ask for the JSON schema only on a repair turn. .with_configure_turn(|turn, request| { if !turn.is_repair { request.response_format = None; } }),));- The
Idnames the agent in errors, run events and spans. - Temperature 0 makes a small model’s answers steadier.
MaxTurnscaps the turns that call tools. A model that keeps calling tools fails the node instead of looping forever.
By default a typed agent asks for its answer type’s JSON schema as the response format on every turn. Ollama then holds the model’s output to that schema, so the model can’t call a tool. In our runs without ConfigureTurn, the model answered on its first turn without calling a tool. So this agent asks for the schema only on a repair turn, and the prompt in the next step names the fields instead.
5. Add the agent to a graph
Section titled “5. Add the agent to a graph”The state is a PicnicRequest: the city and day, and the fields the nodes fill in. AddAgentNode (Rust: add_agent_node) adds a node that runs the agent. prompt builds the messages from the state. apply writes the agent’s result into the state. After it, a plain node writes the message.
var graph = new StateGraph<PicnicRequest>() .AddAgentNode("Plan", agent, prompt: (request, _) => [ new(ChatRole.System, "You plan picnics. Always call weather.forecast and parks.search before you answer. " + "Go ahead only if the forecast is dry. Then answer with only a JSON object with the fields " + "city, day, goAhead (true or false), park (one park from parks.search, or null) and reason."), new(ChatRole.User, $"Can I have a picnic in {request.City} on {request.Day}?"), ], apply: (request, result) => request with { Plan = result.Output, Turns = result.Turns, ToolsUsed = [.. result.ToolCalls.Select(call => call.Name)], }) .AddNode("Announce", request => request with { Message = request.Plan!.GoAhead ? $"Picnic on: {request.Plan.Park}, {request.Day}. {request.Plan.Reason}" : $"No picnic {request.Day}. {request.Plan.Reason}", }) .AddEdge("Plan", "Announce") .SetRecoveryPolicy("Plan", RecoveryPolicy.Retry(1)) .Compile();
public sealed record PicnicRequest(string City, string Day){ public PicnicPlan? Plan { get; init; } public int Turns { get; init; } public IReadOnlyList<string> ToolsUsed { get; init; } = []; public string? Message { get; init; }}#[derive(Debug, Clone, Default, Serialize, Deserialize)]struct PicnicRequest { city: String, day: String, plan: Option<PicnicPlan>, turns: u32, tools_used: Vec<String>, message: Option<String>,}
let graph = StateGraph::<PicnicRequest>::new() .add_agent_node( "Plan", agent, |request: &PicnicRequest, _| { vec![ Message::system( "You plan picnics. Always call weather.forecast and parks.search before you answer. \ Go ahead only if the forecast is dry. Then answer with only a JSON object with the fields \ city, day, goAhead (true or false), park (one park from parks.search, or null) and reason.", ), Message::user(format!( "Can I have a picnic in {} on {}?", request.city, request.day )), ] }, |request: PicnicRequest, result: AgentResult<PicnicPlan>| PicnicRequest { tools_used: result.tool_calls.iter().map(|call| call.name.clone()).collect(), turns: result.turns, plan: Some(result.output), ..request }, ) .add_node("Announce", |request: PicnicRequest| { let plan = request.plan.clone().expect("Plan ran first"); let message = if plan.go_ahead { format!( "Picnic on: {}, {}. {}", plan.park.unwrap_or_default(), request.day, plan.reason ) } else { format!("No picnic {}. {}", request.day, plan.reason) }; PicnicRequest { message: Some(message), ..request } }) .add_edge("Plan", "Announce") .set_recovery_policy("Plan", RecoveryPolicy::retry(1)) .compile() .expect("the graph is valid");add_agent_node comes from the StateGraphAiExt trait.
The agent node is a fallible node. A failed model call, or an agent that gives no valid answer, fails it. RecoveryPolicy.Retry(1) runs it once more, with a fresh conversation. Retries and backoff adds a backoff and a fallback. Only what apply writes is saved in the state. The conversation itself isn’t.
6. Run it
Section titled “6. Run it”Run the graph with a thread ID, the initial state and a checkpoint store:
var result = await graph.RunAsync( "picnic-1", new PicnicRequest("Lisbon", "Saturday"), new InMemoryCheckpointStore());
if (result is GraphExecutionResult<PicnicRequest>.Completed { State: var done }){ Console.WriteLine($"tools used: {string.Join(", ", done.ToolsUsed)}"); Console.WriteLine($"model turns: {done.Turns}"); Console.WriteLine(done.Message);}else{ Console.WriteLine($"The run did not complete: {result}");}dotnet runlet store: Arc<dyn CheckpointStore> = Arc::new(InMemoryCheckpointStore::new());let request = PicnicRequest { city: "Lisbon".to_string(), day: "Saturday".to_string(), ..Default::default()};
match graph.run("picnic-1", request, store).await { GraphExecutionResult::Completed(done) => { println!("tools used: {}", done.tools_used.join(", ")); println!("model turns: {}", done.turns); println!("{}", done.message.unwrap_or_default()); } GraphExecutionResult::Failed(error) => println!("The run failed: {error:?}"), _ => println!("The run did not complete."),}cargo runA run against qwen2.5:3b printed this. A model’s answers vary, so your wording, and sometimes the tools it calls, can differ:
[tool] weather.forecast(Lisbon, Saturday)[tool] parks.search(Lisbon)tools used: weather.forecast, parks.searchmodel turns: 3Picnic on: Jardim da Estrela, Saturday. The weather is sunny with a low chance of rain and there are picnic-friendly parks available.Turn 1 called weather.forecast, turn 2 parks.search. Turn 3 answered without a tool call, so the agent parsed the answer into a PicnicPlan, validated it, and the loop ended. Announce then wrote the message from the typed plan.
The model calls the tools weather_forecast and parks_search, because providers don’t allow a dot in a tool name. The agent maps the names back, so ToolCalls and your run events show the Strata names. How the loop works describes each turn.
7. Stream the answer
Section titled “7. Stream the answer”To see the model’s text as it arrives, run with RunStreaming (Rust: run_streaming) instead. You don’t change the agent. When the run streams, each turn’s model call streams too, and its text reaches you as Token chunks.
Add using Datalium.Strata.Streaming; and replace the run:
var (chunks, completion) = graph.RunStreaming( "picnic-1", new PicnicRequest("Lisbon", "Saturday"), new InMemoryCheckpointStore());
await foreach (var chunk in chunks.ReadAllAsync()){ switch (chunk.Type) { case StreamChunkType.Token: Console.Write(chunk.Payload); break; case StreamChunkType.Retry: Console.WriteLine($"\n[retry] {chunk.NodeName}"); break; }}
var result = await completion;if (result is GraphExecutionResult<PicnicRequest>.Completed { State: var done }){ Console.WriteLine(); Console.WriteLine($"tools used: {string.Join(", ", done.ToolsUsed)}"); Console.WriteLine($"model turns: {done.Turns}"); Console.WriteLine(done.Message);}else{ Console.WriteLine($"\nThe run did not complete: {result}");}run_streaming takes an Arc of the compiled graph. Replace the run:
let (handle, mut chunks) = Arc::new(graph).run_streaming("picnic-1", request, store);
while let Some(chunk) = chunks.recv().await { match chunk.chunk_type { StreamChunkType::Token => { print!("{}", chunk.content); std::io::stdout().flush().ok(); } StreamChunkType::Retry => println!("\n[retry] {}", chunk.node_name), _ => {} }}
match handle.await.expect("the run's task doesn't panic") { GraphExecutionResult::Completed(done) => { println!(); println!("tools used: {}", done.tools_used.join(", ")); println!("model turns: {}", done.turns); println!("{}", done.message.unwrap_or_default()); } GraphExecutionResult::Failed(error) => println!("\nThe run failed: {error:?}"), _ => println!("\nThe run did not complete."),}Add use std::io::Write; for flush and use datalium_strata::streaming::StreamChunkType;.
A streamed run printed this. The JSON arrives as Token chunks while the model writes it:
[tool] weather.forecast(Lisbon, Saturday)[tool] parks.search(Lisbon){ "city": "Lisbon", "day": "Saturday", "goAhead": true, "park": "Jardim da Estrela", "reason": "The weather is sunny with a slight chance of rain, and there are parks available for picnics."}tools used: weather.forecast, parks.searchmodel turns: 3Picnic on: Jardim da Estrela, Saturday. The weather is sunny with a slight chance of rain, and there are parks available for picnics.The tokens are the text of every turn. A turn that only calls tools sends no text, and tool calls aren’t stream chunks. The [tool] lines come from the tools themselves. With a typed agent, the last turn’s text is the JSON of the answer. To stream prose to a reader instead, use a text agent (StrataAgent<string>, Rust: Agent<String>) or a model node. See Stream the answer.
Now ask about Oslo, where it rains. In this run the model wrote its answer as prose. That isn’t JSON, so the agent sent it back to be repaired. The repair turn asked for the schema, and the model answered with JSON:
[tool] weather.forecast(Oslo, Saturday)Based on the weather forecast, there is a high chance of rain on Saturday in Oslo. It's not advisable to go for a picnic under these conditions.{"city": "Oslo", "day": "Saturday", "goAhead": false, "park": null, "reason": "Weather forecast predicts heavy rain"}tools used: weather.forecastmodel turns: 3No picnic Saturday. Weather forecast predicts heavy rainThe model also skipped parks.search, although the prompt said to call it. A prompt guides the model but doesn’t bind it, which is why the answer is parsed and validated.
When a node is retried, the stream has a Retry chunk and the new attempt streams again from the start. Drop the text you printed for the failed attempt when you see one.
8. Test it without a model
Section titled “8. Test it without a model”The agent only sees a chat client, so you can give it a stand-in that plays scripted answers. Every run is then the same, needs no server, and can run in CI. This is the pattern of demo 23’s ScriptedModel, cut down to a list of answers.
Create ScriptedModel.cs:
using System.Runtime.CompilerServices;using Microsoft.Extensions.AI;
// A stand-in for a model: plays one scripted answer per request, in order.public sealed class ScriptedModel(params ChatResponse[] turns) : IChatClient{ private readonly Queue<ChatResponse> _turns = new(turns);
public static ChatResponse Call(string id, string tool, Dictionary<string, object?> arguments) => new(new ChatMessage(ChatRole.Assistant, [new FunctionCallContent(id, tool, arguments)]));
public static ChatResponse Say(string text) => new(new ChatMessage(ChatRole.Assistant, text));
public Task<ChatResponse> GetResponseAsync( IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default) => Task.FromResult(_turns.Count > 0 ? _turns.Dequeue() : throw new InvalidOperationException("the script has no more turns"));
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync( IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { var response = await GetResponseAsync(messages, options, cancellationToken); foreach (var update in response.ToChatResponseUpdates()) { yield return update; } }
public object? GetService(Type serviceType, object? serviceKey = null) => null;
public void Dispose() { }}Write the script. The model knows the tools by their provider names:
static ScriptedModel Script() => new( ScriptedModel.Call("call_1", "weather_forecast", new() { ["city"] = "Lisbon", ["day"] = "Saturday" }), ScriptedModel.Call("call_2", "parks_search", new() { ["city"] = "Lisbon" }), ScriptedModel.Say("""{"city":"Lisbon","day":"Saturday","goAhead":true,"park":"Jardim da Estrela","reason":"Sunny and 24°C, with a 5% chance of rain."}"""));Then choose the client with a command-line switch:
using IChatClient chat = args.Contains("--scripted") ? Script() : CreateClient("qwen2.5:3b", "http://localhost:11434/v1", apiKey: null);dotnet run -- --scriptedCreate src/scripted_model.rs:
use std::collections::VecDeque;use std::sync::Mutex;
use datalium_strata::BoxFuture;use datalium_strata_ai::{ ChatClient, ChatError, ChatRequest, ChatResponse, ChatStream, ChatUpdate, ChatUpdates,};
/// A stand-in for a model: plays one scripted answer per request, in order.pub struct ScriptedModel { turns: Mutex<VecDeque<Vec<ChatUpdate>>>,}
impl ScriptedModel { pub fn new(turns: Vec<Vec<ChatUpdate>>) -> Self { Self { turns: Mutex::new(turns.into()), } }
/// A turn that calls one tool, with its arguments as JSON text. pub fn call(id: &str, tool: &str, arguments: &str) -> Vec<ChatUpdate> { vec![ ChatUpdate::ToolCall { index: 0, id: Some(id.to_string()), name: Some(tool.to_string()), arguments: arguments.to_string(), }, ChatUpdate::Finish("tool_calls".to_string()), ] }
/// A turn that answers with text. pub fn say(text: &str) -> Vec<ChatUpdate> { vec![ ChatUpdate::Text(text.to_string()), ChatUpdate::Finish("stop".to_string()), ] }
fn next(&self) -> Result<Vec<ChatUpdate>, ChatError> { self.turns .lock() .unwrap() .pop_front() .ok_or_else(|| ChatError::fatal("script", "the script has no more turns")) }}
impl ChatClient for ScriptedModel { fn provider(&self) -> &str { "scripted" }
// Without streaming: the whole answer at once. fn complete(&self, _request: ChatRequest) -> BoxFuture<'_, Result<ChatResponse, ChatError>> { let turn = self.next(); Box::pin(async move { let mut assembled = ChatUpdates::new(); for update in turn? { assembled.push(update); } assembled.finish() }) }
// Under run_streaming: the same answer, as a stream. fn stream(&self, _request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, ChatError>> { let turn = self.next(); Box::pin(async move { let stream: ChatStream = Box::pin(futures_util::stream::iter(turn?.into_iter().map(Ok))); Ok(stream) }) }}Write the script. The model knows the tools by their provider names:
fn script() -> ScriptedModel { ScriptedModel::new(vec![ ScriptedModel::call("call_1", "weather_forecast", r#"{"city":"Lisbon","day":"Saturday"}"#), ScriptedModel::call("call_2", "parks_search", r#"{"city":"Lisbon"}"#), ScriptedModel::say( r#"{"city":"Lisbon","day":"Saturday","goAhead":true,"park":"Jardim da Estrela","reason":"Sunny and 24°C, with a 5% chance of rain."}"#, ), ])}Then choose the client with a command-line switch:
let chat: Arc<dyn ChatClient> = if std::env::args().any(|arg| arg == "--scripted") { Arc::new(script())} else { Arc::new(OpenAiChatClient::new( OpenAiOptions::ollama("http://localhost:11434").with_model("qwen2.5:3b"), ))};cargo run -- --scriptedBoth languages print the same, on every run:
[tool] weather.forecast(Lisbon, Saturday)[tool] parks.search(Lisbon){"city":"Lisbon","day":"Saturday","goAhead":true,"park":"Jardim da Estrela","reason":"Sunny and 24°C, with a 5% chance of rain."}tools used: weather.forecast, parks.searchmodel turns: 3Picnic on: Jardim da Estrela, Saturday. Sunny and 24°C, with a 5% chance of rain.The script runs your real tools, registry, validator and graph. It can also play the failures: an answer that doesn’t validate, a tool the agent doesn’t have, a loop that never ends. Demo 23 (.NET, Rust) plays each one. A script can’t tell you whether a real model follows your prompt. Run the live path for that.
If it doesn’t work
Section titled “If it doesn’t work”| What you see | Why | What to do |
|---|---|---|
[retry] Plan, then model call failed (connection): ... with Attempts = 2 (Rust: attempts: 2) |
Nothing answers at localhost:11434. A connection failure is transient, so the node was retried once. |
Start Ollama, or check the port. |
model call failed (404) with Ollama’s message that the model is not found, after one attempt |
Ollama doesn’t have the model. A 404 is fatal, so the node wasn’t retried. | Run ollama pull with the model name in your code. |
tools used: is empty |
The model answered without calling a tool. | Check that ConfigureTurn (Rust: with_configure_turn) turns the response format off, and that the model supports tool calls. |
agent 'picnic-planner' gave no valid answer: ... |
The answer still didn’t parse or validate after the repair. | Name the fields in the prompt, or allow more repairs with MaxRepairs (Rust: with_max_repairs). |
Call a model lists which faults are transient.
Use a hosted model instead
Section titled “Use a hosted model instead”Only the chat client changes. A hosted model costs money per call.
For OpenAI, set OPENAI_API_KEY and give the helper no endpoint:
using IChatClient chat = CreateClient( "gpt-4o-mini", baseUrl: null, apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY"));For Anthropic or another provider, use any IChatClient for it, such as one from the provider’s own .NET package. The agent works with any IChatClient.
// OpenAIlet api_key = std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY is set");let chat: Arc<dyn ChatClient> = Arc::new(OpenAiChatClient::new( OpenAiOptions::new(api_key).with_model("gpt-4o-mini"),));
// Anthropic: set ANTHROPIC_MODEL to the model you want.let api_key = std::env::var("ANTHROPIC_API_KEY").expect("ANTHROPIC_API_KEY is set");let model = std::env::var("ANTHROPIC_MODEL").expect("ANTHROPIC_MODEL is set");let chat: Arc<dyn ChatClient> = Arc::new(AnthropicChatClient::new( AnthropicOptions::new(api_key).with_model(model),));
// Another OpenAI-compatible server, such as vLLM or LM Studiolet chat: Arc<dyn ChatClient> = Arc::new(OpenAiChatClient::new( OpenAiOptions::compatible("http://localhost:8000/v1").with_model("my-model"),));With OpenAI or Anthropic, delete the ConfigureTurn setting, so every turn asks for the schema. OpenAI can call tools on a turn with a response format. The Rust Anthropic client puts the schema in the system prompt. Strata reads no environment variables for model calls: the program reads the key and passes it to the client.
The full program
Section titled “The full program”Program.cs. PicnicTools.cs is in step 3, ScriptedModel.cs in step 8.
using System.ClientModel;using System.ClientModel.Primitives;using Datalium.Strata.AI;using Datalium.Strata.Graph;using Datalium.Strata.Interruption;using Datalium.Strata.Storage;using Datalium.Strata.Streaming;using Datalium.Strata.Tools;using Microsoft.Extensions.AI;using OpenAI;
// 1. The chat client: a local model, or a scripted stand-in with --scripted.using IChatClient chat = args.Contains("--scripted") ? Script() : CreateClient("qwen2.5:3b", "http://localhost:11434/v1", apiKey: null);
// 2. The tools the agent may call.var tools = new ToolRegistry().Register(new PicnicTools());
// 3. The agent, with a typed answer.var agent = new StrataAgent<PicnicPlan>(chat, tools, new StrataAgentOptions<PicnicPlan>{ Id = "picnic-planner", Chat = new ChatOptions { Temperature = 0 }, MaxTurns = 4, Validate = Validate, // Ollama holds the model to the response format on every turn that asks for one, so the // model can't call a tool there. Ask for the JSON schema only on a repair turn. ConfigureTurn = (turn, options) => { if (!turn.IsRepair) { options.ResponseFormat = null; } },});
// 4. The graph: the agent plans, then a plain node writes the message.var graph = new StateGraph<PicnicRequest>() .AddAgentNode("Plan", agent, prompt: (request, _) => [ new(ChatRole.System, "You plan picnics. Always call weather.forecast and parks.search before you answer. " + "Go ahead only if the forecast is dry. Then answer with only a JSON object with the fields " + "city, day, goAhead (true or false), park (one park from parks.search, or null) and reason."), new(ChatRole.User, $"Can I have a picnic in {request.City} on {request.Day}?"), ], apply: (request, result) => request with { Plan = result.Output, Turns = result.Turns, ToolsUsed = [.. result.ToolCalls.Select(call => call.Name)], }) .AddNode("Announce", request => request with { Message = request.Plan!.GoAhead ? $"Picnic on: {request.Plan.Park}, {request.Day}. {request.Plan.Reason}" : $"No picnic {request.Day}. {request.Plan.Reason}", }) .AddEdge("Plan", "Announce") .SetRecoveryPolicy("Plan", RecoveryPolicy.Retry(1)) .Compile();
// 5. Run it, streaming the model's text as it arrives.var (chunks, completion) = graph.RunStreaming( "picnic-1", new PicnicRequest("Lisbon", "Saturday"), new InMemoryCheckpointStore());
await foreach (var chunk in chunks.ReadAllAsync()){ switch (chunk.Type) { case StreamChunkType.Token: Console.Write(chunk.Payload); break; case StreamChunkType.Retry: Console.WriteLine($"\n[retry] {chunk.NodeName}"); break; }}
var result = await completion;if (result is GraphExecutionResult<PicnicRequest>.Completed { State: var done }){ Console.WriteLine(); Console.WriteLine($"tools used: {string.Join(", ", done.ToolsUsed)}"); Console.WriteLine($"model turns: {done.Turns}"); Console.WriteLine(done.Message);}else{ Console.WriteLine($"\nThe run did not complete: {result}");}
static IChatClient CreateClient(string model, string? baseUrl, string? apiKey) => new OpenAI.Chat.ChatClient( model, new ApiKeyCredential(apiKey ?? "not-needed"), new OpenAIClientOptions { RetryPolicy = new ClientRetryPolicy(maxRetries: 0), Endpoint = baseUrl is null ? null : new Uri(baseUrl), }) .AsIChatClient();
static IReadOnlyList<string> Validate(PicnicPlan plan) => plan.GoAhead && string.IsNullOrWhiteSpace(plan.Park) ? ["a picnic that goes ahead needs a park"] : [];
static ScriptedModel Script() => new( ScriptedModel.Call("call_1", "weather_forecast", new() { ["city"] = "Lisbon", ["day"] = "Saturday" }), ScriptedModel.Call("call_2", "parks_search", new() { ["city"] = "Lisbon" }), ScriptedModel.Say("""{"city":"Lisbon","day":"Saturday","goAhead":true,"park":"Jardim da Estrela","reason":"Sunny and 24°C, with a 5% chance of rain."}"""));
public sealed record PicnicPlan(string City, string Day, bool GoAhead, string? Park, string Reason);
public sealed record PicnicRequest(string City, string Day){ public PicnicPlan? Plan { get; init; } public int Turns { get; init; } public IReadOnlyList<string> ToolsUsed { get; init; } = []; public string? Message { get; init; }}src/main.rs. src/tools.rs is in step 3, src/scripted_model.rs in step 8.
mod scripted_model;mod tools;
use std::io::Write;use std::sync::Arc;
use datalium_strata::checkpoint::GraphExecutionResult;use datalium_strata::graph::{RecoveryPolicy, StateGraph};use datalium_strata::prelude::*;use datalium_strata::store::CheckpointStore;use datalium_strata::streaming::StreamChunkType;use datalium_strata_ai::{ Agent, AgentOptions, AgentResult, ChatClient, Message, OpenAiChatClient, OpenAiOptions, StateGraphAiExt,};use datalium_strata_memory::checkpoint::InMemoryCheckpointStore;use scripted_model::ScriptedModel;use serde::{Deserialize, Serialize};use tools::{ParksSearchTool, WeatherForecastTool};
#[derive(Debug, Clone, Serialize, Deserialize, StrataSchema)]#[serde(rename_all = "camelCase")]struct PicnicPlan { city: String, day: String, go_ahead: bool, park: Option<String>, reason: String,}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]struct PicnicRequest { city: String, day: String, plan: Option<PicnicPlan>, turns: u32, tools_used: Vec<String>, message: Option<String>,}
fn validate(plan: &PicnicPlan) -> Vec<String> { let has_park = plan.park.as_deref().is_some_and(|park| !park.trim().is_empty()); if plan.go_ahead && !has_park { vec!["a picnic that goes ahead needs a park".to_string()] } else { Vec::new() }}
fn script() -> ScriptedModel { ScriptedModel::new(vec![ ScriptedModel::call("call_1", "weather_forecast", r#"{"city":"Lisbon","day":"Saturday"}"#), ScriptedModel::call("call_2", "parks_search", r#"{"city":"Lisbon"}"#), ScriptedModel::say( r#"{"city":"Lisbon","day":"Saturday","goAhead":true,"park":"Jardim da Estrela","reason":"Sunny and 24°C, with a 5% chance of rain."}"#, ), ])}
#[tokio::main]async fn main() { // 1. The chat client: a local model, or a scripted stand-in with --scripted. let chat: Arc<dyn ChatClient> = if std::env::args().any(|arg| arg == "--scripted") { Arc::new(script()) } else { Arc::new(OpenAiChatClient::new( OpenAiOptions::ollama("http://localhost:11434").with_model("qwen2.5:3b"), )) };
// 2. The tools the agent may call. let mut tools = ToolRegistry::new(); tools .register(Box::new(WeatherForecastTool)) .register(Box::new(ParksSearchTool));
// 3. The agent, with a typed answer. let agent = Arc::new(Agent::<PicnicPlan>::new( chat, Arc::new(tools), AgentOptions::new("picnic-planner") .with_temperature(0.0) .with_max_turns(4) .with_validate(validate) // Ollama holds the model to the response format on every turn that asks for one, so // the model can't call a tool there. Ask for the JSON schema only on a repair turn. .with_configure_turn(|turn, request| { if !turn.is_repair { request.response_format = None; } }), ));
// 4. The graph: the agent plans, then a plain node writes the message. let graph = StateGraph::<PicnicRequest>::new() .add_agent_node( "Plan", agent, |request: &PicnicRequest, _| { vec![ Message::system( "You plan picnics. Always call weather.forecast and parks.search before you answer. \ Go ahead only if the forecast is dry. Then answer with only a JSON object with the fields \ city, day, goAhead (true or false), park (one park from parks.search, or null) and reason.", ), Message::user(format!( "Can I have a picnic in {} on {}?", request.city, request.day )), ] }, |request: PicnicRequest, result: AgentResult<PicnicPlan>| PicnicRequest { tools_used: result.tool_calls.iter().map(|call| call.name.clone()).collect(), turns: result.turns, plan: Some(result.output), ..request }, ) .add_node("Announce", |request: PicnicRequest| { let plan = request.plan.clone().expect("Plan ran first"); let message = if plan.go_ahead { format!( "Picnic on: {}, {}. {}", plan.park.unwrap_or_default(), request.day, plan.reason ) } else { format!("No picnic {}. {}", request.day, plan.reason) }; PicnicRequest { message: Some(message), ..request } }) .add_edge("Plan", "Announce") .set_recovery_policy("Plan", RecoveryPolicy::retry(1)) .compile() .expect("the graph is valid");
// 5. Run it, streaming the model's text as it arrives. let store: Arc<dyn CheckpointStore> = Arc::new(InMemoryCheckpointStore::new()); let request = PicnicRequest { city: "Lisbon".to_string(), day: "Saturday".to_string(), ..Default::default() }; let (handle, mut chunks) = Arc::new(graph).run_streaming("picnic-1", request, store);
while let Some(chunk) = chunks.recv().await { match chunk.chunk_type { StreamChunkType::Token => { print!("{}", chunk.content); std::io::stdout().flush().ok(); } StreamChunkType::Retry => println!("\n[retry] {}", chunk.node_name), _ => {} } }
match handle.await.expect("the run's task doesn't panic") { GraphExecutionResult::Completed(done) => { println!(); println!("tools used: {}", done.tools_used.join(", ")); println!("model turns: {}", done.turns); println!("{}", done.message.unwrap_or_default()); } GraphExecutionResult::Failed(error) => println!("\nThe run failed: {error:?}"), _ => println!("\nThe run did not complete."), }}Next steps
Section titled “Next steps”- Fail over to another model. A model route tries a hosted model when the local one fails, and goes where a chat client goes. See Model routes.
- Remember across runs. Give the agent a tool that recalls what earlier runs stored. See Long-term memory.
- Ask a person before a risky tool. The loop runs inside one node, so leave the risky tool out, pause after the agent’s node, and act once a person approves. See Put a person before a risky action and Pause for approval.
- Check or refuse tool calls. Tool middleware logs, limits or denies each call the agent makes. See Tool middleware.
- Watch runs. Each turn and tool call records run events and spans. See Observability.
- Build a workflow around an agent. Build a support ticket agent adds an approval step and history.