Skip to main content

ChatGenerator

Trait ChatGenerator 

Source
pub trait ChatGenerator: Send + Sync {
    // Required methods
    fn chat(
        &self,
        messages: &[ChatMessage],
        tools: Option<&Value>,
        tool_choice: Option<&str>,
        params: &GenParams,
        cancel: &Arc<AtomicBool>,
        on_delta: &mut dyn FnMut(Delta),
    ) -> Result<ChatOutcome>;
    fn status(&self) -> GeneratorStatus;
    fn vocab_size(&self) -> usize;

    // Provided methods
    fn complete(
        &self,
        _prompt: &str,
        _params: &GenParams,
        _cancel: &Arc<AtomicBool>,
        _on_text: &mut dyn FnMut(&str),
    ) -> Result<ChatOutcome> { ... }
    fn prepare_completion(
        &self,
        _prompt: &str,
    ) -> Result<Option<(u32, Option<u32>)>> { ... }
    fn complete_with_logprobs(
        &self,
        prompt: &str,
        params: &GenParams,
        cancel: &Arc<AtomicBool>,
        on_text: &mut dyn FnMut(&str),
        _on_logprob: &mut dyn FnMut(TokenLogprob),
    ) -> Result<ChatOutcome> { ... }
    fn supports_logprobs(&self) -> bool { ... }
    fn prepare(
        &self,
        _messages: &[ChatMessage],
        _tools: Option<&Value>,
        _tool_choice: Option<&str>,
        _params: &GenParams,
    ) -> Result<Option<PreparedRequest>> { ... }
    fn chat_prepared(
        &self,
        prepared: PreparedRequest,
        messages: &[ChatMessage],
        tools: Option<&Value>,
        tool_choice: Option<&str>,
        params: &GenParams,
        cancel: &Arc<AtomicBool>,
        on_delta: &mut dyn FnMut(Delta),
    ) -> Result<ChatOutcome> { ... }
}
Expand description

Generation backend the server drives — it never knows the model/GPU underneath. Implemented by the CLI’s per-arch adapters (infr-cli’s ParallelGenerator over infr_llama::ParallelSeam for the Vulkan seam; SeamGenerator wraps any infr_llama::ChatModel for the rest, including DiffusionGemmaChat — see docs/diffusion-gemma.md).

GenParams carries the request’s PER-REQUEST sampling config (temperature/top_p/top_k/seed/ penalties/stop/max_tokens). Every field is an Option whose None means “inherit the process default” — so a request that sends nothing generates EXACTLY as it did before this existed.

&self, Send + Sync. This is the whole concurrency contract: the server calls chat from N request tasks at once and the generator is responsible for its own slot allocation and GPU turn-taking. It used to be &mut self behind an Arc<Mutex<_>> the handlers held for an ENTIRE generation, which meant request #2 waited for request #1 to finish — head-of-line blocking, no parallelism. An implementation that genuinely cannot run concurrently (CPU / Metal / diffusion today) keeps an internal Mutex and is served with --parallel 1, which is honest rather than silently serialising a server the user asked to parallelise.

Required Methods§

Source

fn chat( &self, messages: &[ChatMessage], tools: Option<&Value>, tool_choice: Option<&str>, params: &GenParams, cancel: &Arc<AtomicBool>, on_delta: &mut dyn FnMut(Delta), ) -> Result<ChatOutcome>

Run one chat turn.

  • tools is the request’s tools array as a borrowed serde_json::Value — passed by reference so the generator parses the ONE it was already given instead of a Value→string→Value round-trip (see audit finding 6).
  • cancel is a PER-REQUEST abort latch. The server sets it when the client hangs up (streaming or not) or the request deadline fires; the generator must poll it in its prefill AND decode loops and stop promptly so the GPU slot is freed rather than held to max_tokens. An Arc so the generator can keep it for the whole call — a deadline that fires during prefill comes before any piece, so a copy made from a streaming callback is too late. It is ORed with the process-wide shutdown latch, never a replacement for it.
  • Returns a ChatOutcome carrying the finish reason AND the real prompt/completion token counts so the handler can populate usage truthfully.
  • A request whose prompt does not fit the context should fail with a ContextLengthExceeded error. The server answers it as a 400 on a non-streaming request and as a terminal SSE error frame carrying the same typed error on a streaming one (the 200 is already sent by then), so the client can act on it rather than retry it.
