# Python SDK

Wrap AI calls with track() to attribute them to a customer and feature.

AI Spendbook documentation, Your app's data. Web page: https://www.aispendbook.com/docs/python-sdk

The Python SDK records the provider's own token counts for each AI call and sends them to AI Spendbook with the customer, feature and environment you set. The distribution is `aispendbook`, the import name is `spendbook`, and it is MIT licensed. Install it from GitHub (source: [AISpendbook/aispendbook-python](https://github.com/AISpendbook/aispendbook-python)) with `pip install git+https://github.com/AISpendbook/aispendbook-python`, then set `SPENDBOOK_API_KEY` and `SPENDBOOK_ENDPOINT`. Python 3.10 or later; extras `openai`, `anthropic`, `google`, `bedrock` and `litellm` pull in the provider SDKs.

```python
# pip install git+https://github.com/AISpendbook/aispendbook-python
# Configure with environment variables (never hard-code keys):
#   export SPENDBOOK_API_KEY=afk_your_key
#   export SPENDBOOK_ENDPOINT=https://www.aispendbook.com
import anthropic
import spendbook
from spendbook import track

spendbook.init()        # reads SPENDBOOK_API_KEY / SPENDBOOK_ENDPOINT
spendbook.instrument()  # records usage from the anthropic, openai and google-genai clients
client = anthropic.Anthropic()

with track(customer_id="acme", feature="support-bot", user_id="u_123"):
    client.messages.create(
        model="claude-opus-5-5",
        max_tokens=512,
        messages=[{"role": "user", "content": "Hello"}],
    )
# Token counts, model, latency and attribution are sent. Prompt content is not.
```

- `spendbook.instrument()` records calls from the openai, anthropic and google-genai clients and from boto3 `bedrock-runtime`.
- `track()` works as a context manager, an async context manager or a decorator, and nested scopes merge. Calls outside any scope arrive unattributed.
- `spendbook.init(environment="production")` or `SPENDBOOK_ENVIRONMENT` sets a default environment for events that do not set one.
- Events go onto a bounded in-memory queue and a background thread sends them. Telemetry errors are swallowed, so your AI calls are never blocked. `SPENDBOOK_DISABLED=1` turns the SDK off.
- Content capture is **off** by default. [What the SDK sends](https://www.aispendbook.com/docs/security) is listed on the security page.

## Which provider a call is reported under

Calls are reported under the provider whose bill they appear on. The ledger stores `bedrock` as `aws_bedrock` and `vertex` as `google` (Vertex AI and the Gemini API share the Google Cloud bill), keeping the sent name in `metadata.provider_raw`:

| Client | provider |
| --- | --- |
| openai.OpenAI | openai |
| openai.AzureOpenAI (sync and async) | azure_openai |
| anthropic.Anthropic | anthropic |
| anthropic.AnthropicBedrock, AnthropicBedrockMantle, boto3 bedrock-runtime | bedrock |
| anthropic.AnthropicVertex | vertex |
| genai.Client() | google |
| genai.Client(vertexai=True) | vertex |

## Call types

- Chat and messages, streamed or not, on every client above.
- boto3 `bedrock-runtime`: `converse` (usage block, including cache reads and writes) and `invoke_model` (token-count response headers; the response body is never read).
- Embeddings: OpenAI `embeddings.create` and Gemini `models.embed_content`. The Gemini Developer API returns no token counts, so those events are marked `usage_missing`.
- Batch: downloading an OpenAI Batch output file with `files.content`, or iterating Anthropic `messages.batches.results`, records each successful request with the batch service tier. Reading the results twice does not count them twice.
- Realtime: each `response.done` event on an OpenAI Realtime connection, with text, audio and cached token counts.
- Images: OpenAI `images.generate`, with image count, size and quality, plus tokens for gpt-image models.
- Anything else: `spendbook.record()`.

## LiteLLM

`from spendbook.integrations.litellm import SpendbookCallback`, then `litellm.callbacks = [SpendbookCallback()]`. It works for the LiteLLM SDK and proxy, maps the provider and tokens, and reads `customer_id`, `feature`, `environment` and `run_id` from request metadata or tags such as `customer:acme`. LiteLLM's `response_cost` is stored for comparison only. See the [LiteLLM quickstart](https://www.aispendbook.com/docs/quickstart-litellm).

## Limits

- Streaming Bedrock calls through boto3 (`converse_stream`, `invoke_model_with_response_stream`) are not recorded. `AnthropicBedrock` streams are.
- Batch results are recorded only when downloaded through the instrumented SDK.
- A Realtime session opened through `AzureOpenAI` is reported as `openai`, and `AnthropicFoundry` as `anthropic`.
- DALL-E image calls carry no token counts; pass `model=` so the event has a model name.
- LiteLLM cache hits are not recorded, and on LiteLLM versions that do not count cache writes inside prompt tokens, uncached input is under-counted by the cache writes.
- Token counts are priced by AI Spendbook as estimates. Billed cost comes from the billing connectors. Tested with fakes, not against live provider accounts.

Node.js has its own SDK: [Node.js SDK](https://www.aispendbook.com/docs/node-sdk).
