Provider-neutral LLM requests, transcripts and responses, I/O-free
README.md

llm #

Provider-neutral values for one turn with a language model, an OpenAI-compatible chat-completions client and proxy for Eio, and the fireworks and mistral commands, which chat with the models Fireworks AI and Mistral AI serve and rewrite named sections of a Markdown document, and llm-proxy, which serves those models and a local server's to clients that hold no key, under a token budget.

llm holds checked, inert values: transcripts, requests with their options and tools, streamed events, terminal responses, token usage, classified errors and the record of a call kept in a call log, each with a JSON codec, and the agent loop as a pure state machine. It performs no I/O. A client is an injected interpreter, so a test or another transport supplies its own.

llm-eio interprets requests against any server that speaks the OpenAI Chat Completions protocol, over requests-eio. It streams the reply as server-sent events, retries a failed request within a bound (honouring the server's Retry-After), re-runs a broken stream only while no output has been shown, and classifies failures by HTTP status and the error body. Llm_eio.Fireworks points it at Fireworks AI and lists the models an account serves; Llm_eio.Mistral points it at Mistral AI and lists the models a key may use.

Llm_eio.Chat_server is the server side of the same protocol: it decodes a request body into an Llm.Request.t, the inverse of what the client sends, and encodes a response, its streamed events and an error back. Llm_eio.Proxy serves it over HTTP/1.1 (respond-eio) and answers each call through the client of the upstream that serves its model, which holds the provider's key or, for a local server, none. Its decisions are Llm.Proxy's, with no I/O: a model is routed to one upstream; a call is counted against the job its bearer token names, a token that means nothing to any provider; its ceiling (its body's bytes and its output cap) is debited from the job's and the grant's budgets before it is sent, and settled from the usage the provider reports. A request naming a model off the list, naming no job, or past a budget is refused before any call, and each call's record is built from the request decoded, which never held the key, with its job and grant.

Llm_eio.Relay is the one path that translates nothing: it relays Anthropic's messages protocol to Anthropic, each request's body and headers as they came but for the credential a caller's decide names, and each response as it came, as Anthropic's gateway guide asks a gateway in front of Claude Code to do; a caller's answered reads each response's head. claude-x relay (ocaml-claude) is such a caller.

Mistral's schema refuses any member it does not name, so a Chat_completions.Dialect says how a request is spelled for it: an earlier turn's reasoning goes back as thinking chunks of the assistant content, never as reasoning_content; a tool-call id that is not nine letters or digits, which some Mistral models refuse, is sent as one that is, the same in the call and its result; and reasoning_effort takes all seven levels, from none to max, a model refusing those it does not support. Its streams carry thinking and text chunks in an array content, tool calls whole and without an index, and arguments as an object, all of which the client reads.

Security #

Sending text to Fireworks or Mistral publishes it to a third party. Both commands refuse a file (a prompt, a system prompt, a JSON schema, rewriting instructions or a document) that lives in a git repository whose remote belongs to a private owner, including a local clone of one, unless --allow-private is given. run and eval check the directory the model works in the same way, since the model may read any file under it.

run confines the model to its directory: an absolute path, a .. segment, a symlink out of it, a .git entry and a file named like a secret (.env*, *.key, *.pem, id_rsa* and the like) are refused. A command is an argument vector the caller allows by prefix (--allow 'dune build'), never a shell string, and no argument the model adds may start with -; it runs without the variables whose names hold KEY, TOKEN, SECRET or PASSWORD. Without --unattended each write and each command is asked on the terminal first.

The API key is sent only as an Authorization: Bearer header and never printed: -v names where the key came from, not the key. A key file that its group or others may read is refused, with the chmod that fixes it.

Install #

opam install llm-eio

Usage #

Library #

A request is built and checked without a network:

# let model = Llm_eio.Fireworks.model "accounts/fireworks/models/glm-4p6" ;;
val model : Llm.Model.t = <abstr>
# let transcript = Llm.Transcript.of_list_exn [ Llm.Message.user_text "Hello" ] ;;
val transcript : Llm.Transcript.t = <abstr>
# let request = Llm.Request.v_exn ~model transcript ;;
val request : Llm.Request.t = <abstr>
# Llm.Model.id (Llm.Request.model request) ;;
- : string = "accounts/fireworks/models/glm-4p6"

Sending it with the Eio client:

let reply request =
  Eio_main.run @@ fun env ->
  Eio.Switch.run @@ fun sw ->
  let clock = Eio.Stdenv.clock env in
  let session =
    Requests_eio.v ~sw ~mono:env#mono_clock ~clock (Eio.Stdenv.net env)
  in
  let credential =
    Llm_eio.Chat_completions.Api_key.v (Sys.getenv "FIREWORKS_API_KEY")
  in
  let client = Llm_eio.Fireworks.client ~session ~clock ~credential () in
  match Llm.Client.response client request with
  | Ok r -> print_endline (Llm.Response.text r)
  | Error e -> prerr_endline (Llm.Error.message e)

Llm.Client.response ~on_event sees the reply's text as it streams, the token usage, and each retry before it is made. Llm_eio.Mistral.client is built the same way, from Llm_eio.Chat_completions.Api_key.v, for a model such as Llm_eio.Mistral.model "mistral-small-latest".

Agent loop #

Llm.Agent is a tool-using loop as a pure machine: Agent.v gives the first request, and Agent.incoming takes each response, tool result or provider failure and answers what is owed next: a request, the tool calls to perform, or the stop. The model answers by calling final_answer, whose input schema is the caller's and which the machine validates; the run is bounded by a Budget.t of requests and tokens, a cached input token weighed at its price over the uncached one (Llm_eio.Profile.cached_input). At a bound the machine asks once more, for final_answer only, and marks that answer incomplete. Agent.run drives it through a client and a function performing one call, and Llm_eio.Workspace is such a function: six tools over one directory.

let solve ~process ~clock ~client ~model root =
  let workspace =
    Llm_eio.Workspace.v ~process ~clock
      ~allow:[ Llm_eio.Workspace.Allow.v [ "dune"; "build" ] ]
      root
  in
  let answer =
    Json.Value.of_string_exn
      {|{"type":"object","properties":{"line":{"type":"integer"}},"required":["line"]}|}
  in
  let profile = Llm_eio.Profile.of_model model in
  match
    Llm.Agent.v ~model ~prelude:(Llm_eio.Profile.prelude profile)
      ~options:(Llm_eio.Profile.options profile)
      ~tools:(Llm_eio.Workspace.tools workspace)
      ~answer
      ~budget:
        (Llm.Agent.Budget.v ~steps:20 ~tokens:200_000
           ~cached:(Llm_eio.Profile.cached_input model))
      "Find the line that calls List.fold_left in a.ml."
  with
  | Error (`Msg m) -> Error m
  | Ok start ->
      let _, stop =
        Llm.Agent.run ~client ~perform:(Llm_eio.Workspace.perform workspace)
          start
      in
      Ok stop

Llm_eio.Profile.of_model is the system prompt and options a model's own agent harness uses (Mistral Vibe for mistral-large-4, Kimi CLI for Kimi K3, the vendors' guidance for GLM 5.3, DeepSeek V4 and gpt-oss), each value cited in its source.

Command line #

The fireworks and mistral commands take the same subcommands and options. The key is read from --key-file PATH, then from FIREWORKS_API_KEY or MISTRAL_API_KEY, then from $XDG_CONFIG_HOME/fireworks/token or $XDG_CONFIG_HOME/mistral/token (by default under ~/.config), which must have mode 0600. A Fireworks model is named by its resource name or, for the serverless catalogue, by its last segment; a Mistral model by its id.

$ fireworks chat -m kimi-k2-instruct "Name three moons of Jupiter."
$ fireworks chat -m glm-4p6 --system-file style.md -f draft.md --json
$ git log -1 --format=%B | fireworks chat -s "Shorten this commit message."
$ fireworks models
$ fireworks rewrite -m qwen3-235b-a22b --instructions style.md \
    --in README.md --section Overview --section Usage --out README.new.md
$ mistral chat -m codestral-latest "Write an OCaml function reversing a list."
$ mistral chat -m mistral-small-latest --reasoning-effort high "What is 17*23?"
$ mistral chat --json-schema book.schema.json "A classic French novel."
$ mistral models

chat prints the reply as it streams, or the whole response with --json, and the token usage on standard error; no price table is read, so no cost is estimated. --json-schema FILE asks for a reply valid against that JSON Schema, and --reasoning-effort LEVEL for an effort the provider takes: Fireworks takes low, medium and high, and refuses any other before sending.

rewrite sends each named section, heading and body, with the instructions, and nothing else of the document. It writes a copy in which only those sections' bodies changed, and refuses the result when a reply alters a fenced code block of its section byte for byte, adds a heading at the section's level or higher, or leads to any change outside the named sections.

--base-url URL sends the requests to another OpenAI-compatible server.

run gives the model a brief and tools over a directory, performs the calls it makes, and prints the answer it submits as JSON; each call is shown on standard error, then the requests and the tokens spent. It stops at the answer; at --max-steps requests or the --budget of tokens, after asking once for the answer so far, which it prints; on a second reply in a row cut at --max-output-tokens, or on a provider failure, and exits 0 only on an answer. --answer-schema FILE is the answer's JSON Schema. --generic replaces the model's profile with one common to all.

$ mistral run -m mistral-large-4 --dir . --allow 'dune build' \
    --allow 'dune test' --unattended "Make the failing test pass."
$ fireworks run -m glm-5p3 --answer-schema folds.schema.json \
    -f brief.md --dir src

eval runs the agent on cases and grades each trial in code. A case is a directory holding tree/, copied fresh for each trial, and case.json: the brief, the answer schema, and optionally context (files of the tree appended to the brief), expect (a JSON Schema the answer must satisfy), allow, check (a command that must succeed in the tree afterwards), steps and tokens. It prints each trial as a JSON line, then per case the passes, the mean input and output tokens, steps and seconds. The package's own cases are in eval/.

$ mistral eval -m mistral-large-4 --repeat 3 --trials trials.jsonl eval/*

llm-proxy answers POST /v1/chat/completions and GET /v1/models on an address, for the models named and no other, each sent to its upstream: mistral and fireworks with the key their own commands read, and any other name an OpenAI-compatible server that takes no key, such as a local llama-server, at the URL given. Each call is counted against the job its Authorization: Bearer token names and spends under one grant: --budget tokens for every job together and --job-budget for each, its ceiling debited before the call and settled from its usage. A request with no max_tokens is sent with --max-output-tokens (32768) or what its job has left, whichever is less. With --call-log, each record carries the job and the grant, and the records of the grant already in the log are counted at the start, so a restart spends nothing twice. A request member the request values cannot carry (n, stop, top_p and the rest) is refused, naming it. What a client can make it spend: a decode linear in the body, held whole up to --max-body bytes (4 MiB) and refused beyond; one call at a time per connection, at most --max-connections (16); and upstream, the tokens the grant holds, which any client that reaches the proxy may spend under any job name.

$ llm-proxy --listen 127.0.0.1:8443 --upstream mistral \
    --upstream local=http://127.0.0.1:8080 \
    -m mistral:mistral-small-latest -m local:qwen3 \
    --budget 2000000 --job-budget 200000 --call-log calls.jsonl
$ MISTRAL_API_KEY=job-1 mistral chat --base-url http://127.0.0.1:8443 "Hi."

--call-log FILE appends the record of each request to FILE, one JSON line per request, whether it succeeds or fails; rewrite makes one request per section. The format is the call log's. A log that cannot be opened stops the command before any request.

Call log #

A call log is the evidence a client keeps of each model call, read routinely to tune how models are used and to catch a call that went wrong without failing: a tool server that never connected, a model other than the one asked for, retries that doubled the latency. It is a file of Llm.Call.t records, one JSON object per line. Every client that keeps one writes this format, so one report reads the logs of all of them. A record holds no prompt, answer or tool text: a tool use keeps the MD5 and the size of its input, and a caller that stores prompts elsewhere names one with prompt_digest.

Member Type Meaning
provider string the provider called, such as anthropic or mistral
client string the program or library that made the call
client_version string, optional its version
model string, optional the model asked for; absent for the client's default
served_model string, optional the model that answered
session_id string, optional the client's conversation id
response_id string, optional the provider's response id
prompt_digest string, optional the digest of a prompt stored elsewhere
job string, optional the job a proxy counted the call against
grant string, optional the grant the call was spent under
started_ms integer when the call started, in Unix milliseconds
duration_ms integer how long it took, in milliseconds
first_output_ms integer, optional how long after the start the first text, reasoning or tool call arrived
tools strings the names of the tools the model was offered
servers objects each tool server configured: name, source (optional), status
tool_uses objects each tool call the model made, in order
turns integer the number of model turns
retries integer the number of retried provider requests
stop string, optional the normalized stop reason: end_turn, tool_call, length, content_filter, refusal or another word
provider_stop string, optional the provider's own stop label or result subtype
usage object, optional tokens, in disjoint lanes: input, output, reasoning, cache_read, cache_write
cost_usd number, optional the cost in US dollars, when the provider reports one
error object, optional the failure that ended the call: kind, phase, message, and optionally provider, status, request_id, redacted_body

A server's status is connected, failed, needs_auth, pending, disabled, missing (configured, and reported by nobody) or another lowercase word. A tool use has a name and an outcome: ok, error, or unknown when no result was seen. It may add id, input_md5 with input_bytes, result_bytes and duration_ms. Optional members are omitted when absent, the lists are read as empty when absent, and a reader refuses a member the schema does not name.

This record is of a call whose in-process tool server came up failed, so the model answered without the server's tool:

let line =
  {|{"provider":"anthropic","client":"claude-code","client_version":"2.1.318","model":"claude-sonnet-4-5","started_ms":1762387200000,"duration_ms":41250,"tools":["Read"],"servers":[{"name":"journal","source":"sdk","status":"failed"}],"tool_uses":[],"turns":1,"retries":0,"provider_stop":"success","usage":{"input":12,"output":850,"reasoning":0,"cache_read":40210,"cache_write":3400},"cost_usd":0.25}|}
# let call = Json.of_string_exn Llm.Call.jsont line ;;
val call : Llm.Call.t = <abstr>
# List.map Llm.Call.Server.name (Llm.Call.unconnected call) ;;
- : string list = ["journal"]

Llm.Call.record sends a request through a client and returns its record with the result. Llm.Call.recording wraps a client so that each request it interprets hands its record to a callback. A client driven over another protocol, such as an agent command-line tool that runs several turns and its own tools, builds its records with Llm.Call.v.

Accounts #

The llm-eio.accounts library lists the accounts of a vendor's command-line tool, one per configuration directory (~/.STEM is default, ~/.STEM-NAME is NAME), the allowance windows each has left, and ranks them by deadline, behind the shared commands account list, account show, usage, pick, env and run. Where a vendor mints headless tokens, token add and token remove keep one per account in the tool's store, $XDG_CONFIG_HOME/TOOL/tokens/NAME.token, and account list shows each one's expiry. An account's allowance is lost at the reset of its longest window, its week, so of the accounts with headroom now the one whose week ends first is the one to spend; --at TIME ranks as at another time. A vendor supplies a Provider.S: codex-x (ocaml-codex) applies it to Codex CLI and claude-x (ocaml-claude) to Claude Code.

Tests #

The codec tests decode the examples of the Fireworks API reference, copied verbatim. The client is tested against a local fake of the API, the rewrite against an injected client. The Mistral cases replay streams recorded from its API by an independent client and error bodies recorded by others, each cited. Interop traces of the live Mistral API, recorded with curl, are replayed through the client; two turns of an agent loop replay through Llm.Agent.run once recorded, and those of Fireworks are not recorded. The agent loop is tested by feeding its machine responses and results by hand, and its Fsm description is settled; the workspace's tools run on a temporary directory. Either is recorded by REGEN=1 dune build @traces with FIREWORKS_API_KEY or MISTRAL_API_KEY set.

License #

ISC. See LICENSE.md.