llm

package
v0.7.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 7 Imported by: 0 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 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

View Source
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.

View Source
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.

View Source
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.

View Source
const DefaultOutputTokens = 4096

DefaultOutputTokens is a request's output tokens, for its token estimate, when neither the request nor its policy sets a limit.

View Source
const MaxBodyBytes = 1 << 30

MaxBodyBytes is the largest body Parse reads (offsets are int32).

View Source
const MaxDepth = 64

MaxDepth is how deep a body may nest arrays and objects; the top-level object is at depth 1.

View Source
const MaxModelBytes = 256

MaxModelBytes is the longest model a request is compared with the allowed models by; a longer one matches none.

Variables

Checks are the request checks in the order they're decided: the first that fails decides.

Formats are the formats this engine reads, in order.

Functions

func Parse

func Parse(body []byte, f Format, out *Request) bool

Parse reads body as f into out. It returns false when body is malformed (out.Malformed, Offset and Why say where and why).

Types

type Action

type Action uint8

Action is what became of a request that failed a check.

const (
	// ActionDeny is a request denied.
	ActionDeny Action = iota
	// ActionLog is a request logged and let through (Detect).
	ActionLog
)

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
)

func CheckOf

func CheckOf(id int) (Check, bool)

CheckOf returns the check whose rule ID is id.

func (Check) RuleID

func (c Check) RuleID() int

RuleID is the check's reserved rule ID, 0 for CheckNone.

func (Check) Status

func (c Check) Status() int

Status is the HTTP status a request the check fails is denied with: 413 for the size caps, 400 for the others.

func (Check) String

func (c Check) String() string

String is the check's name, as events and metrics name it.

type CheckSet

type CheckSet uint16

CheckSet is a set of checks.

func (CheckSet) Has

func (s CheckSet) Has(c Check) bool

Has reports whether c is in s.

func (CheckSet) With

func (s CheckSet) With(c Check) CheckSet

With returns s with c.

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.

func (Finding) Status

func (f Finding) Status() int

Status is the HTTP status the request is denied with.

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
)

func (Format) String

func (f Format) String() string

String is the format's name in the API (spec.llm.endpoints[].format).

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.

func (*Metrics) Failed

func (m *Metrics) Failed(c Check, a Action)

Failed counts a check failed, and what became of the request.

func (*Metrics) Read

func (m *Metrics) Read(f Format, ph Phase, malformed bool, took time.Duration)

Read counts a body read as f, malformed or not, and the time it took.

func (*Metrics) Tokens

func (m *Metrics) Tokens(k TokenKind, n int64)

Tokens counts tokens of kind k.

type Phase

type Phase uint8

Phase is what a metric counts: a request, or (later) a response.

const (
	// PhaseRequest is a request's body.
	PhaseRequest Phase = iota
)

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.

func (*Request) FirstRole

func (r *Request) FirstRole(ro Role) (index, offset int, ok bool)

FirstRole reports whether the request has a message of role ro, and the first one's index (-1 for a top-level field: the Responses API's instructions, Anthropic's system) and offset in the body.

func (*Request) Model

func (r *Request) Model() []byte

Model returns the model, unescaped.

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
)

func ParseRole

func ParseRole(s string) (Role, bool)

ParseRole returns the role named s (spec.llm.request.clientRoles).

func (Role) String

func (r Role) String() string

String is the role's name, as the APIs write it.

type Rules

type Rules struct {
	// contains filtered or unexported fields
}

Rules are a compiled Config. They are immutable and safe for concurrent use.

func Compile

func Compile(c Config) (*Rules, error)

Compile checks and compiles c.

func (*Rules) Check

func (r *Rules) Check(body []byte, req *Request, off CheckSet) Finding

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

func (r *Rules) EstimatedTokens(req *Request) int64

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

func (r *Rules) FallbackTokens(bodyBytes int64) int64

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

func (r *Rules) OutputTokens(req *Request) int64

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 TokenKind

type TokenKind uint8

TokenKind is what inkwall_llm_tokens_total counts.

const (
	// TokensEstimated are the tokens charged at request time.
	TokensEstimated TokenKind = iota
	// TokensSettledInput and TokensSettledOutput are the tokens a response
	// reported using.
	TokensSettledInput
	// TokensSettledOutput are the output tokens a response reported.
	TokensSettledOutput
)

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

func ParseUsage(body []byte, f Format) (Usage, bool)

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.

func (Usage) Total

func (u Usage) Total() int64

Total is Input plus Output, saturated.

Jump to

Keyboard shortcuts

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