Skip to main content

Model

A Model answers a GenerateRequest with a GenerateResponse. Client is one, for every provider Freyja has a dialect for, and an Agent or a Summarizer takes any model. Write your own for a model Freyja cannot reach over HTTP, or to put behaviour in front of another model.

When you need one​

A server that speaks one of Freyja's four wire formats needs no Model. Ollama, vLLM, LM Studio and most gateways speak the OpenAI format, and a Client reaches them with an EndpointConfig. See Custom endpoints.

Implement Model for:

  • a model running in your process, through llama.cpp bindings or candle
  • a provider with a wire format or an auth scheme Freyja does not speak
  • a wrapper around another model, such as a cache, a fallback, a router or a rate limiter
  • a fake model for tests, although freyja::testing::ScriptedModel is usually enough

The trait​

pub type ModelFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>;

pub trait Model: Send + Sync {
fn name(&self) -> &str;
fn generate<'a>(&'a self, request: &'a GenerateRequest) -> ModelFuture<'a, GenerateResponse>;

fn stream<'a>(&'a self, request: &'a GenerateRequest) -> ModelFuture<'a, EventStream> {
Box::pin(async move { Ok(EventStream::from_response(self.generate(request).await?)) })
}
}

An agent keeps its model as Arc<dyn Model>, and Freyja forwards Model through Arc<T> and Box<T>. So Agent::new(model.clone()) with an Arc works, and lets a test or a wrapper keep its own handle on the same model.

name​

A short name for the model, used in errors. Every freyja::Error variant carries an endpoint field, and this is what goes in it, so a log line says which model failed. Client returns its endpoint's configured name.

generate​

Answers the request in one response.

The request is provider-neutral. messages holds the transcript, with the agent's system instruction first, and tools holds the definitions of every tool the model may call. model, max_tokens, temperature, response_format and the other fields are None when the caller did not set them, and a model applies its own defaults then. A model that cannot honour a field it was given, such as response_format on a backend with no structured output, should return an error rather than ignore it.

The response needs at least a status and its content:

let mut response = GenerateResponse::new(
ResponseStatus::Completed,
vec![OutputContent::Text("Hello.".into())],
);
response.usage = Some(Usage::new(input_tokens, output_tokens));

The agent adds usage to run.usage and checks the token budget, then reads the response in this order and acts on the first row that matches:

The response hasThe agent
An OutputContent::Refusal partEnds the run with StopReason::Refused
ResponseStatus::IncompleteEnds the run with StopReason::Incomplete
ResponseStatus::Failed or OtherEnds the run with StopReason::Failed
No OutputContent::ToolCall partsEnds the run with StopReason::Answered and the text as run.answer
OutputContent::ToolCall partsRuns each call and sends the results back in a new request

A response that asks for tools therefore needs Completed or RequiresAction as its status, or the calls never run.

Each tool call needs an id that is unique within the response, because the results the agent sends back name the call they answer by it. arguments is the JSON text of the arguments.

Set usage whenever you know it. A response without one counts as zero tokens, so Agent::token_budget cannot stop a run on a model that never reports usage.

stream​

Answers the request as a stream of events: text as it is written, tool calls, and the finished response.

The default awaits generate and replays the whole response at once with EventStream::from_response. A model that cannot stream still works for a caller who streams, without any extra code. Override it only when the backend really produces tokens one at a time, and build the EventStream from them. A wrapper forwards it to the model it wraps, as Client and the Arc and Box forwarding do, so streaming reaches the inner model.

Errors​

A model fails with freyja::Error, the same type Client returns, so a caller handles every model alike. Pick the variant that says what happened, and put self.name() in endpoint:

VariantFor
Error::InvalidRequest { endpoint, message }A request this model cannot answer, such as one with no messages
Error::InvalidResponse { endpoint, message }A backend answer that could not be turned into a response
Error::ServerError { endpoint, status, body }A backend failure that may pass if retried
Error::RateLimit { endpoint, retry_after, body }A backend asking the caller to slow down

error.is_retryable() is true for rate limits, server errors and transport failures that may pass on a second try, and false for anything a retry would only repeat. A wrapper uses it to decide whether trying again, or trying another model, could help.

