provider
import "github.com/barevoidco/zelk/core/provider"Package provider defines the Provider port: how zelk calls a model. Adapters for each provider’s wire format live in its subpackages; they translate request and stream shapes, caching mechanics, opaque reasoning and the schema dialect, and never change behaviour, so one harness serves every model.
A call takes a plain-data Request and returns a Stream of events: live deltas, which subscribers may see but which are never persisted, and one final Done event carrying the assembled Response, which the driver records. Failures are *Error values whose kind says whether a retry is safe. Response.Warnings are persisted with completion so wire-format downgrades remain observable. Response.Usage is nil when usage was not reported, so unknown usage never becomes a measured zero. Reservation uses the recorded bounds before dispatch; adapters with byte bounds use their exact rendered body.
Constants
Section titled “Constants”const RetryAfterNote = "; retry after "RetryAfterNote precedes, in an Error’s text, how long the provider asked to wait, as a time.Duration prints it, so a host can say when to try again from an error a log recorded as text (present.End).
const ToolSearch = "ToolSearch"ToolSearch is the name of zelk’s deferred-tool search. A provider that loads deferred tools natively sends it as its own search tool and its results as loaded definitions (docs/design/tools.md, deferred tools).
Reservation
Section titled “Reservation”func Reservation(req *Request, caps Caps) event.TokensReservation bounds an attempt using its recorded capabilities. Without an adapter-supplied byte bound it reserves the entire context window. Missing bounds produce estimates suitable for reporting, never for hard enforcement.
ReserveRendered
Section titled “ReserveRendered”func ReserveRendered(req *Request, caps Caps, body []byte) event.TokensReserveRendered bounds the exact wire body produced by an adapter that declares InputBoundBytes. Non-text input and unknown tokenizers reserve the full context window. The caller must pass the body it will actually send.
Retryable
Section titled “Retryable”func Retryable(err error) boolRetryable reports whether the driver may retry a call that failed with err: one that never left, a transient or rate-limit failure, or a malformed response.
Example
errs := []error{ &provider.Error{Kind: provider.ErrorRateLimited, StatusCode: http.StatusTooManyRequests, RetryAfter: 2 * time.Second}, &provider.Error{Kind: provider.ErrorContextOverflow, Message: "prompt is too long"},}for _, err := range errs { fmt.Println(provider.KindOf(err), provider.Retryable(err))}// Output:// rate limited true// context overflow falseOutput:
rate limited truecontext overflow falsetype Caps = event.CapabilitiesCaps is a model’s capability snapshot, as recorded in the log.
Compaction
Section titled “Compaction”type Compaction struct { Items []history.Item Usage *event.Usage}Compaction is a provider’s compacted window and what making it cost.
Compactor
Section titled “Compactor”type Compactor interface { Compact(ctx context.Context, req *Request) (Compaction, error)}Compactor is an optional capability of a provider that can compact a context window itself. Compact takes the request an ordinary call would send and returns the provider’s own replacement for its whole history: items of the provider’s family, with raw payloads, to send instead of it to the same family only. zelk always writes its own portable summary as well, for every other family.
type Error struct { Kind ErrorKind // StatusCode is the HTTP status, if there was one. StatusCode int // Message is the provider's own description. Message string // RetryAfter is how long the provider asked to wait, if it said. RetryAfter time.Duration // Err is the underlying cause, if any. Err error}Error is a classified provider failure.
Error.Error
Section titled “Error.Error”func (e *Error) Error() stringError.Unwrap
Section titled “Error.Unwrap”func (e *Error) Unwrap() errorErrorKind
Section titled “ErrorKind”type ErrorKind intErrorKind classifies a provider failure.
const ( // ErrorUnknown is anything not classified, including errors that aren't // *Error. It is not retried. ErrorUnknown ErrorKind = iota // ErrorNotDispatched: the request provably never reached the provider. ErrorNotDispatched // ErrorTransient: a server error or dropped connection worth retrying // with backoff. ErrorTransient // ErrorRateLimited: the provider asked to slow down; RetryAfter says how // long, if it said. ErrorRateLimited // ErrorContextOverflow: the prompt is too long for the model. The loop // compacts and retries. ErrorContextOverflow // ErrorInvalidRequest: the provider rejected the request; retrying it // unchanged won't help. ErrorInvalidRequest // ErrorAuth: missing or rejected credentials. ErrorAuth // ErrorQuota: the account is out of credit or past a usage limit. A // retry won't lift it; more credit, or the limit's reset, will. ErrorQuota // ErrorUnsupported: the provider doesn't offer what the request needs, // such as a capability or route its plan excludes. Retrying it // unchanged won't help; another model or provider might. ErrorUnsupported // ErrorMalformed: the response broke the provider's protocol, such as // a stream whose events arrive out of order or don't parse. A model // call has no side effects, so another attempt is safe, and the next // response may be whole; but a decoder at odds with its provider fails // every time, so the driver allows fewer attempts than for a transient // failure (driver.Retry.Malformed). ErrorMalformed)The kinds of provider failure.
KindOf
Section titled “KindOf”func KindOf(err error) ErrorKindKindOf returns the kind of a provider failure, or ErrUnknown for an error that isn’t an *Error.
ErrorKind.String
Section titled “ErrorKind.String”func (k ErrorKind) String() stringtype Event struct { Kind EventKind // Delta is the text of a delta event. Delta string // CallID and Name identify the tool call of an EventToolInputDelta. CallID, Name string // Usage is set on EventInputUsage. Usage *event.Usage // Response is set on EventDone. Response *Response}Event is one event of a stream. Deltas are live-only and lossy; only the Response in EventDone is recorded.
EventKind
Section titled “EventKind”type EventKind stringEventKind is the type of a stream Event.
const ( // EventTextDelta is a piece of text output. EventTextDelta EventKind = "text_delta" // EventReasoningDelta is a piece of readable reasoning. EventReasoningDelta EventKind = "reasoning_delta" // EventToolInputDelta is a piece of a tool call's arguments as they // stream; CallID and Name identify the call. EventToolInputDelta EventKind = "tool_input_delta" // EventInputUsage carries the prompt's usage before the answer, when // the provider reports it then, as Anthropic does at a message's // start: the input counts only, with no output. It lets a caller that // stops reading early know what its input cost; the response's usage // remains the record. EventInputUsage EventKind = "input_usage" // EventDone ends the stream with the assembled response. EventDone EventKind = "done")The kinds of stream event.
Format
Section titled “Format”type Format struct { // Name identifies the format to providers that ask for one: letters, // digits, '_' and '-', at most 64. Name string // Schema is a JSON Schema object every provider can enforce: objects // list every property as required and allow no others. Schema json.RawMessage}Format is a JSON shape a reply’s text must take.
Format.Validate
Section titled “Format.Validate”func (f *Format) Validate() errorValidate reports whether f can be sent.
Lister
Section titled “Lister”type Lister interface { Models(ctx context.Context) ([]Model, error)}Lister is an optional capability of a provider that knows the models it offers, for a model picker. The adapters list the models the host declared, with their capabilities; none discovers them over the network.
type Model struct { ID string Caps Caps}Model is a model a provider offers, with what it supports.
Provider
Section titled “Provider”type Provider interface { // Stream sends req and returns its stream of events. An error here // means no stream started; errors after that arrive in the stream. // Stream must not modify req or anything it refers to: the caller may // share the history with its own state. Stream(ctx context.Context, req *Request) (Stream, error) // Capabilities reports what the model supports. The result is // snapshotted into the session log, so replay never asks again. Capabilities(ctx context.Context, model string) (Caps, error) // Family is the wire format of the raw payloads the provider puts on // the items it returns. A session records it, and every raw payload // in the session must be of that family. Family() history.Family}Provider calls a model. Implementations must be safe for concurrent use and must honour ctx: cancelling it ends the call and its stream.
Request
Section titled “Request”type Request struct { Model string // System is the rendered system prompt. System string // Tools are the tools the model may call, in a fixed order so the // prompt prefix stays cacheable. Tools []event.ToolSpec // Deferred are the deferred tools a provider that loads them natively // (Capabilities.DeferredTools) may need: every one it can be told of, // though only those a ToolResult's Loaded names are loaded. Empty // otherwise. Deferred []event.ToolSpec // ToolChoice says whether the model may call Tools. ToolChoiceNone // keeps them in the request, so the cached prefix still matches, but // asks for text only. ToolChoice ToolChoice // History is the conversation so far, in order. History []history.Item MaxOutputTokens int64 // Reasoning sets the reasoning effort; nil leaves it to the provider // and model. Reasoning *event.ReasoningSettings // CacheKey is stable across the calls of one conversation, whose // prompts share a growing prefix. Providers that route requests to // their prompt caches by a key send it, so each call reaches the // machine that cached the last one; others ignore it. Empty sends none. CacheKey string // Format, when set, asks the model to reply with text that is one JSON // value matching the format's schema, through the provider's // structured output, so the reply can't be prose. A model that can't // constrain its output fails the request as invalid or unsupported. Format *Format}Request is one model call, as plain data.
Reserver
Section titled “Reserver”type Reserver interface { Reservation(req *Request, caps Caps) event.Tokens}Reserver measures the conservative token bound of an adapter’s rendered request. Implementations must be safe for concurrent use and must not modify req. Input must reserve the full context window unless caps declares a byte bound. Output must bound what the adapter can generate, even if no request cap is sent. A zero output bound means unknown and cannot support hard enforcement.
Response
Section titled “Response”type Response struct { // Warnings describe wire-format downgrades. The driver persists them in // the same record group as this response's completion. Warnings []event.Warning // Items are the turn's output, each with the provider's raw payload. Items []history.Item // StopReason is why the model stopped; RawStopReason is the provider's // own value, kept for reasons zelk doesn't know. StopReason StopReason RawStopReason string // StopDetails, if the provider gave any, says more about why it // stopped: for a refusal, which safety classifier declined. StopDetails *event.StopDetails // Usage is nil unless the provider reported complete usage. Usage *event.Usage}Response is a finished model turn.
StopReason
Section titled “StopReason”type StopReason stringStopReason is why a model stopped, normalized across providers.
const ( // StopEndTurn: the model finished its turn. StopEndTurn StopReason = "end_turn" // StopToolUse: the model is waiting for tool results. StopToolUse StopReason = "tool_use" // StopMaxTokens: the output limit cut the turn short. A tool call cut // off by it is never run (trap 3). StopMaxTokens StopReason = "max_tokens" // StopRefusal: the model declined. StopRefusal StopReason = "refusal" // StopPauseTurn: the provider paused a long turn; continue it. StopPauseTurn StopReason = "pause_turn" // StopUnknown: a reason zelk doesn't know; RawStopReason has it. StopUnknown StopReason = "unknown")The stop reasons. Each has defined handling in the loop.
StopReason.Valid
Section titled “StopReason.Valid”func (r StopReason) Valid() boolValid reports whether r is one of the defined stop reasons.
Stream
Section titled “Stream”type Stream = iter.Seq2[Event, error]Stream yields a call’s events in order, ending with one EventDone, or with an error if the call fails. Breaking out of the loop cancels the call.
ToolChoice
Section titled “ToolChoice”type ToolChoice stringToolChoice is whether a model may call the tools a request carries.
const ( // ToolChoiceAuto lets the model call tools or answer in text. ToolChoiceAuto ToolChoice = "" // ToolChoiceNone forbids tool calls: the model answers in text. ToolChoiceNone ToolChoice = "none")The tool choices. The zero value lets the model decide.
ToolChoice.Valid
Section titled “ToolChoice.Valid”func (c ToolChoice) Valid() boolValid reports whether c is one of the tool choices.