Rust crate to talk to LLM services (OpenAI api, supports quirks and metrics of llama.cpp and ollama)
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-11-24 22:37:09 +01:00
agents Bugfix B005, T4: tools docs for the two-trait split, 0.2.0 bump, book rebuild 2026-11-24 22:31:50 +01:00
crates Bugfix B005, T4: tools docs for the two-trait split, 0.2.0 bump, book rebuild 2026-11-24 22:31:50 +01:00
docs Bugfix B005, T4: tools docs for the two-trait split, 0.2.0 bump, book rebuild 2026-11-24 22:31:50 +01:00
src Bugfix B004, T1: ModelInfo::context_size, served-window-first contract in docs, fixture matrix 2026-11-24 21:43:56 +01:00
tests Bugfix P001, T12: the shared-server anchor releases on claims returned, not a hand-maintained test count 2026-10-29 17:37:45 +01:00
.gitignore Feature P002, T7: the gated real-server assembly test 2026-10-29 22:44:52 +01:00
AGENTS.md Bugfix B005, T4: tools docs for the two-trait split, 0.2.0 bump, book rebuild 2026-11-24 22:31:50 +01:00
Cargo.lock Bugfix B005, T4: tools docs for the two-trait split, 0.2.0 bump, book rebuild 2026-11-24 22:31:50 +01:00
Cargo.toml Bugfix B003, T6: bump llm-api to 0.3.0 and llm-api-assembler to 0.2.0 2026-11-24 21:21:10 +01:00
Changelog.md Docs B001-B004: add the missing changelog entries 2026-11-24 22:37:09 +01:00
README.md Bugfix B005, T1: split Tool's definition half into an object-safe trait 2026-11-24 22:05:23 +01:00

llm-api

llm-api is a Rust client for OpenAI-compatible inference servers. It speaks the subset of the protocol that llama.cpp, OpenAI and Ollama have in common, and it models the llama.cpp additions, such as reasoning deltas, the timings sidecar and prompt progress, instead of dropping them.

The repository is one Cargo workspace with three crates:

  • llm-api, the client. It owns the transport, the chat log, media preparation and capability resolution.
  • crates/llm-api-assembler, the sibling crate. It reassembles the streamed chunks into whole messages you can render and hand back to the log.
  • crates/llm-api-tools, the second sibling crate. It turns a Tool you write into a wire definition, repairs the arguments a model mangles, executes the calls of one turn and answers each one for the log.

What it speaks

Endpoint In this crate
POST /v1/chat/completions yes, always streamed
GET /v1/models yes
GET /props yes, llama.cpp only
POST /v1/embeddings yes

Endpoints outside that set are reachable through LlmClient::get_json, post_json and post_stream, so you never need a second HTTP client. See the documentation for the full picture.

A chat with metrics

The example asks a local llama.cpp server a question, renders the answer as it arrives, logs the metrics as they arrive, and appends the finished turn to the chat log so the next request carries the whole conversation.

[dependencies]
llm-api = { path = "…" }
llm-api-assembler = { path = "…/crates/llm-api-assembler" }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use llm_api::{ChatLogBuilder, ChatOptions, Chunk, ClientConfig, LlmClient};
use llm_api_assembler::{assemble, assistant_turn_items, Assembled, Throttle};

#[tokio::main]
async fn main() -> Result<(), llm_api::LlmError> {
    let client = LlmClient::new(ClientConfig::new("http://127.0.0.1:8080")?)?;

    let mut log = ChatLogBuilder::new()
        .system("Answer briefly.")
        .user("What is the capital of France?")
        .finish();

    let stream = client.chat(&mut log, &ChatOptions::new()).await?;

    // Hold the handle for the whole exchange: dropping it cancels the response.
    let (mut messages, mut response) = assemble(stream, Throttle::default());

    // One acquire: the first call hands out the receiver, every later call answers None.
    let mut metrics = response.metrics().expect("the first acquire");

    let mut turn = Vec::new();
    loop {
        tokio::select! {
            Some(chunk) = metrics.recv() => match chunk {
                Chunk::MetricsDelta { delta, .. } => {
                    println!("metrics: +{} generated tokens", delta.generated_tokens);
                }
                Chunk::MetricsSummary { summary, .. } => {
                    if let Some(tokens) = summary.context_tokens {
                        println!("metrics: {tokens} tokens in context");
                    }
                }
                _ => {}
            },
            Some(message) = messages.recv() => {
                match &message {
                    // Every partial carries the whole text so far: overwrite, never append.
                    Assembled::MessageIncomplete { text, .. } => print!("\r{text}"),
                    Assembled::MessageComplete { text, .. } => print!("\r{text}"),
                    Assembled::Done { finish_reason } => println!("\n[{finish_reason:?}]"),
                    Assembled::Error { error } => eprintln!("stream failed: {error}"),
                    _ => {}
                }
                turn.push(message);
            }
            else => break,
        }
    }

    // Append the finished turn so the next request carries the whole conversation.
    for item in assistant_turn_items(&turn) {
        log.push(item);
    }
    Ok(())
}

The loop ends when both channels close. The metrics side-channel is best-effort: a consumer that stops reading loses telemetry, the chat is unaffected.

The chat log that comes back

After assistant_turn_items has pushed its entries, the log holds the conversation plus the finished turn:

  • the System and User entries you wrote, unchanged;
  • one ChatItem::Agent entry with the final answer text, the reasoning trace and the response identifier as its server identifier. The entry is skipped when the model only called tools;
  • one ChatItem::ToolCall entry per call, in emission order, each carrying the call identifier, the tool name and the raw argument text.

