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 ¶
Constants ¶
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.
const DefaultUserAgent = "llmwire/0.1 (+https://github.com/trick77/llmwire)"
DefaultUserAgent is what this package sends when Config.UserAgent is empty.
Variables ¶
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 ¶
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.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a transport for one endpoint.
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.
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
}
Config configures the transport.
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 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 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 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 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 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.