Documentation
¶
Index ¶
- Constants
- Variables
- func APIKeyRecord(apiKey string) tokenstore.Record
- func KnownModelSurface(surface ModelSurface) bool
- func ListingSurfaces(provider Provider, credential *Credential, evidence TransportEvidence, ...) (native, emulated, unknown []string)
- func NewProviderOperationError(op string, statusCode int, retryAfter string, err error) error
- func PreservesWire(provider Provider, model string, surface ModelSurface) bool
- func PreservesWireFor(provider Provider, credential *Credential, model string, surface ModelSurface) bool
- func ResponseTransportMode(provider Provider, credential *Credential, model string, surface ModelSurface, ...) string
- func ServesNatively(provider Provider, model string, surface ModelSurface) bool
- func SurfacePath(surface ModelSurface) string
- type AccountEvidence
- type AllowAllPolicy
- type Authenticator
- type AuthenticatorFunc
- type Caller
- type CallerKind
- type CatalogEvidence
- type CatalogEvidenceStatus
- type CatalogKey
- type CatalogRecord
- type CatalogStore
- type CompletionProbeEvidence
- type CompletionProbeStatus
- type ConditionalCatalogStore
- type Config
- type Credential
- type CredentialResolver
- type CredentialStore
- type CredentialWirePreserver
- type Disposition
- type Engine
- type EvidenceSink
- type EvidenceSinkFunc
- type FreshnessStatus
- type GenerateImagesRequest
- type GenerateImagesResult
- type GeneratedImage
- type ImageGenerator
- type Loss
- type LossAction
- type LossPolicy
- type LossPolicyError
- type LossReporter
- type LossRule
- type MemoryCatalogStore
- func (s *MemoryCatalogStore) Delete(ctx context.Context, key CatalogKey) error
- func (s *MemoryCatalogStore) Load(ctx context.Context, key CatalogKey) (CatalogRecord, error)
- func (s *MemoryCatalogStore) Save(ctx context.Context, key CatalogKey, evidence CatalogEvidence) (string, error)
- func (s *MemoryCatalogStore) SaveIf(ctx context.Context, key CatalogKey, evidence CatalogEvidence, expected string) (string, error)
- type MemoryCredentialStore
- type MemoryEvidenceSink
- type ModelCapabilities
- type ModelCapabilityConfidence
- type ModelCapabilityFreshness
- type ModelCapabilityLimits
- type ModelCapabilityProvenance
- type ModelCapabilitySource
- type ModelInfo
- type ModelInputCapabilities
- type ModelOperation
- type ModelOperationCapabilities
- type ModelSurface
- type ModelSurfaceCapabilities
- type PolicyGate
- type Principaldeprecated
- func (p *Principal) Caller() Callerdeprecated
- type Provider
- type ProviderAdapter
- type ProviderAuthKind
- type ProviderAuthenticationValidator
- type ProviderCompletionRuntime
- type ProviderConfig
- type ProviderConnectRequest
- type ProviderConnectResult
- type ProviderConnection
- type ProviderConnectionKind
- type ProviderConnector
- type ProviderError
- type ProviderErrorClass
- type ProviderErrorClassification
- type ProviderErrorClassifier
- type ProviderFailure
- type ProviderHealthEvidence
- type ProviderHealthStatus
- type ProviderModelDiscoverer
- type ProviderOperationError
- type ProviderOrchestrator
- type ProviderProbeSelector
- type Request
- type Resolution
- type Response
- type RouteConfig
- type StaticCredentialResolver
- type StreamIter
- type Support
- type SurfaceError
- type Target
- type TargetPublicationPolicy
- type TokenCount
- type TokenCountRequest
- type TokenCounter
- type TransportConfidence
- type TransportDisposition
- type TransportEvidence
- type TransportInterface
- type TransportPlan
- type TransportPlanRequest
- type TransportRejectError
- type TransportRejectReason
- type TransportRequirement
- type UsageHook
- type UsageHookFunc
- type UsageRecord
- type WirePreserver
Constants ¶
const ( // TokenTypeGCPServiceAccount marks a Google Cloud service-account key. // Token is the key's JSON document as Google issues it, which a // provider exchanges for short-lived access tokens and never sends. // Metadata may name, under CredentialMetadataProjectID, the project // calls are billed to when it is not the key's own. The spelling is // llm-provider-auth's gcp.CredentialKind. TokenTypeGCPServiceAccount = "gcp_service_account" // TokenTypeAnthropicSetupToken marks an Anthropic setup token, the // long-lived OAuth token of a Claude subscription. Token is the setup // token, which Anthropic takes as a bearer with its OAuth beta marker // rather than as an x-api-key; llm-provider-auth's anthropic package // validates it and applies those headers. TokenTypeAnthropicSetupToken = "anthropic_setup_token" )
Credential kinds whose material is neither a static API key nor an OAuth access token.
A Credential of such a kind names it in TokenType, carries the kind's material in Token, never in APIKey, and carries its extras in Metadata under the keys the kind documents. A token-store record of the same TokenType, holding the material as its access token without an expiry, becomes such a credential through CredentialFromRecord.
The material is not a bearer token, and only a provider that serves the kind reads it. A product therefore binds such a credential only to an instance whose provider serves its kind.
const ( // CredentialMetadataOAuthProfile names how the owner signed in, such as // a device or a browser login. The provider defines the values. CredentialMetadataOAuthProfile = "oauth_profile" // CredentialMetadataOAuthClientID is the OAuth client the grant belongs to. CredentialMetadataOAuthClientID = "oauth_client_id" // CredentialMetadataOAuthClientMode is how that client authenticates, // such as public or confidential. CredentialMetadataOAuthClientMode = "oauth_client_mode" // CredentialMetadataOAuthRedirectURI is the redirect URI of a browser // login. CredentialMetadataOAuthRedirectURI = "oauth_redirect_uri" // CredentialMetadataOAuthClientSecret is a confidential client's secret. CredentialMetadataOAuthClientSecret = "oauth_client_secret" // CredentialMetadataAccountLabel is a label for the account, such as an // email address, for display. CredentialMetadataAccountLabel = "account_label" // CredentialMetadataProjectID is the upstream project the credential's // calls are billed to, such as the Code Assist project of an Antigravity // login. A provider that discovers it lets the product store it here. CredentialMetadataProjectID = "project_id" )
Metadata keys under which a record carries what its OAuth grant and its provider need later, the way the gateway's credential store keeps them. A refresh reads them so each credential refreshes with the client it was granted to, not whichever client is configured now.
const ( EvidenceOperationInvoke = "invoke" EvidenceOperationStream = "stream" EvidenceOperationListModels = "list_models" )
Operations named in AccountEvidence.
const ( ContentTypeJSON = "application/json" ContentTypeEventStream = "text/event-stream" )
Content types of JSON bodies and SSE streams.
const ( ListingChatCompletions = "/v1/chat/completions" ListingResponses = "/v1/responses" ListingMessages = "/v1/messages" )
The chat surfaces a model list classifies, labelled as the gateway's /v1/models labels them.
const ( TransportModeNative = "native" TransportModeTranslated = "translated" TransportModeTransparent = "transparent" )
The transport labels of a response.
const DefaultTransportFreshness = time.Hour
DefaultTransportFreshness is how long after its catalog was refreshed a row counts as fresh evidence for transport planning: the gateway's hour, whatever TTL the catalog itself has.
const ModelCapabilitiesSchemaVersion = 1
const TokenTypeAPIKey = "api_key"
TokenTypeAPIKey marks a token-store record that holds a static API key rather than an OAuth access token.
Variables ¶
var ErrCatalogConflict = errors.New("core: catalog revision conflict")
ErrCatalogConflict reports a conditional save whose expected revision is no longer the key's revision.
var ErrCatalogNotFound = errors.New("core: catalog not found")
ErrCatalogNotFound reports that no catalog is stored for a key.
var ErrInvalidTransportRequirement = errors.New("core: a requested transport must be transparent when present")
ErrInvalidTransportRequirement reports a requested transport other than transparent.
var ErrNoCredential = errors.New("core: no credential resolves for this caller and instance")
ErrNoCredential reports that no credential resolves for a caller and a provider instance.
var ErrTokenCountUnsupported = errors.New("core: the provider cannot count tokens natively")
ErrTokenCountUnsupported reports a provider that cannot count a request's tokens natively. A product may estimate the count instead, as the gateway does for a target that cannot count.
Functions ¶
func APIKeyRecord ¶ added in v0.9.0
func APIKeyRecord(apiKey string) tokenstore.Record
APIKeyRecord returns the token-store record of a static API key. It has no expiry, so tokenstore.Coordinator never refreshes it.
func KnownModelSurface ¶ added in v0.9.0
func KnownModelSurface(surface ModelSurface) bool
KnownModelSurface reports whether a surface is defined by this version.
func ListingSurfaces ¶ added in v0.14.0
func ListingSurfaces(provider Provider, credential *Credential, evidence TransportEvidence, evaluatedAt time.Time) (native, emulated, unknown []string)
ListingSurfaces classifies the chat surfaces of a model list's row, as the gateway's native_surfaces, emulated_surfaces and unknown_surfaces do: a surface is native when a plan under TransportRequirementAny carries it natively, emulated when the plan adapts it, and unknown when it refuses. A row that neither claims chat in LegacyCapabilities nor lists a chat surface classifies nothing. The row is as the list presents it, so a product that infers capabilities or surfaces for presentation passes them in its LegacyCapabilities and SupportedAPIs. Credential is the one the caller's requests carry.
func NewProviderOperationError ¶ added in v0.3.0
NewProviderOperationError creates a classifiable provider error. Callers should not put response bodies, credentials, or private endpoints in op.
func PreservesWire ¶ added in v0.14.0
func PreservesWire(provider Provider, model string, surface ModelSurface) bool
PreservesWire reports whether provider forwards surface for model in its own wire protocol: each layer serves the surface natively, and the nearest WirePreserver says so.
A decorator that hands the requests of its native surfaces to the provider it wraps unchanged, as translation.Adapter does, exposes that provider through an Unwrap() Provider method, and PreservesWire looks through it. A decorator that changes those requests declares for itself instead. A provider that neither declares nor unwraps preserves nothing.
func PreservesWireFor ¶ added in v0.14.0
func PreservesWireFor(provider Provider, credential *Credential, model string, surface ModelSurface) bool
PreservesWireFor is PreservesWire for a request that carries credential: the nearest layer that declares either interface decides, and a CredentialWirePreserver answers for the credential.
func ResponseTransportMode ¶ added in v0.14.0
func ResponseTransportMode(provider Provider, credential *Credential, model string, surface ModelSurface, evidence *TransportEvidence, evaluatedAt time.Time) string
ResponseTransportMode labels the transport of a response an exact target served a request that carried credential, as the gateway's X-LLMGW-Transport-Mode does. With evidence from the target's stored catalog row, it is native when a plan under TransportRequirementAny carries the surface natively. Without it, it reports the path the provider takes: native when the provider preserves the surface's wire. Anything else is translated.
func ServesNatively ¶ added in v0.9.0
func ServesNatively(provider Provider, model string, surface ModelSurface) bool
ServesNatively reports whether provider serves surface for model without translation.
func SurfacePath ¶ added in v1.3.0
func SurfacePath(surface ModelSurface) string
SurfacePath returns the endpoint path that names surface in a catalog row's SupportedAPIs, with the /v1 prefix: "/v1/chat/completions" for Chat Completions or "/v1/audio/speech" for speech. Core reads each path back as its surface: ParseSurfacePath and AdaptModelCapabilities recognize a chat surface's path, and AdaptModelCapabilities infers the operation of any other. A surface this version does not define has no path: SurfacePath returns the empty string.
Types ¶
type AccountEvidence ¶ added in v0.9.0
type AccountEvidence struct {
Caller Caller
Instance string
// CredentialKey and CredentialRevision identify the token-store record
// that served the operation; AccountID is the account it is bound to.
CredentialKey string
CredentialRevision string
AccountID string
Operation string
Surface ModelSurface
Model string
// Outcome is the classified result, including when it was observed.
Outcome ProviderHealthEvidence
}
AccountEvidence attributes one provider operation to the credential that served it, so a product can audit usage and detect a stale or replaced credential. It carries no secrets.
type AllowAllPolicy ¶
type AllowAllPolicy struct{}
AllowAllPolicy is a PolicyGate that permits all requests.
type Authenticator ¶
Authenticator authenticates an incoming HTTP request. If not configured, requests proceed as anonymous.
type AuthenticatorFunc ¶
AuthenticatorFunc is a functional adapter for Authenticator.
func (AuthenticatorFunc) Authenticate ¶
func (f AuthenticatorFunc) Authenticate(r *http.Request) (*Principal, error)
type Caller ¶ added in v0.9.0
type Caller struct {
ID string `json:"id"`
Kind CallerKind `json:"kind"`
ProjectID string `json:"project_id,omitempty"`
}
Caller identifies who a request acts for. Products map their own identity types onto it; core never needs more than these fields. ProjectID is optional.
func LocalCaller ¶ added in v0.9.0
func LocalCaller() Caller
LocalCaller is the caller of a single-user application. It is a complete, valid Caller.
type CallerKind ¶ added in v0.9.0
type CallerKind string
CallerKind classifies who is making a request.
const ( // CallerHuman is a signed-in person. CallerHuman CallerKind = "human" // CallerService is an automation identity, such as an API key. CallerService CallerKind = "service" // CallerAnonymous is an unauthenticated request. CallerAnonymous CallerKind = "anonymous" // CallerLocal is the single user of a local, single-user application. CallerLocal CallerKind = "local" )
type CatalogEvidence ¶ added in v0.3.0
type CatalogEvidence struct {
Status CatalogEvidenceStatus `json:"status"`
Models []ModelInfo `json:"models,omitempty"`
ObservedAt time.Time `json:"observed_at,omitempty"`
SchemaVersion int `json:"schema_version,omitempty"`
}
CatalogEvidence records what a provider advertised. Discovery alone does not prove that any model can successfully perform inference.
SchemaVersion stamps the rules that wrote the evidence, so a product that changes what a stored row means can refuse rows older rules wrote.
type CatalogEvidenceStatus ¶ added in v0.3.0
type CatalogEvidenceStatus string
const ( CatalogNotProbed CatalogEvidenceStatus = "not_probed" CatalogDiscovered CatalogEvidenceStatus = "discovered" CatalogEmpty CatalogEvidenceStatus = "empty" CatalogFailed CatalogEvidenceStatus = "failed" )
type CatalogKey ¶ added in v0.9.0
CatalogKey identifies one stored catalog: a provider instance and the key of the credential that discovered it. A catalog depends on the credential, not on the caller: callers sharing a system credential share its catalog, while a personal subscription gets its own. An empty CredentialKey is the catalog of a provider discovered without a credential.
type CatalogRecord ¶ added in v0.9.0
type CatalogRecord struct {
Evidence CatalogEvidence
Revision string
}
CatalogRecord is a stored catalog and its revision. The revision is opaque and changes on every save.
type CatalogStore ¶ added in v0.9.0
type CatalogStore interface {
// Load returns the stored record, or ErrCatalogNotFound.
Load(ctx context.Context, key CatalogKey) (CatalogRecord, error)
// Save stores evidence and returns its new revision.
Save(ctx context.Context, key CatalogKey, evidence CatalogEvidence) (revision string, err error)
}
CatalogStore keeps discovered catalogs where every process that shares the store can read them.
Save must be atomic with respect to Load in any process: a reader sees the previous record or the new one, never a mix. Because the revision changes on every save, a Runtime that cached a catalog can tell another process's write from its own. The catalogtest package verifies these guarantees.
type CompletionProbeEvidence ¶ added in v0.3.0
type CompletionProbeEvidence struct {
Target Target `json:"target"`
Status CompletionProbeStatus `json:"status"`
ObservedAt time.Time `json:"observed_at,omitempty"`
Latency time.Duration `json:"latency,omitempty"`
FailureCode string `json:"failure_code,omitempty"`
}
CompletionProbeEvidence records inference evidence for one exact target.
func (CompletionProbeEvidence) InferenceVerified ¶ added in v0.3.0
func (e CompletionProbeEvidence) InferenceVerified() bool
type CompletionProbeStatus ¶ added in v0.3.0
type CompletionProbeStatus string
const ( CompletionNotProbed CompletionProbeStatus = "not_probed" CompletionVerified CompletionProbeStatus = "verified" CompletionFailed CompletionProbeStatus = "failed" )
type ConditionalCatalogStore ¶ added in v0.14.0
type ConditionalCatalogStore interface {
CatalogStore
// SaveIf stores evidence and returns its new revision only while the
// key's revision is expected, atomically. Otherwise it changes nothing
// and returns ErrCatalogConflict.
SaveIf(ctx context.Context, key CatalogKey, evidence CatalogEvidence, expected string) (revision string, err error)
// Delete forgets the key's record and gives the key a new revision, so
// a SaveIf that expects any earlier state conflicts. Deleting a key
// that holds no record succeeds.
Delete(ctx context.Context, key CatalogKey) error
}
ConditionalCatalogStore is a CatalogStore that can fence writes and forget catalogs. A catalog.Service uses it so that a discovery which ran across an invalidation, in this process or another, cannot store what the invalidation removed.
A key's revision is its record's, or the revision Delete left, or empty for a key never saved. Load of a deleted key returns ErrCatalogNotFound together with a record that carries only that revision, so a caller can expect it. The catalogtest package verifies these guarantees.
type Config ¶
type Config struct {
Providers map[string]ProviderConfig `json:"providers"`
Routes map[string]RouteConfig `json:"routes"`
DefaultRoute string `json:"default_route,omitempty"`
// Pluggable extension hooks
Authenticator Authenticator
PolicyGate PolicyGate
CredentialResolver CredentialResolver
UsageHook UsageHook
}
Config configures the core LLM Gateway engine.
type Credential ¶
type Credential struct {
APIKey string `json:"api_key,omitempty"`
Token string `json:"token,omitempty"`
ConnectionID string `json:"connection_id,omitempty"`
CredentialRevision int64 `json:"credential_revision,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
// AccountID identifies the upstream account the credential belongs to,
// such as the ChatGPT account a Codex token acts for. Empty when unknown.
AccountID string `json:"account_id,omitempty"`
// TokenType names the kind of credential: TokenTypeAPIKey for a static
// key, usually "Bearer" for an OAuth token, or a kind the provider
// defines, such as a service account.
TokenType string `json:"token_type,omitempty"`
// Metadata carries provider-specific values, such as a project ID.
// Providers read it and never write it, because a credential may serve
// concurrent requests. It may hold secrets, such as a client secret, so
// it never serializes and its values never print.
Metadata map[string]string `json:"-"`
}
Credential contains authentication secrets for an upstream provider.
fmt and slog print whether each secret is set, never its value. JSON encoding carries every field but Metadata, so slog's JSON handler reveals the secrets of a credential nested in another logged value.
func CredentialFromRecord ¶ added in v0.9.0
func CredentialFromRecord(key string, record tokenstore.Record) *Credential
CredentialFromRecord converts a stored record into the credential a provider receives. The access token becomes APIKey for an API-key record and Token otherwise, and the key becomes ConnectionID. AccountID, TokenType and Metadata carry over, so a provider can address the account, tell what kind of credential it holds and read its provider-specific values. Metadata is copied, so the credential and the record never share a map. The refresh token stays behind, because only tokenstore.Coordinator refreshes. Record revisions are opaque strings, so CredentialRevision stays zero and evidence carries the revision instead.
func (Credential) Format ¶ added in v0.10.0
func (c Credential) Format(state fmt.State, verb rune)
Format keeps every verb from printing secrets. Without it, fmt uses String and GoString only for %v, %s, %q, %x and %X, and prints the fields for any other verb, secrets included. Only %p of a value and %w escape it: fmt reports those as bad verbs and prints the fields without calling a method.
func (Credential) GoString ¶ added in v0.10.0
func (c Credential) GoString() string
GoString keeps %#v from printing secrets.
func (Credential) LogValue ¶ added in v0.10.0
func (c Credential) LogValue() slog.Value
LogValue keeps structured logging from printing secrets. Metadata keys are sorted, so equal credentials log alike.
func (Credential) String ¶ added in v0.10.0
func (c Credential) String() string
String describes the credential without its secrets. The API key, the token and the headers print only whether they are set, and each Metadata key prints with only whether its value is set.
type CredentialResolver ¶
type CredentialResolver interface {
Resolve(ctx context.Context, principal *Principal, providerID string) (*Credential, error)
}
CredentialResolver resolves upstream credentials for a principal and provider.
type CredentialStore ¶ added in v0.9.0
type CredentialStore interface {
tokenstore.Store
// Resolve returns the key of the credential that serves caller on
// instance, or ErrNoCredential.
Resolve(ctx context.Context, caller Caller, instance string) (key string, err error)
}
CredentialStore holds the credentials a Runtime uses.
It is the llm-provider-auth token store plus Resolve. The store's Lease must exclude every process that shares it: a file store holds an OS advisory lock on a separate lock file, and a database store holds a lease row with a holder and an expiry, never a transaction held across a refresh.
Resolve names the credential for a caller and a provider instance. Which credential applies is product policy. Keeping it fresh is not: the Runtime refreshes OAuth credentials through tokenstore.Coordinator, which never lets a refresh change the account.
type CredentialWirePreserver ¶ added in v0.14.0
type CredentialWirePreserver interface {
// PreservesWireFor reports whether the provider forwards surface for
// model in its own wire protocol when the request carries credential,
// which may be nil. It is consulted only for a surface the provider
// serves natively.
PreservesWireFor(credential *Credential, model string, surface ModelSurface) bool
}
CredentialWirePreserver is an optional Provider interface for a provider whose wire preservation depends on the credential a request carries. A provider that reshapes every anonymous request, as OpenCode Zen's admission does, preserves nothing for a request without a key, whatever it preserves for one with a key.
type Disposition ¶ added in v0.9.0
type Disposition string
Disposition is what a failure permits a router to do next.
const ( // DispositionRetryable permits retrying the same target, and failing over. DispositionRetryable Disposition = "retryable" // DispositionFailover permits trying the next target but not repeating // this one. DispositionFailover Disposition = "failover" // DispositionTerminal ends the request: no target would serve it. DispositionTerminal Disposition = "terminal" )
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the core LLM Gateway routing and proxy engine. It implements http.Handler and can be mounted directly on any router.
func (*Engine) RegisterProvider ¶
RegisterProvider registers an active provider backend.
type EvidenceSink ¶ added in v0.9.0
type EvidenceSink interface {
Record(ctx context.Context, evidence AccountEvidence)
}
EvidenceSink receives account evidence. Record must neither fail nor delay the operation it describes: a sink that persists evidence buffers or drops.
type EvidenceSinkFunc ¶ added in v0.9.0
type EvidenceSinkFunc func(ctx context.Context, evidence AccountEvidence)
EvidenceSinkFunc adapts a function to EvidenceSink.
func (EvidenceSinkFunc) Record ¶ added in v0.9.0
func (f EvidenceSinkFunc) Record(ctx context.Context, evidence AccountEvidence)
Record implements EvidenceSink.
type FreshnessStatus ¶ added in v0.3.0
type FreshnessStatus string
const ( FreshnessUnknown FreshnessStatus = "unknown" FreshnessFresh FreshnessStatus = "fresh" FreshnessExpired FreshnessStatus = "expired" )
type GenerateImagesRequest ¶ added in v0.6.0
type GenerateImagesRequest struct {
Model string `json:"model"`
Prompt string `json:"prompt"`
Count int `json:"count,omitempty"`
}
GenerateImagesRequest is the storage-neutral input for image synthesis. Count is a caller-side result bound; providers may return fewer images.
type GenerateImagesResult ¶ added in v0.6.0
type GenerateImagesResult struct {
Images []GeneratedImage `json:"images"`
Usage map[string]any `json:"usage,omitempty"`
}
GenerateImagesResult contains generated bytes and provider-native usage.
type GeneratedImage ¶ added in v0.6.0
GeneratedImage contains one decoded inline image returned by a provider.
type ImageGenerator ¶ added in v0.6.0
type ImageGenerator interface {
GenerateImages(context.Context, GenerateImagesRequest, *Credential) (GenerateImagesResult, error)
}
ImageGenerator is implemented by providers with a typed image-generation operation. It makes no assumptions about credential or image storage.
type Loss ¶ added in v0.9.0
Loss is one compatibility finding from translating between surfaces or from adapting a request to a provider. It is llm-translate's type, so both kinds of finding combine in one report.
func StreamLosses ¶ added in v0.9.0
func StreamLosses(stream StreamIter) []Loss
StreamLosses returns the losses a stream reports, or nil for a stream that does not translate.
type LossAction ¶ added in v0.9.0
type LossAction string
LossAction is what a loss policy does with one loss.
const ( LossAllow LossAction = "allow" LossReject LossAction = "reject" )
type LossPolicy ¶ added in v0.9.0
type LossPolicy struct {
Rules []LossRule
}
LossPolicy decides which translation and adaptation losses a product accepts.
Rules apply in order and the first match decides. A loss that no rule matches is rejected unless it is advisory, so an unknown severity counts as material. Allowed losses are still reported to the caller.
func (LossPolicy) Check ¶ added in v0.9.0
func (p LossPolicy) Check(losses []Loss) error
Check returns a *LossPolicyError when the policy rejects any loss.
func (LossPolicy) Decide ¶ added in v0.9.0
func (p LossPolicy) Decide(loss Loss) LossAction
Decide returns the action for one loss.
func (LossPolicy) Rejected ¶ added in v0.9.0
func (p LossPolicy) Rejected(losses []Loss) []Loss
Rejected returns the losses the policy rejects, in report order.
func (LossPolicy) Validate ¶ added in v0.9.0
func (p LossPolicy) Validate() error
Validate reports a malformed rule.
type LossPolicyError ¶ added in v0.9.0
type LossPolicyError struct {
Losses []Loss
}
LossPolicyError reports losses a policy rejected. Another target may serve the surface natively, so it permits failover.
func (*LossPolicyError) Error ¶ added in v0.9.0
func (e *LossPolicyError) Error() string
func (*LossPolicyError) ProviderErrorClassification ¶ added in v0.9.0
func (e *LossPolicyError) ProviderErrorClassification() ProviderErrorClassification
ProviderErrorClassification permits failover without marking the provider unhealthy.
type LossReporter ¶ added in v0.9.0
type LossReporter interface {
Losses() []Loss
}
LossReporter is implemented by streams that translate. Losses returns the request-side losses before the first frame and adds response-side losses as frames are translated; the report is complete once Next returns io.EOF.
type LossRule ¶ added in v0.9.0
type LossRule struct {
// Path is a glob over the dot-separated loss path. "*" matches exactly one
// segment, "**" matches any number of segments including none, and any
// other segment matches literally. An empty Path matches every loss.
Path string
// Class and Severity narrow the rule. Empty matches any value.
Class translate.LossClass
Severity translate.LossSeverity
Action LossAction
}
LossRule matches losses and decides them.
type MemoryCatalogStore ¶ added in v0.9.0
type MemoryCatalogStore struct {
// contains filtered or unexported fields
}
MemoryCatalogStore is the in-memory reference CatalogStore. It is a ConditionalCatalogStore too.
func NewMemoryCatalogStore ¶ added in v0.9.0
func NewMemoryCatalogStore() *MemoryCatalogStore
NewMemoryCatalogStore returns an empty store.
func (*MemoryCatalogStore) Delete ¶ added in v0.14.0
func (s *MemoryCatalogStore) Delete(ctx context.Context, key CatalogKey) error
Delete implements ConditionalCatalogStore.
func (*MemoryCatalogStore) Load ¶ added in v0.9.0
func (s *MemoryCatalogStore) Load(ctx context.Context, key CatalogKey) (CatalogRecord, error)
Load implements CatalogStore.
func (*MemoryCatalogStore) Save ¶ added in v0.9.0
func (s *MemoryCatalogStore) Save(ctx context.Context, key CatalogKey, evidence CatalogEvidence) (string, error)
Save implements CatalogStore.
func (*MemoryCatalogStore) SaveIf ¶ added in v0.14.0
func (s *MemoryCatalogStore) SaveIf(ctx context.Context, key CatalogKey, evidence CatalogEvidence, expected string) (string, error)
SaveIf implements ConditionalCatalogStore.
type MemoryCredentialStore ¶ added in v0.9.0
type MemoryCredentialStore struct {
*tokenstore.Memory
// contains filtered or unexported fields
}
MemoryCredentialStore is the in-memory reference CredentialStore: tokenstore.Memory plus a resolution table. Resolve prefers a binding for the exact caller and falls back to the instance's shared binding, the way a product prefers a user's own credential over a system one.
func NewMemoryCredentialStore ¶ added in v0.9.0
func NewMemoryCredentialStore() *MemoryCredentialStore
NewMemoryCredentialStore returns an empty store.
func (*MemoryCredentialStore) Bind ¶ added in v0.9.0
func (s *MemoryCredentialStore) Bind(caller Caller, instance, key string)
Bind makes key the credential of caller on instance.
func (*MemoryCredentialStore) BindShared ¶ added in v0.9.0
func (s *MemoryCredentialStore) BindShared(instance, key string)
BindShared makes key the credential of every caller on instance that has no binding of its own.
type MemoryEvidenceSink ¶ added in v0.9.0
type MemoryEvidenceSink struct {
// contains filtered or unexported fields
}
MemoryEvidenceSink is the in-memory reference EvidenceSink.
func (*MemoryEvidenceSink) Record ¶ added in v0.9.0
func (s *MemoryEvidenceSink) Record(_ context.Context, evidence AccountEvidence)
Record implements EvidenceSink.
func (*MemoryEvidenceSink) Records ¶ added in v0.9.0
func (s *MemoryEvidenceSink) Records() []AccountEvidence
Records returns a copy of everything recorded, oldest first.
type ModelCapabilities ¶ added in v0.3.0
type ModelCapabilities struct {
SchemaVersion int `json:"schema_version"`
Operations ModelOperationCapabilities `json:"operations"`
Surfaces ModelSurfaceCapabilities `json:"surfaces"`
Inputs ModelInputCapabilities `json:"inputs"`
Tools Support `json:"tools"`
Reasoning Support `json:"reasoning"`
StructuredOutput Support `json:"structured_output"`
Streaming Support `json:"streaming"`
StatefulResponses Support `json:"stateful_responses"`
Limits ModelCapabilityLimits `json:"limits"`
Provenance ModelCapabilityProvenance `json:"provenance"`
Freshness ModelCapabilityFreshness `json:"freshness"`
}
ModelCapabilities is the bounded version 1 shared model capability contract.
func AdaptModelCapabilities ¶ added in v0.14.0
func AdaptModelCapabilities( legacy map[string]any, surfaces []string, discoveredAt, verifiedAt time.Time, ) *ModelCapabilities
AdaptModelCapabilities converts the gateway's compatibility metadata into the bounded capability contract: legacy is a catalog row's untyped capability map, and surfaces are the endpoints it lists. Missing keys remain unknown; only explicit false values become unsupported.
It is the gateway's function, ported verbatim, so a product and the gateway infer the same capabilities from the same row. The result is inferred with medium confidence. A listed chat surface supports the chat operation, and chat implies text input unless the map says otherwise. Freshness records the times given, in UTC, and never an expiry.
func InferCapabilities ¶ added in v0.14.0
func InferCapabilities(model ModelInfo, discoveredAt, verifiedAt time.Time) *ModelCapabilities
InferCapabilities infers a row's capabilities from what the row lists, its LegacyCapabilities and its SupportedAPIs, through AdaptModelCapabilities. It ignores Capabilities, so the caller decides whether capabilities a catalog reported take precedence over inferred ones, as the gateway's catalog lets them when it stores a row.
func (ModelCapabilities) OperationCompatibility ¶ added in v0.3.0
func (c ModelCapabilities) OperationCompatibility(operation ModelOperation) Support
OperationCompatibility returns unknown for both unreported capabilities and operation values outside this schema version.
func (ModelCapabilities) SurfaceCompatibility ¶ added in v0.3.0
func (c ModelCapabilities) SurfaceCompatibility(surface ModelSurface) Support
SurfaceCompatibility returns unknown for both unreported capabilities and surface values outside this schema version.
type ModelCapabilityConfidence ¶ added in v0.3.0
type ModelCapabilityConfidence string
const ( ModelCapabilityConfidenceLow ModelCapabilityConfidence = "low" ModelCapabilityConfidenceMedium ModelCapabilityConfidence = "medium" ModelCapabilityConfidenceHigh ModelCapabilityConfidence = "high" )
type ModelCapabilityFreshness ¶ added in v0.3.0
type ModelCapabilityFreshness struct {
DiscoveredAt *time.Time `json:"discovered_at,omitempty"`
VerifiedAt *time.Time `json:"verified_at,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
func (ModelCapabilityFreshness) IsFresh ¶ added in v0.3.0
func (f ModelCapabilityFreshness) IsFresh(at time.Time) bool
func (ModelCapabilityFreshness) Status ¶ added in v0.3.0
func (f ModelCapabilityFreshness) Status(at time.Time) FreshnessStatus
Status reports unknown when no expiry was supplied. Expiry is inclusive: a capability is expired at its expires_at instant.
type ModelCapabilityLimits ¶ added in v0.3.0
type ModelCapabilityLimits struct {
ContextTokens *int64 `json:"context_tokens,omitempty"`
MaxOutputTokens *int64 `json:"max_output_tokens,omitempty"`
}
ModelCapabilityLimits uses pointers so an unknown limit is distinct from a provider-reported numeric value.
type ModelCapabilityProvenance ¶ added in v0.3.0
type ModelCapabilityProvenance struct {
Source ModelCapabilitySource `json:"source"`
Confidence ModelCapabilityConfidence `json:"confidence"`
}
type ModelCapabilitySource ¶ added in v0.3.0
type ModelCapabilitySource string
const ( ModelCapabilitySourceUpstreamReported ModelCapabilitySource = "upstream_reported" ModelCapabilitySourceRegistryStatic ModelCapabilitySource = "registry_static" ModelCapabilitySourceModelsDev ModelCapabilitySource = "models_dev" ModelCapabilitySourceInferred ModelCapabilitySource = "inferred" ModelCapabilitySourceOperatorOverride ModelCapabilitySource = "operator_override" )
type ModelInfo ¶
type ModelInfo struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
OwnedBy string `json:"owned_by"`
Description string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
APIEligible *bool `json:"api_eligible,omitempty"`
APIVisibility string `json:"api_visibility,omitempty"`
SupportedAPIs []string `json:"supported_apis,omitempty"`
Capabilities *ModelCapabilities `json:"capabilities,omitempty"`
// DisplayName is the name to show for the model, such as a catalog
// row's display_name.
DisplayName string `json:"display_name,omitempty"`
// Vendor is who makes the model, as the upstream catalog names it.
Vendor string `json:"vendor,omitempty"`
// Free marks a model the upstream serves at no cost, such as a free
// model an anonymous catalog admits. Catalogs that predate the field
// tag such a row "free" instead.
Free bool `json:"free,omitempty"`
// LegacyCapabilities is the gateway's untyped capability map, such as
// {"chat": true, "vision": true, "context_window": 128000}, kept as the
// catalog reported it. InferCapabilities reads it. Copies of a row share
// the map, so copy it before changing it.
LegacyCapabilities map[string]any `json:"legacy_capabilities,omitempty"`
}
ModelInfo describes an available upstream model or alias.
DisplayName, Vendor, Free and LegacyCapabilities carry what the gateway's catalogs record about a row beyond the fields before them. Each is left out of JSON when empty, so a row that sets none of them encodes exactly as it did before they existed.
type ModelInputCapabilities ¶ added in v0.3.0
type ModelOperation ¶ added in v0.3.0
type ModelOperation string
const ( ModelOperationChat ModelOperation = "chat" ModelOperationEmbeddings ModelOperation = "embeddings" ModelOperationImage ModelOperation = "image" ModelOperationAudioIn ModelOperation = "audio_in" ModelOperationAudioOut ModelOperation = "audio_out" ModelOperationVideo ModelOperation = "video" ModelOperationTokenCount ModelOperation = "token_count" )
type ModelOperationCapabilities ¶ added in v0.3.0
type ModelSurface ¶ added in v0.3.0
type ModelSurface string
const ( ModelSurfaceChatCompletions ModelSurface = "chat_completions" ModelSurfaceResponses ModelSurface = "responses" ModelSurfaceMessages ModelSurface = "messages" // Non-chat surfaces. Their request and response bodies are not always // JSON: speech-to-text uploads multipart form data, and speech, image and // video responses are binary. The capabilities schema reports no // compatibility for them yet. ModelSurfaceEmbeddings ModelSurface = "embeddings" ModelSurfaceAudioTranscriptions ModelSurface = "audio_transcriptions" ModelSurfaceAudioSpeech ModelSurface = "audio_speech" ModelSurfaceImages ModelSurface = "images" ModelSurfaceVideos ModelSurface = "videos" )
func ParseSurfacePath ¶ added in v0.14.0
func ParseSurfacePath(path string) ModelSurface
ParseSurfacePath returns the chat surface a request path or a catalog endpoint names, with or without the /v1 prefix: "/v1/responses" and "/responses" are Responses. Anything else, a non-chat surface included, is the empty surface, as in the gateway's transport planning.
type ModelSurfaceCapabilities ¶ added in v0.3.0
type PolicyGate ¶
type PolicyGate interface {
Allows(ctx context.Context, principal *Principal, target Target) (bool, string)
}
PolicyGate controls whether a principal is authorized to access a given provider/model target.
type Principal
deprecated
type Principal struct {
ID string `json:"id"`
Type string `json:"type"` // "user", "api_key", "anonymous", "service"
Name string `json:"name,omitempty"`
ProjectID string `json:"project_id,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
Principal represents the authenticated caller making a request.
Deprecated: new APIs take Caller, and Principal.Caller converts. Principal and the Engine hooks that use it move to Caller in the next minor release.
func (*Principal) Caller
deprecated
added in
v0.9.0
Caller converts a Principal to its Caller.
Deprecated: Principal is replaced by Caller and will be removed in the next minor release. Its Type maps onto a CallerKind: "user" is human, "api_key" and "service" are service, and an empty or "anonymous" type is anonymous.
type Provider ¶ added in v0.9.0
type Provider interface {
// NativeSurfaces lists the surfaces model serves without translation.
NativeSurfaces(model string) []ModelSurface
// Invoke performs one non-streaming operation.
Invoke(ctx context.Context, request Request) (Response, error)
// Stream performs one streaming operation. Each frame is one complete
// SSE record of the surface's stream.
Stream(ctx context.Context, request Request) (StreamIter, error)
// ListModels returns the provider's catalog for the credential.
ListModels(ctx context.Context, credential *Credential) ([]ModelInfo, error)
}
Provider performs wire-level operations on the surfaces it serves natively.
A request for any other surface fails with a *SurfaceError; a translation adapter in front of the provider serves other surfaces. Implementations honour ctx cancellation and take credentials only from the request.
type ProviderAdapter ¶ added in v0.3.0
type ProviderAdapter struct {
ValidateAuthentication ProviderAuthenticationValidator
DiscoverModels ProviderModelDiscoverer
SelectProbeTargets ProviderProbeSelector
Complete ProviderCompletionRuntime
}
ProviderAdapter contains the small provider-specific operations used by the shared connector. Complete is both the probe and reusable runtime path.
type ProviderAuthKind ¶ added in v0.3.0
type ProviderAuthKind string
ProviderAuthKind describes how a provider connection authenticates.
const ( ProviderAuthAPIKey ProviderAuthKind = "api_key" ProviderAuthOAuthDevice ProviderAuthKind = "oauth_device" ProviderAuthOAuthBrowser ProviderAuthKind = "oauth_browser" ProviderAuthServiceAccount ProviderAuthKind = "service_account" ProviderAuthWorkloadIdentity ProviderAuthKind = "workload_identity" ProviderAuthOfficialClient ProviderAuthKind = "official_client" ProviderAuthAnonymous ProviderAuthKind = "anonymous" )
type ProviderAuthenticationValidator ¶ added in v0.3.0
type ProviderAuthenticationValidator func(context.Context, ProviderConnection) error
type ProviderCompletionRuntime ¶ added in v0.3.0
type ProviderConfig ¶
type ProviderConfig struct {
Type string `json:"type"` // "openai_compatible", "anthropic", "googleai", "ollama", "elevenlabs", "mimo", "github_copilot", "codex", "edgetts"
BaseURL string `json:"base_url,omitempty"` // Upstream base endpoint
APIKey string `json:"api_key,omitempty"` // Static API key or token
Timeout time.Duration `json:"timeout,omitempty"` // Request timeout
Headers map[string]string `json:"headers,omitempty"` // Extra HTTP headers
AllowedModels []string `json:"allowed_models,omitempty"` // Whitelist of models
Disabled bool `json:"disabled,omitempty"` // Disable provider
}
ProviderConfig configures a single upstream provider backend.
type ProviderConnectRequest ¶ added in v0.3.0
type ProviderConnectRequest struct {
Connection ProviderConnection `json:"connection"`
PublicationPolicy TargetPublicationPolicy `json:"publication_policy"`
// AuthenticationValidated permits callers that established authentication
// before Connect to omit an adapter authentication validator.
AuthenticationValidated bool `json:"authentication_validated,omitempty"`
}
type ProviderConnectResult ¶ added in v0.3.0
type ProviderConnectResult struct {
Connection ProviderConnection `json:"connection"`
Catalog CatalogEvidence `json:"catalog"`
Probes []CompletionProbeEvidence `json:"probes,omitempty"`
Health ProviderHealthEvidence `json:"health"`
Targets []Target `json:"targets,omitempty"`
}
ProviderConnectResult is the complete, persistence-agnostic outcome of provider onboarding.
type ProviderConnection ¶ added in v0.3.0
type ProviderConnection struct {
ID string `json:"id,omitempty"`
ProviderID string `json:"provider_id"`
Kind ProviderConnectionKind `json:"kind"`
AuthKind ProviderAuthKind `json:"auth_kind"`
OwnerID string `json:"owner_id,omitempty"`
Credential *Credential `json:"-"`
}
ProviderConnection is the persistence-agnostic description of a configured provider connection. Credential is available to connectors but never JSON encoded.
func (ProviderConnection) Validate ¶ added in v0.3.0
func (c ProviderConnection) Validate() error
Validate rejects contradictory connection descriptions. Codex is always a human-owned subscription connection established through device OAuth.
type ProviderConnectionKind ¶ added in v0.3.0
type ProviderConnectionKind string
ProviderConnectionKind describes who owns and may use a provider connection.
const ( ProviderConnectionSystem ProviderConnectionKind = "system" ProviderConnectionPersonal ProviderConnectionKind = "personal" ProviderConnectionPersonalSubscription ProviderConnectionKind = "personal_subscription" ProviderConnectionAnonymous ProviderConnectionKind = "anonymous" )
type ProviderConnector ¶ added in v0.3.0
type ProviderConnector interface {
Connect(ctx context.Context, request ProviderConnectRequest) (ProviderConnectResult, error)
}
ProviderConnector orchestrates provider-specific authentication, discovery, probing, classification, and exact target publication.
type ProviderError ¶ added in v0.9.0
type ProviderError struct {
Message string
Class ProviderErrorClass
Classification ProviderErrorClassification
Cause error
}
ProviderError is the canonical provider failure.
Message is safe to show a client: it never contains credentials, private endpoints or upstream response bodies. Cause keeps the underlying error for errors.Is and errors.As and is never rendered.
func NewConfigurationError ¶ added in v0.9.0
func NewConfigurationError(message string, cause error) *ProviderError
NewConfigurationError reports a provider that cannot run as configured. It permits failover, because another target may be configured correctly, but never marks the provider unhealthy.
func (*ProviderError) Error ¶ added in v0.9.0
func (e *ProviderError) Error() string
func (*ProviderError) ProviderErrorClassification ¶ added in v0.9.0
func (e *ProviderError) ProviderErrorClassification() ProviderErrorClassification
ProviderErrorClassification returns the routing metadata.
func (*ProviderError) Unwrap ¶ added in v0.9.0
func (e *ProviderError) Unwrap() error
type ProviderErrorClass ¶ added in v0.3.0
type ProviderErrorClass string
const ( ProviderErrorNone ProviderErrorClass = "none" ProviderErrorAuth ProviderErrorClass = "auth" ProviderErrorForbidden ProviderErrorClass = "forbidden" ProviderErrorRateLimited ProviderErrorClass = "rate_limited" ProviderErrorTransport ProviderErrorClass = "transport" ProviderErrorUpstream ProviderErrorClass = "upstream" // ProviderErrorBilling is a refusal for want of credit or paid quota, // such as HTTP 402, which waiting out a rate limit does not cure. ProviderErrorBilling ProviderErrorClass = "billing" // ProviderErrorContextOverflow, ProviderErrorToolsUnsupported and // ProviderErrorMediaUnsupported refuse a request's shape: one longer // than the model's context window, one that sends tools to a model // without tool calling, and one that sends an image or other media to a // model that cannot read it. Compacting the history, or leaving out the // tools or the media, may serve it, and so may another model. ProviderErrorContextOverflow ProviderErrorClass = "context_overflow" ProviderErrorToolsUnsupported ProviderErrorClass = "tools_unsupported" ProviderErrorMediaUnsupported ProviderErrorClass = "media_unsupported" )
const ( // ProviderErrorConfiguration is a provider that cannot run as configured. ProviderErrorConfiguration ProviderErrorClass = "configuration" // ProviderErrorInvalidRequest is a request the provider rejects as // malformed; other targets would reject it too. ProviderErrorInvalidRequest ProviderErrorClass = "invalid_request" // ProviderErrorUnsupported is a request this target cannot serve, such as // a surface it lacks or a translation the loss policy rejects. ProviderErrorUnsupported ProviderErrorClass = "unsupported" )
Error classes beyond the upstream causes that health classification reports.
type ProviderErrorClassification ¶ added in v0.4.0
type ProviderErrorClassification struct {
StatusCode int
Retryable bool
FailoverEligible bool
CircuitFailure bool
RetryAfter time.Duration
}
ProviderErrorClassification is the provider-independent routing metadata for an operation failure. StatusCode is zero when no HTTP response was received, and RetryAfter is zero when the provider gave no delay. Disposition summarizes what the failure permits.
func ClassifyError ¶ added in v0.9.0
func ClassifyError(err error) ProviderErrorClassification
ClassifyError returns the routing metadata of any error. An error that does not classify itself, including a canceled context, is terminal.
func (ProviderErrorClassification) Disposition ¶ added in v0.9.0
func (c ProviderErrorClassification) Disposition() Disposition
Disposition summarizes the classification.
type ProviderErrorClassifier ¶ added in v0.4.0
type ProviderErrorClassifier interface {
ProviderErrorClassification() ProviderErrorClassification
}
ProviderErrorClassifier exposes routing metadata without requiring callers to depend on a provider package's concrete error type.
type ProviderFailure ¶ added in v0.3.0
type ProviderFailure struct {
StatusCode int `json:"status_code,omitempty"`
RetryAfter string `json:"retry_after,omitempty"`
ObservedAt time.Time `json:"observed_at,omitempty"`
Err error `json:"-"`
}
ProviderFailure contains only values needed for classification. Err is never serialized because transport errors may include credentials or private hosts.
type ProviderHealthEvidence ¶ added in v0.3.0
type ProviderHealthEvidence struct {
Status ProviderHealthStatus `json:"status"`
ErrorClass ProviderErrorClass `json:"error_class"`
Permanent bool `json:"permanent,omitempty"`
Retryable bool `json:"retryable,omitempty"`
RetryAfter time.Duration `json:"retry_after,omitempty"`
ObservedAt time.Time `json:"observed_at,omitempty"`
}
func ClassifyProviderFailure ¶ added in v0.3.0
func ClassifyProviderFailure(f ProviderFailure) ProviderHealthEvidence
ClassifyProviderFailure maps HTTP and transport outcomes into stable health semantics.
type ProviderHealthStatus ¶ added in v0.3.0
type ProviderHealthStatus string
const ( ProviderHealthUnknown ProviderHealthStatus = "unknown" ProviderHealthHealthy ProviderHealthStatus = "healthy" ProviderHealthDegraded ProviderHealthStatus = "degraded" ProviderHealthUnhealthy ProviderHealthStatus = "unhealthy" )
type ProviderModelDiscoverer ¶ added in v0.3.0
type ProviderModelDiscoverer func(context.Context, ProviderConnection) ([]ModelInfo, error)
type ProviderOperationError ¶ added in v0.3.0
type ProviderOperationError struct {
Failure ProviderFailure
Op string
}
ProviderOperationError preserves classification inputs without exposing an upstream response body or transport error through serialized evidence.
func (*ProviderOperationError) Error ¶ added in v0.3.0
func (e *ProviderOperationError) Error() string
func (*ProviderOperationError) ProviderErrorClassification ¶ added in v0.4.0
func (e *ProviderOperationError) ProviderErrorClassification() ProviderErrorClassification
func (*ProviderOperationError) Unwrap ¶ added in v0.3.0
func (e *ProviderOperationError) Unwrap() error
type ProviderOrchestrator ¶ added in v0.3.0
type ProviderOrchestrator struct {
// contains filtered or unexported fields
}
ProviderOrchestrator resolves only explicitly registered adapters. This is particularly important for Codex: its personal subscription OAuth flow must never fall through to anonymous OpenAI-compatible behavior.
func NewProviderOrchestrator ¶ added in v0.3.0
func NewProviderOrchestrator() *ProviderOrchestrator
func (*ProviderOrchestrator) Connect ¶ added in v0.3.0
func (o *ProviderOrchestrator) Connect(ctx context.Context, request ProviderConnectRequest) (ProviderConnectResult, error)
func (*ProviderOrchestrator) Register ¶ added in v0.3.0
func (o *ProviderOrchestrator) Register(providerID string, adapter ProviderAdapter) error
type ProviderProbeSelector ¶ added in v0.3.0
type ProviderProbeSelector func(ProviderConnection, []ModelInfo) []Target
type Request ¶ added in v0.9.0
type Request struct {
Surface ModelSurface
Model string
Body []byte
ContentType string
Credential *Credential
// Header holds headers the client sent, such as anthropic-version and
// anthropic-beta, that select how the upstream serves the request. A
// provider reads only the headers it explicitly allows, after checking
// their values, and never a credential: only Credential authenticates,
// so a client's Authorization or x-api-key never reaches the upstream.
// Copies of a request, such as its replay after a credential refresh,
// share the map, so providers never write it. Nil means none. Unlike
// Credential, it prints and logs as is.
Header http.Header
}
Request is one wire-level provider operation.
Body is exactly the surface's request body: JSON for the chat surfaces and embeddings, multipart form data for speech-to-text. ContentType names its encoding. The credential is explicit; a provider never looks one up.
type Resolution ¶ added in v0.1.1
type Resolution struct {
Targets []Target `json:"targets"`
Category string `json:"category,omitempty"`
}
Resolution records both the resolved targets and the canonical category name, when the request addressed a category rather than a direct model.
type Response ¶ added in v0.9.0
Response is the result of a non-streaming operation.
Body is the surface's response body, JSON or binary as ContentType says. Losses lists every compatibility loss the operation incurred, including losses the loss policy allowed, so a product can log or label them.
type RouteConfig ¶
type RouteConfig struct {
Targets []Target `json:"targets"` // Ordered targets to try
Fallback bool `json:"fallback,omitempty"` // Fall back to subsequent targets on error
Description string `json:"description,omitempty"` // User-facing description
}
RouteConfig configures an alias (failover chain) across multiple provider targets.
type StaticCredentialResolver ¶
type StaticCredentialResolver struct {
Credentials map[string]Credential
}
StaticCredentialResolver returns pre-configured credentials from a map.
func (StaticCredentialResolver) Resolve ¶
func (s StaticCredentialResolver) Resolve(ctx context.Context, principal *Principal, providerID string) (*Credential, error)
type StreamIter ¶ added in v0.4.0
StreamIter yields complete SSE frames from an active provider stream.
type Support ¶ added in v0.3.0
type Support uint8
Support is an explicitly tri-state capability value. Its zero value is SupportUnknown and marshals as "unknown" rather than false.
func (Support) IsSupported ¶ added in v0.3.0
func (Support) MarshalJSON ¶ added in v0.3.0
func (*Support) UnmarshalJSON ¶ added in v0.3.0
type SurfaceError ¶ added in v0.9.0
type SurfaceError struct {
Surface ModelSurface
Model string
}
SurfaceError reports a request for a surface the provider does not serve natively. Another target may serve it, so it permits failover.
func (*SurfaceError) Error ¶ added in v0.9.0
func (e *SurfaceError) Error() string
func (*SurfaceError) ProviderErrorClassification ¶ added in v0.9.0
func (e *SurfaceError) ProviderErrorClassification() ProviderErrorClassification
ProviderErrorClassification permits failover without marking the provider unhealthy.
type Target ¶
Target represents a resolved provider and model.
func PublishExactTargets ¶ added in v0.3.0
func PublishExactTargets(providerID string, catalog CatalogEvidence, probes []CompletionProbeEvidence, policy TargetPublicationPolicy) ([]Target, error)
PublishExactTargets converts catalog evidence to exact provider/model targets. Under verification policy, only targets with successful inference evidence publish.
type TargetPublicationPolicy ¶ added in v0.3.0
type TargetPublicationPolicy string
const ( PublishDiscoveredTargets TargetPublicationPolicy = "catalog_discovered" PublishVerifiedTargets TargetPublicationPolicy = "inference_verified" )
type TokenCount ¶ added in v0.14.0
type TokenCount struct {
InputTokens int64
}
TokenCount is an upstream's count of a request's input tokens.
func CountTokens ¶ added in v0.14.0
func CountTokens(ctx context.Context, provider Provider, request TokenCountRequest) (TokenCount, error)
CountTokens counts request's input tokens through the nearest TokenCounter, looking through decorators that unwrap as PreservesWire does, and fails with ErrTokenCountUnsupported when there is none. A decorator that applies its own policy to counts, such as retries, implements TokenCounter itself and forwards through CountTokens.
type TokenCountRequest ¶ added in v0.14.0
TokenCountRequest asks how many input tokens a request would use.
Request is the operation as it would be invoked, credential included; Anthropic counts a Messages body. Header holds the protocol headers the client sent that select how the upstream counts, such as anthropic-version and anthropic-beta. A provider forwards only the headers its protocol defines, after checking their values, and never authenticates with one. Header shadows Request.Header: Anthropic counts with Header, or with Request.Header when Header is nil, so a request counts with the headers it would be invoked with.
type TokenCounter ¶ added in v0.14.0
type TokenCounter interface {
CountTokens(ctx context.Context, request TokenCountRequest) (TokenCount, error)
}
TokenCounter is an optional Provider interface for the token_count operation: counting a request's input tokens without running it, as Anthropic's /v1/messages/count_tokens does. A request it cannot count, such as one for another surface, fails with ErrTokenCountUnsupported.
type TransportConfidence ¶ added in v0.4.0
type TransportConfidence string
const ( TransportConfidenceLow TransportConfidence = "low" TransportConfidenceMedium TransportConfidence = "medium" TransportConfidenceHigh TransportConfidence = "high" )
type TransportDisposition ¶ added in v0.4.0
type TransportDisposition string
const ( TransportNative TransportDisposition = "native" TransportAdapted TransportDisposition = "adapted" TransportReject TransportDisposition = "reject" )
type TransportEvidence ¶ added in v0.14.0
type TransportEvidence struct {
// Row is the catalog row.
Row ModelInfo
// RefreshedAt is when the catalog holding Row was refreshed, its
// CatalogEvidence.ObservedAt. Zero means never.
RefreshedAt time.Time
// FreshFor is how long after RefreshedAt the evidence stays fresh. Zero
// or less uses DefaultTransportFreshness.
FreshFor time.Duration
}
TransportEvidence is what a stored catalog says about one of its rows for transport planning.
func (TransportEvidence) Capabilities ¶ added in v0.14.0
func (e TransportEvidence) Capabilities() ModelCapabilities
Capabilities returns the capabilities to plan with, as the gateway plans: the row's reported Capabilities, or those InferCapabilities infers from what it lists, with their freshness replaced by the catalog's. They were discovered at RefreshedAt and expire FreshFor later, or carry no freshness at all when the catalog was never refreshed, so evidence is never fresher than the catalog that holds it. Provenance and confidence stay the row's: freshness never upgrades evidence.
type TransportInterface ¶ added in v0.4.0
type TransportInterface struct {
Surface ModelSurface `json:"surface"`
Native Support `json:"native"`
}
TransportInterface is an available provider interface. Native records whether using this interface for its named surface preserves native provider semantics; SupportUnsupported therefore means available through adaptation, not unavailable.
func TransportInterfaces ¶ added in v0.14.0
func TransportInterfaces(provider Provider, credential *Credential, model string, surfaces []string) []TransportInterface
TransportInterfaces returns the interfaces a catalog row offers for transport planning: one for each chat surface in surfaces, the row's SupportedAPIs, that ParseSurfacePath recognizes, in their order. An interface is native when provider preserves the surface's wire for model and a request that carries credential (see PreservesWireFor), and adapted otherwise. A surface the row does not list gets no interface, so a request for it is adapted or refused. A nil provider, one that could not be built, offers none.
type TransportPlan ¶ added in v0.4.0
type TransportPlan struct {
Disposition TransportDisposition `json:"disposition"`
Surface ModelSurface `json:"surface"`
Confidence TransportConfidence `json:"confidence"`
Losses []translate.Loss `json:"losses,omitempty"`
Reason TransportRejectReason `json:"reason,omitempty"`
}
TransportPlan is a deterministic decision over the supplied evidence.
func PlanTransport ¶ added in v0.4.0
func PlanTransport(request TransportPlanRequest) TransportPlan
PlanTransport selects a native interface when one is confirmed, preserves unknown evidence as eligible at low confidence, and otherwise considers an explicitly reported adaptation. It performs no I/O and applies no gateway or provider policy.
type TransportPlanRequest ¶ added in v0.4.0
type TransportPlanRequest struct {
Operation ModelOperation `json:"operation"`
Surface ModelSurface `json:"surface"`
EvaluatedAt time.Time `json:"evaluated_at"`
ExactTarget bool `json:"exact_target"`
Capabilities ModelCapabilities `json:"capabilities"`
Interfaces []TransportInterface `json:"interfaces"`
Requirement TransportRequirement `json:"requirement"`
TranslationEvaluated bool `json:"translation_evaluated"`
Translation translate.Report `json:"translation"`
}
TransportPlanRequest contains only evidence needed to choose a transport. Translation describes the conversion that would be used by an adapted plan.
type TransportRejectError ¶ added in v0.14.0
type TransportRejectError struct {
Reason TransportRejectReason
Surface ModelSurface
Model string
// NativeInterface reports that the stored catalog lists Surface for
// Model and the provider preserves its wire.
NativeInterface bool
}
TransportRejectError reports a request refused for the transport it requires, before anything reached the provider. A product words the refusal from Reason, as the gateway does, and NativeInterface tells a surface the provider does not preserve from evidence that is stale or untrusted.
func (*TransportRejectError) Error ¶ added in v0.14.0
func (e *TransportRejectError) Error() string
type TransportRejectReason ¶ added in v0.4.0
type TransportRejectReason string
const ( // TransportRejectNotCataloged is a model its stored catalog does not // list, so no evidence can confirm a native surface. TransportRejectNotCataloged TransportRejectReason = "not_cataloged" // TransportRejectStreaming is a transparent request that streams, // which transparency does not support yet. TransportRejectStreaming TransportRejectReason = "streaming_unsupported" )
Reasons a transparent request is refused besides a plan's.
const ( TransportRejectInvalidRequirement TransportRejectReason = "invalid_requirement" TransportRejectOperationUnsupported TransportRejectReason = "operation_unsupported" TransportRejectNoInterface TransportRejectReason = "no_interface" TransportRejectNativeRequired TransportRejectReason = "native_required" TransportRejectExactTargetRequired TransportRejectReason = "exact_target_required" TransportRejectNativeUnconfirmed TransportRejectReason = "native_unconfirmed" TransportRejectTranslationUnevaluated TransportRejectReason = "translation_not_evaluated" TransportRejectTranslationLoss TransportRejectReason = "translation_loss" )
type TransportRequirement ¶ added in v0.4.0
type TransportRequirement string
TransportRequirement constrains whether a request may use adaptation.
const ( TransportRequirementAny TransportRequirement = "any" TransportRequirementNative TransportRequirement = "native" TransportRequirementTransparent TransportRequirement = "transparent" )
func ParseTransportRequirement ¶ added in v0.14.0
func ParseTransportRequirement(value string) (TransportRequirement, error)
ParseTransportRequirement reads the transport a client requests, such as the gateway's X-LLMGW-Transport-Mode header: blank is TransportRequirementAny, and transparent, in any case, is TransportRequirementTransparent. Anything else, native included, is ErrInvalidTransportRequirement, because a client may ask only for transparency.
type UsageHook ¶
type UsageHook interface {
RecordUsage(ctx context.Context, record UsageRecord)
}
UsageHook receives telemetry records after each completed request.
type UsageHookFunc ¶
type UsageHookFunc func(ctx context.Context, record UsageRecord)
UsageHookFunc is a functional adapter for UsageHook.
func (UsageHookFunc) RecordUsage ¶
func (f UsageHookFunc) RecordUsage(ctx context.Context, record UsageRecord)
type UsageRecord ¶
type UsageRecord struct {
RequestID string `json:"request_id"`
PrincipalID string `json:"principal_id,omitempty"`
ProjectID string `json:"project_id,omitempty"`
Provider string `json:"provider"`
Model string `json:"model"`
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
Duration time.Duration `json:"duration"`
Stream bool `json:"stream"`
StatusCode int `json:"status_code"`
Error string `json:"error,omitempty"`
}
UsageRecord holds metrics and token counts from a completed LLM call.
type WirePreserver ¶ added in v0.14.0
type WirePreserver interface {
// PreservesWire reports whether the provider forwards surface for
// model in its own wire protocol. It is consulted only for a surface
// the provider serves natively.
PreservesWire(model string, surface ModelSurface) bool
}
WirePreserver is an optional Provider interface. A provider implements it to declare the surfaces it forwards in their own wire protocol: the request reaches the upstream as that surface's request, and the answer comes back as that surface's response or frames, with no conversion through another surface inside the provider. Setting the model or the stream flag, or encoding the JSON again, keeps a surface preserved; translating it does not.
Preserving a surface is a stronger claim than serving it natively. Codex and Antigravity list Chat Completions among their native surfaces but convert it internally, so they serve it without preserving it, and the gateway labels such an answer translated. A product's response transport label reads PreservesWire, never NativeSurfaces, and preservation is never inferred from any other method.
Source Files
¶
- caller.go
- capabilities_infer.go
- catalog_store.go
- config.go
- credential_kinds.go
- credential_store.go
- engine.go
- evidence.go
- interfaces.go
- invoke.go
- loss_policy.go
- model_capabilities.go
- provider_contracts.go
- provider_error.go
- token_count.go
- transport_evidence.go
- transport_labels.go
- transport_plan.go
- wire_credential.go
- wire_preserving.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package anonymous runs the automation that connects the reviewed anonymous providers, as the gateway's does: it enrolls each profile's provider, discovers what its catalog admits, probes the models with a completion and publishes the exact targets that answered.
|
Package anonymous runs the automation that connects the reviewed anonymous providers, as the gateway's does: it enrolls each profile's provider, discovers what its catalog admits, probes the models with a completion and publishes the exact targets that answered. |
|
Package catalog keeps discovered provider catalogs in a core.CatalogStore the way the gateway keeps its own: reads that serve a stored catalog while it is younger than a TTL and otherwise discover it, reads that never discover, and discovery fenced against invalidation, so a discovery that began before a catalog was invalidated never stores over what came after.
|
Package catalog keeps discovered provider catalogs in a core.CatalogStore the way the gateway keeps its own: reads that serve a stored catalog while it is younger than a TTL and otherwise discover it, reads that never discover, and discovery fenced against invalidation, so a discovery that began before a catalog was invalidated never stores over what came after. |
|
Package catalogtest is the conformance suite for core.CatalogStore implementations.
|
Package catalogtest is the conformance suite for core.CatalogStore implementations. |
|
Package execution provides the primitives failover is built from: a HealthTracker that breaks circuits and cools down instances, and executors that try candidates in order and never fail over once output has reached the caller.
|
Package execution provides the primitives failover is built from: a HealthTracker that breaks circuits and cools down instances, and executors that try candidates in order and never fail over once output has reached the caller. |
|
Package extension is the client side of the extension protocol: the HTTP protocol between a product and an extension daemon, a separate process that serves providers the product does not carry itself.
|
Package extension is the client side of the extension protocol: the HTTP protocol between a product and an extension daemon, a separate process that serves providers the product does not carry itself. |
|
Package oauthflow runs server-side OAuth flows for products that sign users in to LLM providers: browser authorization codes with PKCE, device authorization, and codes the owner pastes back.
|
Package oauthflow runs server-side OAuth flows for products that sign users in to LLM providers: browser authorization codes with PKCE, device authorization, and codes the owner pastes back. |
|
oauthflowtest
Package oauthflowtest is the conformance suite for oauthflow.FlowStore implementations.
|
Package oauthflowtest is the conformance suite for oauthflow.FlowStore implementations. |
|
Package runtime provides Runtime, the one value that owns an embedding product's provider state: the provider registry, the provider cache, the credential refresh coordinators, the catalog cache and provider health.
|
Package runtime provides Runtime, the one value that owns an embedding product's provider state: the provider registry, the provider cache, the credential refresh coordinators, the catalog cache and provider health. |
|
Package translation serves surfaces a provider lacks by translating through llm-translate.
|
Package translation serves surfaces a provider lacks by translating through llm-translate. |