Documentation
¶
Overview ¶
Package llm reads the requests of LLM APIs (OpenAI Chat Completions, Responses and Embeddings, Anthropic Messages) and checks them against a policy's caps (docs/design/0012): the model, the prompt's size, the messages, the choices, the output limit, the roles a client sends and the tools it defines.
Parse reads a body once with a strict, bounded JSON reader: no reflection, no map, no recursion over the body, no allocation. It keeps what the checks need (the model, the numbers, the roles seen, where the tools are), never the prompt's text: the checks count its bytes. A body that isn't valid JSON or UTF-8, nests deeper than MaxDepth, gives a field read here another type, or repeats such a field is malformed: a model server that reads it differently would see another request than the one checked.
Index ¶
Constants ¶
const ( // ImageTokens is an image: Anthropic documents about 1,600 tokens for // the largest image it reads unscaled (about 1.15 megapixels, at // width × height ÷ 750 tokens), above OpenAI's high-detail cost of a // 2048 × 768 image (8 tiles of 170, plus 85: 1,445). ImageTokens = 1600 // AudioTokens is an audio clip: a minute at the 32 tokens a second // Google documents for Gemini (OpenAI's audio models count fewer). AudioTokens = 1920 // FileTokens is a file or document: one PDF page at the most // Anthropic documents for its text (1,500 to 3,000 tokens a page), // not counting the page's image. FileTokens = 3000 )
The floors a part that isn't text is charged in a token estimate, which can't read its tokens from its bytes (docs/llm-apis.md). They are floors, not the most a part can cost: a whole response's usage settles the estimate.
const ( MaxModels = 64 MaxToolNames = 128 MaxPromptCap = 10 << 20 MaxMessagesCap = 100000 MaxOutputCap = 10000000 MaxChoicesCap = 128 )
Limits of a Config, as WAFPolicy's spec.llm.request allows them.
const ( RuleIDMin = 4800000 RuleIDMax = 4800999 )
RuleIDMin and RuleIDMax bound the rule IDs reserved for the LLM checks, which exclusions name (spec.exclusions[].ruleIDs): rule sets may not use them.
const DefaultOutputTokens = 4096
DefaultOutputTokens is a request's output tokens, for its token estimate, when neither the request nor its policy sets a limit.
const MaxBodyBytes = 1 << 30
MaxBodyBytes is the largest body Parse reads (offsets are int32).
const MaxDepth = 64
MaxDepth is how deep a body may nest arrays and objects; the top-level object is at depth 1.
const MaxModelBytes = 256
MaxModelBytes is the longest model a request is compared with the allowed models by; a longer one matches none.
Variables ¶
var Checks = [...]Check{CheckMalformed, CheckModel, CheckMaxPrompt, CheckMaxMessages, CheckMaxChoices, CheckMaxOutputTokens, CheckClientRole, CheckTools}
Checks are the request checks in the order they're decided: the first that fails decides.
var Formats = [...]Format{OpenAIChat, OpenAIResponses, OpenAIEmbeddings, AnthropicMessages}
Formats are the formats this engine reads, in order.
Functions ¶
Types ¶
type Check ¶
type Check uint8
Check is one of the request checks, with a stable name and rule ID.
const ( // CheckNone is no check: the request passed. CheckNone Check = iota // CheckMalformed fails when the body isn't one the parser reads one way. CheckMalformed // CheckModel fails when the model is missing or not allowed. CheckModel // CheckMaxPrompt fails when the prompt's text is over its cap. CheckMaxPrompt // CheckMaxMessages fails on more messages, input items or inputs than the cap. CheckMaxMessages // CheckMaxChoices fails when n is over its cap. CheckMaxChoices // CheckMaxOutputTokens fails when the output limit is over its cap, or missing // where one is required. CheckMaxOutputTokens // CheckClientRole fails on a message of a role clients may not send. CheckClientRole // CheckTools fails on tools the client may not define. CheckTools )
type Config ¶
type Config struct {
// Models are the models allowed: exact, or a prefix ending in "*",
// compared in ASCII lower case. Empty: any, and a request without one.
Models []string
// MaxPromptBytes caps Request.PromptBytes; 0: no cap.
MaxPromptBytes int64
// MaxMessages caps Request.Messages; 0: no cap.
MaxMessages int64
// MaxOutputTokens caps the output limit; 0: no cap.
MaxOutputTokens int64
// RequireOutputTokens refuses a request that sets no output limit.
RequireOutputTokens bool
// MaxChoices caps n; 0: no cap.
MaxChoices int64
// ClientRoles are the roles a client may send; empty: every role.
// RoleNone stands for a role this engine doesn't know (of a newer
// operator): it allows nothing, but makes the list one, so a list of
// unknown roles only allows none rather than every role.
ClientRoles []Role
// Tools is which tools a client may define, ToolNames the ones
// allowed with ToolsListed.
Tools ToolsAllow
ToolNames []string
}
Config is a policy's request checks; the zero value checks nothing but that a body is well-formed.
type Finding ¶
type Finding struct {
// Check failed; CheckNone: none did.
Check Check
// MessageIndex is the message the check is about (-1 for a top-level
// field, the instructions or Anthropic's system); Role its role.
MessageIndex int
Role Role
// Offset is where in the body the check failed: the malformed byte,
// the role, the tool; 0 for the request as a whole.
Offset int
}
Finding is the check a request failed, and where.
type Format ¶
type Format uint8
Format is the shape of an LLM API's requests.
const ( // FormatUnknown is no format: an endpoint of a format this engine // doesn't know is checked as every format it knows. FormatUnknown Format = iota // OpenAIChat is OpenAI's Chat Completions (/v1/chat/completions), as // most OpenAI-compatible servers serve it. OpenAIChat // OpenAIResponses is OpenAI's Responses (/v1/responses). OpenAIResponses // OpenAIEmbeddings is OpenAI's Embeddings (/v1/embeddings). OpenAIEmbeddings // AnthropicMessages is Anthropic's Messages (/v1/messages). AnthropicMessages )
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics are the LLM checks' metrics, labelled only by bounded values: the format, the phase, the check, the action. Its methods are safe for concurrent use and don't allocate; a nil Metrics records nothing.
func NewMetrics ¶
func NewMetrics() *Metrics
NewMetrics returns the metrics, to register (Collectors).
func (*Metrics) Collectors ¶
func (m *Metrics) Collectors() []prometheus.Collector
Collectors returns the metrics' collectors.
type Request ¶
type Request struct {
// Format is the format the body was read as.
Format Format
HasModel bool
ModelTooLong bool
// PromptBytes are the UTF-8 bytes of the prompt's text, every message
// together (token arrays count 4 bytes a token).
PromptBytes int64
// Messages are the messages, input items or embedding inputs.
Messages int64
// OutputTokens is the output limit the request sets, if HasOutputTokens
// (the larger of max_tokens and max_completion_tokens when a chat
// request sets both).
OutputTokens int64
HasOutputTokens bool
// Choices is n, if HasChoices.
Choices int64
HasChoices bool
// Stream is whether the request asks for a streamed answer.
Stream bool
// Tools are the tools the request defines.
Tools int
// Images, Audio and Files count the parts of those kinds (an image,
// an input_audio, a file or document part, each by reference or
// inline), whose tokens the text doesn't tell: each is charged a floor
// (ImageTokens, AudioTokens, FileTokens).
Images, Audio, Files int64
// References: the request names state the server keeps, of tokens
// that can't be known here: the Responses API's previous_response_id,
// conversation or prompt, an item_reference, a file or document by
// file_id, Anthropic's container_upload.
References bool
// Malformed: the body isn't one Parse reads one way, for Why, at byte
// Offset.
Malformed bool
Offset int
Why string
// contains filtered or unexported fields
}
Request is what Parse read of a request. Its zero value is ready for Parse, which resets it; Parse doesn't allocate.
type Role ¶
type Role uint8
Role is who wrote a message: the roles a client may send are a check (Config.ClientRoles).
const ( // RoleNone is no role: a field that isn't a message. RoleNone Role = iota // RoleSystem is the system prompt: a system message, the Responses // API's instructions, Anthropic's system. RoleSystem // RoleDeveloper is OpenAI's developer message, the system prompt of // its newer models. RoleDeveloper // RoleUser is the user's message. RoleUser // RoleAssistant is the model's earlier answer, sent back as history. RoleAssistant // RoleTool is a tool's result (and OpenAI's older function role). RoleTool // RoleOther is a role none of the above: allowed only when every role // is. RoleOther )
type Rules ¶
type Rules struct {
// contains filtered or unexported fields
}
Rules are a compiled Config. They are immutable and safe for concurrent use.
func (*Rules) Check ¶
Check returns the first check, in Checks order, that req, which Parse read from body, fails; off are checks turned off (by exclusions). A malformed request fails llm-malformed, and isn't checked further.
func (*Rules) EstimatedTokens ¶
EstimatedTokens is req's tokens as charged at request time: its prompt's bytes divided by 3, rounded up, plus a floor for each part that isn't text (ImageTokens, AudioTokens, FileTokens), plus its output tokens (OutputTokens) for each of its choices (OpenAI Chat's n), saturated at MaxInt64. Inkwall has no tokenizer: bytes ÷ 3 overestimates English (about 4 bytes a token) and is close for code and CJK text. A request that references state the server keeps (req.References) can't be estimated: the pipeline charges it a limit's whole burst.
func (*Rules) FallbackTokens ¶
FallbackTokens is the estimate of a request whose body can't be read (cut, encoded, not parsed, or not read at all) of bodyBytes, the larger of what was read and its Content-Length: bodyBytes ÷ 3, rounded up, plus the policy's output cap, or DefaultOutputTokens without one, saturated. A body that can't be read is charged as large as it may be, never nothing.
func (*Rules) OutputTokens ¶
OutputTokens is the output tokens a token estimate charges req: its output limit, else the policy's cap, else DefaultOutputTokens; none for embeddings.
type StreamUsage ¶
type StreamUsage struct {
// contains filtered or unexported fields
}
StreamUsage is the usage a streamed response (Server-Sent Events) reports, event by event (Event): OpenAI Chat's last chunk's usage (sent when the request sets stream_options.include_usage), the Responses API's response.completed (or incomplete, failed) response's usage, Anthropic's message_start message's usage and message_delta's, which counts the output so far and replaces the start's. Its zero value is ready; it doesn't allocate.
func (*StreamUsage) Event ¶
func (s *StreamUsage) Event(data []byte, f Format)
Event reads one event's data, of a stream of format f. An event that isn't valid JSON, or reads as ParseUsage refuses, is ignored.
func (*StreamUsage) Usage ¶
func (s *StreamUsage) Usage() (u Usage, ok, final bool)
Usage returns the usage the events read reported, whether any did, and whether it is final: the stream's last usage came (OpenAI's, or Anthropic's message_delta), so it is the whole request's, not the part so far.
type ToolsAllow ¶
type ToolsAllow uint8
ToolsAllow is which tools a client may define.
const ( // ToolsAny allows any tool (the default). ToolsAny ToolsAllow = iota // ToolsNone allows none. ToolsNone // ToolsListed allows the tools Config.ToolNames lists. ToolsListed )
type Usage ¶
type Usage struct {
Input, Output int64
}
Usage is the tokens a whole response says the request used.
func ParseUsage ¶
ParseUsage reads the usage a whole (not streamed) response of format f reports (design 0012 §6): usage.prompt_tokens and completion_tokens (OpenAI Chat and Embeddings), usage.input_tokens and output_tokens (Responses, Anthropic, whose cache_creation_input_tokens and cache_read_input_tokens count as input). It reports false for a body that isn't valid JSON, has no usage, gives it another type, repeats it, or has a key that differs from one it reads only in case (a client in Go would read "Usage" or "PROMPT_TOKENS" as it, as the request parser refuses them): the request's estimate then stands. It doesn't allocate.