The partials, the terminal marker, an error and a cancellation contribute nothing, so a superseded partial cannot duplicate the turn. Arguments that did not parse as JSON travel unchanged; repairing them is the caller's job. When the next request is built, the serialiser merges the agent entry and any tool-call entries that follow it into one assistant message, which is the shape chat templates expect. Whether the reasoning on the agent entry is sent back is governed by ClientConfig::with_send_reasoning_back.

A log that carried images has already been prepared: chat replaces raw image bytes with the data URLs preparation produced, so a follow-up turn over the same log never decodes the same image twice.

LlmClient::chat_once covers the same round trip without the streaming loop: it drains the channel, appends exactly this turn and hands the log back.

A tool call round trip

The example defines one tool, registers it, runs a turn, executes the call the model made and feeds the answer back, so a second call finds the whole exchange in the log.

[dependencies]
llm-api = { path = "…" }
llm-api-assembler = { path = "…/crates/llm-api-assembler" }
llm-api-tools = { path = "…/crates/llm-api-tools" }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use llm_api::{ChatLogBuilder, ChatOptions, ClientConfig, LlmClient, ParamType};
use llm_api_assembler::{assemble, assistant_turn_items, Throttle};
use llm_api_tools::{
    execute_turn, tool_response_item, CallArguments, RepairReport, Tool, ToolDefinition,
    ToolError, ToolParam, ToolRegistry,
};
use serde_json::{json, Value};

struct Forecast {
    city: String,
    days: i64,
}

struct ForecastTool;

impl ToolDefinition for ForecastTool {
    fn name(&self) -> &str {
        "forecast"
    }

    fn description(&self) -> Option<&str> {
        Some("Weather forecast for one city.")
    }

    fn parameters(&self) -> Vec<ToolParam> {
        vec![
            ToolParam::new("city", ParamType::String),
            ToolParam::new("days", ParamType::Integer).with_default(json!(3)),
        ]
    }
}

impl Tool for ForecastTool {
    type Args = Forecast;
    type Output = String;

    fn parse_arguments(
        &self,
        call: &CallArguments<'_>,
        report: &mut RepairReport,
    ) -> Result<Self::Args, ToolError> {
        // Repair first: it closes lost delimiters, fills declared defaults and
        // records every change it made in the report.
        let args = self.parse_repaired(call, report)?;
        let Some(city) = args.get("city").and_then(Value::as_str) else {
            return Err(ToolError::unrepairable(Some("city".into()), "not a string"));
        };
        let Some(days) = args.get("days").and_then(Value::as_i64) else {
            return Err(ToolError::unrepairable(Some("days".into()), "not an integer"));
        };
        Ok(Forecast { city: city.to_string(), days })
    }

    async fn execute(&self, args: Self::Args) -> Result<Self::Output, ToolError> {
        Ok(format!("{} days sunny in {}", args.days, args.city))
    }
}

#[tokio::main]
async fn main() -> Result<(), llm_api::LlmError> {
    let mut registry = ToolRegistry::new();
    registry
        .register(ForecastTool)
        .expect("a fresh registry has no duplicate name");

    let mut client = LlmClient::new(ClientConfig::new("http://127.0.0.1:8080")?)?;
    // Every chat call of this client now carries the registry's definitions.
    client.register_tools(registry.definitions());

    let mut log = ChatLogBuilder::new()
        .system("Answer a request that names a tool by calling that tool.")
        .user("Call forecast for Hannover over 5 days.")
        .finish();

    let stream = client.chat(&mut log, &ChatOptions::new()).await?;
    // Hold the handle for the whole exchange: dropping it cancels the response.
    let (mut messages, _stream) = assemble(stream, Throttle::default());

    let mut turn = Vec::new();
    while let Some(message) = messages.recv().await {
        turn.push(message);
    }

    // Lay the turn out the way `chat_once` does: the agent entry, then one
    // `ChatItem::ToolCall` per call, in the order the model made them.
    for item in assistant_turn_items(&turn) {
        log.push(item);
    }

    // Run every call the turn produced and answer each one. An answer must
    // reuse the call identifier the assembler reported.
    for outcome in &execute_turn(&registry, &turn).await {
        log.push(tool_response_item(outcome));
    }

    // The second call carries the answers; the model reads them and replies,
    // and the finished turn lands in the log as an agent entry.
    client.chat_once(&mut log, &ChatOptions::new()).await?;
    Ok(())
}

Which helper does what:

Helper Part
ToolRegistry collects your tools and builds every wire definition once
LlmClient::register_tools puts those definitions on every chat call
execute_turn parses and runs each complete tool call of the turn
assistant_turn_items appends the turn itself to the log
tool_response_item appends one answer per call, under the call's identifier

A failed call is feedable too: tool_response_item renders the tool error's message, and a model that reads required parameter city is absent can correct itself on the next turn. See defining and running tools for the repair rules, their limits and the reference-server findings.

Documentation

The user documentation is an mdbook; each page opens with a hidden comment naming the source files and symbols it is grounded in.

Build it with mdbook build docs -d docs/book.

Testing

The offline suite needs no network and no server binary:

cargo test --workspace

The gated suite runs against a real llama.cpp server and needs a llama-server binary plus a warm model cache; see the testing chapter for what it covers and how to point it at your own server.