Skip to main content

Responses

Agent::ask and Conversation::send return a Run, which is the result of a whole agent run. GenerateResponse is what one model call returns, and it is the shape the rest of this page describes.

pub struct Run {
pub answer: String,
pub stop: StopReason,
pub usage: Usage,
pub turns: usize,
}

answer is the final assistant text, usage is summed across every turn, and turns counts the requests the run made. stop says why the loop ended: Answered, MaxTurns, Refused, Incomplete, Failed, Stopped(reason) when a hook or a Cancel ended it, or OverBudget. Run, like GenerateResponse and Usage below, is #[non_exhaustive], so you read its fields but do not build one with a struct literal. StopReason is #[non_exhaustive] too.

GenerateResponse is the normalized answer. Whatever the vendor returned, this is the shape you work with.

Derives Debug, Clone, PartialEq, Serialize and Deserialize.

GenerateResponse is #[non_exhaustive], so a struct literal does not compile outside Freyja. GenerateResponse::new(status, content) builds one for tests and models of your own, with id and model empty and usage and provider_metadata unset. Assign the public fields to change them:

let mut response = GenerateResponse::new(
ResponseStatus::Completed,
vec![OutputContent::Text("hi".into())],
);
response.usage = Some(Usage::new(3, 1));
FieldMeaning
id: StringProvider assigned identifier, usable as previous_response_id
model: StringThe model that actually served the request, which can differ from what you asked for
status: ResponseStatusWhy the response ended
content: Vec<OutputContent>The parts the model produced, in order
usage: Option<Usage>Token accounting, when the provider reports it
provider_metadata: Option<Value>Provider fields Freyja does not model, preserved verbatim

OutputContent​

pub enum OutputContent {
Text(String),
Refusal(String),
ToolCall { id: String, name: String, arguments: String },
Reasoning { data: Value },
}

The enum is #[non_exhaustive], so a match on it needs a trailing _ arm.

VariantMeaning
TextGenerated text. A response can contain several parts
RefusalThe model declined to answer
ToolCallThe model wants a tool executed. arguments is a raw JSON string
ReasoningOpaque provider state that must be replayed verbatim

Refusal is distinct from Text on purpose. A refusal is not an answer, and folding it into text would hide that from callers. Note that output_text() excludes refusals, so a refusal shows up as an empty string there. Check content directly when you need to tell the two apart.

Only OpenAI emits Refusal today. Gemini's response format carries no separate refusal block that Freyja parses. Anthropic signals a refusal through stop_reason instead, which arrives as ResponseStatus::Other("refusal") with content empty or partial, so check status before reading content or you will mistake a refusal for an empty answer.

Helpers​

output_text​

pub fn output_text(&self) -> String

Concatenates every Text part into one string. Refusals and tool calls are skipped. This is the fast path when you just want the answer.

println!("{}", response.output_text());

tool_calls​

pub fn tool_calls(&self) -> impl Iterator<Item = (&str, &str, &str)>

Iterates the tool calls as (id, name, arguments). Borrows, so no allocation.

has_tool_calls​

pub fn has_tool_calls(&self) -> bool

Whether the model asked for at least one call. This is the loop condition in an agent loop, and it is more reliable than checking status, since providers differ in whether they report requires_action.

Reasoning, and what it is not​

OutputContent::Reasoning carries opaque provider reasoning state: Gemini thought signatures, Anthropic thinking blocks, and OpenAI reasoning items. It also catches any other top level output item, content block, or step that Freyja does not model, since those sit in the same position in the response and a dropped one breaks the next request. Ignore it unless you are assembling a transcript by hand, in which case preserve it exactly and in order. See Tool calling.

Three different things happen to what Freyja does not model, and they are worth keeping apart:

Unmodeled thingWhere it goes
A reasoning item, or any other unknown output item, block, or stepOutputContent::Reasoning, verbatim
A field on the response bodyprovider_metadata, verbatim
A content part inside a message itemDropped

The third is the lossy one. See provider_metadata.

to_message​

pub fn to_message(&self) -> Message

Converts the response into a Role::Assistant turn so it can be appended to the transcript. Text stays text, tool calls become InputContent::ToolCall, and refusals become text, because that is how a refusal reads in a transcript.

request = request.message(response.to_message());

You need this before sending tool results back. See Tool calling.

