cheapmodel

package
v0.7.15 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 23 Imported by: 1 module, 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 cheapmodel provides a minimal Anthropic Messages client used as the engine's injected extraction model. It implements engine.Model. (An OpenAI variant is a straightforward follow-up; the canonical model is Anthropic-shaped, so the Anthropic client is the natural first.)

Index

Constants

View Source
const DefaultMaxTokens = 4096

DefaultMaxTokens is the reply budget for one cheap-model call.

Raised from 2048 after a measured failure: on a real session a sonnet-class extraction model's reply stopped exactly at 2048, so the Starlark program was incomplete and unparseable and the call bought nothing for 26.8 s and ~$0.08. A truncated reply is the worst outcome available — full price, zero result — and output tokens are billed on what is actually produced, so a larger cap costs nothing when it is not used. Callers that reserve this out of an input budget must use this constant, not a literal, or the two drift.

View Source
const PrefixAskMaxTokens = 16000

PrefixAskMaxTokens is the reply budget for a PREFIX ASK, which needs far more than a compaction.

16000, from `659e7a6`, the commit about exactly this failure: an adjudication arm's replies were being cut off at a 2048-token default and the parse failure was misread as a model declining to act for three iterations. One prefix-ask reply carries a verdict for EVERY candidate — each with an obligation label and a VERBATIM quote — and the request model runs adaptive thinking, which spends part of the budget before emitting any text at all (a probe at max_tokens 900 returned thinking blocks and no text whatsoever).

Output bills as generated and not as budgeted, so the ceiling costs nothing until it is used. Kept separate from DefaultMaxTokens because the two answer different questions: what a Starlark program needs, against what a verdict array over an unbounded candidate list needs.

Variables

This section is empty.

Functions

func AskBridge added in v0.6.0

func AskBridge(lastRole string) string

AskBridge returns the assistant text to insert between a last message of role lastRole and an appended user question, or "" when the question may follow directly. Only a trailing `system` message needs one; see insertAskMessage for why.

func AvgCallCost

func AvgCallCost(p Pricing) (float64, bool)

AvgCallCost returns the OBSERVED mean dollar cost of one extraction call so far, and whether there is any observation yet. This is what the economic gate should spend against: it reflects this deployment's real prompt sizes, this model's real pricing, and whether the preamble cache is actually working — none of which a constant can. Callers must handle ok==false (no calls yet) with a prior estimate.

func CacheUsage

func CacheUsage() (cacheWrite, cacheRead int64)

CacheUsage returns the cumulative cache-tier token counts (write, read) for the cheap model. read==0 after many calls means the preamble breakpoint is inert.

func CacheablePrefix

func CacheablePrefix(model string, promptTokens int) bool

CacheablePrefix reports whether a system prefix of promptTokens would actually be cached by this model. Exported so a caller pricing a call does not have to duplicate the table (the economic gate must not assume a cache it will not get). promptTokens is an o200k count (internal/tokens), the same unit systemBlocks uses, so the conversion to the provider's tokens happens in exactly one place.

func PricingConfigured

func PricingConfigured() bool

PricingConfigured reports whether the operator priced the cheap model at all, i.e. whether any CHEAP_MODEL_PRICE_* is set to a usable value.

It exists so a caller can SAY SO when it is spending against a list price nobody confirmed. MEASURED on this deployment: none of the four variables is set, so the economic gate priced every call at haiku LIST ($1.00/$5.00 per MTok) while the request-level figure on the dashboard came from the operator's own card ($0.80/$4.00) — about 25% apart, in the numerator of every allow/suppress decision, with nothing anywhere reporting the divergence. A silent 25% is worse than a wrong 25%: the wrong one can be corrected.

func ReplayUsage

func ReplayUsage(ctx context.Context, model string, inTok, outTok, cacheWrite, cacheRead int)

ReplayUsage attributes usage that was INCURRED EARLIER, ELSEWHERE, to the sink scoping ctx.

