Documentation
¶
Overview ¶
Package client is a thin Go client that speaks the relay canonical shape (sdk/v1). Callers build a *v1.Request once and get a *Response or a stream of canonical events — regardless of the target.
Use Relay for the primary relay-server path (key pooling, routing, limits). Use For(ref, apiKey) to call any catalogued upstream host directly by model ref ("gpt-4o", "openai/gpt-4o", "gpt-4o@openai-direct") with zero manual baseURL/path/auth wiring. OpenAI, Anthropic, and Gemini constructors remain for explicit off-catalog targets.
Models lists the model ids a client can use and Catalog the catalog document behind a model picker. A relay client reads them from relay, scoped to its credential; any other client reads the latest public catalog through catalogsource.Latest, narrowed to its catalog host, and never contacts relay. Each result names its Origin: OriginRelay is relay's answer for the credential, OriginCatalog the catalog server's latest release, OriginEmbedded the public catalog compiled into this SDK, served when neither can be read. Stale marks an earlier copy served after a failed refresh.
Configuration mirrors the OpenAI SDK: base URL, API key, auth header/scheme, extra default headers, request path, and HTTP client are all settable.
Imports only the standard library, pkg/relay/v1, and the pure vendor translators — none of relay's server-side dependency graph.
Index ¶
- Constants
- func KnownAdapterNames() []string
- type APIError
- type Adapter
- type Auth
- type Client
- func Anthropic(baseURL, apiKey string, opts ...Option) *Client
- func For(ref, apiKey string, opts ...TargetOption) (*Client, error)
- func ForFrom(cat *catalog.IndexedCatalog, ref, apiKey string, opts ...TargetOption) (*Client, error)
- func ForMode(ref string, opts ...ModeOption) (*Client, error)
- func Gemini(baseURL, apiKey string, opts ...Option) *Client
- func New(translator v1.Translator, baseURL, path, apiKey string, opts ...Option) *Client
- func OpenAI(baseURL, apiKey string, opts ...Option) *Client
- func OpenAIResponses(baseURL, apiKey string, opts ...Option) *Client
- func Relay(baseURL, relayKey string, opts ...Option) *Client
- func RelayWS(baseURL, relayKey string, opts ...Option) *Client
- func (c *Client) Catalog(ctx context.Context) (*ModelCatalog, error)
- func (c *Client) Close() error
- func (c *Client) Generate(ctx context.Context, req *v1.Request) (*Response, error)
- func (c *Client) GenerateStream(ctx context.Context, req *v1.Request) (*Stream, error)
- func (c *Client) Models(ctx context.Context) (*ModelList, error)
- func (c *Client) Telemetry() *telemetry.Emitter
- type Event
- type Mode
- type ModeOption
- type ModelCatalog
- type ModelList
- type Option
- func WithAuth(a Auth) Option
- func WithCatalogSource(s *catalogsource.LatestSource) Option
- func WithHTTPClient(h *http.Client) Option
- func WithHeader(k, v string) Option
- func WithPath(p string) Option
- func WithPathFn(fn func(model string, stream bool) string) Option
- func WithTelemetry(e *telemetry.Emitter) Option
- func WithWireRules(rules v1.WireRules) Option
- type Origin
- type Response
- type Stream
- type StreamTiming
- type Target
- type TargetOption
Constants ¶
const ( EnvBaseURL = "WR_BASE_URL" EnvAPIKey = "WR_API_KEY" EnvUsage = "WR_USAGE" EnvHeaders = "WR_HEADERS" EnvTimeout = "WR_TIMEOUT" )
Relay env vars, mirroring the OpenAI SDK's OPENAI_BASE_URL / OPENAI_API_KEY convention. Only the relay target consults them — direct-to-vendor clients do not, so an upstream call never depends on relay config.
WR_BASE_URL relay endpoint (fallback when baseURL == "")
WR_API_KEY relay key (fallback when relayKey == "")
WR_USAGE default X-WR-Usage value (e.g. "full" to echo usage inline)
WR_HEADERS default headers, "k1=v1,k2=v2"
WR_TIMEOUT sync-call timeout, a Go duration (e.g. "30s"); streams are
unaffected — a stream needs no overall deadline.
const ( EnvOpenAIKey = "OPENAI_API_KEY" EnvAnthropicKey = "ANTHROPIC_API_KEY" // Gemini reads GEMINI_API_KEY first, then GOOGLE_API_KEY — matching the // google-genai SDK precedence. EnvGeminiKey = "GEMINI_API_KEY" EnvGoogleKey = "GOOGLE_API_KEY" )
Conventional per-vendor key env vars, read when a direct-to-vendor constructor is called with an empty apiKey. These are the vendor's own credential — never WR_API_KEY, which is a relay key bound to a relay endpoint and meaningless to a vendor. An empty key after fallback is left as-is (Ollama and other keyless OpenAI-compatible hosts are valid).
const EnvMode = "WR_MODE"
EnvMode selects the Mode of ForMode when no WithMode option is given.
Variables ¶
This section is empty.
Functions ¶
func KnownAdapterNames ¶
func KnownAdapterNames() []string
KnownAdapterNames returns every adapter name registered in the SDK.
Types ¶
type APIError ¶
APIError is a non-2xx response from the target. Host names the upstream the call actually hit (a relay deployment or a vendor host dialed directly), so the error self-identifies its origin.
type Adapter ¶
type Adapter struct {
// contains filtered or unexported fields
}
Adapter is the atomic wire bundle: translator, path resolution, and auth always travel together. Selecting an adapter swaps all three at once.
func AdapterByName ¶
AdapterByName returns a registered adapter bundle, or false.
type Auth ¶
type Auth struct {
Header string // header name, e.g. "Authorization" or "x-api-key"
Scheme string // value prefix, e.g. "Bearer"; "" sends the raw key
}
Auth describes how the API key is attached to requests.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client sends canonical requests to one target (relay or a vendor).
func Anthropic ¶
Anthropic targets the Anthropic Messages API directly. Bypasses relay. Empty apiKey falls back to ANTHROPIC_API_KEY.
func For ¶
func For(ref, apiKey string, opts ...TargetOption) (*Client, error)
For resolves a model ref against the embedded catalog and returns a wired client. ref forms: "gpt-4o", "openai/gpt-4o", "gpt-4o@openai-direct".
func ForFrom ¶ added in v0.7.0
func ForFrom(cat *catalog.IndexedCatalog, ref, apiKey string, opts ...TargetOption) (*Client, error)
ForFrom is For against a caller-supplied catalog (catalog.LoadFile / LoadBytes) instead of the embedded one — newer or self-curated catalog data without upgrading the lib.
func ForMode ¶ added in v0.7.11
func ForMode(ref string, opts ...ModeOption) (*Client, error)
ForMode builds a client for the model ref in one of three modes. The mode is WithMode, else WR_MODE, else proxy when WR_BASE_URL and WR_API_KEY are set, else direct; telemetry is never implied. Proxy sends every call through relay with ref as its model. Telemetry and direct resolve ref against the embedded catalog like For and call the provider; telemetry also reports each call (to WR_BASE_URL + "/otlp" with WR_API_KEY, or the OTEL_EXPORTER_OTLP_* settings, unless WithEmitter is given).
func Gemini ¶
Gemini targets the Gemini native generateContent API directly. Bypasses relay. Point baseURL at the API host (e.g. https://generativelanguage.googleapis.com). Empty apiKey falls back to GEMINI_API_KEY, then GOOGLE_API_KEY. Auth is the raw key in x-goog-api-key.
func New ¶
func New(translator v1.Translator, baseURL, path, apiKey string, opts ...Option) *Client
New builds a client for an arbitrary translator/target — the extension point for future adapters. Defaults to Authorization: Bearer auth.
func OpenAI ¶
OpenAI targets the OpenAI Chat Completions API directly (also Ollama and any OpenAI-compatible host — point baseURL at it). Bypasses relay. Empty apiKey falls back to OPENAI_API_KEY.
func OpenAIResponses ¶
OpenAIResponses targets the OpenAI Responses API (POST {baseURL}/v1/responses) directly. Point baseURL at the vendor root (e.g. https://api.openai.com). Backends that serve the same wire without a /v1 segment, such as the Codex/ChatGPT subscription backend (https://chatgpt.com/backend-api/codex), need WithPath("/responses"). Bypasses relay. Empty apiKey falls back to OPENAI_API_KEY; for OAuth, pass a placeholder + WithAuth(Auth{}) and supply the bearer via WithHTTPClient. The Responses translator always sends store:false, so no server-side persistence is requested.
func Relay ¶
Relay targets a relay server's canonical endpoint (POST /v1/generate). The primary use: full key pooling, routing, limits, and observability.
Empty baseURL/relayKey fall back to WR_BASE_URL / WR_API_KEY; WR_USAGE, WR_HEADERS, and WR_TIMEOUT supply further defaults. Explicit opts override env-derived headers. Any missing/invalid config is returned on the client anyway and surfaces on the first Generate/GenerateStream call — never at construction.
func RelayWS ¶
RelayWS targets a relay server's canonical WebSocket endpoint (/v1/ws). One long-lived connection carries every request, so the TLS + auth handshake is paid once instead of per turn — the win for agent loops doing many sequential generations against the same relay.
The connection is stateless: each turn still sends the full request (relay holds no conversation state). This v1 client is sequential — one request in flight at a time per Client; concurrent multiplexing from a single Client is a future enhancement. Call Close when done.
Config resolution matches Relay: WR_* env fallback, and missing/invalid config surfaces on the first call rather than as a dial error.
func (*Client) Catalog ¶ added in v0.7.23
func (c *Client) Catalog(ctx context.Context) (*ModelCatalog, error)
Catalog returns the catalog relay serves for the client's credential (GET /v1/catalog): the models, hosts and prices it can route to, with no upstream addresses. The last good copy is kept in memory and revalidated with its ETag. When the refresh fails on a network error or a 5xx, the last good copy is returned with Stale and Err set; with none held, the embedded catalog is returned with Origin embedded and Err set. A 401 or 403 returns an error and forgets the held copy; a 404 means the relay predates /v1/catalog and returns an error.
A client that doesn't go through relay reads the latest public catalog from its catalog source (WithCatalogSource) and sends nothing to its base URL or to relay. A client built by For, ForFrom or ForMode gets only its catalog host, with the models and providers that host's bindings reference; a host the fetched catalog lacks gives an empty catalog. A client built by a constructor (OpenAI, Anthropic, New, ...) has no catalog host and gets the whole catalog.
func (*Client) Close ¶
Close releases the client's transport. For the default HTTP transport it is a no-op; for a WebSocket client (RelayWS) it closes the connection. A telemetry emitter that ForMode built for the client is closed too, which waits for its queued calls to be exported. Safe to call once when done with the client.
func (*Client) Generate ¶
Generate runs a non-streaming generation. OutputMode is forced to sync; the caller's request is not mutated.
func (*Client) GenerateStream ¶
GenerateStream runs a streaming generation. The returned *Stream yields canonical events until io.EOF; the caller must Close it. OutputMode is forced to stream.
func (*Client) Models ¶ added in v0.7.23
Models returns the model ids relay lists for the client's credential (GET /v1/models). When the refresh fails on a network error or a 5xx, the last good list is returned with Stale and Err set; with none held, the error is returned, since the embedded catalog's ids are not the credential's. A 401 or 403 returns an error and forgets the held list.
A client that doesn't go through relay returns the binding slugs of Catalog instead, with its Origin, Stale and Err.
type Event ¶
Event is one canonical stream event: its name (a v1.Event* constant) and the raw JSON payload. Decode Data into the matching v1 event struct as needed.
type Mode ¶ added in v0.7.11
type Mode string
Mode is where a model call goes and who records it.
const ( // ModeProxy sends calls through relay (WR_BASE_URL, WR_API_KEY), which records them. ModeProxy Mode = "proxy" // ModeTelemetry sends calls to the provider with the caller's provider key and reports each one to relay's OTLP receiver. ModeTelemetry Mode = "telemetry" // ModeDirect sends calls to the provider; nothing is reported. ModeDirect Mode = "direct" )
type ModeOption ¶ added in v0.7.11
type ModeOption func(*modeConfig)
ModeOption configures ForMode.
func WithClientOptions ¶ added in v0.7.11
func WithClientOptions(opts ...Option) ModeOption
WithClientOptions applies client options (an HTTP client, headers, ...) to the client of any mode.
func WithEmitter ¶ added in v0.7.11
func WithEmitter(e *telemetry.Emitter) ModeOption
WithEmitter sets the emitter of the telemetry mode. Without it ForMode builds one from the environment, which the client's Close closes. The other modes ignore it.
func WithMode ¶ added in v0.7.11
func WithMode(m Mode) ModeOption
WithMode picks the mode, overriding WR_MODE.
func WithProviderKey ¶ added in v0.7.11
func WithProviderKey(key string) ModeOption
WithProviderKey sets the provider key of the telemetry and direct modes, overriding the vendor's key env var (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY then GOOGLE_API_KEY, by the resolved binding's adapter).
type ModelCatalog ¶ added in v0.7.23
type ModelCatalog struct {
*catalog.IndexedCatalog
Origin Origin
// Stale marks the last good copy, served because a refresh failed.
Stale bool
// Err is the fetch error behind Stale or an embedded fallback; nil when the catalog is fresh.
Err error
}
ModelCatalog is a catalog for building a model picker or computing cost.
type ModelList ¶ added in v0.7.23
type ModelList struct {
IDs []string
Origin Origin
// Stale marks the last good copy, served because a refresh failed.
Stale bool
// Err is the fetch error behind Stale; nil when the list is fresh.
Err error
}
ModelList is the model ids a client can use: for a relay client those its credential can use, in the order relay lists them; for any other client those its catalog host serves, in catalog order.
type Option ¶
type Option func(*Client)
Option configures a Client. Options apply over the preset defaults.
func WithCatalogSource ¶ added in v0.7.23
func WithCatalogSource(s *catalogsource.LatestSource) Option
WithCatalogSource sets where a client that doesn't go through relay reads the public catalog for Models and Catalog. Without it every such client shares one catalogsource.Latest().
func WithHTTPClient ¶
WithHTTPClient overrides the *http.Client. Streaming needs a client without a short overall timeout.
func WithHeader ¶
WithHeader sets one extra default header sent on every request (e.g. an OpenAI-Organization header, or anthropic-version override).
func WithPathFn ¶
WithPathFn sets a per-call path resolver, for targets that encode the model or the stream/sync choice in the URL path (e.g. Gemini). When set it overrides the static path. The model is the request's first model ref.
func WithTelemetry ¶ added in v0.7.11
WithTelemetry reports every call the client makes to e, for clients that call a provider directly (For, ForFrom, OpenAI, OpenAIResponses, Anthropic, Gemini). On a relay client (Relay, RelayWS) it is a configuration error surfaced on the first call: relay records those calls itself, and reporting them too would count them twice.
func WithWireRules ¶ added in v0.7.28
WithWireRules sets the wire rules requests are serialized under, replacing the ones the client picked from sdk/wirerules: a Chat Completions client built by For takes the row of its catalog host, else of its base URL's host; one built by OpenAI or New takes the row of its base URL's host. Use it for an address the table cannot know, such as a self-hosted Ollama; v1.WireRules{} sends the shape as defined. Non-zero rules on a translator that does not implement v1.WireRulesSerializer fail every call.
type Origin ¶ added in v0.7.23
type Origin string
Origin names where a Models or Catalog result came from.
const ( // OriginRelay is a result the relay server returned for the client's credential: only what that credential can route to, from the deployment's live catalog. OriginRelay Origin = "relay" // OriginCatalog is the latest public catalog from the catalog server, read by a client that doesn't go through relay. It is what the catalog says the host serves, not what the provider key can call. OriginCatalog Origin = "catalog" // OriginEmbedded is the public catalog compiled into this SDK. A relay client gets it when relay could not be reached and no earlier relay copy is held; it is not scoped to the credential and may list models the relay doesn't serve. Any other client gets it when the catalog server is off or unreachable, or its latest release is older than the embed. OriginEmbedded Origin = "embedded" )
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream iterates canonical events. For a relay target the upstream stream is already canonical (toCanon is nil, frames pass through); for a vendor target toCanon converts each vendor SSE frame to canonical.
func (*Stream) Close ¶
Close releases the underlying response body. With telemetry on, a stream closed before it ended is recorded with the usage seen so far.
func (*Stream) Cost ¶
Cost returns total cost from the target's pricing rate sheet after the stream's terminal usage event has been received. ok is false for relay targets, unpriced hosts, and when usage is not yet available.
func (*Stream) Recv ¶
Recv returns the next canonical event, or io.EOF at end. An upstream frame the translator cannot convert returns its error without ending the stream: calling Recv again continues with the next frame.
func (*Stream) Timing ¶
func (s *Stream) Timing() StreamTiming
Timing reports the stream timing observed so far. Call it after draining the stream for the full picture; mid-stream it reflects events up to the last Recv (ResponseEnd is zero until io.EOF).
type StreamTiming ¶
type StreamTiming struct {
Upstream usage.UpstreamTiming // Start == ResponseStart == TTFT; ResponseEnd == close
Reasoning *usage.ReasoningTiming // nil when the stream carried no reasoning
}
StreamTiming is the client-side timing of one streamed generation, in the exact shape relay ships server-side (usage.UpstreamTiming + usage.ReasoningTiming, microseconds from the GenerateStream call). A consumer reads identical fields whether it called relay or a provider directly — no drift, no branching on the path.
The client has no separate relay→upstream handoff, so Upstream.Start is collapsed onto ResponseStart (both = TTFT); when relay is in the path the relay server records its own earlier Start in its own event.
type Target ¶
type Target struct {
// contains filtered or unexported fields
}
Target is a fully-resolved, self-consistent upstream call config.
binding (and therefore the pricing behind Cost) reflects the catalog entry the ref resolved to. Overrides (WithBaseURL/WithAdapterName) change where and how the call is made but keep that pricing — fine for a same-price proxy, potentially stale if pointed at a genuinely different upstream.
type TargetOption ¶
TargetOption overrides one whole piece of a catalog-resolved Target before the client is built. Each option yields a consistent config — path and translator are only ever swapped via an Adapter.
func WithAdapterName ¶
func WithAdapterName(name string) TargetOption
WithAdapterName swaps the whole wire bundle (translator + path + auth). A path the catalog host sets still wins over the new adapter's default, as on relay's server.
func WithBaseURL ¶
func WithBaseURL(url string) TargetOption
WithBaseURL overrides the resolved host base URL (proxy/gateway). Adapter and auth are unchanged; the request path becomes the adapter's default even when the catalog host sets its own path. Add WithClient(WithPath(...)) for another layout.
func WithClient ¶
func WithClient(opts ...Option) TargetOption
WithClient attaches client Options (custom *http.Client, extra headers, sync timeout, ...) to a catalog-resolved client. They apply over the adapter's defaults at construction.
func WithUpstreamModel ¶
func WithUpstreamModel(name string) TargetOption
WithUpstreamModel overrides the wire model name sent upstream.