Documentation
¶
Overview ¶
Package nativeapi is the contract between LLM vendors and the native proxy routes (/llm/rest|stream|call/{slug}/...) for SDK-specific endpoints that do not fit the single synchronous "POST with a top-level model" shape: Anthropic Message Batches and count_tokens, OpenAI Responses ownership and OpenAI Batches and Files.
The package is deliberately small and dependency-free: it imports only the standard library and models, never proxy, switches or vendors. Vendor code is declarative data plus small pure functions; it never calls the proxy. The proxy runs a fixed pipeline (auth, ACL, per-item model checks and filters, budget, ledger, ID wrapping, accounting) and supplies everything stateful.
Adding an extension to a vendor ¶
Implement Provider on the vendor's LLMVendorProvider:
func (p *MyVendor) NativeAPI() nativeapi.Spec { return mySpec }
The proxy type-asserts Provider on switches.VendorMap[v](), the same way it discovers IDecisionResponse. Build the Spec once (a package variable) and return it; it must not change at runtime.
Declare every vendor-side object the gateway hands out an ID for as a ResourceType. Its Name is namespaced by vendor ("anthropic.message_batch") and is part of the signed ID, so an ID minted for one type never verifies as another. IDCharset is an anchored regexp the raw vendor ID must match. A non-nil Async marks the resource as long-running: it is written to the native resource ledger, polled by the reconciler and accounted once.
Declare each endpoint as an Operation with its exact Method and canonical vendor Path ("/v1/messages/batches/{id}/results"). Paths are matched exactly, segment by segment; there is no prefix matching, so declaring "/v1/messages/batches" never captures "POST /v1/messages". A {name} segment matches one non-empty path segment; PathResource names the ResourceType of the {id} segment so the proxy verifies and unwraps it before the request leaves the gateway.
Fill the optional hooks the operation needs: Admit to split a body into per-item admission units (model allow-list, request filters), Results for JSONL result downloads (per-line response filters, usage), List for ledger-served listings, RequestRefs/ResponseIDs for IDs embedded in bodies, Transform to rewrite vendor URLs (never follow them), Upstream to allow-list query parameters and headers, ErrorShape for vendor-shaped errors.
For calls that stay on the synchronous chain but hand out or name resource IDs (OpenAI's POST /v1/responses), declare a ChainHook: its RequestRefs are verified and unwrapped before the filters run, its ResponseIDs are wrapped in the JSON response and in the EventObject of every server-sent event, and a created object its async type tracks (AsyncSpec.Tracked) is ledgered. The vendor's usage analysis must then skip that object.
Test the Spec with NewMatcher (it validates the Spec) and add proxy harness tests for the end-to-end behaviour.
Signed resource IDs ¶
Every vendor ID returned to a client is wrapped by Codec as
<vendor_id>.t1k<kid>.<mac>
where mac is a truncated HMAC-SHA256 over the length-prefixed resource type, vendor ID, LLM ID and App ID, and kid identifies the key. CodecForLLM keys it with HKDF(the LLM's hub-generated signing secret, "tyk-native-resource/secret/v1") and still accepts the LLM's previous key (a rotated secret, or the vendor-credential key HKDF(credential, "tyk-native-resource/v1") that signed IDs before secrets existed) until its grace period ends; an LLM without a secret signs with the vendor-credential key. Any replica, edge or the hub verifies an ID statelessly. Callers must answer every verification failure with the same 404 so the check is not an oracle.
JSONL results ¶
LineReader reads JSONL result files line by line with a bounded line size so multi-hundred-megabyte result files stream through the gateway without being buffered.
Index ¶
- Constants
- Variables
- func CheckJSONKeys(b []byte, foldAt ...string) error
- func FoldKey(key string) string
- type AdmitSpec
- type AsyncSpec
- type BodyRef
- type ChainHook
- type ChainHooks
- type Codec
- type DuplicateKey
- type Item
- type Key
- type LedgerEffect
- type LineReader
- type ListSpec
- type Match
- type Matcher
- type Operation
- type ParsedID
- type PathElem
- type Provider
- type ResourceState
- type ResourceType
- type ResultView
- type ResultsSpec
- type Scope
- type Spec
- type StateInfo
- type TransformEnv
- type UpstreamReq
- type UpstreamSpec
- type Usage
- func (u Usage) GetCacheReadPromptTokens() int
- func (u Usage) GetCacheWritePromptTokens() int
- func (u Usage) GetChoiceCount() int
- func (u Usage) GetModel() string
- func (u Usage) GetPromptTokens() int
- func (u Usage) GetResponseTokens() int
- func (u Usage) GetToolCount() int
- func (u Usage) PriceMultiplier() float64
- func (u Usage) ServiceTier() string
Constants ¶
const DefaultMaxLineSize = 16 << 20
DefaultMaxLineSize caps one JSONL line.
const IDParam = "id"
IDParam is the path parameter bound to PathResource.
Variables ¶
var ( // ErrEmptyKey: the LLM has no signing secret or vendor credential to // derive a key from. // The proxy answers 501, never an unsigned ID. ErrEmptyKey = errors.New("nativeapi: empty signing key") // ErrMalformedID: the ID is not in the wrapped format or the vendor ID // fails the resource's charset. ErrMalformedID = errors.New("nativeapi: malformed resource id") // ErrKeyMismatch: well-formed, but signed with a key the codec does not // hold (a rotated key past its grace period, or another installation). ErrKeyMismatch = errors.New("nativeapi: resource id signed with another key") // ErrBadSignature: the MAC does not match this type, LLM and App. ErrBadSignature = errors.New("nativeapi: resource id signature mismatch") )
var DefaultIDCharset = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,256}$`)
DefaultIDCharset is used for a ResourceType without an IDCharset.
var ErrDuplicateKey = errors.New("duplicate key")
ErrDuplicateKey is a JSON object with two keys the gateway and a vendor may read differently.
var ErrLineTooLong = errors.New("nativeapi: jsonl line exceeds the size limit")
ErrLineTooLong is returned when a line exceeds the reader's cap.
Functions ¶
func CheckJSONKeys ¶
CheckJSONKeys reports whether b is one JSON value without duplicate keys the gateway and a vendor might read differently:
- Exact duplicates are refused in every object, at any depth. JSON parsers disagree on which one wins (Go's encoding/json, behind the gateway's model checks and filter extractors, takes the last; a vendor may take the first), so {"model":"ok","model":"evil"}, or a message with two "content" keys, could show the gateway one value and the vendor another.
- Keys equal under Unicode simple case folding are refused only in the objects at foldAt: the ones the gateway decodes into Go structs, whose fields encoding/json matches case-insensitively ({"messages":[x], "Messages":[y]} shows a struct y and the vendor x). Elsewhere, such as a tool's JSON Schema properties or a tool call's arguments, "id" and "ID" are different keys to everyone.
A foldAt path is a dotted key path from the root ("" is the root object); a "[]" suffix names the elements of an array: "messages[]" is every message, "messages[].content[]" every content block.
Types ¶
type AdmitSpec ¶
type AdmitSpec struct {
// Multipart marks a multipart/form-data body (an OpenAI file upload).
// The proxy requires the Content-Type boundary to open the body (no
// preamble), so Split, which reads the boundary from the body's first
// line, parses the body as the vendor will.
Multipart bool
Split func(body []byte) ([]Item, error)
// Join rebuilds the upstream body from the original body and the items in
// Split order; only items whose Body changed need rewriting.
Join func(original []byte, items []Item) ([]byte, error)
}
AdmitSpec splits a request body into items that are admitted (model allow-list, request filters) one by one, and joins them back after filters may have rewritten some of them.
type AsyncSpec ¶
type AsyncSpec struct {
// Poll returns the request that fetches the current vendor object.
Poll func(vendorID string) UpstreamReq
// State extracts the lifecycle state from a vendor object.
State func(obj []byte) (StateInfo, error)
// Results returns the request that downloads the results, and false if
// the object has no results (yet).
Results func(vendorID string, obj []byte) (UpstreamReq, bool)
// LineUsage extracts usage from one results line. ok=false means the line
// carries no usage.
LineUsage func(line []byte) (u Usage, ok bool, err error)
// Cancel returns the request that cancels the resource upstream; nil if
// it cannot be cancelled. The proxy cancels a resource it created but
// could not record in its ledger, so it never runs unaccounted.
Cancel func(vendorID string) UpstreamReq
// ObjectUsage, when set, reads the usage of an ended resource from the
// polled object itself (an OpenAI background response) instead of a
// results download; Results and LineUsage are then not used. ok=false
// means the object carries no billable usage.
ObjectUsage func(obj []byte) (u Usage, ok bool, err error)
// Tracked, when set, reports whether an object of the type is a
// long-running resource the gateway ledgers and accounts (an OpenAI
// response created with background: true); other objects of the type
// are accounted synchronously and never ledgered. Nil: every object is.
Tracked func(obj []byte) bool
}
AsyncSpec describes how the reconciler drives a long-running resource.
type BodyRef ¶
type BodyRef struct {
Path string
Resource string
// Child marks, in ResponseIDs of an operation on an async resource, an
// ID of a resource derived from it (a batch's output file). The node
// that holds the async resource's ledger row records the child there
// too (ParentID), so it can be listed and retrieved, and cannot be
// deleted before its parent is accounted.
Child bool
// ObjectID marks a field that holds the ID itself or an object whose
// "id" holds it (OpenAI's conversation: "conv_..." or {"id": ...}).
ObjectID bool
// Screened marks, in RequestRefs, a reference to a resource whose
// content the gateway screened when an admitting operation created it
// (a batch input file) and that this operation runs at the vendor. The
// gateway refuses the reference unless the LLM's request filters are
// still the ones that screened it.
Screened bool
}
BodyRef points at a resource ID inside a JSON body. Path is a dotted path; a "[]" suffix on a segment iterates an array ("data[].id").
type ChainHook ¶
type ChainHook struct {
Name string
Method string
Path string
// RequestRefs are IDs in the request body to verify and unwrap.
RequestRefs []BodyRef
// ResponseIDs are IDs in the resource object to wrap. The resource
// object is the response body, or EventObject inside an event's data.
ResponseIDs []BodyRef
// EventObject is the dotted path of the resource object inside a
// server-sent event's JSON data ("response"); events without it pass
// through unchanged. Empty: streamed responses are not rewritten.
EventObject string
// DropHeaders are client headers removed before the request leaves the
// gateway, so it reaches the vendor account the native operations and
// the reconciler use (OpenAI-Project would create a response elsewhere).
DropHeaders []string
// FilterFormat is the format the request filters read the body as (a
// key of the proxy's message extractor and reconstructor registries,
// such as "openai_responses"); empty means the vendor's own.
FilterFormat string
// CheckBody, when set, vets the request body before the model checks
// and filters see it (CheckJSONKeys refuses duplicate keys); an error is
// a 400 naming it.
CheckBody func(body []byte) error
// ErrorShape renders a vendor-shaped error body.
ErrorShape func(status int, typ, msg string) []byte
}
ChainHook applies to synchronous-chain requests with exactly Method and the canonical Path (no parameters). The proxy verifies and unwraps RequestRefs before the request filters run (any failure is the same 404 as for a native operation), and wraps ResponseIDs in a successful JSON response and in the resource object of every server-sent event.
When the created object is a tracked async resource (ResponseIDs[0] names a ResourceType with Async, and Async.Tracked reports the object), the proxy records it in the native resource ledger so the reconciler accounts it; the vendor's synchronous usage analysis must then record no usage for it, or it is counted twice.
type ChainHooks ¶
type ChainHooks struct {
Hooks []ChainHook
}
ChainHooks are a vendor's hooks on the synchronous chain.
func (*ChainHooks) Declares ¶
func (h *ChainHooks) Declares(path string) bool
Declares reports whether a chain hook declares exactly path, for any method.
type Codec ¶
type Codec struct {
// contains filtered or unexported fields
}
Codec wraps resource IDs with one key and verifies them against that key and any older keys still in their grace period.
func CodecForLLM ¶
CodecForLLM builds the codec for llm's resource IDs at now. An LLM with a signing secret signs with it and still accepts its previous key (a rotated secret, or the stored vendor-credential key) until the grace period ends (PreviousKeyForLLM). An LLM without one, a standalone edge's, signs with the vendor-credential key.
func NewKeyringCodec ¶
NewKeyringCodec signs with sign and also accepts IDs signed with any of accept (previous keys in their grace period).
type DuplicateKey ¶
DuplicateKey is the first exact duplicate key FindDuplicateKey found: Key as encoding/json decodes it, in the object at Path.
func FindDuplicateKey ¶
func FindDuplicateKey(b []byte) (*DuplicateKey, error)
FindDuplicateKey reads all of b, as CheckJSONKeys does with no foldAt. It returns a syntax error when b is not one JSON value json.Valid would accept (nesting deeper than encoding/json's 10000 included), even after a duplicate (a caller that ignores bodies it cannot read keeps ignoring them); otherwise the first exact duplicate key in document order, or nil.
type Item ¶
type Item struct {
// Key identifies the item to the client (e.g. custom_id) in errors and
// filter script context.
Key string
// Format names the message format the proxy's filter extractor reads the
// item Body as (e.g. "anthropic").
Format string
// Model is the model the item asks for; checked against the LLM's
// allow-list. Empty: the item invokes no model (items stored in an
// OpenAI conversation) and only the filters run on it. A Split for an
// item that does invoke a model must refuse one without it.
Model string
// Body is the item's request body as the filters see it.
Body []byte
}
Item is one admission unit of a request body: one batch request, one JSONL line of an uploaded file, or the whole body for a single-body operation.
type Key ¶
type Key struct {
// contains filtered or unexported fields
}
Key is one signing key and its identifier.
func CredentialKey ¶
CredentialKey derives a signing key from an LLM's plaintext vendor credential: the key of LLMs without a signing secret, and of every ID minted before signing secrets existed.
func PreviousKeyForLLM ¶
PreviousKeyForLLM returns llm's previous signing key, whether or not its grace period is over: a rotated secret, the vendor-credential key the backfill stored (ResourceSigningDerivedKeyPrefix), or, for the legacy sentinel, the key of the LLM's current credential. ok is false when the LLM has none.
type LedgerEffect ¶
type LedgerEffect int
LedgerEffect is what an operation does to the native resource ledger.
const ( LedgerNone LedgerEffect = iota LedgerCreate LedgerRead LedgerList LedgerMutate LedgerDelete )
func (LedgerEffect) String ¶
func (e LedgerEffect) String() string
type LineReader ¶
type LineReader struct {
// contains filtered or unexported fields
}
LineReader reads JSONL line by line with a bounded line size. It accepts LF and CRLF line endings and a missing trailing newline, and skips blank lines.
func NewLineReader ¶
func NewLineReader(r io.Reader, maxLine int) *LineReader
NewLineReader reads from r with lines capped at maxLine bytes (excluding the line ending); maxLine <= 0 means DefaultMaxLineSize.
func (*LineReader) Line ¶
func (l *LineReader) Line() int
Line is the 1-based number of the last line returned or that failed, counting blank lines.
func (*LineReader) Next ¶
func (l *LineReader) Next() ([]byte, error)
Next returns the next non-blank line without its line ending. The slice is only valid until the next call. It returns io.EOF after the last line, and ErrLineTooLong (wrapped with the line number) without reading the rest of an oversized line into memory; SkipLine then moves past it.
func (*LineReader) SkipLine ¶
func (l *LineReader) SkipLine() error
SkipLine discards the rest of the oversized line the last Next rejected with ErrLineTooLong, without buffering it, so the next Next reads the line after it. It is a no-op when the last Next did not stop inside a line.
type ListSpec ¶
type ListSpec struct {
// Envelope renders a page of (already wrapped) objects.
Envelope func(items [][]byte, firstID, lastID string, hasMore bool) ([]byte, error)
// Query parameter names for the page size and keyset cursors.
LimitParam, AfterParam, BeforeParam string
DefaultLimit, MaxLimit int
}
ListSpec describes a ledger-served listing.
type Matcher ¶
type Matcher struct {
// contains filtered or unexported fields
}
Matcher resolves a request to an Operation by exact method and path.
func NewMatcher ¶
NewMatcher validates spec and compiles its operation paths. It rejects two operations with the same method whose paths match the same requests.
func (*Matcher) Match ¶
Match resolves method and a canonical vendor path. Matching is exact: the method must be equal, every segment must match, and there is no prefix, trailing-slash or empty-segment tolerance. When several patterns match, the one with the most literal segments wins ("/batches/count" before "/batches/{id}").
func (*Matcher) MatchesFold ¶
MatchesFold reports whether path names a path some operation or chain hook declares once case and empty segments are ignored ("/v1/Messages/ Batches/", "/V1/responses"). The proxy refuses such a spelling of a native path rather than let it reach the vendor around the native handling: an upstream that routes paths case-insensitively would serve it.
func (*Matcher) MatchesPath ¶
MatchesPath reports whether any operation (of any method) matches path. The proxy uses it to tell "native path, wrong method" (vendor-shaped 405) from a path that is not native at all (legacy chain).
type Operation ¶
type Operation struct {
Name string
Method string
// Path is the canonical vendor path pattern. {name} matches one
// non-empty segment.
Path string
// PathResource is the ResourceType of the {id} path parameter.
PathResource string
Ledger LedgerEffect
// Budget applies the same budget pre-check as synchronous calls.
Budget bool
Admit *AdmitSpec
// RequestRefs are IDs in the request body to verify and unwrap;
// ResponseIDs are IDs in the response body to wrap.
RequestRefs []BodyRef
ResponseIDs []BodyRef
Transform func(obj map[string]any, env TransformEnv)
Results *ResultsSpec
List *ListSpec
Upstream UpstreamSpec
// ErrorShape renders a vendor-shaped error body.
ErrorShape func(status int, typ, msg string) []byte
}
Operation is one native endpoint.
type ParsedID ¶
ParsedID is the structure of a wrapped ID. Nothing in it is verified except its format.
type PathElem ¶
PathElem is one step from the root to a value: an object key, or (when IsIndex) an array index.
type Provider ¶
type Provider interface {
NativeAPI() Spec
}
Provider is implemented by an LLMVendorProvider that exposes native API extensions. The proxy type-asserts it on the vendor provider; vendors that do not implement it keep the legacy native chain unchanged.
type ResourceState ¶
type ResourceState string
ResourceState is the coarse lifecycle state of an async resource.
const ( StateInProgress ResourceState = "in_progress" StateCanceling ResourceState = "canceling" StateEnded ResourceState = "ended" )
type ResourceType ¶
type ResourceType struct {
// Name is namespaced by vendor, e.g. "anthropic.message_batch". It is
// bound into the signed ID.
Name string
// IDCharset is an anchored (^...$) regexp a raw vendor ID must match.
// It is always applied to the whole ID (as ^(?:...)$), so a top-level
// alternation such as ^a|b$ cannot match a substring. Nil means
// DefaultIDCharset.
IDCharset *regexp.Regexp
// Async, when non-nil, marks a long-running resource: it is ledgered,
// reconciled and accounted exactly once.
Async *AsyncSpec
}
ResourceType is a vendor-side object the gateway hands out IDs for.
func (ResourceType) ValidVendorID ¶
func (rt ResourceType) ValidVendorID(id string) bool
ValidVendorID reports whether id is an acceptable raw vendor ID for rt: it matches the whole charset and contains at least one letter or digit, so "." and ".." can never become path segments upstream.
type ResultView ¶
type ResultView struct {
// Key is the line's item key (custom_id).
Key string
// Model is the model that produced the line, if any.
Model string
// Message is the response body response filters inspect; nil if the line
// has no message (errored, canceled, expired).
Message []byte
Usage Usage
}
ResultView is one parsed results line.
type ResultsSpec ¶
type ResultsSpec struct {
View func(line []byte) (ResultView, error)
// Blocked returns the replacement line for a line a response filter
// blocked, keeping the item key.
Blocked func(line []byte, msg string) ([]byte, error)
}
ResultsSpec describes a JSONL results download.
type Scope ¶
Scope is what an ID is bound to besides its type. IDs are the hub's IDs; edges see the same values.
type Spec ¶
type Spec struct {
Resources []ResourceType
Operations []Operation
// ChainHooks are hooks on the existing synchronous chain: calls that stay
// on the legacy native pass-through (model validation, filters, usage
// analysis) but hand out or reference vendor resource IDs, such as
// OpenAI's POST /v1/responses and its previous_response_id.
ChainHooks *ChainHooks
}
Spec is a vendor's complete set of native extensions.
type StateInfo ¶
type StateInfo struct {
State ResourceState
EndedAt *time.Time
ResultsExpireAt *time.Time
}
StateInfo is what AsyncSpec.State extracts from a vendor object.
type TransformEnv ¶
type TransformEnv struct {
// PublicBaseURL is the configured absolute base URL of this gateway's
// native route for the LLM; empty means emit root-relative URLs.
PublicBaseURL string
// Wrap wraps a raw vendor ID of the named resource type for the calling
// App and LLM.
Wrap func(resourceType, vendorID string) (string, error)
}
TransformEnv is what a Transform may use.
type UpstreamReq ¶
type UpstreamReq struct {
Method string
Path string
Query url.Values
// Header holds default headers the vendor needs (an API version) when
// the gateway calls it without a client request (the reconciler); a
// client request's allow-listed headers take precedence.
Header http.Header
}
UpstreamReq is a request the proxy builds against the vendor's upstream endpoint. Path is a canonical vendor path; the proxy joins it to the LLM's configured endpoint and never follows a vendor-supplied URL.
type UpstreamSpec ¶
type UpstreamSpec struct {
// QueryAllow and HeaderAllow are the only query parameters and headers
// forwarded (header names are canonicalised).
QueryAllow []string
HeaderAllow []string
// LongRunning marks responses that may stream for a long time (results);
// the proxy uses an idle timeout instead of the request timeout.
LongRunning bool
// RefuseQuery are query parameters the gateway does not support on the
// operation: a request carrying one with a value other than "false" is
// refused with 400 (OpenAI's ?stream=true on a response retrieve would
// expect a stream the operation does not serve).
RefuseQuery []string
}
UpstreamSpec controls what of the client request reaches the vendor.
type Usage ¶
type Usage struct {
Model string
InputTokens int
OutputTokens int
CacheCreationInputTokens int
CacheReadInputTokens int
// Tier is the vendor service tier the usage was billed at, e.g. "batch".
Tier string
// Multiplier scales the list price (0.5 for batch). Zero means 1.
Multiplier float64
// Billed is false for lines the vendor does not charge for (errored,
// canceled, expired).
Billed bool
}
Usage is the billable usage of one result line (or an aggregate of lines). It implements models.ITokenResponse so the proxy can price it through the normal chat-record path, and exposes the service tier and price multiplier for price-adjusted accounting.