It exists for exactly one caller and the reason is worth stating, because a general "add arbitrary usage" function is otherwise an invitation to double-count. summarize produces its summary on a DETACHED goroutine so that a slow model call cannot hold a request past its own prompt-cache lifetime. That goroutine outlives the request that started it, so by the time it knows what the call cost, that request's row has already been written and its `cg_llm_cost_usd` is 0 — measured, and caught by proxy's own TestCGLLMCostIsChargedToTheRequestThatSpentIt.

Leaving it there was not an option: the compaction-episode measurement charges the summarizer's spend as a DEBIT, so a missing cost makes the panel overstate its own saving, which is the one direction a savings figure must never lean.

So the goroutine records what it used, and the NEXT turn of the same session replays it here. The attribution is one turn late by construction — the same deliberate lag Ctx.PrevBilledInput carries, and for the same reason: a figure that arrives slightly late is worth far more than one that never arrives. The whole-process totals were never wrong; only the per-request row was.

Replaying twice would double-count, so the caller must delete its record before replaying — see summarize's takeDeferredUsage.

func SnapshotUsageForTest added in v0.7.13

func SnapshotUsageForTest() (restore func())

SnapshotUsageForTest saves the process-wide usage totals and returns a function that puts them back. A test that sends through a real client calls it, so its calls do not reach the totals that other tests read (the extract economics tests). Tests only: no code path outside tests calls it.

func Usage

func Usage() (calls, inTokens, outTokens int64)

Usage returns the cumulative cheap-model usage (calls, input tokens, output tokens) since process start. Kept at this exact signature for backward compatibility — /stats' existing three fields are parsed by deploy/harbor/*.py.

func WithSink

func WithSink(ctx context.Context, s *Sink) context.Context

WithSink scopes cheap-model accounting for everything done under ctx to s. A call made under a context with no sink still counts toward the process totals — nothing is lost, it is simply not attributable to one request.

Types

type Anthropic

type Anthropic struct {
	D         dispatch.Dispatcher
	Ref       dispatch.Ref
	Model     string // e.g. claude-haiku-4-5
	MaxTokens int    // default DefaultMaxTokens (4096)
}

Anthropic calls a small Anthropic model with a single user prompt and returns the text of the first content block. The destination and the credential are the host's: D and Ref name which one, resolved by the host's Dispatcher at send time. Anthropic itself never sees either.

func (Anthropic) AsModel

func (a Anthropic) AsModel(id string) components.Model

AsModel is components.Remodeler: same endpoint, same credential, different model.

func (Anthropic) Complete

func (a Anthropic) Complete(ctx context.Context, prompt string) (string, error)

func (Anthropic) CompleteBlocks

func (a Anthropic) CompleteBlocks(ctx context.Context, system []string, prompt string) (string, error)

CompleteBlocks sends the invariant instructions as ORDERED system blocks and the per-call part as the user message. It exists so a caller whose preamble has a deployment-wide half and a per-configuration half can keep them as separate blocks rather than one joined string (see extract.SystemBlocksModel).

THE BREAKPOINT IS CONDITIONAL, and that is the point. A cache_control below the model's minimum cacheable prefix is not an error and not a no-op you can see — the response simply reports cache_creation_input_tokens: 0. Measured against the gateway: a ~1.5k-token prefix on claude-haiku-4-5 gives write=0 read=0, while the same prefix on claude-sonnet-5 caches. Asking for a cache we cannot get is a request field with no effect at best; asking for one we get but never read is a 1.25x write we pay for once and waste. So place the mark only when the blocks actually clear the floor.

One breakpoint, on the last block, not one per block: nested marks on a two-block prefix would create a second cache entry whose only benefit is being shared between configurations that differ in the second block, and it is paid for with another write. Revisit if two levels are ever measured to be in flight at once often enough to matter.

func (Anthropic) CompletePrefixed

