llmwire

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 19 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.

Status: under construction. Phase 0 (transport + live probes) is in progress. The API below is the target shape and is not stable yet.

resp, warnings, err := client.Chat(ctx, llmwire.ChatRequest{
    Model:     "glm-5.3-flash",
    Messages:  []llmwire.Message{{Role: "system", Content: "..."}, {Role: "user", Content: q}},
    Reasoning: llmwire.ReasoningEffort("high"),
})

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;
         use ReasoningEffort with one of [low high max], or pass BestEffort()

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). BestEffort() 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. The rate is a function, not a constant — it varies by request size (long-context surcharges), by wall-clock time (off-peak windows), and by unit, because subscription endpoints bill credits rather than dollars. A rate we have not verified reports Unpriced and warns, because zero means unknown, not free.

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.

Scope

One wire protocol: /chat/completions and /embeddings. 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. 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:
    unit: usd
    source_url: https://mimo.mi.com/docs/en-US/price/pay-as-you-go
    verified_on: 2026-09-12
    input: 0.435
    cache_read: 0.0036
    output: 0.87

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 LiteLLM entry is not a new model. It names the model it really is, inherits every capability, and adds only what the gateway changes:

- id: litellm/openai-gpt-5.4
  base: azure/gpt-5.4          # inherits capabilities and parameters
  gateway: litellm
  wire_model_id: ai-gateway/gpt-5.4   # the proxy's alias
  cost:
    source: reported           # the gateway reports real spend per call

Because the entry names its base, validation still works behind a proxy whose wire id is opaque: Temperature(0.3) is rejected locally, since gpt-5.4 rejects it.

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 Eval ./...

Evals skip unless that variable is set, so they never run in CI. 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

gofmt -l .          # must print nothing
./hack/secret-scan.sh
go vet ./...
go build ./...
go test -race ./...

Keys are read from the environment only. .env is gitignored, and hack/secret-scan.sh refuses keys and .env files entering the tree — from the pre-commit hook and from CI, since a hook only protects one machine.

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 (
	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 DefaultUserAgent = "llmwire/0.1 (+https://github.com/trick77/llmwire)"

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

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")
)

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 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 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 when the failure happened before a
	// response (dial, TLS, a stall guard firing).
	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 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

	Tools      []Tool
	ToolChoice ToolChoice

	ResponseFormat ResponseFormat

	// Stop sequences, when the endpoint supports them.
	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.
	ExtraBody map[string]any

	// 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
}

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 New

func New(cfg Config) *Client

New builds a Client.

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) 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

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.
	Now func() time.Time

	// 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
}

Config configures the transport.

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
}

EmbedRequest is one embeddings request.

type EmbedResponse added in v0.0.4

type EmbedResponse struct {
	Vectors [][]float32
	Usage   Usage
	Model   string
}

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

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"
)

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

func System added in v0.0.4

func System(text string) Message

System, 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

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 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"
)

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"`
	// 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"`
	BaseURLEnv  string `yaml:"base_url_env"`
	APIKeyEnv   string `yaml:"api_key_env"`

	// 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"`

	// 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) 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 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 a 429 that carried a Retry-After header.

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.
	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"`
}

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 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
}

Reasoning 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 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 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.

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) 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) Models added in v0.0.3

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

Models lists every registered id, sorted.

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 ResponseFormatKind = ""
	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"
)

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 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 during which the endpoint sent
	// only comment or blank lines and no `data:` frame. Recorded because the
	// idle guard deliberately does NOT re-arm on those lines, so this is the
	// margin between that policy and a false abort — the number the transport
	// probe exists to measure.
	MaxCommentGap time.Duration
}

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"`
}

Streaming describes SSE behaviour.

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. Profile-gated: some compat
	// servers reject the field outright.
	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  ToolChoiceMode = "auto"
	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. Off for every profile measured; kept because loom observed markup
	// leaking from a deployment that otherwise returns native calls.
	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"`
	// 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"`
}

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

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: the request asked for something the model does not
	// support, and it was dropped.
	WarnUnsupported WarningKind = "unsupported"
	// WarnCompatibility: 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"
)

Jump to

Keyboard shortcuts

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