accountant

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 1 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.

README

accountant

accountant is the context accountant: a Go library that keeps the books for a context optimizer. It says how many tokens each change to an LLM request saved or caused, for each billing tier.

A tool such as a context optimizer edits a request before it goes to the provider. It may shorten a tool output, remove unused tool declarations, or replace old messages with a summary. accountant answers one question for each change:

If this change had never been made, how would the provider have billed these tokens on this request?

The answer depends on the provider's prompt cache. A change inside a cached prefix can break the cache and cost more than it saves. accountant keeps that state for each conversation thread and prices every change in tokens for the input, cache write (5-minute and 1-hour) and cache read tiers. The host turns tokens into money with its own rates.

Use

The library is stateful, and Compute is deterministic. For each request:

  1. Trackers.BeginRequest takes the body the client sent.
  2. Request.Add records each change an operator reports (rewrite, spend, setting).
  3. Request.EndRequest takes the body that was forwarded and the cache facts.
  4. Request.Compute takes the billed Usage and returns a Result.
ts := accountant.NewTrackers()
r := ts.BeginRequest(accountant.RequestMeta{RequestID: "r2", Session: "s1", At: now}, client, clientBreakpoints)
r.Add(accountant.Operation{Kind: accountant.KindRewrite, ChangeID: "mask:1", At: at,
    SizeBefore: accountant.Size{Bytes: 8000}, SizeAfter: accountant.Size{Bytes: 1000}})
r.EndRequest(accountant.Thread{ID: "main"}, forwarded, forwardedBreakpoints, facts)
res := r.Compute(accountant.Usage{CacheRead: 4000, CacheWrite: 1000})
// res.Ops[0].Saved is a accountant.TierTokens

example_test.go is a complete program that runs under go test.

A change is reported once, on its first request. Compute applies it again on later requests until it ends, so one thread's result depends on the requests before it. Results fail open: a failed check goes into Result.Checks and is logged as a warning, and pricing goes on.

The module imports only the standard library, so any host can use it. boundary_test.go enforces that.

Layout

Path What it holds
accountant.go The whole public API: type aliases, constants and three functions
internal/engine/ The implementation and its unit tests. Not importable by hosts
test/cases/ The JSON cases and the loader (import "github.com/rossoctl/accountant/test/cases")
test/gen/ The Python generator that writes the cases
docs/ Specification, design, examples

Documents

Document What it holds
docs/spec.md The specification: words, requirements (R1 and on), scope
docs/design.md The design: types, Compute, cache effects, checks
docs/testing.md How the library is tested, and the exhaustive test-case list
docs/examples.md Eight worked examples with figures
docs/cached-prefix.md How providers decide what a cache read covers
docs/cortex-wiring.md How Cortex and context-guru plug it in

Test cases

test/ is the list of cases an implementation must meet: JSON files, each a sequence of requests with the expected Result. A host can play them through its own pricing code and compare. The cases are generated by test/gen/gen_cases.py (go generate ./test/cases), which computes the body hashes.

go vet ./...
go test ./...

Status

Pre-release. The API follows the design in docs/design.md and may change before the first tag.

Not implemented yet: Result.Interaction, the order check, and storing a reported change in EndRequest. Each is marked "Not implemented in v0" in the design. A Tracker is never evicted, so memory grows with every thread.

License

Apache 2.0. See LICENSE.

Documentation

Overview

Package accountant is the context accountant: it tracks what a context optimizer saves. It prices the changes that the optimizer makes to an LLM request, in tokens for each billing tier.

A host calls it in four steps for each request. [Trackers.BeginRequest] takes the body the client sent. [Request.Add] records each change an operator reported. [Request.EndRequest] takes the body that was forwarded and the cache facts. [Request.Compute] takes the billed Usage and returns a Result: the tokens each change saved or caused. The host turns tokens into money. A keep-alive ping has no request record: use ComputeStandalone.

The module imports only the standard library. Its design is in docs/design.md, and a complete program is in the package example.

This file is the whole public API. The implementation is in internal/engine, with the state it keeps for each thread; none of that is part of the API.