ResponseStatus​

pub enum ResponseStatus {
Completed,
Incomplete,
RequiresAction,
Failed,
Other(String),
}
VariantMeaning
CompletedThe model finished normally
IncompleteCut short, typically by max_tokens
RequiresActionWaiting on tool results
FailedThe provider could not produce a response
Other(String)A status Freyja does not model, preserved verbatim

Other exists so a provider adding a new status does not break parsing. The enum is also #[non_exhaustive], so a match on it needs a trailing _ arm, and Other is not that arm for you: handle it rather than assuming the four known variants are all there is.

Provider status strings map like this:

Wire valueVariant
completedCompleted
incompleteIncomplete
budget_exceeded (Gemini)Incomplete
requires_actionRequiresAction
failedFailed
cancelled (Gemini)Failed
end_turn, stop_sequence (Anthropic)Completed
max_tokens (Anthropic)Incomplete
tool_use (Anthropic)RequiresAction
refusal, pause_turn (Anthropic)Other
anything elseOther

Anthropic reports its reason as stop_reason rather than status, and two of its values deliberately stay as Other rather than being flattened into a near neighbour. A refusal is not a Failed, the request succeeded and the model chose not to answer. A pause_turn is not a RequiresAction either, since it is resumed by re-sending the transcript rather than by supplying a tool result, so treating it as one would send an agent loop hunting for tool calls that are not there.

A non Completed status is not an error. The call succeeded, so you get Ok. Only transport and API failures produce Err. See Errors.

Usage​

FieldMeaning
input_tokens: u64Prompt tokens
output_tokens: u64Generated tokens
total_tokens: u64Input and output together
cached_input_tokens: u64The part of input_tokens read from the prompt cache
cache_write_tokens: u64The part of input_tokens written to the prompt cache

Derives Debug, Clone, Copy, Default, PartialEq, Eq, Serialize and Deserialize. The struct is #[non_exhaustive], so build one with Usage::new(input_tokens, output_tokens), which sets total_tokens to their sum, or Usage::default(). Usage::cached(read, written) sets the two cache fields. Overwrite total_tokens when a provider reports another total. Usage implements +=, which adds every field.

response.usage is an Option, since not every provider reports usage on every response.

if let Some(usage) = response.usage {
println!("{} in, {} out, {} total",
usage.input_tokens, usage.output_tokens, usage.total_tokens);
}

Field names are normalized. Gemini reports total_input_tokens and total_output_tokens on the wire, and Freyja maps them onto the same three fields so cost accounting does not have to branch per provider.

Anthropic needs more than renaming. It reports no total at all, so Freyja computes one, and its input_tokens counts only the uncached part of the prompt, with cached tokens reported in two separate fields. Freyja sums all three, so input_tokens means the same thing on every provider, and reports the cached parts in cached_input_tokens and cache_write_tokens. See Prompt caching.

Cost turns usage into money, pricing cache reads and writes apart from plain input. See Observability.

provider_metadata​

Anything in the response body Freyja does not model is captured here rather than dropped, using serde's flatten. Use it to read provider specific fields without waiting for Freyja to add support:

if let Some(meta) = &response.provider_metadata {
if let Some(fingerprint) = meta.get("system_fingerprint") {
println!("fingerprint: {fingerprint}");
}
}

A streamed response fills this field differently: generate collects the leftovers, while a drained stream carries the provider's terminal object whole. Everything else on the response matches. See Streaming.

Forward compatibility inside content works differently, and this is where the two mechanisms get confused. An unknown output item, content block, or step is not dropped and does not fail deserialization: it becomes OutputContent::Reasoning holding the raw JSON, so it survives into the next request. Only an unknown part inside a message item is skipped outright, and that is the one place new content silently disappears until Freyja models it. Check content for Reasoning parts when output looks shorter than expected.

Handling a response​

A run is handled by its stop:

let run = agent.ask("What is 20 + 22?").await?;

match run.stop {
StopReason::Answered => println!("{}", run.answer),
StopReason::Incomplete => println!("truncated: {}", run.answer),
StopReason::MaxTurns => eprintln!("still asking for tools after {} turns", run.turns),
StopReason::Refused => eprintln!("the model declined"),
_ => eprintln!("stopped early: {:?}", run.stop),
}

A single model call is handled by its status, and Calling the model directly has that example.