Skip to content
These docs cover Strata 0.9.0-preview.3.It is a preview, and the API can still change before 1.0.

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.

  • 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:3b

    Or run Ollama in Docker:

    Terminal window
    docker run -d --name ollama -p 11434:11434 ollama/ollama:0.40.4
    docker exec ollama ollama pull qwen2.5:3b

    Either way, Ollama answers at http://localhost:11434.

  • You should know what a graph, a node and the state are. The Quickstart covers all three.

Create a console app. Add Strata and the OpenAI provider for Microsoft.Extensions.AI, which also talks to Ollama:

Terminal window
dotnet new console -n PicnicAgent
cd PicnicAgent
dotnet add package Datalium.Strata.Hosting --version 0.9.0-preview.2
dotnet add package Microsoft.Extensions.AI.OpenAI --version 10.11.0

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.

Call a model lists the client options.

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());

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.

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 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"] : [];
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;
}
},
});
  • The Id names the agent in errors, run events and spans.
  • Temperature 0 makes a small model’s answers steadier.
  • MaxTurns caps 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.

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; }
}

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.

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}");
}
Terminal window
dotnet run

A 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.search
model turns: 3
Picnic 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.

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}");
}

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.search
model turns: 3
Picnic 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.forecast
model turns: 3
No picnic Saturday. Weather forecast predicts heavy rain

The 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.

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);
Terminal window
dotnet run -- --scripted

Both 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.search
model turns: 3
Picnic 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.

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.

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.

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.

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; }
}
  • 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.