func (a Anthropic) CompletePrefixed(ctx context.Context, prefixBody []byte, ask string) (string, PrefixUsage, error)

CompletePrefixed sends `ask` as a trailing user message appended to prefixBody — an ENTIRE previously-sent Anthropic request — so the provider reads the prompt cache that body populated instead of being charged fresh for the transcript again.

NOTE WHAT THE CACHED REGION IS HERE, because it is not what the rest of this file deals with. systemBlocks places OUR OWN cache_control on a system prefix we built, and is therefore subject to the provider's minimum cacheable size (4,096 provider tokens on haiku-class). This method places no breakpoint at all: the marks are the ones the AGENT's own request already carried, and the region they cover is the transcript. That clears any minimum by orders of magnitude — the measurement below read 19,595 tokens — so the size floor that governs systemBlocks does not apply, and neither does its model-family asymmetry.

Measured against the live gateway (docs/experiments/loca/iter019/results.md §2):

  • appending a trailing user message to a byte-identical prefix reads the whole prefix from cache and writes nothing: 19,595 read / 0 created.

  • NO `tool_choice` IS SET, and a structured-answer tool IS declared. Those two halves are ONE change: the earlier comment here claimed forcing "none" was free and necessary "because the model will otherwise answer with a tool_use instead of the verdicts", and it was RIGHT about the mechanism and WRONG about the remedy. Three arms over the same transcript and ask model, three benchmark passes each, run sequentially:

    tool_choice tool declared asks replied unusable answered via tool_use {"type":"none"} no 20 6 (30.0%) 0 (omitted) NO 24 14 (58.3%) 0 (omitted) yes 77 7 (9.1%) 43 (55.8%)

    Fisher two-tailed: row 1 vs row 3 p = 0.0245, row 2 vs row 3 p = 0.0000.

    THE MIDDLE ROW IS THE POINT, and it is the arm that had never been run before: dropping the suppression WITHOUT declaring an answer tool is worse than leaving it in. Freed to call something and offered only the agent's tools plus context_guru_expand, the model calls one of those — observed directly by logging every reply's content blocks, as `thinking,tool_use:context_guru_expand` with NO text block, which this function's text extraction reads as "" and the caller files as unusable. That arm also lost 5 asks to the 90 s llmCallTimeout, against 0 and 1 in the others. So `none` was suppressing a real failure mode; declaring a tool worth calling is what removes the mode instead of trading it for prose.

    Forcing a NAMED tool is separately not free: it wrote a second cache entry (8,378 against the 8,268 already cached), so tool_choice DOES participate in the key when it names a tool even though "none" does not. Omitting it entirely reads the prefix for free.

  • `tools` ARE part of the key. They are therefore left exactly as the prefix had them; dropping them read a different, smaller entry (19,129) i.e. a separate cache line and a fresh write.

  • this route REJECTS assistant prefill ("the conversation must end with a user message"), which the ask satisfies by construction: it is always the LAST message insertAskMessage appends, even on the trailing-system-message shape below, which inserts one more message BEFORE it but never after.

  • THE ASK IS NOT ALWAYS THE ONLY THING APPENDED. See insertAskMessage: when prefixBody's own last message is a `role: system` mid-conversation reminder — which Claude Code sends on effectively every turn — appending the ask directly after it is a guaranteed 400 ("role 'system' must precede an 'assistant' message or end the array"). insertAskMessage leaves that system message where it is and appends a short synthetic assistant turn plus the ask after it. It changes no existing byte: it copies the last message's breakpoint onto the appended bridge (#721), and only while the request stays at or under the provider's 4-breakpoint cap (#776).

Everything else about the body is preserved untouched, because every byte before the appended message is prefix and any edit to it costs the cache read this method exists for. `stream` is the one exception: the caller wants a single JSON answer, and a streamed response is not that.

func (Anthropic) CompleteSystem

func (a Anthropic) CompleteSystem(ctx context.Context, system, prompt string) (string, error)

CompleteSystem sends the invariant instructions as a stable `system` block carrying a `cache_control` breakpoint, and the per-call variable part as the user message. On a repeated call the preamble bills at the cache-READ rate instead of fresh input.

MEASURED CAVEAT (this is why the caller must not assume a win): a breakpoint below the model's MINIMUM CACHEABLE PREFIX is silently ignored — no error, no cache entry, `cache_creation_input_tokens: 0`. That minimum is 4096 PROVIDER tokens on claude-haiku-4-5 and 1024 on claude-sonnet-5, while the extractor's invariant preamble is 1,893 o200k tokens. So on the CHEAP model (haiku) the preamble ALONE still caches nothing, and on the agent model (model.source: incoming, the default) it does. Split anyway — it is free, correct, and wins on the source that can win.

The preamble PLUS the conversation context (extract.Cfg.CacheContext, on a multi-candidate request) does clear the floor and does cache on haiku, and that only started working once the comparison was fixed to convert units — see minCacheableO200k. Verified against the gateway: haiku 1.5k => write=0 read=0; haiku 3,673 o200k => write=4,217 then read=4,217; sonnet 1.5k => write then read.

func (Anthropic) WithMaxTokens

func (a Anthropic) WithMaxTokens(n int) components.Model

WithMaxTokens is components.Budgeter: same call, larger reply budget. See the interface for why a caller asking a long question has to be able to raise this.

type OpenAI

type OpenAI struct {
	D         dispatch.Dispatcher
	Ref       dispatch.Ref
	Model     string // e.g. gpt-4o-mini
	MaxTokens int    // default DefaultMaxTokens (4096)
	// Path is the chat-completions path on the host's endpoint. Empty means /v1/chat/completions.
	// A host sets it when its route uses another path (IBM Bob).
	Path string
}

OpenAI calls a small OpenAI chat-completions model with a single user prompt and returns the content of the first choice. It implements engine.Model. The destination and the credential are the host's: D and Ref name which one, resolved by the host's Dispatcher at send time.

func (OpenAI) AsModel

func (o OpenAI) AsModel(id string) components.Model

AsModel is components.Remodeler: same endpoint, same credential, different model.

func (OpenAI) Complete

func (o OpenAI) Complete(ctx context.Context, prompt string) (string, error)

func (OpenAI) CompleteBlocks

func (o OpenAI) CompleteBlocks(ctx context.Context, system []string, prompt string) (string, error)

CompleteSystem puts the invariant instructions in a leading `system` message. OpenAI has no explicit cache breakpoints — caching is automatic on a shared prefix — so there is nothing to mark; a stable leading system message IS the cacheable-prefix idiom here. The split is therefore honest on both backends: same call shape, provider-appropriate mechanism, and no `cache_control` field invented for an API that would reject it. CompleteBlocks joins the ordered blocks into that one leading system message. There is no per-block mechanism to preserve here: OpenAI caches automatically on the longest shared prefix, and two system messages would cache exactly as one does. Keeping the method means the extractor gets the same content on both backends and only the caching mechanism differs (see extract.SystemBlocksModel).

func (OpenAI) CompleteMessages

func (o OpenAI) CompleteMessages(ctx context.Context, system string, msgs []bschemas.ChatMessage) (string, error)

THE MAPPING IS AN EXPLICIT ALLOWLIST, and both halves of that are load-bearing.

CONTENT IS PASSED THROUGH AS-IS, not flattened to text. m.Content is a *ChatMessageContent whose MarshalJSON emits either a bare string or the ORIGINAL block array, via MarshalSorted (deterministic key order — non-deterministic serialization is itself a silent cache invalidator). Flattening blocks to a string would change the rendered prompt and forfeit the prefix match this method exists to get.

EVERY OTHER FIELD IS NAMED EXPLICITLY, because marshalling the struct whole leaks fields that are not part of an OpenAI chat-completions REQUEST. Measured:

{"role":"assistant","reasoning":"...","tool_calls":[{"index":0,"id":"call_1",
 "function":{"name":null,"arguments":""}}]}

Three defects in one line. `reasoning` is not a request field at all (and a thinking model puts one on most assistant turns). `index` is a STREAMING-DELTA field. `"name":null` is invalid where the backend requires a string. ChatAssistantMessage also carries Refusal, Audio, ReasoningDetails and Annotations, and ChatMessage carries Name — all with omitempty, so all silently present the moment they are set.

system is prepended only when non-empty. Pass "" to send the messages EXACTLY as given, which is what a cache-reuse caller wants: a leading block the parent request did not have changes the prefix in the costliest position.

func (OpenAI) CompletePrefixedChat added in v0.7.2

func (o OpenAI) CompletePrefixedChat(ctx context.Context, prefixBody []byte, ask string) (string, PrefixUsage, error)

CompletePrefixedChat asks the incoming Chat Completions model one question over the exact request body previously accepted upstream. The only prompt change is one trailing user message, so the provider's automatic prefix cache (it matches the longest shared prefix) is read, not re-written.

tools and tool_choice stay exactly as the prefix had them: tools are part of the cache key, and the model may call context_guru_adjudicate when the request declares it. The reply is read from that call when present and from message.content otherwise, so the method works with or without the declaration. The cache READ is judged by the caller from the returned usage (prompt_tokens_details.cached_tokens).

The path and credential are the incoming client's own (o.Ref and o.Path). A wrong path or auth scheme fails here with a non-200, and the caller fails open.

func (OpenAI) CompletePrefixedResponses

func (o OpenAI) CompletePrefixedResponses(ctx context.Context, prefixBody []byte, ask string) (string, PrefixUsage, error)

CompletePrefixedResponses asks the incoming Responses model one question over the exact request body previously accepted upstream. The only prompt change is one trailing user item, preserving the implicit-cache prefix and opaque input.

func (OpenAI) CompleteSystem

func (o OpenAI) CompleteSystem(ctx context.Context, system, prompt string) (string, error)

func (OpenAI) WithMaxTokens

func (o OpenAI) WithMaxTokens(n int) components.Model

WithMaxTokens is components.Budgeter: same call, larger reply budget. See the interface for why a caller asking a long question has to be able to raise this.

type PrefixUsage

type PrefixUsage struct {
	CacheRead  int
	CacheWrite int
	// CacheWrite1h is the SUBSET of CacheWrite billed at the one-hour write premium rather than
	// the default five-minute rate — never an addition to CacheWrite. See
	// components.PrefixUsage.CacheWrite1h, which this converts to directly (components/
	// prefixask.go), so the two types must keep identical field names, types and order.
	CacheWrite1h int
	Fresh        int
	Output       int
	// ViaTool: the answer came back as a tool_use for adjudicate.ToolName, not as reply text. See
	// components.PrefixUsage.ViaTool -- the field exists so the caller can COUNT which shape it got,
	// because the text parser accepts both and therefore hides the difference.
	ViaTool bool
}

PrefixUsage is what one CompletePrefixed call cost, straight from the provider's usage block. Returned rather than only recorded because the CALLER has to gate on it: a prefix ask whose whole justification is the cache read must be able to see that the read happened.

type Pricing

type Pricing struct {
	InputPerMTok      float64
	OutputPerMTok     float64
	CacheWritePerMTok float64
	CacheReadPerMTok  float64
}

Pricing is the per-million-token price of the extraction model, in dollars. The economic gate needs the real cost of a call, not a hard-coded "$0.012" — that figure was one workload's average, and it changes with the model, the gateway's contract, and the prompt size. Rates come from the environment so an operator prices their own deployment without a rebuild; the defaults are claude-haiku-4-5 list rates.

func HaikuPricing

func HaikuPricing() Pricing

HaikuPricing is the default: claude-haiku-4-5 list rates ($1/$5 per MTok), with the standard Anthropic cache multipliers (write 1.25x input, read 0.1x input).

func PricingFromEnv

func PricingFromEnv() Pricing

PricingFromEnv returns HaikuPricing overridden by any of CHEAP_MODEL_PRICE_IN, _OUT, _CACHE_WRITE, _CACHE_READ (dollars per million tokens). An unparseable or absent value leaves the default — pricing must never fail a request. Use PricingConfigured to find out whether the result is the operator's card or our guess.

func (Pricing) Cost

func (p Pricing) Cost(inTok, outTok, cacheWrite, cacheRead int64) float64

Cost prices one call's token usage in dollars.

type Sink

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

Sink accumulates the cheap-model usage of ONE scope — in the proxy, one request. The totals above are a per-PROCESS fact and stay that way (/stats and the benchmark read them); a per-request bill cannot be derived from them by subtraction, because on a multi-tenant proxy any other tenant's call landing inside the subtraction window is billed to whoever happens to be in flight. That was the cg_llm_cost_usd defect: it propagated into tenant_spend and month-to-date spend, and let a tenant infer other tenants' compaction activity from its own rows.

Carried on the CONTEXT rather than as a components.Ctx field, because the context is what already reaches every model call: apply builds components.Ctx from it, components derive their timeouts from it, and internal/extract sees only a context.Context. One plumbing point, and no call path can silently miss it.

func SinkFrom

func SinkFrom(ctx context.Context) *Sink

SinkFrom returns the sink scoping ctx, or nil.

func WithCallSink

func WithCallSink(ctx context.Context) (context.Context, *Sink)

WithCallSink scopes a NARROWER accounting window inside whatever sink already scopes ctx, returning the child so the caller can read exactly one call's usage. Usage recorded under the child also reaches every ancestor, so installing one never costs the request its own attribution.

func WithDetachedSink

func WithDetachedSink(ctx context.Context) (context.Context, *Sink)

WithDetachedSink installs a sink that does NOT chain to whatever sink already scopes ctx, returning it so the caller can read its usage and attribute it deliberately later.

It exists because WithCallSink's chaining — normally the right behaviour, since a narrower window should still credit its request — is a DOUBLE-COUNT hazard for work that outlives the request that started it. summarize's detached summarizer inherits the commissioning request's context, so a chained sink reaches that request's row: if the call happens to finish before that row is written, the cost lands there AND is replayed onto the next turn, charging one call twice. Measured, at exactly 2x, by proxy's TestOurOwnSpendCountsTheCacheTiersToo.

Detaching makes the attribution single-valued: the commissioning row can never see this usage, and exactly one later turn replays it. Process-wide totals are unaffected — those are counted by the model wrapper itself, not by walking the sink chain.

func (*Sink) CacheTotals

func (s *Sink) CacheTotals() (cacheWrite, cacheRead int64)

CacheTotals returns this scope's cache-tier tokens (write, read).

func (*Sink) CacheWrite1h

func (s *Sink) CacheWrite1h() int64

CacheWrite1h returns the SUBSET of CacheTotals' cacheWrite this scope billed at the one-hour write premium, never an addition to it. 0 on every backend but Anthropic, and 0 there too unless the call actually requested a 1h TTL breakpoint.

func (*Sink) Header added in v0.7.2

func (s *Sink) Header() http.Header

Header returns the response headers of the newest call in this scope that got an answer, or nil. The caller must not change them.

func (*Sink) Model

func (s *Sink) Model() string

Totals returns this scope's usage so far, at the same shape as Usage(). Model reports the model these calls were made with, or "" when nothing was recorded or the scope mixed several (in which case no single rate is honest and the caller must fall back).

func (*Sink) Totals

func (s *Sink) Totals() (calls, inTokens, outTokens int64)

Jump to

Keyboard shortcuts

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