Example: fall back to a second model​

For trying the same model again, Freyja ships Retry. See Handling outages.

Fallback tries one model, and tries a second when the first fails with an error that a retry could fix. A bad request would fail the same way on the second model, so it is returned as it is.

use freyja::{GenerateRequest, GenerateResponse, Model, ModelFuture};

struct Fallback<A, B> {
primary: A,
secondary: B,
}

impl<A: Model, B: Model> Model for Fallback<A, B> {
fn name(&self) -> &str {
self.primary.name()
}

fn generate<'a>(&'a self, request: &'a GenerateRequest) -> ModelFuture<'a, GenerateResponse> {
Box::pin(async move {
match self.primary.generate(request).await {
Err(error) if error.is_retryable() => self.secondary.generate(request).await,
other => other,
}
})
}
}
let primary = Client::from_env(EndpointPreset::Anthropic)?;
let secondary = Client::from_env(EndpointPreset::OpenAi)?;
let agent = Agent::new(Fallback { primary, secondary });

The two models get the same request. A request that sets model names a model only one provider has, so leave it unset on the agent and give each Client its own default model instead. Fallback leaves stream at its default, so a streaming caller gets the answer all at once. Forward stream the same way as generate to stream from whichever model answers.

Example: a model in your process​

Echo answers with the text of the last user turn. It stands in for a local model: the shape is the same when the text comes from a llama.cpp context instead.

use freyja::{
Error, GenerateRequest, GenerateResponse, InputContent, Model, ModelFuture, OutputContent,
ResponseStatus, Role, Usage,
};

struct Echo;

impl Model for Echo {
fn name(&self) -> &str {
"echo"
}

fn generate<'a>(&'a self, request: &'a GenerateRequest) -> ModelFuture<'a, GenerateResponse> {
Box::pin(async move {
let Some(last) = request.messages.iter().rev().find(|m| m.role == Role::User) else {
return Err(Error::InvalidRequest {
endpoint: self.name().into(),
message: "nothing to echo: the request has no user turn".into(),
});
};
let text: String = last
.content
.iter()
.filter_map(|part| match part {
InputContent::Text(text) => Some(text.as_str()),
_ => None,
})
.collect();
let mut response =
GenerateResponse::new(ResponseStatus::Completed, vec![OutputContent::Text(text.clone())]);
response.model = "echo".into();
response.usage = Some(Usage::new(text.len() as u64, text.len() as u64));
Ok(response)
})
}
}

Inference in a local model is CPU or GPU work that does not await. Run it on a blocking thread, with tokio::task::spawn_blocking or your runtime's equivalent, so it does not stall the async runtime the agent and its tools run on.

Testing it​

A model is tested by calling it, or by running an agent on it. A model that always fails with a chosen error is a few lines, and pairs with the model under test:

struct Down;

impl Model for Down {
fn name(&self) -> &str {
"down"
}
fn generate<'a>(&'a self, _request: &'a GenerateRequest) -> ModelFuture<'a, GenerateResponse> {
Box::pin(async move {
Err(Error::ServerError { endpoint: self.name().into(), status: 503, body: String::new() })
})
}
}

#[tokio::test]
async fn a_server_error_falls_back() {
let run = Agent::new(Fallback { primary: Down, secondary: Echo }).ask("hello").await.unwrap();
assert_eq!(run.answer, "hello");
}

#[tokio::test]
async fn a_bad_request_does_not_fall_back() {
let model = Fallback { primary: Echo, secondary: Echo };
let error = model.generate(&GenerateRequest::new()).await.unwrap_err();
assert!(!error.is_retryable());
}

freyja::testing::Recorder wraps any model and saves what it answered, so a run against a real local model can be replayed in tests later with ScriptedModel::replay. See Testing.

Stability​

Model stays usable as dyn Model. A method added to it later comes with a default, as stream has. Error, GenerateResponse, ResponseStatus and OutputContent are #[non_exhaustive]: build a response with GenerateResponse::new and set its public fields, and give every match on them a trailing _ arm.

See also​