requestformat

package
v2.3.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: AGPL-3.0 Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package requestformat names the wire shape of an LLM request body (its filter format) from the LLM's vendor and the request's method and path. The proxy reads request filters, guardrails and buffered responses in this format, and gateway plugins that parse or rewrite bodies use the same function so they agree with the proxy.

The format is a key of the proxy's message extractor and reconstructor registries and of guardrails/segments: a vendor name ("openai", "anthropic", "bedrock", ...) for the vendor's own chat shape, or one of the constants below for a body that is not.

For resolves requests on the native /llm/{mode}/{slug}/ pass-through only, which is also the only route post_auth plugins see. The bridges carry their own formats and never reach post_auth with them:

  • /ai/{slug} and /v1 (unified) take OpenAI-shaped bodies, and /anthropic/{slug} (Bedrock only) Anthropic-shaped ones. They are translated and re-enter the proxy on /llm/call/{slug}/, where post_auth sees the vendor-native body this package resolves (a Converse body for Bedrock, from AI Studio 2.3; before, the Bedrock bridges called AWS directly and ran no post_auth).

Model, IsStreaming and ParseUsage read the model, the streaming flag and the token usage of an exchange in each vendor's wire shape. pkg/plugin_sdk exposes them to plugins as RequestModel, IsStreamingRequest and ResponseUsage.

The package depends on nothing in this module but pkg/decisions, so plugins can import it without the proxy, models or GORM.

Index

Constants

View Source
const (
	// OpenAI and Anthropic are the bridges' formats (and those vendors' own).
	OpenAI    = "openai"
	Anthropic = "anthropic"
	// OpenAIResponses is an OpenAI Responses API body: "input" items and
	// "instructions" instead of "messages".
	OpenAIResponses = "openai_responses"
	// OpenAIInput is an embeddings, completions or moderations body, read
	// through "input" or "prompt".
	OpenAIInput = "openai_input"
	// OpenAIDecisions and SystemOne are decision-model bodies (see
	// pkg/decisions), whatever the LLM's vendor.
	OpenAIDecisions = "openai_decisions"
	SystemOne       = "systemone"
)

Filter formats besides the vendors' own chat shapes.

Variables

View Source
var ChainFormats = map[string][]ChainFormat{
	"openai": {
		{Method: "POST", Path: "/v1/responses", Format: OpenAIResponses},
		{Method: "POST", Path: "/v1/responses/input_tokens", Format: OpenAIResponses},
		{Method: "POST", Path: "/v1/responses/compact", Format: OpenAIResponses},
		{Method: "POST", Path: "/v1/embeddings", Format: OpenAIInput},
		{Method: "POST", Path: "/v1/completions", Format: OpenAIInput},
		{Method: "POST", Path: "/v1/moderations", Format: OpenAIInput},
	},
}

ChainFormats lists, per vendor, the operations with their own format.

Functions

func BodyFields

func BodyFields(body []byte) (model string, stream bool)

BodyFields reads the "model" (a string) and "stream" (a bool) fields of a JSON request body; a field of another type, or a body that is not JSON, reads as absent. Keys match as encoding/json matches struct fields: an exact match, or else one that differs only in case.

func CanonicalVendorPath

func CanonicalVendorPath(upstreamPath, remainingPath string) string

