Skip to main content

Workflows

A workflow is a fixed order of agent calls that your code decides, such as one agent's answer feeding the next or several agents working on parts of a question at once. Freyja has no workflow type. Each call is an async function, so ordinary Rust composes them, and a shared Context carries a token budget, a stop signal and any state across every call. This guide shows the common shapes.

When the model should decide who works next, use a team or an agent as a tool instead. A workflow fits when you already know the steps.

A chain​

Await one call, then pass its answer into the next prompt.

let outline = planner.ask(format!("Outline a post about {topic}.")).await?;
if outline.stop != StopReason::Answered {
return Err(anyhow!("planner stopped: {:?}", outline.stop));
}

let post = writer
.ask(format!("Write the post from this outline:\n\n{}", outline.answer))
.await?;

Check stop between steps. A run that ends with MaxTurns or Refused still returns Ok, and its answer may be empty or a refusal, which is not something the next step should build on. See Why a run stopped.

Each step can use its own model, system prompt and tools. A cheap model for the outline and a stronger one for the writing is a common split.

Fan-out​

Start several calls and wait for all of them. try_join_all from the futures crate runs them concurrently on the current task and returns the first error, if any.

use futures::future::try_join_all;

let questions = [
"What changed in the last Rust release?",
"What changed in the last Go release?",
"What changed in the last Python release?",
];

let runs = try_join_all(questions.iter().map(|question| researcher.ask(*question))).await?;

for run in &runs {
println!("{}", run.answer);
}

The results come back in the order of questions. Use join_all instead to keep every result, errors included, when one failed branch should not discard the others.

Agent is cheap to clone and every ask starts a fresh conversation, so the branches share nothing but the agent's configuration. See Sharing an agent.

One budget and one stop signal​

ask runs with an empty Context. To give every step the same Budget and Cancel, build one context and pass it to each ask with .context(&cx). Every branch borrows the same context, so they all charge one count and all stop together.

use freyja::{Budget, Cancel, Context};
use futures::future::try_join_all;

let budget = Budget::tokens(100_000);
let cancel = Cancel::new();
let mut cx = Context::new();
cx.insert(budget.clone());
cx.insert(cancel.clone());

let runs = try_join_all(questions.iter().map(|question| researcher.ask(*question).context(&cx))).await?;

println!("spent {} tokens", budget.spent());

A chain works the same way: pass &cx to every step.

Once the budget is spent, each branch stops before its next model call with StopReason::OverBudget. Once cancel.cancel(reason) is called, from a timeout or a stop button, each branch ends with StopReason::Stopped(reason). Either way every branch still returns Ok with its usage, so try_join_all returns all of them, and you check each stop.

Picking the best answer​

Fan out for candidates, then chain a judge over them.

let drafts = try_join_all((0..3).map(|_| writer.ask(brief.clone()))).await?;

let numbered = drafts
.iter()
.enumerate()
.map(|(i, run)| format!("Draft {}:\n{}", i + 1, run.answer))
.collect::<Vec<_>>()
.join("\n\n");

let verdict = judge
.ask(format!("Pick the best draft for this brief and say why.\n\nBrief: {brief}\n\n{numbered}"))
.await?;

Three calls with one prompt only differ when the writer's temperature is above zero. For a choice your code acts on, have the judge return a typed value, such as the winning draft's number, with structured output.

Shared state​

State that tools in different steps read and write goes in the Context too. The context is borrowed, never cloned, so a value inside it is shared by every branch as it is. Wrap it in a Mutex when tools write to it.

use freyja::{Context, ToolError, tool};
use std::sync::Mutex;

#[derive(Default)]
struct Notes(Mutex<Vec<String>>);

#[tool(description = "saves a fact for the final report")]
fn note(cx: &Context, fact: String) -> Result<String, ToolError> {
cx.require::<Notes>()?.0.lock().unwrap().push(fact);
Ok("saved".into())
}

let mut cx = Context::new();
cx.insert(Notes::default());

// run the steps with `ask(...).context(&cx)`, then read what they saved
let notes = cx.get::<Notes>().unwrap().0.lock().unwrap().clone();

Context is keyed by type, so give each value its own newtype. See Where state goes.

See also​