Source

fn status(&self) -> GeneratorStatus

Where this generator runs and how much room it has, read fresh on each call, for GET /status and the device gauges in /metrics. Report None for what the backend cannot see rather than a placeholder. It must not wait on a generation: both routes call it while requests are running.

Source

fn vocab_size(&self) -> usize

How many token ids this generator’s model has — the length of the logits row a logit_bias is applied to — so a request’s logit_bias may name only ids below it. The server asks only for a request that carries a bias, and before the request reaches chat, so a bad id is a 400 on a streaming request too, where the 200 goes out before generation starts. It is read on the request path, so return a value computed once rather than counting the vocabulary each time.

Provided Methods§

Source

fn complete( &self, _prompt: &str, _params: &GenParams, _cancel: &Arc<AtomicBool>, _on_text: &mut dyn FnMut(&str), ) -> Result<ChatOutcome>

Continue prompt as raw text — no chat template, no reasoning/tool splitting — streaming the decoded pieces to on_text. Backs /v1/completions; cancel and the return value behave as in chat. A prompt that comes to no tokens should fail with ParamError::empty_prompt, which the server answers as a 400 naming prompt, and an over-long one with a ContextLengthExceeded naming prompt.

Default: the model cannot serve raw completions, which the server answers as a 400 naming model rather than a 500 that reads as a server fault.

Source

fn prepare_completion( &self, _prompt: &str, ) -> Result<Option<(u32, Option<u32>)>>

prompt’s token count and the model’s usable prompt budget, counted before a slot is taken so an over-long raw completion is refused instead of queued. None for a backend that cannot count a raw prompt without generating it — its generator still reports the overflow, and the server answers that as the same 400.

Source

fn complete_with_logprobs( &self, prompt: &str, params: &GenParams, cancel: &Arc<AtomicBool>, on_text: &mut dyn FnMut(&str), _on_logprob: &mut dyn FnMut(TokenLogprob), ) -> Result<ChatOutcome>

complete with per-token log probabilities. Default: refuse a request that asked for them rather than return text without the promised data; backends that support the dense seam override it. on_text still receives the generated text.

Source

fn supports_logprobs(&self) -> bool

Does this backend produce log probabilities? Checked before the response headers so a request for them is a 400 naming the field, not a reply shaped as if it had them.

Source

fn prepare( &self, _messages: &[ChatMessage], _tools: Option<&Value>, _tool_choice: Option<&str>, _params: &GenParams, ) -> Result<Option<PreparedRequest>>

Ready a request before it waits for a slot, and before a stream’s 200 goes out: render its prompt, count it, build whatever it needs to generate, and hand all of that back as a PreparedRequest the server passes to chat_prepared, so the work is done once per request.

The server logs PreparedRequest::prompt_tokens on the arrival line and answers a prompt longer than PreparedRequest::context_length with 400 context_length_exceeded — on a stream too, so the client gets a real 400 rather than a 200 and an error frame, and an over-long prompt never takes a slot. An error is answered before the request is queued, as chat’s would be: a ParamError or ContextLengthExceeded is a 400, anything else a 500.

Never wait on a generation here: it runs while other requests generate. The default, Ok(None), prepares nothing, and the server calls chat as it always has.

Source

fn chat_prepared( &self, prepared: PreparedRequest, messages: &[ChatMessage], tools: Option<&Value>, tool_choice: Option<&str>, params: &GenParams, cancel: &Arc<AtomicBool>, on_delta: &mut dyn FnMut(Delta), ) -> Result<ChatOutcome>

Run a turn prepare readied, with the same request it was prepared from. A generator that implements prepare implements this too; the default ignores prepared and calls chat.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§