Example

An operator shortens a tool output from 8,000 bytes to 1,000 on the second request. The first two messages are already cached, so they are read in both bills. The new message would have been written to the cache, so the saving is the tokens it did not write, at the 5-minute write tier.

package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/rossoctl/accountant"
)

// body hashes one request body: one entry per message, in order.
func body(sizes ...int) accountant.Body {
	msgs := make([][]byte, len(sizes))
	for i, n := range sizes {
		msgs[i] = []byte(fmt.Sprintf("m%d", i) + strings.Repeat(".", n))
	}
	return accountant.NewBody(nil, nil, msgs)
}

// An operator shortens a tool output from 8,000 bytes to 1,000 on the second request. The first
// two messages are already cached, so they are read in both bills. The new message would have been
// written to the cache, so the saving is the tokens it did not write, at the 5-minute write tier.
func main() {
	ts := accountant.NewTrackers()
	t0 := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC)
	facts := accountant.EntryFacts{TTL: 5 * time.Minute, Lifetime: accountant.LifetimeExact}
	thread := accountant.Thread{ID: "main"}
	last := accountant.Position{Section: accountant.SectionMessages, Index: 1}

	// Request 1: nothing changed, the provider wrote the cache.
	first := body(2000, 2000)
	r1 := ts.BeginRequest(accountant.RequestMeta{RequestID: "r1", Session: "s1", At: t0}, first,
		[]accountant.Breakpoint{{Pos: last, TTL: "5m"}})
	r1.EndRequest(thread, first, []accountant.Breakpoint{{Pos: last, TTL: "5m"}}, facts)
	r1.Compute(accountant.Usage{CacheWrite: 4000})

	// Request 2: the client sent 8,000 bytes at message 2; an operator forwarded 1,000.
	client, forwarded := body(2000, 2000, 8000), body(2000, 2000, 1000)
	at := accountant.Position{Section: accountant.SectionMessages, Index: 2}
	r2 := ts.BeginRequest(accountant.RequestMeta{RequestID: "r2", Session: "s1", At: t0.Add(10 * time.Second)},
		client, []accountant.Breakpoint{{Pos: at, TTL: "5m"}})
	r2.Add(accountant.Operation{ID: "op1", Kind: accountant.KindRewrite, Operator: "mask", ChangeID: "mask:1", At: at,
		SizeBefore: accountant.Size{Bytes: 8000}, SizeAfter: accountant.Size{Bytes: 1000}})
	r2.EndRequest(thread, forwarded, []accountant.Breakpoint{{Pos: at, TTL: "5m"}}, facts)
	res := r2.Compute(accountant.Usage{CacheRead: 4000, CacheWrite: 1000})

	p := res.Ops[0]
	fmt.Printf("saved %+v\ncaused %+v\nchecks %d\n", p.Saved, p.Caused, len(res.Checks))
}
Output:
saved {Input:0 CacheWrite5m:6992 CacheWrite1h:0 CacheRead:0}
caused {Input:0 CacheWrite5m:0 CacheWrite1h:0 CacheRead:0}
checks 0

Index

Examples

Constants

View Source
const (
	KindRewrite = engine.KindRewrite
	KindSpend   = engine.KindSpend
	KindSetting = engine.KindSetting

	SectionTools    = engine.SectionTools
	SectionSystem   = engine.SectionSystem
	SectionMessages = engine.SectionMessages

	PhaseHot     = engine.PhaseHot
	PhaseCold    = engine.PhaseCold
	PhaseUnknown = engine.PhaseUnknown

	LifetimeExact   = engine.LifetimeExact
	LifetimeMinimum = engine.LifetimeMinimum
	LifetimeUnknown = engine.LifetimeUnknown

	BillingAPI          = engine.BillingAPI
	BillingSubscription = engine.BillingSubscription
	BillingUnknown      = engine.BillingUnknown

	EffectBreak      = engine.EffectBreak
	EffectRescue     = engine.EffectRescue
	EffectSplit      = engine.EffectSplit
	EffectTTLPremium = engine.EffectTTLPremium
	EffectTTLRescue  = engine.EffectTTLRescue

	CauseModelChanged = engine.CauseModelChanged
)
View Source
const (
	ReasonEndRequestMissing = engine.ReasonEndRequestMissing
	ReasonPingResultUnknown = engine.ReasonPingResultUnknown
	ReasonUnknownKind       = engine.ReasonUnknownKind
	ReasonNegativeSize      = engine.ReasonNegativeSize
	ReasonPenaltyUnknown    = engine.ReasonPenaltyUnknown
	ReasonNoUsage           = engine.ReasonNoUsage
	ReasonNotSpend          = engine.ReasonNotSpend
)

