openaiapi

package
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 26 Imported by: 0 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.

Documentation

Overview

Package openaiapi is abcd's OpenAI-compatible API adapter (itd-2609081951381895): one client over the chat-completions protocol, which OpenRouter and a local OpenAI-compatible server both speak, so a provider is configuration of this adapter and never code (the intent's Decision 2).

The client asks for the model it is given and nothing else: which models a provider may serve (its allowlist, and any oracle.denylist entry the configuration writes) is internal/core/oracle's to decide before a Client is ever built (adr-2609221009491186, adr-2609300107513982). The adapter's own guarantees are the network path's:

  • the base URL is pinned per provider block, plain HTTP is admitted only to this machine (a local server), and a redirect is never followed, so a provider cannot move the key or the brief to another host;
  • the answer is streamed, every response is bounded (MaxResponseBytes, a stream's events and its whole length besides) and every call is bounded in time, by a first-byte limit, an idle limit between reads, an event limit between a stream's events (a keep-alive comment is not one) and a total cap, so a provider that floods or stalls is refused rather than waited on, while one still sending is never cut off at an arbitrary age; a call that ends early closes its connection, so the server sees it go;
  • the key travels only as the Authorization header of a request to the pinned base URL. No error, result or log line carries it: a provider's own text (its error, the model it reports and the answer itself) is decoded and scrubbed of every representation of the key (Scrub), the error and the model bounded and sanitised as well, before it can reach an error or a result, because a provider may echo what it was sent, in whatever encoding its stack applies;
  • a setting the protocol does not take is refused before any call, and the answer is judged by the caller's output contract, the same one the host sub-agent's payload is judged by, so an answer that does not satisfy it is refused rather than used.

It uses net/http and encoding/json alone; it reads no file and no credential store: the caller resolves the key by name through internal/core/credential and hands the value in. The one environment it honours is net/http's own, through the default transport: the standard proxy variables for https (HTTPS_PROXY, NO_PROXY) and the platform's trust roots. An https call through a proxy is a CONNECT tunnel, so the key and the brief stay inside TLS, and a call to this machine (the only one plain HTTP may reach) is never proxied.

Index

Constants

View Source
const (
	// The answer is streamed, so a call is bounded three ways rather than by
	// one end-to-end deadline, which abandoned a reasoning model's answer that
	// was still arriving (iss-2610030931521214: such answers run past ten
	// minutes).
	//
	// DefaultFirstByteTimeout bounds the wait from sending the brief to the
	// answer's first byte: a local server reads a long prompt before it says
	// anything.
	DefaultFirstByteTimeout = 5 * time.Minute
	// DefaultIdleTimeout bounds the silence between two reads once the answer
	// has begun; a keep-alive comment counts as the server being alive.
	DefaultIdleTimeout = 2 * time.Minute
	// DefaultTotalTimeout caps one call end to end however steadily it
	// streams: connecting, sending the brief and reading the whole answer.
	DefaultTotalTimeout = 30 * time.Minute

	// MaxResponseBytes bounds a successful answer: a plain body, one event of
	// a stream, and the answer a stream assembles. A chat completion carrying a
	// verdict is a few kilobytes; 4 MiB refuses a flood without ever refusing a
	// real one.
	MaxResponseBytes = 4 << 20

	// MaxModelBytes bounds the model a provider reports.
	MaxModelBytes = 200
)
View Source
const (
	RuntimeOllama   = "ollama"
	RuntimeLlamaCpp = "llama.cpp"
	RuntimeMLX      = "mlx"
)

The runtimes a local pin names.

View Source
const (
	// ListTimeout bounds one listing end to end, connecting and reading the
	// whole list, whatever the client's call limits are: those are sized for
	// a completion, and a list either arrives quickly or is not worth waiting
	// for.
	ListTimeout = 10 * time.Second
	// MaxListedModels is how many ids a listing keeps, in the service's order.
	MaxListedModels = 5000
)
View Source
const (
	// GenerationTimeout bounds one readback end to end: every ask, every
	// wait between asks and every body read.
	GenerationTimeout = 20 * time.Second

	// MaxAttempts bounds the provider attempts a record keeps.
	MaxAttempts = 16
)
View Source
const LocalProbeTimeout = 5 * time.Second

LocalProbeTimeout bounds one probe end to end, every request in it.

View Source
const MaxTopLogprobs = 20

MaxTopLogprobs bounds how many alternatives a call asks for at a token: the protocol's own ceiling.

View Source
const ProviderRoutingField = "provider"

ProviderRoutingField is the request member the routing object rides in.

View Source
const StreamUsageField = "stream_options.include_usage"

StreamUsageField is the request field the adapter adds to ask for usage in the stream. It is the adapter's own, never a setting, and a record names it as added by the adapter rather than as a setting sent.

Variables

View Source
var ErrBriefCounted = errors.New("openaiapi: the brief had already reached the provider for the size count")

ErrBriefCounted is wrapped beside ErrNoAnswer when the size count (size.go) had connected to the provider before the chat call failed to: the brief had already reached it to be counted.

View Source
var ErrNoAnswer = errors.New("openaiapi: the chat call never connected, so no answer was received")

ErrNoAnswer is what a call's error wraps when the chat call never connected to the provider, so no answer was received, whatever a check before it sent (iss-2610090701491123: no answer received, not nothing sent, is what lets a caller leave the step to another leg). It is ErrUnreachable as well only when nothing at all connected; ErrBriefCounted says the size count had already carried the brief to the provider.

View Source
var ErrStreamUsage = errors.New("openaiapi: the server refused the request's usage in the stream")

ErrStreamUsage is the ErrUsageRefused whose refusal names the field (stream_options or include_usage): the field is likely what it refused, so the caller names the setting that stops asking.

View Source
var ErrUnreachable = errors.New("openaiapi: the provider could not be reached")

ErrUnreachable is what a call's error wraps when the provider could not be reached at all: no connection to it (or to the proxy in front of it) was ever made, so nothing of the request, the key or the brief left this machine. Every ErrUnreachable is also ErrNoAnswer. A provider that answered, or that took the request and never answered, is not unreachable: the brief may already have been sent. Nor is one a check before the call connected to (size.go): the key, and the brief a count carries, may have left.

View Source
var ErrUsageRefused = errors.New("openaiapi: the server refused a request that asked for usage in the stream")

ErrUsageRefused is what a refusal is when the server refused, with HTTP 400 or 422, a request that asked for usage in the stream, whatever its body says: the field may be what it refused. Only a setup acts on it, by asking once more without the field (oracle.Connect); an ordinary call is never sent twice.

Runtimes is every runtime a local pin may name, in the order a refusal lists them.

Functions

func AcceptedSettings

func AcceptedSettings() []string

AcceptedSettings returns the settings this adapter accepts, sorted: the declaration internal/core/oracle carries on a provider connection, so a setting outside it is refused before a step runs (spc-2609251028149555, AC 8). The slice is a copy.

func IsLocal added in v0.16.0

func IsLocal(baseURL string) bool

IsLocal reports whether baseURL reaches a server on this machine (localhost or a loopback address): a local route, whose weights and runtime only a local pin names (local.go).

func PromptSHA256 added in v0.16.0

func PromptSHA256(b Brief) string

PromptSHA256 is the SHA-256, in hex, of the brief's messages as the call renders them (itd-166 decision 5): what was sent is recorded by its hash, never its text.

func ReadableCost added in v0.16.0

func ReadableCost(c float64) bool

ReadableCost reports whether a cost a route reported is one a record keeps: zero or more, and finite. It is the one policy every route's cost is held to (the adapter's usage member, and the runners' harness costs through oracle.ReadableCost); a cost that fails it is not reported.

func Scrub

func Scrub(s, key string) string

Scrub replaces every representation of key in s with "[credential]": the key itself and the forms an encoder in a provider's stack or in abcd's own error path may give it (JSON with and without HTML escaping, with '/' escaped and with non-ASCII escaped, Go's quoting, HTML escaping, URL query and path escaping, and the terminal-safe renderings). An empty key scrubs nothing. A front door that formats an error built from a provider's text scrubs it with this a last time.

func ValidateBaseURL

func ValidateBaseURL(raw string) error

ValidateBaseURL admits an absolute https URL, or an http URL to this machine (localhost or a loopback address), with a host and no credentials, query or fragment. The refusal never quotes the URL, which may carry a secret.

Types

type Attempt added in v0.16.0

type Attempt struct {
	Provider string `json:"provider"`
	Status   string `json:"status"`
}

Attempt is one provider OpenRouter tried for a generation: its name and the status it answered, each cleaned and bounded like the model.

type Brief

type Brief struct {
	Instructions string
	Input        string
}

Brief is what the host sub-agent is given, in the protocol's two roles: Instructions is the agent's prompt (the system message) and Input is the request the verb emitted for it (the user message).

type Client

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

Client is one provider connection. It holds the key; it never prints it.

func New

func New(baseURL, key string, opts ...Option) (*Client, error)

New returns a client for the provider at baseURL (validated by ValidateBaseURL), sending key as a bearer token; an empty key sends none, for a local server that needs none.

func (*Client) Complete

func (c *Client) Complete(ctx context.Context, req Request, contract func([]byte) error) (Result, error)

Complete sends one brief and returns the answer the contract admits. The request is refused before any call when it names no model or carries a setting the protocol does not take. contract is the output contract the host sub-agent's payload is judged by; nil admits any answer (a verification call, which judges only that the provider answered).

Before sending, the request is judged against the model's served size where the service's model list publishes one and the service counts the request exactly (size.go): a request counted over it is refused there, and without both it is sent as before. The checks are spent inside the call's total cap.

The call asks for a stream and assembles its events into the answer (stream.go); a server that answers with one chat-completion body instead is read as that. It is bounded by ctx and by the first-byte, idle and total limits, and whichever ends it cancels the request, which closes the connection, so a server still generating sees the client go away.

func (*Client) Generation added in v0.16.0

func (c *Client) Generation(ctx context.Context, id string) (Generation, error)

Generation reads OpenRouter's record of the generation id names, bounded by the client's readback limit (GenerationTimeout). It is a request of its own: a caller makes it only when the run it belongs to asked for it. Every failure is an error in abcd's words, scrubbed of the key, and quotes no part of the provider's body.

func (*Client) Models added in v0.13.0

func (c *Client) Models(ctx context.Context, keep func(id string) bool) (Listing, error)

Models asks the service for the models it lists: one GET of {base}/models.

The request carries the client's key as its bearer token and none when the client holds none; it follows no redirect (the pinned CheckRedirect); it is bounded by ListTimeout, and its body by MaxResponseBytes. The answer is read as the standard list, data[].id; an id is kept only when it is a non-empty line of valid UTF-8 within maxListedIDBytes that no reading of it (as sent, JSON escapes undone, character references resolved) reveals the key in, and that carries no rune the terminal sanitiser masks. Every other entry is dropped and counted, never kept redacted: a scrubbed id names no model. Which names the configuration admits is the caller's to judge, through keep: a usable id keep refuses is dropped and counted the same way, and a nil keep keeps every usable id. The kept ids are then read together for the key split across them, so the run read is exactly the ids returned, whatever keep removed from between them. Every failure is a *ListError, its reason in plain words, and no part of the service's body is quoted in it.

func (*Client) ProbeLocal added in v0.16.0

func (c *Client) ProbeLocal(ctx context.Context, runtime, model string) (LocalReport, error)

ProbeLocal reads what the server at the client's base URL says it serves for model, through runtime's own endpoints. A base URL off this machine is never probed. A server that cannot be reached, does not answer as runtime, or does not serve model fails the probe; a detail it does not report is left empty in the report, never a failure.

type Generation added in v0.16.0

type Generation struct {
	Model        string
	Provider     string
	FinishReason string
	// Attempts is every provider the record names as tried, in its order,
	// at most MaxAttempts; empty when it names none.
	Attempts []Attempt
	// Usage holds the native prompt, completion, reasoning and cached
	// counts and the total cost; nil when none of them reads.
	Usage *Usage
}

Generation is what OpenRouter's record of one generation says served it. Every string is the provider's own text, scrubbed of the key, cleaned and bounded; a field it did not carry readably is empty, or nil in Usage.

type ListError added in v0.13.0

type ListError struct {
	NeedsKey bool   // the service answered 401 or 403
	Reason   string // "answered not found", "answered with a redirect, which abcd never follows", ...
	// contains filtered or unexported fields
}

ListError says why there is no list, in words a question can carry.

func (*ListError) Error added in v0.13.0

func (e *ListError) Error() string

Error is the reason with the adapter's prefix and the host, scrubbed of the key like every other error the client returns.

type Listing added in v0.13.0

type Listing struct {
	IDs     []string // in the service's own order, each sanitised and bounded
	Dropped int      // listed names that were not usable model names
}

Listing is what a service lists. An id is bounded and free of the key and of every rune a terminal acts on, but not of characters a shell acts on (`;`, `$(`, a quote): a caller checks it as a model name (internal/core/oracle's validModel), through Models' keep, before offering it or printing it in a command.

type LocalReport added in v0.16.0

type LocalReport struct {
	// Version is the runtime's version (llama-server's build, b9860).
	Version string
	// Digest is the model's sha256 in hex, as the runtime names it.
	Digest string
	// Quantisation is the model's quantisation as the runtime names it.
	Quantisation string
	// Context is the context length the model is served at (llama-server's
	// is each slot's).
	Context int
	// ToolCalls is whether the model's template takes tool calls.
	ToolCalls *bool
	// Model is the model as the server names it: the name Ollama lists it
	// under, the llama-server model file's name, mlx's listed id.
	Model string
	// WeightsFile is the base name of the model file llama-server loaded
	// (/props model_path); the other runtimes report none.
	WeightsFile string
	// Slots is llama-server's slot count (/props total_slots, its
	// --parallel): the context it reports is each slot's, and --ctx-size is
	// the total the slots share.
	Slots int
}

LocalReport is what a local server says it serves. Every string is the server's own text, scrubbed of the key, cleaned and bounded; a value the runtime did not report readably is empty, 0, or nil.

type LogprobSink added in v0.16.0

type LogprobSink func(top []TokenLogprob, carried bool)

LogprobSink receives the first answer token's alternatives once an answer is admitted: the alternatives that read (the top list, or the token chosen alone when the provider sent no list), and whether the answer carried any log-probabilities at all.

It runs when the client admits the answer, before Complete returns, so a layer above the client can still refuse the call after it ran: oracle's Call discards an answer whose reported model its denylist refuses. The alternatives count only when the whole call returns no error. A sink keeps them for its caller to read after the call, and never acts on them itself.

type Option

type Option func(*Client)

Option configures a Client.

func WithFirstByteTimeout added in v0.13.0

func WithFirstByteTimeout(d time.Duration) Option

WithFirstByteTimeout bounds the wait for the answer's first byte; d <= 0 keeps DefaultFirstByteTimeout.

func WithIdleTimeout added in v0.13.0

func WithIdleTimeout(d time.Duration) Option

WithIdleTimeout bounds the silence between two reads once the answer has begun; d <= 0 keeps DefaultIdleTimeout.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout caps one call end to end, however steadily its answer streams; d <= 0 keeps DefaultTotalTimeout. A caller with a step it knows to be long raises it here; the first-byte and idle limits still apply within it.

func WithTopLogprobs added in v0.16.0

func WithTopLogprobs(n int, sink LogprobSink) Option

WithTopLogprobs asks the call for the log-probabilities of its answer's tokens, n alternatives at each (bounded to 1 through MaxTopLogprobs), and hands the first token's to sink. A nil sink, or n below 1, asks nothing.

type ProviderRouting added in v0.16.0

type ProviderRouting struct {
	Order             []string `json:"order"`
	AllowFallbacks    bool     `json:"allow_fallbacks"`
	RequireParameters bool     `json:"require_parameters"`
	DataCollection    string   `json:"data_collection"`
	Quantizations     []string `json:"quantizations"`
}

ProviderRouting is OpenRouter's provider routing object, as a request carries it under ProviderRoutingField.

type Request

type Request struct {
	Model    string
	Brief    Brief
	Settings map[string]json.RawMessage
	// NoStreamUsage leaves stream_options.include_usage out of the request.
	// The adapter asks for usage in the stream by default (itd-166 decision
	// 4); a provider connection whose server refuses the field turns it off.
	NoStreamUsage bool
	// Provider is OpenRouter's provider routing object, sent as the
	// request's provider member when set (routing.go); nil sends none.
	Provider *ProviderRouting
}

Request is one call: the model asked for, the brief and the settings as sent. Settings are JSON scalars keyed by an accepted setting's name.

type Result

type Result struct {
	Content       []byte
	ModelAsked    string
	ModelReported string
	// FinishReason is why the provider stopped ("stop", "length"), bounded
	// and cleaned like the model; empty when it gave none.
	FinishReason string
	// GenerationID is the answer's own id (OpenRouter's gen-..., OpenAI's
	// chatcmpl-...), and Provider the upstream provider an aggregator names
	// as the one that served it. Each is the provider's own text, bounded and
	// cleaned like the model; empty when the answer names none.
	GenerationID string
	Provider     string
	// Usage is the token count the provider reported, nil when it sent none.
	Usage *Usage
}

Result is one validated answer: the document the output contract admitted, the model asked for, and the model the provider reported (bounded, with any hidden or control rune percent-encoded), so a substitution is visible.

type TokenLogprob added in v0.16.0

type TokenLogprob struct {
	// Token is the provider's own text, scrubbed of the key and at most
	// maxLogprobToken bytes, and NOT safe for a terminal. It is kept byte for
	// byte so a caller can compare it with its labels: termsafe.Sanitize
	// would turn a newline inside it into '?' and an invalid UTF-8 byte into
	// U+FFFD, and the comparison would no longer read what the model said. A
	// caller that prints it sanitises it where it prints, as the decision
	// adapter's error does (strconv.Quote, then the router's termsafe pass).
	Token   string
	Logprob float64
}

TokenLogprob is one alternative at the answer's first token: the token as the provider spelled it, scrubbed and bounded, and its natural-log probability.

type Usage added in v0.13.0

type Usage struct {
	PromptTokens     *int `json:"prompt_tokens,omitempty"`
	CompletionTokens *int `json:"completion_tokens,omitempty"`
	TotalTokens      *int `json:"total_tokens,omitempty"`
	// CachedTokens is prompt_tokens_details.cached_tokens, the prompt tokens
	// read from the provider's cache, and CacheWriteTokens
	// prompt_tokens_details.cache_write_tokens, the ones written to it.
	CachedTokens     *int `json:"cached_tokens,omitempty"`
	CacheWriteTokens *int `json:"cache_write_tokens,omitempty"`
	// ReasoningTokens is completion_tokens_details.reasoning_tokens.
	ReasoningTokens *int `json:"reasoning_tokens,omitempty"`
	// Cost is the usage member's cost, in the provider's own unit
	// (OpenRouter's credits); nil when it reports none.
	Cost *float64 `json:"cost,omitempty"`
}

Usage is the token count a provider reports with its answer. Every count is a pointer: nil is a count the provider did not report, or reported in a shape the adapter could not read, never a zero it did.

Jump to

Keyboard shortcuts

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