respfacts

package
v0.7.10 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 8 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 respfacts reads the facts a provider response states, from its bytes: the billed token tiers and why they could not be read (#200), the stop reason, the tool calls and their wait parameters, and the subagent spawns. One rule, one place, so every host reads a response the same way. It reads wire format only. It holds no transport and no stored customer data.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ResetShapeRecordForTest

func ResetShapeRecordForTest()

ResetShapeRecordForTest forgets the shapes recorded so far. For TESTS only: the record is the diagnostic this whole change exists to produce, so a test has to be able to observe it, and the per-process bound makes that a one-shot for the entire binary otherwise.

func StopReason

func StopReason(sse bool, body []byte) string

StopReason reads the terminal reason off a response body. For SSE the events are scanned newest-first: the terminal reason is in the LAST event that carries one, and an earlier chunk's `finish_reason: null` must not win.

Whatever this returns is still client-influenced text by the time it reaches the database (an upstream is configurable, so its response is not trusted input), so it is re-checked by dash.metaEnum before the insert.

func ToolUseNames

func ToolUseNames(sse bool, body []byte) []string

ToolUseNames reads every tool_use / function-call block NAME off a response, in the order they appear, for issue #424's waitcause package. Three dialects, each read structurally (never a regex over tool names) off the same bytes StopReason reads:

Anthropic Messages   content[].{type: "tool_use", name}         (buffered JSON, or an SSE
                      content_block_start event's content_block)
OpenAI chat           choices[0].message.tool_calls[].function.name (buffered), or a
                      streamed delta.tool_calls[].function.name chunk
OpenAI Responses      output[].{type: "function_call", name}    (buffered); not read from
                      an SSE stream — Responses event names and nesting are not the same as
                      Anthropic's and this proxy does not splice that transport (see
                      proxy.go's own comment where it tests schema.IsResponses(wire)), so a streamed
                      Responses tool call reads as if the response had none, same honest gap
                      as a sniffer-truncated Anthropic stream.

Best-effort by construction: a sniffed stream only has a bounded head+tail window (see sniffer), so a tool_use far into a very long response can fall outside it. That under-reports own_tool, it never invents one.

func UsageGaps

func UsageGaps() (unparsed, unreadable int64)

UsageGaps returns how many responses carried usage this proxy could not read (an unrecognised dialect) and how many carried bytes it could not parse at all. Non-zero on either means fresh_input_tokens / cache_read_tokens / cache_write_tokens are 0 for some route or provider while everything else about the request looks healthy.

RESPONSES, not requests, and the distinction matters when reading them against traffic: one request can drive several upstream rounds through the expand continuation loop, so a single unaccounted request can move these more than once. The 4,015-of-4,015 figure this was filed against is a per-REQUEST count, so it is not directly comparable.

Types

type Facts

type Facts struct {
	providerusage.Tiers
	Miss Miss
	// StopReason is the provider's terminal reason, in its own vocabulary (see StopReason).
	StopReason string
	// ToolUseNames is every tool_use or function-call name, in order (see ToolUseNames).
	ToolUseNames []string
	// ToolUseIncomplete is true when ToolUseNames may miss the true last call, because the bytes
	// read were a spliced head+tail window. The terminal-tool rule never applies then (#857).
	ToolUseIncomplete bool
	// ToolParams is the `timeout` and `run_in_background` of the last tool call (#1198). Zero on a
	// spliced window.
	ToolParams ToolParams
	// Spawn is the subagent calls of the response (#1198). Zero on a spliced window.
	Spawn Spawn
}

Facts is everything one response says, read from its bytes. Tiers is the zero value when Miss is not MissNone: a caller must report the request as partially accounted, not price it as free. The facts other than the tiers are filled whatever Miss says, because they are independent: an OpenAI response without `stream_options` reports no usage at all and still reports finish_reason.

func Read

func Read(contentType string, body []byte, spliced bool) Facts

Read reads one response: usage, stop reason and tool calls. It is the ONE place a miss is counted and recorded — the whole response is in scope here, which is what it takes to say anything about it (ParseUsage is also called per-event by the SSE path, where a skip means nothing).

spliced says the bytes in body are a head+tail WINDOW rather than the whole response (the sniffer's own knowledge, sn.spliced()). It upgrades an `absent` verdict to unreadable: over a window, "no usage block in what we kept" is not "the provider sent none" — the middle of the response was dropped on the floor, and the remedy is upstream of any parser. Only `absent` is upgraded; a block that was present and rejected is a real dialect finding whatever the window did, and `found` wins over everything (#207).

The reason reaches the lifecycle log line beside `usage_reported`, so a deployment that has quietly stopped accounting tokens says which of the five cases it is at the moment it happens, instead of being reconstructed two iterations later from a cost figure.

type Miss

type Miss uint8

Miss says WHY no billed tiers came back, because "ok=false" meant five different things and nothing distinguished them (#200). Only two of the five are benign, and the other three call for THREE DIFFERENT REMEDIES — which is the whole argument for classifying rather than counting: a shared signal reports "nothing to account" and "token accounting is offline" with one value, and the second is silent by construction (a healthy 200, correct savings counters, correct latency, and three token fields quietly at 0).

It ran for 4,015 of 4,015 requests in one benchmark iteration and was found two iterations later, in a post-mortem chasing a different question.

const (
	MissNone       Miss = iota // tiers were read; not a miss
	MissNoBody                 // nothing to look at (empty response). BENIGN
	MissAbsent                 // no usage block anywhere we know to look. BENIGN
	MissZero                   // a recognised block, every tier zero. LEGITIMATE
	MissUnparsed               // a block IS there, no recognised spelling read it
	MissUnreadable             // the bytes are not parseable, so nothing could be sought
)

THE ORDER IS PART OF THE TYPE, ascending in severity: ParseSSEUsage compares two reasons with `>` to keep the worst one any event of a stream produced. A new value goes at its severity position, not at the end.

func NoteMiss

func NoteMiss(sofar, this Miss, accounted bool) Miss

NoteMiss folds one round's reason into the request's, so `usage_miss` cannot contradict `usage_reported` on the log line.

A request can drive several upstream rounds (the expand continuation loop). usageOK is sticky — it is only ever set true and never reset, because a request whose usage was read once IS accounted — but the reason was last-write-wins, so round 2 carrying no usage relabelled an accounted request `absent`. The rule that removes the contradiction: once anything accounted the request, the reason is `parsed`; while nothing has, keep the WORST reason seen, for the same severity-ordering reason ParseSSEUsage keeps one.

func ParseSSEUsage

func ParseSSEUsage(raw []byte) (providerusage.Tiers, Miss, string)

ParseSSEUsage pulls usage out of a streamed response, with #200's classification. Both dialects report it in terminal events (Anthropic: message_start carries the input tiers and message_delta the output; OpenAI: a final chunk with `usage`).

The INPUT tiers (fresh, cache read, cache write) are taken as ONE set from the last event that carries an input count, so a later event replaces an earlier one's tiers (#745): a litellm gateway puts the TOTAL prompt in message_start and the true split in message_delta, and a per-field maximum counted the read twice. An event with no input count (a real Anthropic message_delta) leaves the earlier tiers alone. Output keeps the maximum, because the last event carries the final count and a repeat must not double it.

An event stream that carried a usage block that no event of it could read is the streamed form of the dialect gap, and it must not be reported as "the provider streamed no usage" — the remedies differ. The third return is the PAYLOAD OF THE EVENT THAT SET THE REASON, for the shape record.

The record used to describe the stream's LAST data: event, which on the Anthropic-family transport is `message_stop` — usage arrives in `message_start`. So a streamed unrecognised dialect produced a record of the terminal event: no usage_at, no usage_keys, nothing about the dialect, and it consumed one of the bounded record slots to say it. That is exactly the shape a streamed Bedrock aws/claude-* response has, which is where the gap this record exists to diagnose would sit. Returning it from here also collapses two walks over the transport into one.

func ParseUsage

func ParseUsage(body []byte) (providerusage.Tiers, Miss)

ParseUsage reads the four billed token tiers from a buffered response body, in whichever dialect it is written, and says why when it cannot (#200). The field names are in providerusage.Parse.

Anthropic's `input_tokens` already EXCLUDES the cached tiers, so it is the fresh figure directly. OpenAI's `prompt_tokens` INCLUDES its cached_tokens, so fresh is the difference. Getting this backwards double-counts the whole transcript on every turn.

ParseSSEUsage calls this per event and must not have its skips classified. Only Read, which sees the whole response, is in a position to say anything about it.

func (Miss) String

func (m Miss) String() string

String is the reason as it appears in the lifecycle log line, so an operator reading `usage_reported=false` can see which of the five it was without a body dump.

type Spawn

type Spawn struct {
	N    int
	Type string
}

Spawn is the subagent calls one response made: N of them, and the subagent_type of the last that stated one. Only the type is read from their input, never the prompt.

func Spawns

func Spawns(sse bool, body []byte) Spawn

Spawns counts the subagent calls of a response and reads the subagent_type of the last one. A streamed Anthropic response joins each call's input_json_delta pieces. Other streams are not read.

type ToolParams

type ToolParams struct {
	TimeoutMs     int64 // the call's `timeout`, in ms (Claude Code's Bash and others); valid when HasTimeout
	HasTimeout    bool
	Background    bool // the call's `run_in_background`; valid when HasBackground
	HasBackground bool
}

ToolParams is what the last tool call of a response said about how long its wait may last (#1198). Each value has its own "stated" flag, because an absent parameter and a zero are different facts. Metadata only: one number and one flag; the rest of the input is dropped.

func LastToolParams

func LastToolParams(sse bool, body []byte) ToolParams

LastToolParams reads the parameters of the LAST tool call of a response, the call ToolUseNames reports last (and the wait tool of the row). A buffered response of any dialect carries the input whole. A streamed Anthropic response carries it as input_json_delta pieces, joined here per content block. A streamed OpenAI response is not read: that is a gap, and the value stays unstated rather than guessed. The caller skips a spliced window, whose last call may be missing.

func ToolParamsOf

func ToolParamsOf(input string) ToolParams

ToolParamsOf reads ONLY `timeout` (a positive number) and `run_in_background` (a boolean) off a tool call's input JSON. Any other key, and any other type, is ignored.

Jump to

Keyboard shortcuts

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