Skip to main content

Calling the model directly

Agent is the way to build with Freyja, and this page is the layer under it. Reach for Client when you want one request and one response, typed output, raw stream events, a pre-flight check, or your own tool loop.

One request, one response​

use freyja::{Client, EndpointPreset, GenerateRequest, Message, Role};

let client = Client::from_env(EndpointPreset::OpenAi)?;
let request = GenerateRequest::new().message(Message::text(Role::User, "Name three Rust crates."));

let response = client.generate(&request).await?;
println!("{}", response.output_text());

if let Some(usage) = &response.usage {
println!("{} tokens", usage.total_tokens);
}

generate buffers the whole answer and returns a normalized GenerateResponse. The request is borrowed, so you can extend it and send it again.

Typed output​

use freyja::ResponseFormat;
use serde::Deserialize;

#[derive(Deserialize)]
struct Person { name: String, age: u32 }

let request = GenerateRequest::new()
.message(Message::text(Role::User, "Extract the name and age."))
.response_format(ResponseFormat::JsonSchema {
name: "person".into(),
schema: serde_json::json!({
"type": "object",
"properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
"required": ["name", "age"],
"additionalProperties": false
}),
strict: true,
});

let person: Person = client.generate_as(&request).await?;

generate_as deserializes the answer into your type. A well-formed answer of the wrong shape fails with Error::OutputMismatch, which keeps the text and says whether it was cut short.

Streaming events​

use freyja::StreamEvent;

let mut stream = client.stream(&request).await?;
while let Some(event) = stream.next().await? {
if let StreamEvent::TextDelta(text) = event {
print!("{text}");
}
}

let response = stream.into_response()?;

Text arrives as deltas, while tool calls and reasoning arrive only once complete. After the drain, into_response gives the same GenerateResponse that generate would have returned.

Checking a request before sending​

match client.check(&request) {
Ok(()) => { /* generate() will get as far as the network */ }
Err(error) => eprintln!("this endpoint cannot carry the request: {error}"),
}

check runs the conversion generate runs and stops before the network, so it uses no credentials and costs almost nothing.

Your own tool loop​

use freyja::{Context, OutputContent, Tool};
use std::sync::Arc;

let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(add)];
let cx = Context::new();
let definitions = tools.iter().map(|tool| tool.definition()).collect::<Vec<_>>();

let mut request = GenerateRequest::new()
.message(Message::text(Role::User, "What is 20 + 22?"))
.tools(definitions);

for _ in 0..5 {
let response = client.generate(&request).await?;

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

let mut results: Vec<Message> = Vec::new();
for (id, name, arguments) in response.tool_calls() {
let output = match tools.iter().find(|tool| tool.name() == name) {
Some(tool) => tool
.call(arguments, &cx)
.await
.unwrap_or_else(|error| format!("error: {error}")),
None => format!("error: unknown tool '{name}'"),
};
results.push(Message::tool_result(id, output));
}

request = request
.message(response.to_message())
.extend_messages(results);
}

Each round sends the request, runs every tool call the model asked for, and appends the assistant turn plus the results before sending again. The bound on rounds is not optional, since a model that keeps asking for tools would otherwise loop forever. Agent runs this loop for you, with guards, hooks and a token budget.

One result per call​

Each Message::tool_result answers exactly one call id. When the model requests three tools in one turn, you send three result messages. The loop over tool_calls() already does this.

Parallel calls arrive together​

A model may ask for several tools at once. tool_calls() yields all of them. Run them concurrently if they are independent, but send every result back before the next request. A call left unanswered is an error on most providers.

Where to go next​