llmwire

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 28 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

llmwire

A dependency-light Go library for talking to OpenAI-compatible inference endpoints — chat, tools, vision and embeddings — with each model's quirks kept as data rather than scattered through call sites. It is an adapter over model dialects, not over wire protocols: one request contract, one protocol, and the per-model bends live in profiles.yaml.

// The host comes from the model's profile (profiles.yaml carries each
// vendor's base URL); the key from LLMWIRE_<PROVIDER>_API_KEY, the provider
// named by the profile (zai here, mimo and openai for the others). An
// application configures a key and nothing else; a LLMWIRE_<PROVIDER>_BASE_URL
// beside a shipped host is refused as the old contract. New(Config{...}) is
// there for a custom transport or an explicit URL.
client, err := llmwire.FromEnv("glm-5.3-flash", llmwire.Config{})
if err != nil {
    return err // names the missing variable
}

resp, warnings, err := client.Chat(ctx, llmwire.ChatRequest{
    Model:     "glm-5.3-flash",
    Messages:  []llmwire.Message{llmwire.System("..."), llmwire.User(q)},
    Reasoning: llmwire.ReasoningEffort("high"),
    MaxTokens: &cap,
})

Streaming is an iterator, so an early return closes cleanly and the usage that only arrives in the final chunk has somewhere to live:

stream, warnings, err := client.ChatStream(ctx, req)
if err != nil {
    return err
}
defer stream.Close()

for stream.Next() {
    if ev := stream.Event(); ev.Kind == llmwire.EventContent {
        fmt.Print(ev.Text)
    }
}
if err := stream.Err(); err != nil {
    return err
}
cost := stream.Usage().Cost
ttft := stream.Result().Timing.FirstData // also Headers and Total, on every response

Why

Every OpenAI-compatible endpoint bends the protocol somewhere, and the bends are not discoverable from the spec:

  • mimo-v2.5-pro takes max_completion_tokens; glm-5.3-flash takes max_tokens.
  • mimo-v2.5-pro returns 404 for any image_url part. Its sibling mimo-v2.5 does not.
  • On glm-5.3-flash, a prompt that says "reply as JSON" parses 0 times out of 8; the same prompt with response_format parses 8 out of 8.
  • gpt-5.x rejects a non-default temperature outright, with a 400.
  • Some models cannot turn reasoning off at all.

Hard-coding those into one application means the next application relearns them — usually in production. llmwire keeps them in a profile registry so a wrong assumption fails locally, before the request is sent.

What it does

Fails fast on an impossible request. Ask a model to disable thinking when it cannot, and you get an error before a socket is opened, naming what is accepted:

llmwire: model "glm-5.3-flash": thinking cannot be disabled on this model;
         accepted: low, high, max; or pass BestEffort to send the nearest supported request

Validate(req) is exported and needs no network, so a service can check its configuration at boot.

Three tiers, by how lossy the fix is. A hard error when semantics would change and you asked explicitly. A silent coercion when it is lossless (max_tokens → max_completion_tokens). A coercion plus a returned Warning when the request can be honoured approximately (json_schema → json_object). Setting BestEffort on the request demotes the first tier to the third for a single call.