CanonicalVendorPath is the vendor's own path for a request: the path JoinUpstreamPath sends upstream, less any corporate prefix the LLM's endpoint carries. A version segment that ends the endpoint (the /v1 of https://gw/anthropic/v1) belongs to the vendor's API and is kept; whatever precedes it (the /anthropic) is the proxy's mount point and is dropped. So every endpoint shape that sends .../v1/messages/batches upstream names the same canonical /v1/messages/batches, which native operations are matched on.

func For

func For(vendor, method, requestPath, upstreamEndpoint string) string

For is the filter format of a request on the native pass-through: the vendor's own, a decision format for a decision request, or the format ChainFormats names for the operation. requestPath is the gateway path (/llm/rest/my-llm/v1/responses); upstreamEndpoint is the LLM's API endpoint (a URL or a bare path, "" when it has none), which decides the operation's canonical path. Edge plugins get it from GetLLM (LLMInfo.Endpoint).

func IsStreaming

func IsStreaming(vendor, path string, body []byte) bool

IsStreaming reports whether a request asks for a streamed answer. Where the vendor's own API decides it in the path, the path alone does, and the body is not read: Bedrock's /model/{modelId}/{operation} (converse-stream and invoke-with-response-stream stream), and Google AI's and Vertex's .../models/{model}:{method} (:streamGenerateContent, or alt=sse). Bedrock's API has no body "stream" field, nor has Gemini's. Everywhere else, which includes those vendors' OpenAI-compatible paths and Vertex's :rawPredict / :streamRawPredict (partner models such as Anthropic's, whose bodies say "stream"), it is "stream": true in the body (or alt=sse).

func IsVersionSegment

func IsVersionSegment(seg string) bool

IsVersionSegment reports whether seg names an API version: v1, v2, v1beta, v1alpha2 and the like.

func JoinUpstreamPath

func JoinUpstreamPath(upstreamPath, remainingPath string) string

JoinUpstreamPath composes the path sent to the vendor from the path of the LLM's configured endpoint and the path the caller put after the route slug.

Operators configure endpoints in every shape: the bare host (https://api.anthropic.com), the versioned root (https://api.anthropic.com/v1), and corporate proxies with or without a version segment (https://gw/anthropic, https://gw/anthropic/v1). Callers likewise arrive both with and without a version segment: native SDK clients send /v1/messages, and so does the OpenAI-compatible bridge. Concatenating naively yields /anthropic/v1/v1/messages for the last shape; only passing the caller's path through when the endpoint path is a prefix of it yields /messages for the first.

So the two are joined with their overlap removed: the longest run of whole segments that ends the endpoint path and begins the caller's path appears once. Every shape above then resolves to .../v1/messages.

func Model

func Model(vendor, path string, body []byte) string

Model is the model a request names: for Bedrock the {modelId} of its /model/{modelId}/{operation} path, for Google AI and Vertex the {model} of .../models/{model}:{method}, and otherwise (or when the path names none) the body's "model" field. "" when the request names none.

path may be the gateway path (/llm/rest/{slug}/model/...) or the vendor's, escaped or not: the AWS SDK escapes the model ID, so an ARN or inference profile arrives as arn%3Aaws%3Abedrock%3A...%2F..., and an unescaped ARN contains a "/". Both come back unescaped and whole.

func ModelAndStreaming

func ModelAndStreaming(vendor, path string, body []byte) (model string, stream bool)

ModelAndStreaming is Model and IsStreaming together, reading the body at most once: a caller that needs both on every request pays for one JSON parse of a body that may be megabytes, not two, and none on a path that decides both.

func ModelAndStreamingFunc

func ModelAndStreamingFunc(vendor, path string, bodyFields func() (model string, stream bool)) (model string, stream bool)

ModelAndStreamingFunc is ModelAndStreaming with the body's fields from bodyFields, called at most once and only when the path does not decide both: a caller that has already decoded the body passes what it read (ObjectFields) rather than parse it again.

func ObjectFields

func ObjectFields(obj map[string]any) (model string, stream bool, ok bool)

ObjectFields is BodyFields of a body already decoded into obj (as encoding/json decodes a JSON object into map[string]any), so a caller that has decoded it need not parse it again. ok is false when obj cannot say: when it has two keys that match "model" (or "stream") but for case, encoding/json keeps the later one in the body, an order a map has lost. Call BodyFields then.

func SplitNativePath

func SplitNativePath(p string) (mode, slug, rest string, ok bool)

SplitNativePath splits a native pass-through path /llm/{mode}/{slug}/{rest} into its mode (rest, stream or call), slug and "/"+rest.

Types

type ChainFormat

type ChainFormat struct {
	Method string
	Path   string
	Format string
}

ChainFormat is a vendor operation whose body is not the vendor's chat shape: requests with Method to the vendor-canonical Path are read as Format. The proxy's native chain hooks (pkg/nativeapi.ChainHook.FilterFormat) declare the same operations; a proxy test keeps the two in step.

type Usage

type Usage struct {
	InputTokens      int
	OutputTokens     int
	TotalTokens      int
	CacheReadTokens  int
	CacheWriteTokens int
	// Reported is true when the body carried usage at all, so a response
	// that reports none can be told from one that reports zero.
	Reported bool
}

Usage is the token usage a response reports.

InputTokens is the vendor's own input count. OpenAI and Google count cached tokens inside it (CacheReadTokens is a part of it); Anthropic and Bedrock count them apart (CacheReadTokens and CacheWriteTokens come on top). TotalTokens is the vendor's total when it reports one, and never less than InputTokens + OutputTokens.

func ParseUsage

func ParseUsage(vendor string, body []byte) Usage

ParseUsage reads the token usage from a response body: a REST response, or a whole streamed one as OnStreamComplete gets it (SSE "data:" lines, newline-delimited JSON, or Google's JSON array), for OpenAI (Chat Completions and Responses), Anthropic, Google AI, Vertex, Bedrock Converse (camelCase usage) and Ollama. For Bedrock it also reads raw eventstream frames, the stream chunks response hooks get. In a stream, counts reported later replace earlier ones, as vendors report running totals.

Jump to

Keyboard shortcuts

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