Machine-stable reasons in Result.Unpriced.

Variables

This section is empty.

Functions

This section is empty.

Types

type Billing

type Billing = engine.Billing

What a host reports.

type BillingMode

type BillingMode = engine.BillingMode

Parts of an operation.

type Body

type Body = engine.Body

What a host reports.

func NewBody

func NewBody(tools, system, messages [][]byte) Body

NewBody hashes the content of one request body, one entry for each position of each section.

type Breakpoint

type Breakpoint = engine.Breakpoint

What a host reports.

type CacheEffect

type CacheEffect = engine.CacheEffect

What the library returns.

type CacheEffectCause

type CacheEffectCause = engine.CacheEffectCause

Parts of an operation.

type CacheEffectKind

type CacheEffectKind = engine.CacheEffectKind

Parts of an operation.

type CachePhase

type CachePhase = engine.CachePhase

Parts of an operation.

type CallUsage

type CallUsage = engine.CallUsage

What a host reports.

type CheckFailure

type CheckFailure = engine.CheckFailure

What the library returns.

type EntryFacts

type EntryFacts = engine.EntryFacts

What a host reports.

type Kind

type Kind = engine.Kind

Parts of an operation.

type LifetimeKind

type LifetimeKind = engine.LifetimeKind

Parts of an operation.

type MessageSplice

type MessageSplice = engine.MessageSplice

Parts of an operation.

type ModelCall

type ModelCall = engine.ModelCall

What a host reports.

type Operation

type Operation = engine.Operation

What a host reports.

type Position

type Position = engine.Position

Parts of an operation.

type PricedOp

type PricedOp = engine.PricedOp

What the library returns.

type Request

type Request = engine.Request

Request is the record of one request, made by [Trackers.BeginRequest].

type RequestMeta

type RequestMeta = engine.RequestMeta

What a host reports.

type RequestOps

type RequestOps = engine.RequestOps

What a host reports.

type Result

type Result = engine.Result

Result is what [Request.Compute] returns.

func ComputeStandalone

func ComputeStandalone(ops RequestOps) Result

ComputeStandalone prices operations that have no request record, such as a keep-alive ping.

type Section

type Section = engine.Section

Parts of an operation.

type SettingChange

type SettingChange = engine.SettingChange

Parts of an operation.

type Size

type Size = engine.Size

Parts of an operation.

type Span

type Span = engine.Span

Parts of an operation.

type Thread

type Thread = engine.Thread

What a host reports.

type TierTokens

type TierTokens = engine.TierTokens

What the library returns.

type Trackers

type Trackers = engine.Trackers

Trackers holds the state of every thread. Make one with NewTrackers, and share it.

func NewTrackers

func NewTrackers() *Trackers

NewTrackers returns an empty set: every thread starts with no history.

type Unpriced

type Unpriced = engine.Unpriced

What the library returns.

type Usage

type Usage = engine.Usage

What a host reports.

Directories

Path Synopsis
events module
host module
internal
engine
Package engine is the implementation of package accountant, which re-exports its public names.
Package engine is the implementation of package accountant, which re-exports its public names.
metrics module
test
cases
Package cases is the exhaustive list of test cases the implementation must meet (testing.md §10).
Package cases is the exhaustive list of test cases the implementation must meet (testing.md §10).

Jump to

Keyboard shortcuts

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