Reports what a call cost. Usage is captured with its cache and reasoning lanes broken out, and priced per call with the model that actually ran, in integer nano-USD. The rate is a function, not a constant: it varies by request size (long-context surcharges) and by wall-clock time (off-peak windows, evaluated in the provider's own timezone). Figures are always the vendor's published pay-as-you-go rate — a comparable equivalent, not an invoice, since a call routed over a subscription host is billed in plan credits nobody can compare across models. Behind a gateway the cost is what the proxy reports, on usage.cost in the body first and in its response header second, or nothing at all. A rate we have not verified reports Unpriced and warns, because zero means unknown, not free. What else the proxy said rides on ChatResponse.Gateway / StreamResult.Gateway / EmbedResponse.Gateway: the call id it logged under, the deployment that really ran, the key's cumulative spend (a gauge, never summed) and the cost header verbatim, so an unpriced call can be matched to the gateway's own log.

Recovers tool calls a model wrote as markup. Some deployments answer with <tool_call>…</tool_call> blocks (or an invented <tool_invocation …/>) in the content instead of the native tool_calls field, on tool-free calls too. A profile with tools.recover_inline_markup has that markup withheld from streamed deltas, the calls surfaced as tool-call events (name first, arguments when they land, EventFinish last) and cut from the returned text, with a Warning saying what was recovered or that text was cut with nothing coming out of it. The returned text is what streamed: everything from the first marker on is gone.

Shows what the endpoint really sent. NewSpoolTransport(dir, next, skip) is an http.RoundTripper that writes every response — status line, headers, body as read, a truncated stream included — to one .http file per call. Hand it to Config.HTTPClient while diagnosing; skip keeps a request the caller promised to keep ephemeral off disk.

Handles the stream cases that bite. Separate header / idle / whole-call bounds, and a failure says which one fired. Completion is asserted by [DONE] or finish_reason, never inferred from a clean EOF — a connection dropping mid-answer looks exactly like a finished one. An error frame arriving inside a 200 stream is surfaced rather than read as an empty answer.

Can present as opencode. Some endpoints are sold as one client's backend and treat a neutral User-Agent as a bot. A provider marked emulate_opencode in profiles.yaml gets opencode's client string and its session header pair from FromEnv; LLMWIRE_EMULATE_OPENCODE=1 (global, default off) does the same for a provider the file does not mark; a client built with an explicit Config.BaseURL sets EmulateOpenCode: true by hand. Headers only, never a request body. The session id is the client's own — minted at construction, rotated after a 30-minute idle gap, the way a person's session starts and ends — and there is deliberately no way to supply one.

Reports every call, never its text. Config.Logger (slog; slog.Default() when nil, so the line is JSON or text as the process already logs) gets one line per call: what went on the wire (message and tool counts, cap, sampling, reasoning), what came back (finish_reason, content and reasoning lengths, tool calls), tokens per lane (input, cache read, cache write, output, reasoning), cost_usd with its provenance, headers_ms/first_data_ms/ total_ms, output tokens per second, warnings. Debug when it worked; Warn when it failed (with the bound or status that ended it) or when the answer needs a look: cut by the output cap, empty on a stop, no usage reported. Client.Stats() returns the same figures summed per model since New, with unpriced and unreported calls counted apart so a low total is never read as cheap; it is a slog.LogValuer, for a shutdown summary. Prompt, answer and key never appear.

Lists what the key may use. ListModels(ctx) is GET {base}/models, one row per id with the gateway's own max_input_tokens / max_output_tokens as *int64 (nil when the endpoint does not carry them) and the raw object for the rest. Behind LiteLLM the listing is the key's own model set, so it doubles as the access check, and a gateway that caps a deployment below the vendor's window says so here and nowhere else. A limit present but unusable is a Warning, not a failed listing.

Carries the small helpers every consumer was copying. Stream.Collect(onDelta) drains a stream into its result. JSONObject(s) cuts the first brace-balanced object out of a reply that was asked for JSON and came back fenced or wrapped in prose. Registry.LookupEmbedding(id) is Lookup that refuses a chat model, for an embeddings client built from a constant. Redact and Truncate are exported for the same reason.

Swapping a model is config

A client says what it wants; the profile says what that is on the model at hand. Nothing below names a level, a cap spelling or a host:

// One client, each model on its own provider's host and key. Every missing
// LLMWIRE_<PROVIDER>_API_KEY is named in one error; an unlisted model is a
// *ModelNotConfiguredError.
client, err := llmwire.FromEnvModels(llmwire.Config{}, cfg.ChatModel, cfg.VisionModel, cfg.EmbedModel)

// Boot check: the vision lane needs images and tools. The error names the gap
// and the registered models that would do (Registry.ChatModels(needs)).
_, err = client.Registry().Require(cfg.VisionModel, llmwire.Needs{Vision: true, Tools: true})

n := 64
resp, _, err := client.Chat(ctx, llmwire.ChatRequest{
    Model:           cfg.ChatModel,
    Messages:        msgs,
    Reasoning:       llmwire.ReasoningMinimal(), // or ReasoningBalanced()
    MaxAnswerTokens: &n,                         // answer; reasoning allowance added
})
log.Print(resp.ReasoningSent) // "off", "low", "medium", "budget:256", or "" (default)
  • ReasoningMinimal(): off where the model can be disabled, else its shallowest effort_values entry, else reasoning.min_budget; nothing on a model that does not reason. ReasoningBalanced(): reasoning.balanced, else the model's default. Both validate and render exactly as what they resolve to.
  • MaxAnswerTokens: the wire cap is the answer plus reasoning.overhead for the resolved level (DefaultReasoningOverhead = 1024 where unmeasured, 0 with thinking off, the budget itself on a budget), clamped to max_output. Refused beside MaxTokens.
  • Profile.DisplayName is the human label; Profile.Streaming.BuffersToolArgs says when to widen ToolCallIdleTimeout.
  • ForModel(id) is the one-host client for ListModels and the raw calls.

Tests in a consuming module use llmwiretest: Registry() holds the synthetic ChatModel / EmbedModel, and NewServer(t) is a recording fake (srv.Client(), or Config{Registry: llmwiretest.Registry(), Lookup: srv.Lookup} for code that calls FromEnvModels). Assert srv.Last().Reasoning() against llmwiretest.MinimalSent and srv.Last().MaxTokens() against n + llmwiretest.MinimalOverhead: intent, not a vendor's spelling.

Scope

One wire protocol: /chat/completions and /embeddings. llmwire adapts models within that protocol; it does not abstract over protocols. Anthropic, Gemini-native and Bedrock are permanently out of scope — supporting a second protocol would require the provider abstraction this library exists to avoid.

Also out of scope, by design: vector stores, chunking, embedding caches, retry policy and prompt content. llmwire never retries; it parses Retry-After into a typed error and leaves the decision to you, because a library-level retry turns a transient outage into a permanent failure for a whole job queue.

Adding a model

Add an entry to profiles.yaml and run the evals against it; ONBOARDING.md is the step-by-step procedure, including which probe establishes which field and what to record where. A model's behaviour is never inferred from its name — ids are matched exactly, and an unknown id is an error rather than a silent set of defaults.

- id: mimo-v2.5-pro
  endpoint: chat
  max_tokens_param: max_completion_tokens  # verified live: a cap of 8 returned
                                           # exactly 8, finish_reason=length
  reasoning:
    supported: true
    enabled_by_default: true               # thinking defaults ON
    can_be_disabled: true
    control: toggle_object                 # thinking:{type}, not reasoning_effort
    stream_field: reasoning_content
  vision: false                            # 404s on any image_url part
  cost:                                    # USD per 1M tokens, the vendor's own
    input: 0.435                           # decimals, converted exactly from text
    cache_read: 0.0036
    cache_write: 0                         # "limited-time free" as of verified_on
    output: 0.87
    source_url: https://mimo.mi.com/docs/en-US/price/pay-as-you-go
    verified_on: 2026-09-12

All four chat lanes are required, or the block is left out entirely and the model reports Unpriced: a lane falling back to another lane's rate would be a call-site default, and this registry resolves everything at load.

A toggle model may also list effort_values: MiMo takes reasoning_effort beside its thinking switch, so ReasoningEffort("high") renders the level and ReasoningOff() renders the toggle. effort_values are listed shallowest first (checked against a fixed depth ladder at load), balanced names one of them, and overhead maps a level (or off, default) to measured reasoning tokens.

enabled_by_default and can_be_disabled are deliberately separate flags. "Can this model turn reasoning off" is not answerable from whether none appears in a list of effort levels — inferring it is how published model catalogues get it wrong.

Behind a gateway

A gateway is a deployment, not a model: its URL, its key and the names it serves models under belong to whoever runs it, so they are environment, never profiles.yaml. Three variables, read by FromEnv:

LLMWIRE_LITELLM_BASE_URL=https://ai-gateway.example/v1
LLMWIRE_LITELLM_API_KEY=<the gateway's key>
LLMWIRE_LITELLM_MODELS=gpt-5.4-mini=ai-gateway-gpt-5.4-mini,text-embedding-3-small

The URL passes the same checks a shipped host does: https, a bare root with no query string or credentials, no route suffix. Plain http:// is accepted for localhost, 127.0.0.1 and ::1 only, where the key never crosses a wire; a gateway on any other host needs TLS in front of it.

LLMWIRE_LITELLM_MODELS lists which profiles the gateway serves, as <profile id>[=<name on the gateway>]; a bare id means the gateway takes the public name. An application keeps asking for gpt-5.4-mini; a listed model is built as a route to the gateway under its alias, an unlisted one reaches its vendor as before. The left-hand side must be a profile id, because that is the model the route inherits from: every capability, every parameter rule.

A route carries no cost block and inherits none: the proxy reports real per-call spend (on usage.cost, or in a response header for a non-streamed call), and it knows which deployment ran and at what discount, where this table does not. Nothing reported, no price — never a list rate standing in for one.

Because the route names its model, validation still works behind a proxy whose wire id is opaque: a Temperature of 0.3 is rejected locally, since gpt-5.4-mini rejects it. The same shape can be written into a profile document by hand (base + gateway + provider + wire_model_id); the variable builds it in memory.

Evals

Profile data is verified against live endpoints, not taken from documentation — published catalogues disagree with each other and with the endpoints.

LLMWIRE_EVAL=1 go test -run Probe ./...

Evals skip unless that variable is set, so they never run in CI. With it set, the harness loads a gitignored .env (see .env.example for the names; a value already in the environment wins). They call real, paid endpoints, so the suite is bounded by a spend budget, a call ceiling, a wall-clock deadline and minimal per-call caps, all fail-closed. It does not retry: a failed eval is a finding, not a flake.

Development

The gate is ship, configured in ship.yaml:

ship() { go run "github.com/trick77/ship@$(git ls-remote https://github.com/trick77/ship refs/heads/master | cut -f1)" "$@"; }
ship hooks   # once per clone: the pre-push hook runs ship check on every push
ship check   # gofmt, build, golangci-lint, secret scan, go test -race, coverage

Keys are read from the environment only. .env is gitignored, and scripts/secret-scan.sh refuses keys and .env files entering the tree — a step of ship check, so it runs on every push from a clone with ship hooks and in CI when dispatched by hand.

Licence

MIT.

Documentation

Overview

Package llmwire is a dependency-light client for OpenAI-compatible inference endpoints — chat, tools, vision and embeddings — with each model's quirks held as data rather than scattered through call sites.

It speaks exactly one wire protocol: POST {base}/chat/completions and POST {base}/embeddings. Anthropic, Gemini-native and Bedrock are out of scope permanently; supporting a second protocol would require the provider abstraction this package exists to avoid.

This file is the transport. It knows nothing about model profiles: it takes a request body already built, sends it, and returns what came back. Profile lookup, validation and pricing sit above it.

Index

Examples

Constants

View Source
const (
	// DefaultHeaderTimeout is how long the endpoint may take to send response
	// headers. Generous, because it competes with nothing — a stall costs a
	// minute rather than the whole call budget.
	DefaultHeaderTimeout = 60 * time.Second
	// DefaultIdleTimeout is how long a started stream may go without a data
	// frame. Note that comment and blank lines do NOT re-arm this; see
	// readStream.
	DefaultIdleTimeout = 90 * time.Second
	// DefaultCallTimeout is the backstop for a stream that stays alive forever
	// without finishing — dribbling frames past any sane answer length.
	DefaultCallTimeout = 15 * time.Minute
)

Bounds.

Three separate timeouts replace the single whole-request timeout these clients usually carry. That one timeout has to cover both "the endpoint never answered" and "the model is thinking hard", so it can only ever be wrong for one of them — and when it fires, minutes in, the log cannot say which happened. Splitting them makes each failure nameable.

http.Client.Timeout is deliberately NOT set anywhere in this package: it caps body reads too, so it would cut a legitimately long stream mid-answer.

View Source
const (
	HeaderSessionID       = "X-Session-Id"
	HeaderSessionAffinity = "X-Session-Affinity"
)

The two headers opencode sends, both carrying the same id. The upstream sends the pair back too; "affinity" is what it is for — pinning the many calls one session makes to a single upstream node.

View Source
const (
	VerifiedMeasured = "measured"
	VerifiedSource   = "source-derived"
)

Valid values for Verified.

View Source
const (
	ParamMaxTokens           = "max_tokens"
	ParamMaxCompletionTokens = "max_completion_tokens"
)

Wire names for the two output-cap parameters.

View Source
const DefaultReasoningOverhead = 1024

DefaultReasoningOverhead is the reasoning allowance MaxAnswerTokens adds for a thinking request whose level has no reasoning.overhead entry. A budget, not a measurement: the one measured point is that 1024 was NOT enough at glm-5.3-flash's deepest level, which spent a 1024-token cap on reasoning and returned no content. A profile with a measured figure overrides it per level.

View Source
const DefaultUserAgent = "llmwire/0.1 (+https://github.com/trick77/llmwire)"

DefaultUserAgent is what this package sends when Config.UserAgent is empty.

View Source
const EmulateOpenCodeEnv = "LLMWIRE_EMULATE_OPENCODE"

EmulateOpenCodeEnv is the variable FromEnv reads to present as opencode on a provider profiles.yaml does not mark. Global, not per provider; boolean per strconv.ParseBool; unset or false leaves the provider's own setting in place. It adds the identity, never removes it.

View Source
const GatewayModelsEnv = "LLMWIRE_LITELLM_MODELS"

GatewayModelsEnv lists the profiles a self-hosted gateway serves, and under which names. Comma-separated `<profile id>[=<name on the gateway>]`; a bare id means the gateway takes the public name unchanged. A listed profile is reached through the litellm provider (LLMWIRE_LITELLM_BASE_URL and LLMWIRE_LITELLM_API_KEY), an unlisted one through its own vendor as before.

The names are the operator's, never the library's: a gateway is a deployment, its aliases are that deployment's, and putting them in profiles.yaml would publish one company's proxy layout as everyone's. What the library owns is the model behind the alias, which is why the left-hand side must be a profile id: the route inherits that profile's capabilities and validates against them, exactly as a YAML route does.

View Source
const OpenCodeUserAgent = "opencode/1.18.11 ai-sdk/openai-compatible/2.0.41 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14"

OpenCodeUserAgent is the client string opencode sends: the app, the SDK that built the request, and the runtime it ran on. Pinned to one release rather than tracking opencode's, since the point is a plausible client, not the latest one.

The four tokens must come from ONE opencode release, or the string is a version mix no real client has ever sent. Where each comes from, at the pinned tag of github.com/anomalyco/opencode:

opencode/<v>                   packages/opencode/src/session/llm/request.ts, USER_AGENT
ai-sdk/openai-compatible/<v>   bun.lock, the packages/opencode entry for @ai-sdk/openai-compatible
ai-sdk/provider-utils/<v>      bun.lock, the packages/opencode entry for @ai-sdk/provider-utils
runtime/bun/<v>                package.json, packageManager

The order is the SDK's: the openai-compatible provider appends its own token to opencode's, then provider-utils appends its version and the runtime (navigator.userAgent lowercased) as it sends the request.

Variables

View Source
var (
	// ErrRateLimited is a 429 from any layer — the model, the gateway's own
	// key limit, or a budget cap. A typed *RateLimitError carries Retry-After
	// when the endpoint sent one.
	ErrRateLimited = errors.New("rate limited")
	// ErrAuth is a 401/403.
	ErrAuth = errors.New("authentication failed")
	// ErrBadRequest is a 4xx that is neither of the above: a rejected
	// parameter, an unknown model, a context overflow.
	ErrBadRequest = errors.New("bad request")
	// ErrUpstream is a 5xx, or a transport failure with no status at all.
	ErrUpstream = errors.New("upstream failure")

	// ErrMalformedResponse is a 2xx whose body could not be read as an answer
	// — an HTML error page from a proxy, a stream that ended without
	// finish_reason or [DONE]. The wrapped error carries the decoder's own
	// complaint and, for a body, a redacted and bounded slice of it.
	ErrMalformedResponse = errors.New("malformed response")
	// ErrResponseShape is a 2xx that decoded but does not answer the request:
	// no choices and no error object, the wrong number of embeddings, an
	// embedding index outside or repeated within the batch. Distinct from
	// ErrMalformedResponse because a caller retries the two differently — a
	// proxy page is transient, a shape the endpoint chose to send is not.
	ErrResponseShape = errors.New("response shape")

	// The three bounds this package enforces on a call, so a caller can act
	// on which one gave up without matching the message. Each is wrapped by
	// the error that names the duration: "llmwire: stream idle for 1m30s".
	//
	// ErrNoResponseHeaders: the endpoint sent nothing within the header bound
	// (HeaderTimeout on a stream; the call cap on a non-streaming call, which
	// withholds headers until the whole answer is ready).
	ErrNoResponseHeaders = errors.New("no response headers")
	// ErrStreamIdle: a started stream sent no data frame for IdleTimeout (or
	// the request's ToolCallIdleTimeout once a tool call was underway).
	ErrStreamIdle = errors.New("stream idle")
	// ErrCallCap: the whole call outran CallTimeout.
	ErrCallCap = errors.New("exceeded the call cap")
)

Sentinel errors for the failure classes a caller acts on differently. Compare with errors.Is; the concrete *APIError is still available via errors.As when the status, code or param matter.

Functions

func JSONObject added in v0.0.18

func JSONObject(s string) (string, bool)

JSONObject returns the first JSON object in s, or false when there is none. It is the salvage step before json.Unmarshal on a reply that was asked for JSON: models fence it in ```json, lead with "Sure, here it is:", or trail a sentence after the closing brace, and every consumer was carrying its own strip-the-fence helper — three of them in one program, each slightly different.

Each '{' is tried as a start, the candidate is cut where its braces balance (string-aware: a brace inside a JSON string does not count, an escaped quote does not close the string), and the first candidate that is valid JSON wins. Trying every start is what survives prose that mentions a brace before the object — `wrap it in {braces}: {"a":1}` yields the second. It is the FIRST object, not first-brace-to-last-brace: a reply offering two parses on the first, where the widest cut includes the prose and fails. What it does not do is repair: an unbalanced object is reported as none, and the caller's parse failure path is the right place for that.

Consider ChatRequest.ResponseFormat first. On one model a prompt asking for JSON parsed 0 times out of 8 and the response format 8 out of 8 — but a fenced reply still arrives with the format set on some endpoints, so the salvage stays useful behind it.

func Redact

func Redact(s string) string

Redact removes anything shaped like a credential from a string bound for a log, an error, or a committed findings note. It is applied at construction time rather than at print time: a value that is never redacted until it is printed is one Printf away from a leak.

func RedactURL

func RedactURL(raw string) string

RedactURL renders a URL as scheme://host/path, dropping the query and any userinfo. Used wherever an endpoint is named in an error or an observation: the host and path are what identify a deployment, and the query is where a credential hides.

func Tokens added in v0.0.21

func Tokens(lane *int64) int64

Tokens reads one lane for a log line or a running total: the count, or 0 when the endpoint did not report it. The pointer exists so that "not reported" and "reported zero" stay distinct — a consumer that needs the distinction checks nil or Reported() itself; one that is about to print or sum the number does not, and every such consumer was carrying its own three-line copy of this. Exported for the same reason Truncate is.

func Truncate added in v0.0.13

func Truncate(s string, max int) string

Truncate caps a string at max bytes, cutting on a rune boundary and marking the cut. Byte-offset truncation would split a multi-byte character and put invalid UTF-8 in the log, which is not hypothetical: these endpoints return non-ASCII error text routinely (see the Chinese 1210 body above). Exported for the same reason Redact is: every consumer logging a raw usage object or an error body needs exactly this and was carrying its own copy.

func Warnings added in v0.0.4

func Warnings(ws []Warning) string

Warnings renders a list for a log line, sorted so the output is stable.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status, or 0 for an error object inside a
	// SUCCESSFUL response: a 2xx whose body is {"error":…}, or an error frame
	// in a stream. A dial or TLS failure and a stall guard firing are not
	// APIErrors; they carry no body to decode.
	StatusCode int
	// Code is the provider's own error code, ALWAYS held as a string. MiMo and
	// LiteLLM send it as a JSON string; Z.ai's schema declares it an integer
	// and its live bodies send a string. Keeping one Go type for both means
	// call sites compare against "1210", never against two spellings.
	Code string
	// Type is OpenAI's error type ("invalid_request_error", …) when present.
	Type string
	// Param names the request field the endpoint objected to, when it says.
	Param string
	// Message is the human-readable text, already redacted.
	Message string
	// Class is the sentinel this error matches, for errors.Is.
	Class error
}

APIError is a decoded error response. Every field is best-effort: endpoints populate different subsets, and an absent field must read as "not reported" rather than as an empty value that means something.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is lets errors.Is(err, ErrRateLimited) and friends work against the class the status mapped to.

type CapabilityError added in v0.0.39

type CapabilityError struct {
	Model   string
	Missing []string
	// Satisfying is every chat model in the registry that meets the same
	// Needs, sorted.
	Satisfying []string
}

CapabilityError is a model that cannot fill a role: which model, what it lacks, and which registered chat models would do, so a boot error reads as the fix.

func (*CapabilityError) Error added in v0.0.39

func (e *CapabilityError) Error() string

type ChatRequest added in v0.0.4

type ChatRequest struct {
	// Model is a registry id, matched exactly.
	Model    string
	Messages []Message

	Reasoning   ReasoningRequest
	Temperature *float64
	TopP        *float64
	// MaxTokens caps the completion. Written once here; the profile decides
	// which wire parameter carries it, because the two spellings are not
	// interchangeable and one endpoint accepts the wrong one and ignores it.
	MaxTokens *int
	// MaxAnswerTokens caps the visible answer instead of the whole completion.
	// The cap sent is this plus the reasoning overhead of the request as
	// resolved (Reasoning.Overhead, DefaultReasoningOverhead where the profile
	// has no figure for the level, 0 with thinking off), clamped to the model's
	// max_output. Setting it beside MaxTokens is refused.
	//
	// Exists because the completion cap counts reasoning: a 1024-token cap at
	// glm-5.3-flash's deepest level returned zero content characters.
	MaxAnswerTokens *int

	Tools      []Tool
	ToolChoice ToolChoice

	ResponseFormat ResponseFormat

	// Stop sequences. Always sent when non-empty: no profile in the registry
	// records an endpoint refusing them, so there is no capability to gate on.
	Stop []string

	// ExtraBody is merged into the request body verbatim, for the long tail of
	// provider-specific parameters this package does not model. Keys collide
	// with generated ones at the caller's risk: they win, deliberately, since
	// the point is to reach something the package does not know about.
	//
	// Four keys are refused by plan rather than merged, because each would
	// make the body lie about itself: "stream" and "stream_options" (the
	// method called and the profile decide them), "model" (the route decides
	// what goes on the wire) and the output-cap spelling this model does NOT
	// take (the one an endpoint accepts and silently ignores).
	ExtraBody map[string]any

	// ToolCallIdleTimeout replaces the client's IdleTimeout for the rest of a
	// streamed call once the first tool-call fragment has arrived, or once
	// inline markup has been seen. Zero leaves the idle bound as it is.
	//
	// The only per-request bound, because it answers a per-request question.
	// A model whose profile sets Streaming.BuffersToolArgs does not stream
	// tool-call arguments incrementally: it emits the name, goes silent while
	// it serializes the whole argument server-side, then flushes it in one
	// burst, past any idle bound sized for prose (profiles.yaml has the
	// measurement). Which calls can carry such an argument depends on which
	// tools the request offered, so the caller widens only those and keeps the
	// narrow bound for every other turn. The whole-call cap stays the backstop.
	ToolCallIdleTimeout time.Duration

	// BestEffort demotes what would be a hard error into a coercion plus a
	// Warning, for one call. Deliberately per-request rather than a package
	// global: a process-wide switch is a landmine, because the call that
	// silently changes behaviour is never the one that set it.
	BestEffort bool
}

ChatRequest is one completion request, before profile resolution.

Pointers where "unset" and "zero" differ: a temperature of 0 is a real request, and so is a MaxTokens the caller deliberately left alone.

type ChatResponse added in v0.0.4

type ChatResponse struct {
	Content   string
	Reasoning string
	ToolCalls []ToolCall
	// FinishReason is the endpoint's own string, treated as an open set.
	FinishReason string
	Usage        Usage
	// Model is what actually ran, which behind a gateway is not what was asked
	// for: the response body carries the alias, and the real deployment is only
	// in a header.
	Model string
	// Raw is the undecoded response, kept for fields this package does not model.
	Raw    json.RawMessage
	Timing Timing
	// Gateway is what the proxy said in its headers: call id, deployment, key
	// spend, the cost text. Empty on a direct route.
	Gateway Gateway
	// ReasoningSent is the reasoning knob this call put on the wire, intents
	// resolved: "off", an effort level, "budget:<tokens>", or "" when nothing
	// was sent and the model ran at its own default. Named by wire meaning:
	// effort "none" and a zero budget are the off switch and read "off".
	ReasoningSent string
}

ChatResponse is a completed non-streaming turn.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a transport for one endpoint.

func FromEnv added in v0.0.12

func FromEnv(model string, cfg Config) (*Client, error)

FromEnv builds a Client for one model. The host comes from the profile's provider (profiles.yaml providers:), the key from the environment variable that provider implies, LLMWIRE_<PROVIDER>_API_KEY. An application supplies a key and nothing else; the URL is the library's to know, so it is not repeated in every application's configuration. cfg.Lookup replaces the process environment as the source.

LLMWIRE_<PROVIDER>_BASE_URL exists only for a provider that ships no host (a self-hosted gateway): there it is required, and unset is a MissingEnvError naming it. For a provider that ships a host the variable is REFUSED with a StaleEnvError: the host is the library's, and an application still carrying one is on the old contract, where every deployment copied the URL. Accepting it as an override would let that copy live on unnoticed and diverge; a different host is a different provider entry.

A cfg.BaseURL already set means the caller is wiring the endpoint itself, and no variable is consulted at all: cfg.APIKey goes as given, empty included. The provider's key belongs to the provider's host, and a test fake or a stand-in endpoint must not be handed it just because the model is the same. With cfg.BaseURL empty, a cfg.APIKey already set still wins over the variable.

A key variable that is unset or empty is a MissingEnvError, never a fallback. A profile with no_api_key sends no key at all, which is the self-hosted case.

A provider marked emulate_opencode in profiles.yaml gets Config.EmulateOpenCode set here, which replaces a cfg.UserAgent the caller supplied: on such a host the caller's own string is exactly what gets refused. EmulateOpenCodeEnv set true does the same for any provider, marked or not: a gateway fronting such a host is not in profiles.yaml, and the operator running it knows. A value that is not a boolean is an error, never ignored.

func FromEnvModels added in v0.0.39

func FromEnvModels(cfg Config, models ...string) (*Client, error)

FromEnvModels builds one Client serving exactly the models named, each reached the way FromEnv would reach it: host from its provider (or LLMWIRE_<PROVIDER>_BASE_URL where the provider ships none, refused where it does), key from LLMWIRE_<PROVIDER>_API_KEY, LLMWIRE_LITELLM_MODELS routing and LLMWIRE_EMULATE_OPENCODE applied as there. Models sharing a provider share one connection pool and one opencode session identity, except that its no_api_key profiles, which send no key, get a client of their own.

Every unset variable is named in one error (errors.Join of *MissingEnvError, each variable once), so a deployment is fixed in one pass. A request for a model not named here is a *ModelNotConfiguredError, before any socket opens: the list is the contract, not whichever host a key happens to open.

cfg is FromEnv's: an explicit cfg.BaseURL sends every model to that one host with cfg.APIKey as given and reads no variable (a test fake, a stand-in). A cfg.APIKey with no BaseURL is refused when the models span more than one provider, since it would carry one vendor's key to another's host.

Stats() and Registry() cover every model; ListModels, RawStream and RawPost need one host, which ForModel returns.

func New

func New(cfg Config) *Client

New builds a Client.

func (*Client) Chat added in v0.0.5

func (c *Client) Chat(ctx context.Context, req ChatRequest) (*ChatResponse, []Warning, error)

Chat sends one request and returns the completed turn.

The three returns are (response, warnings, error) in that order: a coercion that succeeded is not an error, and a caller who ignores the middle value still gets a working call — which is the point of the tier-3 policy.

Example

One completion, against a stub endpoint so the example is runnable. Warnings ride back alongside a successful response, which is the whole tier-3 policy: a coercion that worked is not an error, and a caller who ignores the middle value still gets a working call.

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/trick77/llmwire"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Echo back which output-cap parameter arrived. On this model only
		// max_tokens is honoured — max_completion_tokens is ACCEPTED and then
		// ignored, which is why the caller never chooses the spelling.
		var body map[string]any
		_ = json.NewDecoder(r.Body).Decode(&body)
		_, capped := body["max_tokens"]
		fmt.Println("max_tokens sent:", capped)

		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, `{"model":"glm-5.3-flash","choices":[{"finish_reason":"stop",`+
			`"message":{"content":"four"}}],`+
			`"usage":{"prompt_tokens":10,"completion_tokens":2}}`)
	}))
	defer srv.Close()

	c := llmwire.New(llmwire.Config{BaseURL: srv.URL})
	cap := 16
	resp, warnings, err := c.Chat(context.Background(), llmwire.ChatRequest{
		Model:     "glm-5.3-flash",
		Messages:  []llmwire.Message{llmwire.User("What is two plus two?")},
		MaxTokens: &cap,
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("answer:", resp.Content)
	fmt.Println("finish:", resp.FinishReason)
	fmt.Println("cost:", resp.Usage.Cost.NanoUSD, "nano-USD via", resp.Usage.Cost.Provenance)
	fmt.Println("warnings:", len(warnings))

}
Output:
max_tokens sent: true
answer: four
finish: stop
cost: 2500 nano-USD via from-table
warnings: 0

func (*Client) ChatStream added in v0.0.5

func (c *Client) ChatStream(ctx context.Context, req ChatRequest) (*Stream, []Warning, error)

ChatStream starts a streaming completion.

The returned warnings are the VALIDATION warnings, available before any byte is consumed so a caller who wants to abort on a coercion can. Pricing cannot run until usage arrives, so the complete set — validation plus pricing — comes from Warnings() after Next() returns false.

Example

Streaming is an iterator. Close is always correct to defer, including after reading to the end, and the accumulated result plus its usage and cost are available once the loop finishes — usage arrives in the final chunk, so there is nowhere earlier for it to be.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/trick77/llmwire"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/event-stream")
		for _, frame := range []string{
			`{"choices":[{"delta":{"content":"two "}}]}`,
			`{"choices":[{"delta":{"content":"plus two"}},{"delta":{}}]}`,
			`{"choices":[{"delta":{"content":" is four"},"finish_reason":"stop"}]}`,
			`[DONE]`,
		} {
			fmt.Fprintf(w, "data: %s\n\n", frame)
			if f, ok := w.(http.Flusher); ok {
				f.Flush()
			}
		}
	}))
	defer srv.Close()

	c := llmwire.New(llmwire.Config{BaseURL: srv.URL})
	stream, _, err := c.ChatStream(context.Background(), llmwire.ChatRequest{
		Model:    "glm-5.3-flash",
		Messages: []llmwire.Message{llmwire.User("What is two plus two?")},
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer stream.Close()

	for stream.Next() {
		if ev := stream.Event(); ev.Kind == llmwire.EventContent {
			fmt.Print(ev.Text)
		}
	}
	fmt.Println()
	if err := stream.Err(); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("finish:", stream.Result().FinishReason)

}
Output:
two plus two is four
finish: stop

func (*Client) Embed added in v0.0.5

func (c *Client) Embed(ctx context.Context, req EmbedRequest) (_ *EmbedResponse, warnings []Warning, err error)

Embed returns one vector per input, in the order of the inputs.

func (*Client) ForModel added in v0.0.39

func (c *Client) ForModel(model string) (*Client, error)

ForModel returns the client that talks to model's host: itself on a New or FromEnv client, the model's provider client on a FromEnvModels one. That client serves only the models on its provider, so it cannot carry its key to another host. Use it for the host-level calls: ListModels, RawStream, RawPost.

func (*Client) ListModels added in v0.0.32

func (c *Client) ListModels(ctx context.Context) ([]ModelEntry, []Warning, error)

ListModels fetches the listing behind the client's base URL and key.

The three returns follow Chat: an entry whose limit is present but unusable (a bool, a string, a fraction, zero) keeps a nil limit and adds a Warning naming it, rather than failing the whole listing over one row the caller may never look at. Only the listing's own shape is an error: `data` must be a list. A bad status is the same typed error a completion would return.

Bounded by the caller's context and the whole-call cap, like every other route. A listing is quick, so a caller wanting a tighter bound for a boot check passes a context with one.

func (*Client) Now

func (c *Client) Now() time.Time

Now exposes the client's clock, so pricing and tests share one source of time.

func (*Client) RawPost

func (c *Client) RawPost(ctx context.Context, route string, body []byte) (json.RawMessage, http.Header, error)

RawPost sends an already-built body to an arbitrary route and returns the decoded JSON response, the response headers and the status. Used for non-streaming completions, for embeddings, and by the probe suite when the interesting part of a response is its headers.

The headers are returned because a gateway reports per-call spend and the real deployment name there and nowhere else.

func (*Client) RawStream

func (c *Client) RawStream(ctx context.Context, body []byte, onDelta func(string)) (StreamResult, error)

RawStream POSTs an already-built request body to /chat/completions with stream:true and consumes the SSE response.

It takes raw JSON rather than a typed request because it sits below profile resolution: the probe suite needs to send deliberately malformed and endpoint-specific bodies that no validated type would permit.

onDelta, when non-nil, is called for each content fragment as it arrives. It runs on the reading goroutine, so it must not block.

func (*Client) Registry added in v0.0.4

func (c *Client) Registry() *Registry

Registry exposes the profiles this client validates against, so a caller can ask what a model supports without making a request.

func (*Client) Stats added in v0.0.29

func (c *Client) Stats() Stats

Stats returns the per-model counters accumulated since New. Every call that reached its end is in here, failures included; a stream the caller closed early counts as Closed, with whatever usage had arrived by then.

func (*Client) Validate added in v0.0.4

func (c *Client) Validate(req ChatRequest) ([]Warning, error)

Validate checks a request against its model's profile without touching the network, returning the warnings the request would produce.

Exported and network-free on purpose. It is what makes "fails fast" testable, and it lets a service check its configuration at boot rather than on the first user request.

Example (UnsupportedEffort)

An effort level outside the model's accepted set is refused the same way. The set is per-model and narrower than the vendor's global enum: this model takes three of the seven levels its provider documents.

package main

import (
	"fmt"

	"github.com/trick77/llmwire"
)

func main() {
	c := llmwire.New(llmwire.Config{})

	_, err := c.Validate(llmwire.ChatRequest{
		Model:     "glm-5.3-flash",
		Messages:  []llmwire.Message{llmwire.User("hello")},
		Reasoning: llmwire.ReasoningEffort("medium"),
	})
	fmt.Println(err)

}
Output:
llmwire: model "glm-5.3-flash": effort "medium" is not accepted by this model; accepted: low, high, max; or pass BestEffort to send the nearest supported request
Example (UnsupportedReasoning)

The refusal a caller sees when they ask a model to stop thinking and it cannot. It arrives before any socket opens, and it names what the model does take — an error that only says "no" leaves the reader to go and find the accepted set, which for these models is not reliably documented anywhere.

package main

import (
	"fmt"

	"github.com/trick77/llmwire"
)

func main() {
	c := llmwire.New(llmwire.Config{})

	_, err := c.Validate(llmwire.ChatRequest{
		Model:     "glm-5.3-flash",
		Messages:  []llmwire.Message{llmwire.User("hello")},
		Reasoning: llmwire.ReasoningOff(),
	})
	fmt.Println(err)

}
Output:
llmwire: model "glm-5.3-flash": thinking cannot be disabled on this model; accepted: low, high, max; or pass BestEffort to send the nearest supported request
Example (Warnings)

A request that can be honoured approximately succeeds and reports a warning, rather than failing. Here the model cannot enforce a schema but can still be held to JSON.

package main

import (
	"fmt"

	"github.com/trick77/llmwire"
)

func main() {
	c := llmwire.New(llmwire.Config{})

	warnings, err := c.Validate(llmwire.ChatRequest{
		Model:       "mimo-v2.5-pro",
		Messages:    []llmwire.Message{llmwire.User("hello")},
		Temperature: ptr(0.2),
	})
	fmt.Println("error:", err)
	for _, w := range warnings {
		fmt.Printf("%s: %s\n", w.Kind, w.Feature)
	}

}

func ptr(f float64) *float64 { return &f }
Output:
error: <nil>
compatibility: temperature

func (*Client) ValidateStream added in v0.0.38

func (c *Client) ValidateStream(req ChatRequest) ([]Warning, error)

ValidateStream is Validate for a request that will go to ChatStream. The one difference is the streaming refusal, which a non-streaming plan never reaches, so a boot check for a streamed call needs this form.

type Config

type Config struct {
	// BaseURL is the OpenAI-compatible root. The client appends the route, so
	// this must NOT already end in /chat/completions.
	BaseURL string
	// APIKey is sent as a bearer token. Optional: some self-hosted endpoints
	// take none, and an empty string sends no Authorization header at all
	// rather than an empty one, which some gateways reject.
	APIKey string
	// UserAgent overrides the default. Go's own "Go-http-client/1.1" names the
	// HTTP library and says nothing about the protocol being spoken; several
	// of these upstreams behave better when told they are talking to an
	// ordinary OpenAI-compatible SDK.
	UserAgent string
	// Headers are added to every request. Used for session-affinity pairs and
	// for gateway-specific headers.
	Headers map[string]string

	HeaderTimeout time.Duration
	IdleTimeout   time.Duration
	CallTimeout   time.Duration

	// HTTPClient is optional. The default has no whole-request timeout (see
	// above) and carries ResponseHeaderTimeout as a backstop under the guard.
	HTTPClient *http.Client

	// Now is the clock, injectable because cost depends on wall-clock time on
	// endpoints with off-peak pricing, and a test that only passes during a
	// particular local window is worse than no test. Defaults to time.Now.
	// It is also the clock behind Timing and MaxCommentGap, so a fixed clock
	// pinned for pricing reports every duration as zero.
	Now func() time.Time

	// Lookup is where FromEnv reads a profile's endpoint variables from. Nil
	// means the process environment. An application whose own config loader
	// is the single source of settings passes its getter; a test passes a
	// map.
	Lookup func(name string) (string, bool)
	// Logger is where the client reports. Nil means slog.Default(). FromEnv
	// writes one Info line with the settings it built the client with; every
	// call then ends in one line, Debug when it worked, Warn when it failed
	// or the answer needs a look (truncated, empty, unaccounted); a session
	// rotation under EmulateOpenCode is a Debug line. Never the prompt, the
	// answer or the key: lengths, counts, the key's variable name. See
	// observe.go.
	Logger *slog.Logger
	// Registry supplies the model profiles this client validates against.
	// Defaults to the built-in one. Injectable so a caller can add a deployment
	// without waiting for it to be upstreamed here, and so tests can drive
	// validation with a profile that does not exist in the real world.
	Registry *Registry

	// EmulateOpenCode presents every request as the opencode client: its
	// User-Agent, and the session header pair it sends. Headers only, never a
	// request body. It overrides UserAgent, since that string is the whole point;
	// it does not override a session header set by hand in Headers.
	//
	// Some endpoints are sold as one client's backend and treat a neutral
	// User-Agent as a bot. The session id is the Client's own — minted at
	// construction, rotated after an idle gap — and there is deliberately no way
	// to supply one. See identity.go.
	EmulateOpenCode bool
}

Config configures the transport.

type Cost added in v0.0.5

type Cost struct {
	// NanoUSD is billionths of one US dollar. Integer end to end, because a float
	// total drifts in the digits displayed — which is where a billing figure is
	// read.
	NanoUSD int64 `json:"nano_usd"`
	// Provenance is what gives NanoUSD its meaning, and its zero value is
	// Unpriced: a forgotten fill then reads "unknown", never "the table said
	// zero", which would read as free.
	Provenance CostProvenance `json:"provenance"`
	// AppliedAt is the clock value captured at REQUEST START. Which instant bills
	// is unspecified by both vendors, so this records the one that was used.
	AppliedAt time.Time `json:"applied_at,omitempty"`
	// Window and Tier name the multipliers that applied, empty when none did.
	// Always empty under Reported: a gateway's figure is already final.
	Window string `json:"window,omitempty"`
	Tier   string `json:"tier,omitempty"`
}

Cost is what one call cost.

A FromTable figure is the vendor's published pay-as-you-go LIST rate in USD. It is a comparable equivalent, NOT an invoice: a call billed as subscription credits on a token-plan host still reports the list rate here, because a credit figure cannot be compared between models and an Unpriced one leaves a budget cap with nothing to check.

type CostBlock added in v0.0.5

type CostBlock struct {
	// Lanes, in nano-USD per million tokens. Pointers so an absent lane is
	// distinguishable from an explicit zero: absent is a load refusal, zero is
	// the vendor saying free.
	Input      *rate `yaml:"input"`
	CacheRead  *rate `yaml:"cache_read"`
	CacheWrite *rate `yaml:"cache_write"`
	Output     *rate `yaml:"output"`

	// Tiers raise the rate for a large prompt. Selected by the request.
	Tiers []CostTier `yaml:"tiers"`
	// Windows move it by wall-clock time, in the provider's own zone. None ships
	// attached today — see the note on glm-5.3-flash in profiles.yaml.
	Windows []CostWindow `yaml:"windows"`
	// OutsideWindowsPermille applies when no window matches. Defaults to 1000
	// (the list rate) at load, because both vendors express the rule as "peak is
	// list, everything else is cheaper".
	OutsideWindowsPermille int32 `yaml:"outside_windows_permille"`

	// SourceURL and VerifiedOn are mandatory. Two models in this registry have
	// prices differing by 2x between the vendor's page and a published
	// catalogue, and a rate whose origin is not recorded cannot be audited when
	// that happens again.
	SourceURL  string `yaml:"source_url"`
	VerifiedOn string `yaml:"verified_on"`
}

CostBlock is one model's published rate, per lane.

Whole block or nothing: every lane a chat model bills is mandatory. A "missing cache rate falls back to the input rate" rule would be a call-site default, and this registry resolves everything at load precisely so that no call site invents a value. A lane the vendor genuinely gives away is an explicit 0.

type CostProvenance added in v0.0.5

type CostProvenance int

CostProvenance says where a figure came from. There is no unit here: every figure is USD, and a one-value enum would be a switch nobody should write.

const (
	// Unpriced is the ZERO VALUE, deliberately: no rate was available. NanoUSD is
	// 0, and 0 means unknown, never free.
	Unpriced CostProvenance = iota
	// FromTable was computed from the embedded list rate. See the Cost doc
	// comment: a list-rate equivalent, not an invoice.
	FromTable
	// Reported came from the gateway, which knows what it actually charged.
	Reported
)

func (CostProvenance) MarshalText added in v0.0.5

func (p CostProvenance) MarshalText() ([]byte, error)

MarshalText renders the provenance as its name. A bare integer in a log or a stored record would be unreadable exactly where it matters most.

func (CostProvenance) String added in v0.0.5

func (p CostProvenance) String() string

func (*CostProvenance) UnmarshalText added in v0.0.5

func (p *CostProvenance) UnmarshalText(text []byte) error

UnmarshalText reads back what MarshalText wrote, so a stored Cost round-trips. Without it the name marshals out fine and then fails to decode, which turns "keep a record of what this call cost" into a runtime error at read time.

An unrecognised name decodes to Unpriced rather than failing: a record written by a later version that knows a fourth source should read as "provenance unknown", which is true, rather than making the whole record unreadable.

type CostTier added in v0.0.5

type CostTier struct {
	Name string `yaml:"name"`
	// MinInputTokens is the threshold on the prompt's TOTAL tokens, cached ones
	// included: vendors threshold on how much context they had to hold, not on
	// what they ended up billing at the full rate.
	MinInputTokens int64 `yaml:"min_input_tokens"`
	// MultiplierPermille applies to the whole call. At least 1000: a tier making
	// a call cheaper would under-report, and under-reporting is the direction
	// that silently raises what a budget cap allows.
	MultiplierPermille int32 `yaml:"multiplier_permille"`
}

CostTier is a surcharge for a large prompt, selected by the request.

type CostWindow added in v0.0.5

type CostWindow struct {
	Name string `yaml:"name"`
	// Zone is an IANA name, e.g. Asia/Singapore. Resolved at load, so a bad zone
	// fails the load and pricing never fails at call time.
	Zone string `yaml:"zone"`
	// Days are Mon..Sun; empty means every day.
	Days []string `yaml:"days"`
	// From is inclusive, To is EXCLUSIVE, both "HH:MM". No midnight wrap:
	// express that as two windows, so "which window applied" stays answerable.
	From               string `yaml:"from"`
	To                 string `yaml:"to"`
	MultiplierPermille int32  `yaml:"multiplier_permille"`
	// contains filtered or unexported fields
}

CostWindow is a wall-clock multiplier in the provider's own timezone.

type EmbedRequest added in v0.0.4

type EmbedRequest struct {
	Model  string
	Inputs []string
	// Dimensions shortens the returned vectors. Only the -3 generation accepts
	// it; older models reject it outright.
	Dimensions *int

	// BestEffort demotes a capability refusal into a coercion plus a Warning, as
	// on a chat request. It cannot rescue a malformed request: an empty input list
	// or an empty string has nothing to send instead.
	BestEffort bool
}

EmbedRequest is one embeddings request.

type EmbedResponse added in v0.0.4

type EmbedResponse struct {
	Vectors [][]float32
	Usage   Usage
	Model   string
	// Timing is summed over the batches the inputs were split into, so it is
	// the wall-clock the whole call spent on the wire, not one request's.
	Timing Timing
	// Gateway is the last batch's proxy headers, as on ChatResponse: its call
	// id, and the key spend as of the end of the call. Empty on a direct route.
	Gateway Gateway
}

EmbedResponse is a batch of vectors, in the order of the inputs that produced them.

type Embedding added in v0.0.5

type Embedding struct {
	// Dimensions: the model accepts the dimensions parameter, which shortens the
	// returned vectors. Only the -3 generation does; older models reject it
	// outright, so this cannot be inferred from the endpoint.
	Dimensions bool `yaml:"dimensions"`
	// DefaultDimensions is the length of a vector this model returns when the
	// dimensions parameter is not sent. Required on an embeddings profile.
	//
	// It is here because it is a property of the MODEL, and because the callers
	// need it before they ever make a call: a vector column, a similarity index
	// and a stored corpus are all built to one width, and a model swapped for one
	// of a different width silently invalidates every row already written. An
	// application carrying its own copy of this number has two sources of truth
	// for one fact, and nothing to compare them against — which is precisely the
	// footgun this field removes.
	DefaultDimensions int `yaml:"default_dimensions"`
}

Embedding describes embeddings-only behaviour. Separate from the chat capabilities so a chat profile declaring it fails the load, the same way an embeddings profile declaring tools does.

type Endpoint added in v0.0.3

type Endpoint string

Endpoint is the route a profile is for. It gates the whole request path, and separating it means a tool or a temperature aimed at an embeddings model is refused by the schema rather than by the endpoint.

const (
	EndpointChat       Endpoint = "chat"
	EndpointEmbeddings Endpoint = "embeddings"
)

The endpoints a profile can describe.

type EventKind added in v0.0.5

type EventKind string

EventKind says which channel an event came from.

const (
	EventContent   EventKind = "content"
	EventReasoning EventKind = "reasoning"
	EventToolCall  EventKind = "tool_call"
	EventFinish    EventKind = "finish"
)

The channels a stream event can arrive on.

type Gateway added in v0.0.33

type Gateway struct {
	// CallID is the id the proxy logged the call under: the handle for matching
	// an unpriced or failed review to the gateway's own log.
	CallID string
	// ModelName is the deployment that ran (`azure/gpt-5.5`), which the
	// response body's model field, carrying the alias, never says.
	ModelName string
	// KeySpendNanoUSD is what the key has spent in total, as of this call. A
	// GAUGE the proxy maintains across every call made with the key, not a
	// per-call amount: show it, never add it up. nil when absent or unusable.
	KeySpendNanoUSD *int64
	// ResponseCost is the per-call cost header verbatim, for a log line. The
	// parsed figure is Usage.Cost; this is the text that produced it, or the
	// literal "None" an older proxy sends for a deployment it cannot price,
	// which is exactly what an operator needs to see.
	ResponseCost string
}

Gateway is the proxy's own account of one call, read from its headers.

func (Gateway) Reported added in v0.0.33

func (g Gateway) Reported() bool

Reported says whether any gateway header arrived at all. An endpoint that sends none is not a LiteLLM proxy and never prices; one that sends some and no cost priced this deployment on another worker, and that difference is what a caller warns about.

type InputTokens

type InputTokens struct {
	Total *int64 `json:"total,omitempty"`
	// NoCache is Total minus CacheRead — the tokens billed at the full input
	// rate. Derived, not reported: no endpoint sends it.
	NoCache *int64 `json:"no_cache,omitempty"`
	// CacheRead is prompt_tokens_details.cached_tokens: prompt tokens the
	// endpoint served from its own cache, billed at a reduced rate.
	CacheRead *int64 `json:"cache_read,omitempty"`
	// CacheWrite is tokens written INTO the cache. Free on every model this
	// library currently targets, and billed at a premium on newer OpenAI
	// models, which is why it is a lane of its own rather than folded into
	// NoCache.
	CacheWrite *int64 `json:"cache_write,omitempty"`
}

InputTokens is the prompt side. Total is what the endpoint billed as prompt tokens; the rest break that total down where the endpoint says.

type Limits added in v0.0.3

type Limits struct {
	Context   int64 `yaml:"context"`
	MaxOutput int64 `yaml:"max_output"`
}

Limits are the model's context and output bounds, in tokens.

type Message added in v0.0.4

type Message struct {
	Role Role
	// Text is the whole content, for the common single-string case.
	Text string
	// Parts, when non-empty, replaces Text. Used for multimodal turns.
	Parts []Part

	// ToolCalls are the calls an assistant turn requested.
	ToolCalls []ToolCall
	// ToolCallID ties a tool result back to the call that asked for it.
	// Required on a RoleTool message.
	ToolCallID string

	// ReasoningContent is the model's thinking from a previous assistant turn.
	//
	// OPTIONAL, and measured to be so. A vendor issue reports a 400 with "The
	// reasoning_content in the thinking mode must be passed back to the API"
	// when an assistant turn carrying tool_calls is replayed without it. That
	// does not reproduce on the deployments in the registry — a replay omitting
	// it was accepted — and a production caller has been omitting it for
	// months. The field exists so a deployment that does demand it can be fed,
	// not because one currently does.
	ReasoningContent string
}

Message is one turn.

Content is either plain text or a sequence of parts. Both spellings exist on the wire and the difference is not cosmetic: a text-only model rejects the parts form outright once it contains an image, so the encoder emits whichever the message actually needs rather than always using the richer one.

func Assistant added in v0.0.4

func Assistant(text string) Message

Assistant builds an assistant message.

func System added in v0.0.4

func System(text string) Message

System builds a system message. It, User and Assistant are shorthands for the three ordinary roles.

func TextMessage added in v0.0.4

func TextMessage(role Role, text string) Message

TextMessage builds a plain-text turn.

func ToolResult added in v0.0.4

func ToolResult(callID, content string) Message

ToolResult builds the reply to a tool call.

func User added in v0.0.4

func User(text string) Message

User builds a user message.

func (Message) HasImage added in v0.0.4

func (m Message) HasImage() bool

HasImage reports whether the message carries an image part, which is what validation checks against a model's vision capability.

type MissingEnvError added in v0.0.12

type MissingEnvError struct {
	Model    string
	Provider string
	Var      string
}

MissingEnvError names the variable a profile's provider expects, so the fix is one export away rather than a search. Var is empty when the profile names no provider at all, which is a profile bug rather than a deployment one.

func (*MissingEnvError) Error added in v0.0.12

func (e *MissingEnvError) Error() string

type ModelEntry added in v0.0.32

type ModelEntry struct {
	ID string
	// MaxInputTokens is the gateway's context window for this alias. A gateway
	// may cap below the vendor's own limit, so this is the figure to size
	// prompts against, not the profile's.
	MaxInputTokens *int64
	// MaxOutputTokens is the gateway's completion cap for this alias.
	MaxOutputTokens *int64
	Raw             json.RawMessage
}

ModelEntry is one row of the listing.

Only the id is promised by the OpenAI shape. The limits are LiteLLM extensions (`max_input_tokens`, `max_output_tokens`) and are nil when the entry does not carry them; a caller that needs one has to say so itself. Raw keeps the whole object for fields this package does not model.

type ModelNotConfiguredError added in v0.0.39

type ModelNotConfiguredError struct {
	Model      string
	Configured []string
}

ModelNotConfiguredError is a request for a model the client was not built for. Named rather than routed anywhere: a model missing from the list is a configuration mistake, and guessing a host for it could send it with another provider's key.

func (*ModelNotConfiguredError) Error added in v0.0.39

func (e *ModelNotConfiguredError) Error() string

type ModelStats added in v0.0.29

type ModelStats struct {
	// Calls is every call that reached finish, Errors those that failed,
	// Closed those the caller stopped reading.
	Calls, Errors, Closed int64
	// Token lanes, summed over calls that reported them. UnreportedCalls
	// counts the ones that did not, so a low total is read beside it.
	InputTokens, CacheReadTokens, CacheWriteTokens, OutputTokens, ReasoningTokens int64
	UnreportedCalls                                                               int64
	// CostNanoUSD sums priced calls only; UnpricedCalls says how many are
	// missing from it. 0 with UnpricedCalls > 0 is unknown, never free.
	CostNanoUSD   int64
	UnpricedCalls int64
}

ModelStats is what one model has done since the client was built.

type Needs added in v0.0.39

type Needs struct {
	// Tools: native or recovered tool calling (Profile.Tools.Supported).
	Tools bool
	// Vision: image parts (Profile.Vision).
	Vision bool
	// JSONObject: response_format json_object.
	JSONObject bool
	// JSONSchema: response_format json_schema, enforced rather than downgraded.
	JSONSchema bool
	// Streaming: ChatStream.
	Streaming bool
}

Needs is what a role requires of a chat model. The zero value requires nothing beyond being a chat model.

type Output added in v0.0.3

type Output struct {
	JSONObject bool `yaml:"json_object"`
	JSONSchema bool `yaml:"json_schema"`
	// StrictSchema is whether "strict": true is accepted inside a json_schema
	// block. Some compat servers reject it.
	StrictSchema bool `yaml:"strict_schema"`
}

Output describes structured-output support. json_object and json_schema are tracked separately because they are separately supported, and because a downgrade from one to the other is a real, lossy coercion a caller deserves to be warned about.

type OutputTokens

type OutputTokens struct {
	Total *int64 `json:"total,omitempty"`
	// Text is Total minus Reasoning — the part the caller actually received.
	// Derived when the endpoint reports reasoning but not text, which is the
	// usual case.
	Text *int64 `json:"text,omitempty"`
	// Reasoning is completion_tokens_details.reasoning_tokens: tokens spent
	// thinking, already counted inside Total.
	Reasoning *int64 `json:"reasoning,omitempty"`
}

OutputTokens is the completion side.

type Part added in v0.0.4

type Part struct {
	Kind PartKind
	// Text is set when Kind is PartText.
	Text string
	// URL is set when Kind is PartImage. A data: URI is accepted and is how an
	// inline image is sent.
	URL string
}

Part is one element of a multimodal message.

type PartKind added in v0.0.4

type PartKind string

PartKind distinguishes the content parts a message can carry.

const (
	PartText  PartKind = "text"
	PartImage PartKind = "image_url"
)

The content part kinds a message can carry.

type Profile added in v0.0.3

type Profile struct {
	// ID is what callers name. It is matched EXACTLY: no globbing, no prefix
	// matching. Prefix matching is how a new model silently inherits an older
	// family's quirks, and one published catalogue documents its own collision
	// between a model and that model's "-pro" variant.
	ID string `yaml:"id"`
	// DisplayName is the human label ("GLM 5.3 Flash"), for a model picker or a
	// log a person reads. Defaults to ID at load, so a document written before
	// the field still loads; every shipped profile sets it. A route keeps its
	// model's label unless it names its own.
	DisplayName string `yaml:"display_name"`
	// Base names another profile to inherit from. See resolve for the rules.
	Base string `yaml:"base"`
	// Gateway marks a profile as reached through a proxy rather than directly.
	Gateway string `yaml:"gateway"`

	Endpoint Endpoint `yaml:"endpoint"`
	// WireModelID is what goes in the request body's "model" field, which is not
	// always the ID a caller uses: behind a gateway it is the proxy's alias.
	WireModelID string `yaml:"wire_model_id"`
	// Provider names the host and account this model is reached through:
	// zai, mimo, openai, litellm. It decides the environment variables
	// FromEnv reads, LLMWIRE_<PROVIDER>_BASE_URL and _API_KEY, so two profiles
	// on one host cannot name different variables. Lowercase letters and
	// digits only; it is uppercased into the variable name.
	Provider string `yaml:"provider"`
	// NoAPIKey marks a host that authenticates nothing: FromEnv sends no
	// Authorization header and does not look for the key variable.
	NoAPIKey bool `yaml:"no_api_key"`
	// BaseURL is the provider's endpoint root, resolved at load from the
	// providers: map. Not a profile key: the host belongs to the provider, and
	// a profile restating it would be the per-model copy this field removes.
	// Empty when the provider ships no host; FromEnv then requires the
	// LLMWIRE_<PROVIDER>_BASE_URL variable, which it otherwise refuses.
	BaseURL string `yaml:"-"`
	// EmulateOpenCode follows the provider the same way BaseURL does.
	EmulateOpenCode bool `yaml:"-"`

	// MaxTokensParam is which output-cap parameter this endpoint honours.
	// Getting it wrong is not always an error: one endpoint accepts the wrong
	// name and IGNORES it, returning thirty times the requested tokens with no
	// signal at all.
	MaxTokensParam string `yaml:"max_tokens_param"`

	Reasoning   Reasoning `yaml:"reasoning"`
	Temperature Sampling  `yaml:"temperature"`
	TopP        Sampling  `yaml:"top_p"`
	Tools       Tools     `yaml:"tools"`
	Output      Output    `yaml:"output"`
	Streaming   Streaming `yaml:"streaming"`
	Limits      Limits    `yaml:"limits"`
	Vision      bool      `yaml:"vision"`
	Embedding   Embedding `yaml:"embedding"`

	// Cost is the published pay-as-you-go rate, or nil when no rate has been
	// verified for this model. Nil is not "free": pricing reports Unpriced and
	// warns, because a zero nobody can explain is worse than a missing number.
	// Absent for every gateway route by construction — see CostBlock.
	Cost *CostBlock `yaml:"cost"`

	// FinishReasonsExtra are vendor-specific finish_reason values beyond the
	// OpenAI vocabulary. Recorded for documentation: the parser treats the field
	// as an open set regardless, because an unknown value must never be fatal.
	FinishReasonsExtra []string `yaml:"finish_reasons_extra"`

	// Verified says how this profile's facts were established. "measured" means
	// a probe in eval_probe_test.go produced them; "source-derived" means they
	// were read from vendor source or documentation and never confirmed against
	// a live endpoint. A reader must be able to tell the two apart at a glance.
	Verified string `yaml:"verified"`
	// Notes carries per-profile caveats into godoc and error messages.
	Notes string `yaml:"notes"`
}

Profile is everything known about one model at one endpoint, fully resolved.

There are no optionals here beyond the explicit pointers: defaults are applied once at load, so no call site ever asks "what if this field is unset". A profile in memory is complete or the registry refused to load.

func (Profile) APIKeyEnv added in v0.0.3

func (p Profile) APIKeyEnv() string

APIKeyEnv is the variable FromEnv reads the bearer token from: LLMWIRE_<PROVIDER>_API_KEY. Empty when the profile names no provider or takes no key.

func (Profile) BaseURLEnv added in v0.0.3

func (p Profile) BaseURLEnv() string

BaseURLEnv is LLMWIRE_<PROVIDER>_BASE_URL: required when BaseURL is empty, refused when it is not. Empty when the profile names no provider.

func (Profile) String added in v0.0.3

func (p Profile) String() string

String renders a profile for an error message: enough to identify which deployment is meant, without dumping the whole struct.

type Provider added in v0.0.24

type Provider struct {
	// BaseURL is the OpenAI-compatible root the client appends routes to.
	// Empty means the library ships no host for this provider (a self-hosted
	// gateway), and LLMWIRE_<PROVIDER>_BASE_URL is then required.
	BaseURL string `yaml:"base_url"`
	// EmulateOpenCode: this host is sold as opencode's backend and refuses a
	// neutral User-Agent as a bot, so FromEnv presents as that client. A
	// property of the host, which is why it is here and not in every
	// application's configuration. See Config.EmulateOpenCode.
	EmulateOpenCode bool `yaml:"emulate_opencode"`
}

Provider is one host and account a profile is reached through: the thing `provider:` names. It carries the endpoint root so an application supplies a key and nothing else. The URL is a property of the provider, not of the model, which is why it lives here rather than on every profile.

type RateLimitError

type RateLimitError struct {
	*APIError
	// RetryAfter is how long the endpoint asked us to wait. Zero means it sent
	// no usable hint — NOT "retry immediately".
	RetryAfter time.Duration
}

RateLimitError is every 429, whether or not it carried a Retry-After header: the type is what a caller dispatches on, and the hint is optional.

func (*RateLimitError) Unwrap added in v0.0.6

func (e *RateLimitError) Unwrap() error

Unwrap exposes the embedded *APIError to errors.As.

Embedding alone is not enough and the difference is silent: errors.As matches on the dynamic type or on what Unwrap returns, and *RateLimitError is neither an *APIError nor, without this, wrapping one. So

var apiErr *APIError
errors.As(err, &apiErr)

returned FALSE for exactly one status — 429 — while succeeding for every other refusal. A caller rendering "failed with status %d" from that check therefore dropped the one status worth retrying on, and the only visible symptom was a differently-worded log line. The first consumer to migrate hit it, and it would have been a per-repo rediscovery otherwise.

type Reasoning added in v0.0.3

type Reasoning struct {
	Supported bool `yaml:"supported"`
	// EnabledByDefault: the model reasons when the knob is omitted entirely.
	EnabledByDefault bool `yaml:"enabled_by_default"`
	// CanBeDisabled: the model accepts being told not to reason at all.
	CanBeDisabled bool             `yaml:"can_be_disabled"`
	Control       ReasoningControl `yaml:"control"`
	// EffortValues is the exact accepted set, never a superset. The vendor's
	// global enum is wider than any single model takes: glm-5.3-flash accepts
	// three of the seven values its provider documents.
	//
	// Listed shallowest first, in effortLadder order, and checked at load:
	// ReasoningMinimal reads the first entry as the model's floor.
	//
	// Required for ControlEffort. Optional for ControlToggleObject, where a
	// non-empty set says the model ALSO takes reasoning_effort beside its
	// on/off switch: ReasoningEffort(level) then renders the field instead of
	// being refused, and ReasoningOff() still renders the toggle. Empty on a
	// toggle model means the switch is the only knob.
	EffortValues []string `yaml:"effort_values"`
	// DefaultEffort is what the model uses when the field is omitted. Empty
	// means the vendor does not say.
	DefaultEffort string `yaml:"default_effort"`
	// StreamField names the delta field reasoning arrives on: "reasoning_content"
	// on every model measured so far, "reasoning" on some servers. Empty means
	// reasoning is not streamed separately.
	StreamField string `yaml:"stream_field"`
	// BudgetParam is the wire key a token budget is sent under, and is required
	// when Control is ControlBudget. There is no default because the vendors
	// that take a budget disagree on the name, and guessing it would send a key
	// the endpoint ignores — the same silent failure max_tokens_param exists to
	// prevent. Must be empty for every other control.
	BudgetParam string `yaml:"budget_param"`
	// LeaksCloseTag: the model writes a stray "</think>" into content, after a
	// draft of its answer, even with thinking disabled. Chat then cuts content
	// at the first such tag, on requests with thinking off and no JSON format,
	// and moves the part before it to Reasoning. Observed,
	// not documented by any vendor; see profiles.yaml for the case. Applies to
	// Chat only: a stream has already sent the draft by the time the tag
	// arrives.
	LeaksCloseTag bool `yaml:"leaks_close_tag"`
	// Balanced is the level ReasoningBalanced resolves to: fast but not
	// shallow. Must be one of EffortValues, and never "none". Empty means the
	// intent sends nothing and the model runs at its own default.
	Balanced string `yaml:"balanced"`
	// Overhead is the reasoning tokens to budget beside a MaxAnswerTokens
	// answer, per resolved level: an effort level, "off", or "default" for a
	// request that sends no knob (DefaultEffort's entry wins there when both
	// exist). A level with no entry on a thinking request takes
	// DefaultReasoningOverhead; thinking off takes 0. A budget request is its
	// own overhead. Absent unless measured, like every other bit.
	Overhead map[string]int `yaml:"overhead"`
	// MinBudget is the budget ReasoningMinimal sends on a budget_tokens model
	// that cannot be disabled. Forbidden on every other control. Absent there,
	// that intent is refused: a guessed floor is either rejected by the
	// endpoint or not a floor.
	MinBudget int `yaml:"min_budget"`
}

Reasoning describes a model's thinking controls.

EnabledByDefault and CanBeDisabled are SEPARATE booleans, and that is the most important decision in this file. "Can this model stop reasoning?" is not answerable from whether "none" appears in a list of effort levels: published catalogues infer exactly that and get glm-5.3-flash wrong, because it rejects "none" AND rejects the disable toggle AND rejects three other levels, all with one overloaded error code. Three separate projects independently concluded the same thing and gave the flag three different names.

func (Reasoning) Accepts added in v0.0.3

func (r Reasoning) Accepts(effort string) bool

Accepts reports whether effort is in the model's accepted set.

type ReasoningControl added in v0.0.3

type ReasoningControl string

ReasoningControl is HOW a model's reasoning depth is expressed on the wire. Models that reason differ in the knob, not just in its values: one takes a nested object, another an effort string, a third a token budget.

const (
	// ControlNone is a model that exposes no reasoning knob.
	ControlNone ReasoningControl = "none"
	// ControlToggleObject is thinking:{"type":"enabled"|"disabled"}.
	ControlToggleObject ReasoningControl = "toggle_object"
	// ControlEffort is reasoning_effort:"<level>".
	ControlEffort ReasoningControl = "effort"
	// ControlBudget is a token budget. No model in the registry uses it yet; it
	// exists so adding one is data rather than a new concept.
	ControlBudget ReasoningControl = "budget_tokens"
)

type ReasoningRequest added in v0.0.4

type ReasoningRequest interface {
	// contains filtered or unexported methods
}

ReasoningRequest is how much thinking to ask for.

A sum type rather than a string, so validation is "does this variant match one the profile allows" rather than a string comparison against a set the caller had to know. The three variants mirror the three controls models actually expose; a request variant that does not match the profile's control is refused by name rather than sent and rejected.

func ReasoningBalanced added in v0.0.39

func ReasoningBalanced() ReasoningRequest

ReasoningBalanced asks for fast-but-not-shallow: the profile's reasoning.balanced level where one is declared, else the model's own default (nothing is sent).

func ReasoningBudget added in v0.0.4

func ReasoningBudget(tokens int) ReasoningRequest

ReasoningBudget asks for a token budget.

func ReasoningEffort added in v0.0.4

func ReasoningEffort(level string) ReasoningRequest

ReasoningEffort asks for a named depth. The accepted levels are per-model and narrower than the vendor's global enum.

func ReasoningMinimal added in v0.0.39

func ReasoningMinimal() ReasoningRequest

ReasoningMinimal asks for the shallowest thinking the model has: off where the profile says it can be disabled, else the first (shallowest) of its effort_values, else, on a budget model, its reasoning.min_budget. On a model that does not reason it sends nothing and warns nothing: the request is already as shallow as it gets.

func ReasoningOff added in v0.0.4

func ReasoningOff() ReasoningRequest

ReasoningOff asks the model not to reason.

Refused before any request is sent when the profile says the model cannot comply — which is the case for at least one model in the registry, whose vendor documentation claims otherwise.

type Registry added in v0.0.3

type Registry struct {
	// contains filtered or unexported fields
}

Registry holds fully-resolved profiles, keyed by exact model id, and the providers they are reached through.

func Default added in v0.0.3

func Default() *Registry

Default returns the built-in registry.

It panics if the embedded profiles are malformed, because that is a programming error in this package rather than anything a caller can handle: the data is compiled in, so if it is broken here it is broken everywhere, and the tests would have caught it.

func NewRegistry added in v0.0.3

func NewRegistry(doc []byte) (*Registry, error)

NewRegistry parses and validates a profile document.

Everything is resolved here: bases merged, defaults applied, cross-field rules checked. A profile that survives this is complete, so no call site ever has to ask "what if this field is unset". A profile that does not survive fails the load rather than the request.

func (*Registry) ChatModels added in v0.0.39

func (r *Registry) ChatModels(needs Needs) []string

ChatModels lists the chat model ids that meet needs, sorted: the "valid choices are ..." of a configuration error.

func (*Registry) Lookup added in v0.0.3

func (r *Registry) Lookup(id string) (*Profile, error)

Lookup returns the profile for an exact model id.

An unknown id is an ERROR, never a zero profile. The alternative — returning something empty and letting capability checks read false — turns a typo into "this model supports nothing", which is indistinguishable from a real answer and fails much later, somewhere unrelated. One widely-used library does exactly that, and it is why a missing model there presents as a mysteriously featureless one. The returned profile is a COPY. The registry is cached for the life of the process and shared by every caller, so returning the stored pointer would make one caller's experiment everyone else's configuration.

func (*Registry) LookupEmbedding added in v0.0.18

func (r *Registry) LookupEmbedding(id string) (*Profile, error)

LookupEmbedding is Lookup for a model that must be an embeddings model. An embeddings client that is handed a chat id fails at its first request with a body about messages; this fails at construction, naming the id, which is where a build-time constant is checked. The width is guaranteed by the profile: an embeddings profile without default_dimensions does not load.

func (*Registry) Models added in v0.0.3

func (r *Registry) Models() []string

Models lists every registered id, sorted.

func (*Registry) Provider added in v0.0.24

func (r *Registry) Provider(name string) (Provider, error)

Provider returns the host a provider name resolves to. An unknown name is an error rather than an empty Provider, for the same reason Lookup errors: a typo must not read as "no host shipped".

func (*Registry) Require added in v0.0.39

func (r *Registry) Require(id string, needs Needs) (*Profile, error)

Require returns the profile for id if it is a chat model meeting needs. An unknown id is an *UnknownModelError, a model short of a need a *CapabilityError naming every gap and every model that has none.

type ResponseFormat added in v0.0.4

type ResponseFormat struct {
	Kind ResponseFormatKind
	// Name identifies the schema. Required by FormatJSONSchema.
	Name string
	// Schema is a JSON Schema object, for FormatJSONSchema.
	Schema map[string]any
	// Strict asks for exact schema adherence.
	Strict bool
}

ResponseFormat constrains the shape of the reply.

Worth reaching for rather than trusting a prompt: on one model in the registry a prompt saying "reply as JSON" produced a raw reply that parsed 0 times out of 8, while the same prompt with a response format parsed 8 out of 8.

type ResponseFormatKind added in v0.0.4

type ResponseFormatKind string

ResponseFormatKind is the structured-output mode.

const (
	// FormatUnset leaves the field off the wire entirely.
	FormatUnset ResponseFormatKind = ""
	// FormatText asks for ordinary text.
	FormatText ResponseFormatKind = "text"
	// FormatJSONObject asks for a single JSON object, with no schema.
	FormatJSONObject ResponseFormatKind = "json_object"
	// FormatJSONSchema asks for output conforming to a named schema.
	FormatJSONSchema ResponseFormatKind = "json_schema"
)

type Role added in v0.0.4

type Role string

Role is a message author.

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

The four roles the wire format defines.

type Sampling added in v0.0.3

type Sampling struct {
	// Supported: the parameter may be sent at all.
	Supported bool `yaml:"supported"`
	// ForcedValue, when non-nil, is the ONLY value accepted. Sending anything
	// else is a 400. This is distinct from unsupported: omitting the parameter
	// is fine, and sending the forced value is fine.
	ForcedValue *float64 `yaml:"forced_value"`
	// InertWhileReasoning: the parameter is accepted and then overridden by the
	// model while it is thinking. Neither rejected nor honoured — which is why
	// it cannot be expressed as Supported alone. Sending it is harmless;
	// believing it took effect is not.
	InertWhileReasoning bool `yaml:"inert_while_reasoning"`
	// RecommendedValue is the vendor's tuned operating point, sent when the
	// caller expresses no preference. It matters because omitting the parameter
	// does NOT mean "the model's default" on every endpoint: at least one falls
	// back to a materially lower value than the model was tuned for.
	RecommendedValue *float64 `yaml:"recommended_value"`
}

Sampling describes temperature and top_p handling, which is subtler than a bool on every model in the registry.

type SpoolTransport added in v0.0.19

type SpoolTransport struct {
	// contains filtered or unexported fields
}

SpoolTransport writes every response it carries to a directory, one file per response, as the status line, the headers and the body exactly as they came off the wire. It is the debugging aid for the question no log line answers: what did the endpoint actually send. A stream is written once the body is closed, so the file holds every frame the client read, including a truncated tail when the read failed.

Handed to Config.HTTPClient as the transport:

hc := &http.Client{Transport: llmwire.NewSpoolTransport("logs/llm", nil, nil)}
client := llmwire.New(llmwire.Config{HTTPClient: hc})

Files are named <UTC timestamp>-<sequence>.http. The directory is created on first use with mode 0700 and the files with 0600: the bodies are the caller's prompts and the model's answers. A file that cannot be written is dropped silently; a diagnostic must never fail the request it observes.

The request body is not spooled. The response is what the caller could not otherwise see; the request is what the caller built.

func NewSpoolTransport added in v0.0.19

func NewSpoolTransport(dir string, next http.RoundTripper, skip func(*http.Request) bool) *SpoolTransport

NewSpoolTransport wraps next, writing responses under dir. A nil next means http.DefaultTransport. skip, when set, is asked per request and a true answer leaves that response unwritten — the hook for a request whose body must not touch disk, such as a turn the caller promised to keep ephemeral.

func (*SpoolTransport) RoundTrip added in v0.0.19

func (t *SpoolTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type StaleEnvError added in v0.0.26

type StaleEnvError struct {
	Model    string
	Provider string
	Var      string
}

StaleEnvError names a variable from the old contract that is still set: LLMWIRE_<PROVIDER>_BASE_URL for a provider whose host the library ships. The fix is to delete the line, and the error says so, because a deployment carrying a URL the library already knows is one that nobody will notice drifting.

func (*StaleEnvError) Error added in v0.0.26

func (e *StaleEnvError) Error() string

type Stats added in v0.0.29

type Stats struct {
	Models map[string]ModelStats
}

Stats is the client's counters, per model, as of the call. A copy: mutate it freely.

func (Stats) LogValue added in v0.0.29

func (s Stats) LogValue() slog.Value

LogValue renders the stats as one line of flat attributes per model, for a shutdown or periodic summary from the application's own logger.

type Stream added in v0.0.5

type Stream struct {
	// contains filtered or unexported fields
}

Stream is a live streamed completion. Close it when done; a deferred Close is always correct, including after reading to the end.

func (*Stream) Close added in v0.0.5

func (s *Stream) Close() error

Close stops the stream and releases its goroutine and connection.

Idempotent, and correct to defer: a caller who read to the end gets a no-op, and one who returns early gets a cancelled request. A deliberate close is not an error, so Err stays nil for it.

func (*Stream) Collect added in v0.0.18

func (s *Stream) Collect(onDelta func(string)) (StreamResult, error)

Collect drains the stream: every content delta goes to onDelta as it arrives, in order, and the assembled result comes back once the stream ends. It is the loop every consumer that does not need the event kinds was writing by hand — Next, switch on Kind, keep the finish reason, then read Usage — and getting subtly different: one forgot the usage frame follows the finish, another read Usage before Next returned false.

The result is returned WITH the error. A stream cut after its usage frame, or after content the reader has already seen, was paid for; a caller that accounts per call needs the figures whether or not the read completed, and gates on Usage.Total() — Reported() is true for an object with nothing countable in it. onDelta may be nil.

func (*Stream) Err added in v0.0.5

func (s *Stream) Err() error

Err returns why the stream ended, or nil. Valid once Next has returned false.

A failure names the bound that gave up — "stream idle for 1m30s", "exceeded the 15m0s call cap" — rather than surfacing a bare context error, and a stream that ended without [DONE] or a finish_reason is an error rather than a short answer: a dropped connection looks exactly like a finished one otherwise.

func (*Stream) Event added in v0.0.5

func (s *Stream) Event() StreamEvent

Event returns the event Next advanced to.

func (*Stream) Next added in v0.0.5

func (s *Stream) Next() bool

Next advances to the next event, blocking until one arrives. It returns false when the stream is finished or has failed; check Err afterwards.

func (*Stream) Result added in v0.0.5

func (s *Stream) Result() StreamResult

Result returns the accumulated answer: content, reasoning, assembled tool calls, finish reason and usage. Valid once Next has returned false.

func (*Stream) Usage added in v0.0.5

func (s *Stream) Usage() Usage

Usage returns the token accounting and its cost. Valid once Next has returned false — usage arrives in the final or trailing chunk, so mid-stream it is the zero Usage, which reads as "not reported" rather than as zero tokens.

func (*Stream) Warnings added in v0.0.5

func (s *Stream) Warnings() []Warning

Warnings returns the validation warnings plus anything the stream produced as it finished, which in practice means pricing. It is the union, not only the late ones, so a caller who checks one place gets everything.

type StreamEvent added in v0.0.5

type StreamEvent struct {
	Kind EventKind
	// Text is the content or reasoning delta.
	Text string
	// Index, ID, Name and ArgumentsDelta describe a tool-call fragment. ID and
	// Name are present on the first fragment only.
	Index          int
	ID             string
	Name           string
	ArgumentsDelta string
	// FinishReason is the endpoint's own string, treated as an open set.
	FinishReason string
}

StreamEvent is one increment of a streamed answer.

Tool calls arrive as FRAGMENTS keyed by Index: the id and name come on the first one and the arguments build up as text across the rest. Assembled calls are on Result() once the stream ends, so a caller who only wants the finished calls need not reassemble them.

type StreamResult

type StreamResult struct {
	Content   string
	Reasoning string
	ToolCalls []ToolCall
	// FinishReason is the endpoint's own string and is treated as an OPEN set.
	// Vendors add their own beyond the OpenAI vocabulary — MiMo sends
	// "repetition_truncation", Z.ai sends "sensitive",
	// "model_context_window_exceeded" and "network_error" — so this is never
	// switched on exhaustively.
	FinishReason string
	Usage        Usage
	// Events counts `data:` frames received, Chars counts runes of content.
	Events int64
	Chars  int64
	// Done records that the endpoint sent [DONE].
	Done bool
	// MaxCommentGap is the longest interval between two `data:` frames,
	// measured from the moment the body opened, whatever the endpoint sent in
	// between: comment lines, blank keepalives, or nothing. Recorded because
	// the idle guard deliberately does NOT re-arm on non-data lines, so this
	// is the margin between that policy and a false abort — the number the
	// transport probe exists to measure. The silence after the last frame is
	// not in it. It differs from MaxDataGap only in excluding the wait for the
	// first frame.
	MaxCommentGap time.Duration
	// Timing is set on the error path too: a stream cut mid-answer still has
	// a measured Total, and that figure beside the named bound in the error is
	// what settles whether the bound or the endpoint was wrong.
	Timing Timing
	// MaxDataGap is the longest silence between two `data:` frames, the wait
	// for the first one included. It is exactly what the idle guard raced
	// against, so comparing it to IdleTimeout says how close a healthy stream
	// came to a false abort.
	MaxDataGap time.Duration
	// Gateway is what the proxy said in its headers. A stream carries no cost
	// there, but the call id and the deployment still arrive.
	Gateway Gateway
	// Bytes counts the SSE lines read, data lines and comments alike, without
	// their line terminators.
	Bytes int64
	// ReasoningSent is the reasoning knob the request put on the wire, as on
	// ChatResponse. Empty from RawStream, which sits below the plan.
	ReasoningSent string
}

StreamResult is what a completed stream yielded.

type Streaming added in v0.0.3

type Streaming struct {
	Supported bool `yaml:"supported"`
	// NeedsIncludeUsage: without stream_options.include_usage the endpoint
	// reports no usage at all. Measured false on both direct endpoints in the
	// registry; forced true behind a gateway that strips the usage chunk from
	// a client that did not ask for it.
	NeedsIncludeUsage bool `yaml:"needs_include_usage"`
	// AcceptsStreamOptions: whether the parameter may be sent. An endpoint that
	// rejects it must never receive it, even when harmless elsewhere.
	AcceptsStreamOptions bool `yaml:"accepts_stream_options"`
	// BuffersToolArgs: the model emits a tool call's name, then goes silent
	// while it serializes the whole argument server-side, then flushes it in
	// one burst. A caller offering tools that carry large arguments widens
	// ChatRequest.ToolCallIdleTimeout for those turns.
	BuffersToolArgs bool `yaml:"buffers_tool_args"`
}

Streaming describes SSE behaviour.

type Timing added in v0.0.22

type Timing struct {
	// Headers is request sent to response headers received. On a non-streaming
	// route the endpoint withholds headers until the answer is ready, so this
	// is the model's whole latency there, not the time to first byte.
	Headers time.Duration
	// FirstData is request sent to the first `data:` frame. Zero on a
	// non-streaming route, where the body arrives whole with the headers.
	FirstData time.Duration
	// Total is request sent to the last byte read.
	Total time.Duration
}

Timing is where one call's wall-clock went, measured with the client's clock (Config.Now) from the instant the request was handed to the transport. It is returned, never logged: a log line is invisible to the caller, and the caller is the one with the retry loop, the queue and the batch these figures belong to. What it adds over a time.Since around the call is the split only the transport can see, which lines up with the three bounds the client arms: Headers against HeaderTimeout, FirstData minus Headers against IdleTimeout (the idle guard is only armed once headers are in), Total against CallTimeout. A call that took 38s to headers against a 60s bound is a margin worth knowing before the bound fires, the same way MaxCommentGap reports the margin on the idle guard.

type Tool added in v0.0.4

type Tool struct {
	Name        string
	Description string
	// Parameters is a JSON Schema object. Held as a decoded value rather than a
	// string so a caller can build it however it likes.
	Parameters map[string]any
	// Strict asks for strict schema adherence. Passed through as sent: no
	// profile measures tool-level strictness, so it is not gated on the
	// unrelated response_format bit. Some compat servers reject the field.
	Strict bool
}

Tool is a function offered to the model.

type ToolCall

type ToolCall struct {
	ID        string `json:"id"`
	Type      string `json:"type"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ToolCall is a completed tool call assembled from its fragments.

type ToolChoice added in v0.0.4

type ToolChoice struct {
	Mode ToolChoiceMode
	// Name is the tool to compel, when Mode is ToolChoiceFunction.
	Name string
}

ToolChoice constrains tool selection.

type ToolChoiceMode added in v0.0.4

type ToolChoiceMode string

ToolChoiceMode is how the model should decide about calling a tool.

const (
	// ToolChoiceUnset leaves the field off the wire entirely.
	ToolChoiceUnset ToolChoiceMode = ""
	// ToolChoiceAuto lets the model decide whether to call a tool.
	ToolChoiceAuto ToolChoiceMode = "auto"
	// ToolChoiceNone forbids tool calls for this request.
	ToolChoiceNone ToolChoiceMode = "none"
	// ToolChoiceRequired compels some tool call.
	ToolChoiceRequired ToolChoiceMode = "required"
	// ToolChoiceFunction compels one named tool; set ToolChoice.Name too.
	ToolChoiceFunction ToolChoiceMode = "function"
)

type ToolFormat added in v0.0.3

type ToolFormat string

ToolFormat is how a model emits a tool call.

const (
	// FormatNative populates the OpenAI tool_calls field.
	FormatNative ToolFormat = "native"
	// FormatXML emits markup inside the content stream instead. Measured as NOT
	// occurring on the MiMo deployments (see FINDINGS.md), but retained because
	// loom observed it in production against a longer history than a probe
	// reproduces, and because deleting the capability would make its return a
	// rewrite rather than a flag.
	FormatXML ToolFormat = "xml"
)

type Tools added in v0.0.3

type Tools struct {
	Supported bool       `yaml:"supported"`
	Format    ToolFormat `yaml:"format"`
	// ToolChoiceValues is the accepted set. Several endpoints take only "auto"
	// and SILENTLY DROP anything else, so a caller asking for a forced call gets
	// an unforced one with no error.
	ToolChoiceValues []string `yaml:"tool_choice_values"`
	// SupportsForcedChoice is whether a specific tool can be compelled. Always
	// false for FormatXML: with no tool_calls field there is nothing for the
	// server to force.
	SupportsForcedChoice bool `yaml:"supports_forced_choice"`
	SupportsParallel     bool `yaml:"supports_parallel"`
	// RecoverInlineMarkup runs the inline-XML recovery even when Format is
	// native. On for the MiMo profiles although no probe reproduces the leak:
	// loom observed markup leaking from a deployment that otherwise returns
	// native calls (see profiles.yaml).
	RecoverInlineMarkup bool `yaml:"recover_inline_markup"`
}

Tools describes tool-calling support.

type UnknownModelError added in v0.0.3

type UnknownModelError struct {
	ID    string
	Known []string
}

UnknownModelError names what was asked for and what is available, because an error that does not say which ids exist leaves the reader to guess at a typo.

func (*UnknownModelError) Error added in v0.0.3

func (e *UnknownModelError) Error() string

type UnsupportedError added in v0.0.4

type UnsupportedError struct {
	Model   string
	Feature string
	Reason  string
	// Accepted, when non-empty, is the set the model does take.
	Accepted []string
	// Demotable says whether BestEffort would have let this request through.
	// False for a malformed request and for a model/endpoint mismatch, where
	// suggesting the flag would be advice that does not work — or worse, advice
	// that suppresses the error and sends something broken.
	Demotable bool
}

UnsupportedError is a refusal: the request cannot be sent as written.

The message always names what IS accepted where there is such a set. An error that only says "no" leaves the reader to go and find it, which for these models is not reliably documented anywhere.

func (*UnsupportedError) Error added in v0.0.4

func (e *UnsupportedError) Error() string

type Usage

type Usage struct {
	Input  InputTokens  `json:"input"`
	Output OutputTokens `json:"output"`
	// Cost is what this call cost, priced at the call site with the model that
	// actually ran. Its zero value means Unpriced, which is why it is a field
	// rather than a second return: parseUsage and RawStream sit BELOW profile
	// resolution, so a usage object from either already reads as "not priced"
	// with nobody having to remember to say so.
	Cost Cost `json:"cost"`
	// Raw is the endpoint's own usage object, verbatim and undecoded. Kept
	// because these endpoints carry fields nobody has modelled yet (image and
	// video token counts, web-search request counts), and because it is the
	// only way to settle whether a zero is the endpoint's answer or a field
	// name this package does not know about.
	Raw json.RawMessage `json:"raw,omitempty"`
	// contains filtered or unexported fields
}

Usage is one call's token accounting, normalised across endpoints.

func (Usage) Reported added in v0.0.13

func (u Usage) Reported() bool

Reported says the endpoint sent a usage object with something in it, so a zero lane is the endpoint's answer rather than silence. It is NOT "this call can be counted": a bare {"total_tokens":N} or an empty details object is reported and yields no lane. A consumer recording per-call figures gates on Total()'s ok, or a call arrives in its ledger as 0/0 and reads as free. A malformed object keeps its bytes in Raw and is NOT reported. Every consumer that counts "how many of my calls were accounted for" needs exactly this and was re-deriving it from the lane pointers.

func (Usage) Total added in v0.0.13

func (u Usage) Total() (total int64, ok bool)

Total is prompt plus completion — the OpenAI-compatible total_tokens, which parseUsage does not keep as its own lane because it is by definition the sum of two lanes that are. ok is false when neither side was reported; a side that is absent counts as zero, so a completion-only object still totals.

type Warning added in v0.0.4

type Warning struct {
	Kind WarningKind
	// Feature names the request field concerned.
	Feature string
	// Details says what happened to it, and why.
	Details string
}

Warning is something the caller should know about a request that otherwise succeeded.

func (Warning) String added in v0.0.4

func (w Warning) String() string

type WarningKind added in v0.0.4

type WarningKind string

WarningKind classifies a warning. Three cases, deliberately: a longer taxonomy invites callers to switch on distinctions that do not change what they should do.

const (
	// WarnUnsupported means the request asked for something the model does not
	// support, and it was dropped.
	WarnUnsupported WarningKind = "unsupported"
	// WarnCompatibility means the request was honoured approximately. The call
	// worked; the result may differ from what was asked for.
	WarnCompatibility WarningKind = "compatibility"
	// WarnOther is anything that fits neither.
	WarnOther WarningKind = "other"
)

Directories

Path Synopsis
Package llmwiretest lets a module that uses llmwire test what it ASKS for without pinning what any real model is called, how its knobs are spelled on the wire, or what it costs.
Package llmwiretest lets a module that uses llmwire test what it ASKS for without pinning what any real model is called, how its knobs are spelled on the wire, or what it costs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL