aispendbook: AI Spendbook Python tracking SDK
Attributes every OpenAI, Anthropic and Google Gemini call to the customer, user and feature that caused it, then sends the provider's own token usage to AI Spendbook for cost reporting.
Supported provider SDKs: openai (including AzureOpenAI), anthropic (including
AnthropicBedrock and AnthropicVertex), google-genai (Gemini API and Vertex AI) and boto3
bedrock-runtime. A LiteLLM callback covers traffic that goes through LiteLLM. Any other provider
can be recorded with the manual spendbook.record() API.
The distribution is aispendbook; the import name is spendbook. MIT licensed.
- No extra dependencies. HTTP goes through the standard library (
urllib).openai,anthropic,google-genai,boto3andlitellmare optional extras. - Never blocks or breaks your app. Events go onto a bounded queue and a background thread sends
them. Any telemetry error is swallowed and logged at DEBUG on the
spendbooklogger. - Exact tokens. Counts come from the provider SDK's
usageobjects. They are never estimated. - Private by default. Prompts and responses are not captured unless you turn it on, and when you do, built-in redaction runs first.
Requires Python 3.10 or later. The current openai, anthropic and google-genai SDKs need Python
3.10 or later.
Install
pip install git+https://github.com/AISpendbook/aispendbook-python # core SDK, no dependencies
pip install "aispendbook[openai,anthropic,google] @ git+https://github.com/AISpendbook/aispendbook-python"
pip install "aispendbook[bedrock] @ git+https://github.com/AISpendbook/aispendbook-python" # boto3
pip install "aispendbook[litellm] @ git+https://github.com/AISpendbook/aispendbook-python" # LiteLLM callback
The SDK installs from GitHub (AISpendbook/aispendbook-python). It is not published to PyPI yet.
Quick start
Set two environment variables (or pass them to init()):
export SPENDBOOK_API_KEY=afk_... # ingestion key from Settings > Ingestion keys
export SPENDBOOK_ENDPOINT=https://www.aispendbook.com # AI Spendbook API base URL (your own URL if self-hosted)
import spendbook
spendbook.init() # reads SPENDBOOK_API_KEY / SPENDBOOK_ENDPOINT
spendbook.instrument() # records usage from the anthropic, openai and google-genai clients
from spendbook import track
with track(user_id="user_123", customer_id="company_456", feature="diet_generation", category="health"):
response = existing_ai_function() # every OpenAI / Anthropic / Gemini call inside is attributed
Gemini example (full version in examples/python/basic_gemini.py):
from google import genai
client = genai.Client() # GOOGLE_API_KEY
with track(customer_id="company_456", feature="summarize"):
client.models.generate_content(model="gemini-3.8-flash", contents="Summarize this ticket: ...")
track comes in several forms:
@track(feature="summarize") # decorator: sync or async functions
async def summarize(text): ...
async with track(customer_id=tenant.id): # async context manager
...
with track(customer_id="acme", feature="chat", metadata={"plan": "pro"}):
with track(feature="chat.rewrite"): # nested: inner non-None values override, metadata merges
... # -> customer_id="acme", feature="chat.rewrite", plan="pro"
Fields: user_id (sent as end_user_id), customer_id, feature, category, workload_type,
project_id, organization_ref, trace_id, session_id, run_id, environment, metadata.
Lifecycle: spendbook.flush(timeout=5.0) -> bool, spendbook.shutdown(timeout=5.0) -> bool,
spendbook.uninstrument(). An atexit hook flushes with a short timeout (shutdown_timeout, 2s).
For a FastAPI app, see examples/python/fastapi_app.py. It
adds per-request attribution through middleware.
Configuration
init() argument |
Env var | Default | Description |
|---|---|---|---|
api_key |
SPENDBOOK_API_KEY |
– | Ingestion key (afk_...). If missing, tracking is disabled and a warning is logged. |
endpoint |
SPENDBOOK_ENDPOINT |
– | API base URL. Events go to {endpoint}/api/v1/ingest/batch. |
environment |
SPENDBOOK_ENVIRONMENT |
– | Deployment environment (production, staging) sent on every event that does not set environment in track(). Use this, not project_id, for environments: project_id is a project or team and scopes team budgets. |
enabled |
SPENDBOOK_DISABLED=1 turns it off |
True |
When disabled, instrument() patches nothing and record() returns None. |
capture_content |
– | False |
Send prompt and response text (redacted). Opt-in. |
redact |
– | None |
Callable[[str], str] that runs after the built-in redaction. If it raises, the content is dropped. |
metadata_allowlist |
– | None |
When set, only these metadata keys are sent. |
max_queue_size |
– | 10000 |
Size of the bounded in-memory queue. |
overflow_policy |
– | "drop_newest" |
What to drop when the queue is full: drop_newest (the incoming event) or drop_oldest. Dropped events are counted in stats["dropped"]. |
max_batch_size |
– | 100 |
Events per request (capped at 500). |
flush_interval |
– | 2.0 |
Seconds after the first event in a batch before the batch is sent. |
request_timeout |
– | 10.0 |
HTTP timeout per attempt, in seconds. |
max_retry_duration |
– | 60.0 |
Total retry budget per batch, in seconds. |
gzip |
– | False |
Gzip request bodies (Content-Encoding: gzip). Turn it on only if your endpoint accepts gzip. |
shutdown_timeout |
– | 2.0 |
Flush timeout used by the atexit hook and by init() when it replaces a client. |
instrument(openai=True, anthropic=True, google=True, bedrock=True, openai_include_usage=False)
returns {"openai": bool, "anthropic": bool, "google": bool, "bedrock": bool}. Calling it again is safe, and it skips SDKs
that are not installed. Pass google=False (or another provider flag) to leave that SDK untouched.
Delivery counters are available from spendbook.get_client().stats: enqueued, dropped, sent,
accepted, duplicates, rejected, failed, requests and retries.
What gets captured
Instrumented methods (sync and async):
- Anthropic:
messages.create(includingstream=True),messages.stream,messages.parse,messages.batches.results - OpenAI:
chat.completions.create(includingstream=True),chat.completions.parse,responses.create(includingstream=True),responses.parse,embeddings.create,images.generate(includingstream=True),files.contentfor Batch output files, and the Realtime connection'srecv()(which also backs iteration) - Google Gemini (
google-genai):client.models.generate_content,generate_content_stream,embed_content, the asyncclient.aio.modelstwins, andclient.chats(which calls the same methods) - boto3
bedrock-runtime:converseandinvoke_model
Provider ids
| Client | provider |
|---|---|
openai.OpenAI / AsyncOpenAI |
openai |
openai.AzureOpenAI / AsyncAzureOpenAI |
azure_openai |
anthropic.Anthropic / AsyncAnthropic |
anthropic |
anthropic.AnthropicBedrock (and AnthropicBedrockMantle), boto3 bedrock-runtime |
bedrock |
anthropic.AnthropicVertex |
vertex |
genai.Client() (Gemini Developer API) |
google |
genai.Client(vertexai=True) |
vertex |
Each provider is reported separately, so usage is matched against the bill that actually charges it.
Embeddings, batches, Realtime and images
- Embeddings: OpenAI
usage.prompt_tokensis recorded as input tokens. Vertex AIembed_contentsums each embedding'sstatistics.token_countand addsmetadata.billable_character_count. The Gemini Developer API returns no usage for embeddings, so those events have 0 tokens andmetadata.usage_missing = true. Events carrymetadata.operation = "embeddings". - OpenAI Batch API: when you download a batch output file with
client.files.content(file_id), each successful request line is recorded withservice_tier = "batch"andmetadata.batch = true, so the batch discount applies.metadata.batch_custom_idholds yourcustom_id. The event id is derived from the batch request id, so downloading the same file twice does not double count. Other files are ignored. - Anthropic Message Batches: iterating
client.messages.batches.results(batch_id)records everysucceededresult withservice_tier = "batch". Errored, canceled and expired results are not recorded (they are not billed). Event ids areanthropic-batch-<batch_id>-<custom_id>. - OpenAI Realtime: every
response.doneevent received throughconnection.recv()(or by iterating the connection) is recorded with its usage. Input text, audio and image tokens and output text and audio tokens go toother_tokens. The model comes from thesession.created/session.updatedevent. - OpenAI images:
images.generaterecordsimage_count,image_sizeandimage_qualityin metadata. gpt-image models also report input and output tokens. DALL-E models return no tokens, so those events carryusage_missing = true; passmodel=explicitly so the event has a model.
LiteLLM
import litellm
import spendbook
from spendbook.integrations.litellm import SpendbookCallback
spendbook.init()
litellm.callbacks = [SpendbookCallback()]
await litellm.acompletion(
model="anthropic/claude-sonnet-4-5",
messages=[...],
user="user_123", # -> end_user_id
metadata={"customer_id": "company_456", "feature": "chat"}, # -> attribution
)
For the LiteLLM proxy, register a module that calls spendbook.init() and exposes a
SpendbookCallback() instance under litellm_settings.callbacks in the proxy config.
- Attribution comes from request metadata keys (
customer_id,feature,environment,run_id,category,workload_type,project_id,organization_ref,trace_id,session_id) or from tags such ascustomer:company_456/feature:chat. Request metadata wins over tags, and both win over the activetrackcontext. The OpenAIuserfield (or the proxy's end user) isend_user_id. custom_llm_providermaps to AI Spendbook provider ids:azuretoazure_openai,bedrockandbedrock_conversetobedrock,vertex_aitovertex,geminitogoogle. Other ids pass through unchanged.- LiteLLM's
response_costis sent assource_reported_cost_micros. It is kept for comparison and never used as spend. - The LiteLLM call id is the event id, so a repeated callback is deduplicated.
- LiteLLM cache hits are not recorded, because no provider request was made. Failed calls are
recorded as
errorwith 0 tokens.
Each provider request produces exactly one IngestEvent. For Gemini this is per HTTP request: when
generate_content sends several requests for one call (automatic function calling with Python
functions as tools, or automatic continuation), each request is recorded with its own usage.
| Field | Source |
|---|---|
event_id |
uuid4 generated by the client. It stays the same across transport retries, so the server can deduplicate. |
occurred_at / completed_at |
UTC (...Z). Request start / response end. For streams, the time the stream finished. |
latency_ms |
Monotonic clock, from request start to completion (or to stream end). |
provider |
See Provider ids |
model |
The model the API actually used: response.model (Gemini: response.model_version). Falls back to the requested model on errors. |
request_id |
response._request_id, or the request-id / x-request-id header for streams and the request id on API errors. Gemini: response.response_id. |
input_tokens |
Uncached input. Anthropic: usage.input_tokens. OpenAI: prompt_tokens − cached_tokens (Responses API: input_tokens − cached_tokens). Gemini: prompt_token_count − cached_content_token_count + tool_use_prompt_token_count. |
cache_read_tokens |
Anthropic: cache_read_input_tokens. OpenAI: *_tokens_details.cached_tokens. Gemini: cached_content_token_count (implicit and explicit caching). |
cache_write_tokens |
Anthropic: cache_creation_input_tokens (5m + 1h). Gemini: 0 (explicit caches are created through a separate API). |
cache_write_1h_tokens |
Anthropic: cache_creation.ephemeral_1h_input_tokens, a subset of cache_write_tokens |
output_tokens |
Anthropic: output_tokens. OpenAI: completion_tokens / output_tokens. Gemini: candidates_token_count + thoughts_token_count. Reasoning and thinking tokens are included because they are billed as output. |
other_tokens |
Informational breakdowns: reasoning_tokens, thinking_tokens, input_audio_tokens, output_audio_tokens, input_image_tokens, input_video_tokens, tool_use_prompt_tokens, accepted_prediction_tokens, rejected_prediction_tokens, and OpenAI cache_write_tokens |
service_tier |
Anthropic: usage.service_tier. OpenAI: response.service_tier. Gemini: not sent. |
status / error_type |
success, error (with the exception class name, e.g. RateLimitError), or cancelled |
streamed |
True for streaming calls |
| attribution | customer_id, end_user_id, feature, category, workload_type, project_id, organization_ref, taken from the active track context when the call is made |
metadata |
Merged track metadata after sanitizing, plus SDK flags such as usage_missing: true |
content |
{prompt, response}. Sent only when capture_content=True. |
sdk |
{"name": "spendbook-python", "version": ...} |
Provider exceptions are re-raised unchanged after an error event is recorded (Gemini: ClientError
/ ServerError from google.genai.errors). Return values are the SDK's own objects (Message,
ChatCompletion, Stream, MessageStreamManager, GenerateContentResponse, ...), and method
signatures are preserved.
Streaming
Streams are observed in place, so you get back the SDK's own stream object.
- Anthropic
messages.stream(...): input and cache tokens come frommessage_start. Output tokens come from the final cumulativemessage_delta.usage. The event is recorded when the stream is fully consumed, whether through iteration,text_stream,get_final_message()oruntil_done(). - Anthropic
messages.create(stream=True): the same raw events are read, and the event is recorded when iteration finishes. - OpenAI Chat Completions
stream=True: OpenAI sends usage only when you request it withstream_options={"include_usage": True}. It arrives in a final chunk whosechoiceslist is empty.- The SDK does not change your request by default. If usage is not sent, the event is recorded
with 0 tokens and
metadata.usage_missing = true. Tokens are never guessed. - With
spendbook.instrument(openai_include_usage=True), the SDK addsinclude_usage: Trueto streamed chat requests that do not set it. An explicitinclude_usage: Falseis respected. Make sure your loop tolerates the extra chunk with emptychoices(if chunk.choices: ...).
- The SDK does not change your request by default. If usage is not sent, the event is recorded
with 0 tokens and
- OpenAI Responses
stream=True: usage comes from the terminalresponse.completedevent, or fromresponse.incomplete/response.failed. Aresponse.failedevent is recorded aserror. - Gemini
generate_content_stream(sync andclient.aio): chunks carry cumulativeusage_metadata. The SDK records the last one it saw, which is normally on the final chunk, when the stream ends. If a stream ends without anyusage_metadata, the event has 0 tokens andmetadata.usage_missing = true. Gemini streams are lazy: the request is sent on the first iteration, so a stream that is never iterated sends nothing and records nothing. Attribution is taken from thetrackcontext active whengenerate_content_streamwas called, even if you iterate the stream after leaving thewith track(...)block. - Early exit: if you stop reading a stream early, an event is still recorded with status
cancelledand whatever usage was observed up to that point. That coversbreakplusclose()/ exiting thewithblock, and also dropping the stream object so it is garbage collected. For an Anthropic stream this includes input tokens and the output tokens seen so far. An OpenAI chat stream usually has no usage at that point, so it is recorded asusage_missing. - Errors mid-stream: the event is recorded as
errorwith the usage observed so far, and the exception is re-raised.
Concurrency and context propagation
Attribution is stored in a contextvars.ContextVar.
- asyncio: each task copies the context when it is created, so concurrent requests
(
asyncio.gather, web frameworks) never share attribution. - Threads: a new thread starts with an empty context, so attribution does not leak between
requests. To carry the caller's attribution into a worker thread, use
contextvars.copy_context().run(fn)orasyncio.to_thread(which copies the context for you). - A
trackinstance used as a context manager should not be entered concurrently from several tasks. The decorator form is safe because it creates fresh state on every call.
Manual API (providers that are not instrumented)
event_id = spendbook.record(
provider="mistral", model="mistral-large-2411",
input_tokens=412, output_tokens=128, cache_read_tokens=0, # from the provider's usage object
occurred_at=started_at, latency_ms=840, status="success", request_id="req_123",
customer_id="company_456", feature="contract_review", metadata={"region": "eu"},
)
Explicit arguments override the active track context. record() never raises: invalid token values
are logged and sent as 0. It returns None when the SDK is not initialized or is disabled.
Delivery and reliability
enqueuetakes O(1) time and never blocks. One daemon thread sends batches of up tomax_batch_sizeevents, or whatever has accumulatedflush_intervalseconds after a batch started.- 5xx responses, 429 responses and network errors are retried with exponential backoff and jitter
(0.5s base, 30s cap). A
Retry-Afterheader is honored. Retries stop aftermax_retry_duration. Other 4xx responses are not retried. A 401 or 403 logs a single warning. - A retry resends the identical body, so every event keeps its
event_idand the server deduplicates. Per-event rejections in the response are logged at DEBUG and counted. - Fork-safe: after
os.fork(), the child process gets a fresh queue, lock and worker thread, registered throughos.register_at_fork. Events the child inherited from the parent are discarded, because the parent still sends them. - Events still queued when the process is killed hard are lost. Call
spendbook.flush()at the end of short scripts and serverless handlers.
Privacy and security
- The API key is never logged, and
repr()of the config, client and transport shows onlyafk_****. - Content capture is off. With
capture_content=True, the prompt (messages / system / input / instructions) and the response text are truncated tomax_content_chars(16,000). Built-in redaction then replaces emails, phone numbers, Luhn-valid card numbers, and API keys and tokens (sk-…,sk-ant-…,afk_…,Bearer …, AWS, GitHub, Slack and Google keys). Yourredacthook runs last. - Metadata values must be
str,int,floatorbool. The SDK keeps at most 20 keys, cuts keys to 64 characters and string values to 256 characters, and appliesmetadata_allowlistwhen it is set. It drops keys that look like secrets (password,token,secret,api_key,authorization,cookie,session_id, …) and values that look like credentials. - Gemini content: with
capture_content=True, only text parts are captured (contents andsystem_instruction; thought parts are skipped). Images, audio, video and file parts are never captured. - Disabling: set
SPENDBOOK_DISABLED=1or callinit(enabled=False). To remove the patches, callspendbook.uninstrument(). To skip one provider, useinstrument(google=False)(oropenai=False/anthropic=False).
Sending events from TypeScript / any language
For Node.js and TypeScript apps, the aispendbook npm package (AISpendbook/aispendbook-node) wraps the
OpenAI, Anthropic and Google Gen AI clients and the Vercel AI SDK. The ingestion API is plain HTTPS
and JSON. A runnable, dependency-free Node 18+ version with retries
is in examples/typescript/ingest.ts.
import { randomUUID } from "node:crypto";
const res = await fetch(`${process.env.SPENDBOOK_ENDPOINT}/api/v1/ingest/batch`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SPENDBOOK_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
events: [{
event_id: randomUUID(), // reuse the same id if you retry
occurred_at: new Date().toISOString(),
provider: "anthropic",
model: msg.model,
request_id: msg._request_id,
input_tokens: msg.usage.input_tokens, // Anthropic input is already uncached
output_tokens: msg.usage.output_tokens,
cache_read_tokens: msg.usage.cache_read_input_tokens ?? 0,
cache_write_tokens: msg.usage.cache_creation_input_tokens ?? 0,
status: "success",
customer_id: "company_456",
feature: "diet_generation",
}],
}),
});
// -> { accepted, duplicates, cross_source_duplicates, rejected: [{ index, event_id, reason }] }
Limitations
- Not instrumented:
with_raw_response/with_streaming_responsecalls,client.beta.*(Anthropic beta messages and beta batches), the OpenAIchat.completions.stream()/responses.stream()helpers,images.edit/create_variation, audio, and the OpenAI Assistants API. Usespendbook.record()for these. - Batch output is recorded only when it is downloaded through the instrumented SDK
(
files.content/messages.batches.results). Output fetched another way is not seen. - Realtime: only
response.doneusage is recorded. A Realtime session opened throughAzureOpenAIis reported asopenai. - boto3
bedrock-runtime:converse_streamandinvoke_model_with_response_streamare not observed.invoke_modelusage comes from thex-amzn-bedrock-*-token-countresponse headers; models that do not send them are recorded withusage_missing = true. anthropic.AnthropicFoundry(Claude on Microsoft Foundry) is reported asanthropic.- Gemini: only
generate_content/generate_content_stream(and chats built on them) andembed_contentare instrumented. The Interactions API, Live API,count_tokens, image and video generation and batch jobs are not; usespendbook.record()for these. - LiteLLM: input tokens are
prompt_tokensminus cache reads and cache writes. This matches LiteLLM versions that count cache writes insideprompt_tokens; on versions that do not, uncached input is under-counted by the cache-write count. To record each HTTP request, the SDK wraps google-genai's per-request methods (Models._generate_contentand_generate_content_stream). If a future google-genai release renames them, the SDK falls back to the public methods and records one event per call with the final response's usage. - OpenAI
cache_write_tokensis reported only inother_tokens, because it is unclear whetherprompt_tokensalready includes those tokens. - Anthropic server-tool request counts (
web_search_requests) are not sent. - Decorating generator functions with
@tracksets the context only while the generator is created, not while it is iterated. Usewith track(...)inside the generator instead.
Development
uv sync --all-extras
uv run pytest -q
uv build # sdist + wheel in dist/ (publishing to PyPI is done by the owner)
The tests use the real openai, anthropic and google-genai client classes over an httpx
MockTransport, botocore's Stubber for bedrock-runtime, a fake LiteLLM payload, and an
in-process http.server on 127.0.0.1 as the ingestion endpoint.
Metadata
Release files for aispendbook 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| aispendbook-0.1.0.tar.gz | 41.0 kB | With provenance | Details for aispendbook-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| aispendbook-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for aispendbook-0.1.0-py3-none-any.whl |
Total release size: 91.9 kB
Release files / aispendbook-0.1.0.tar.gz
| Download URL | aispendbook-0.1.0.tar.gz |
|---|---|
| Size | 41.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3173f4abb5b98a3e851b9d68f2210ab6e5a6644a719c60885b7cf22552fbaab3
|
|
BLAKE2b-256 checksum How to use checksums |
0c47c72112f46106d493b86f4624f6c50fc92e500eb7420e9bc66b5cb6cd6324
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / aispendbook-0.1.0-py3-none-any.whl
| Download URL | aispendbook-0.1.0-py3-none-any.whl |
|---|---|
| Size | 50.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1dab7a8181fc8e4d89ed75ac0204df4193e35c7bef75a138aadb36e1b8f6ac8b
|
|
BLAKE2b-256 checksum How to use checksums |
4a34e6f9045bd2404c061d32ef429d52d52d49155f1dbfdcdba4bdb142ba169d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logSecurity for aispendbook 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for aispendbook-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.