AgentBill Python SDK
OpenTelemetry-based SDK for automatically tracking and billing AI agent usage.
Installation
From PyPI (Recommended)
pip install agentbill-io
From PyPI (Coming Soon)
pip install agentbill
From Source
# Clone your repository and install
git clone https://github.com/yourusername/agentbill-python-sdk.git
cd agentbill-python-sdk
pip install -e .
OpenTelemetry requirements (v12.2.0+)
The SDK is built only from official OpenTelemetry packages, installed with it:
opentelemetry-api, opentelemetry-sdk and opentelemetry-exporter-otlp-proto-http
(all >=1.27,<2). Spans go to /otel-collector through the official
OTLPSpanExporter (OTLP/HTTP protobuf) with static headers. No custom exporter,
no fallback mode. Python 3.10+.
Already using OpenTelemetry? If your app already set an OpenTelemetry SDK
TracerProvider, AgentBill adds its exporter to it instead of creating a second
one, so its spans join your traces. To send your own spans with nothing but the
standard library and environment variables:
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.agentbill.io/functions/v1/otel-collector
export OTEL_EXPORTER_OTLP_HEADERS="X-API-Key=agb_..."
Version conflicts: pip install -U opentelemetry-api opentelemetry-sdk to align them.
File Structure
agentbill-python/
├── agentbill/
│ ├── __init__.py
│ ├── client.py
│ ├── tracer.py
│ └── types.py
├── examples/
│ ├── openai_basic.py
│ ├── anthropic_basic.py
│ ├── bedrock_basic.py
│ ├── azure_openai_basic.py
│ ├── mistral_basic.py
│ └── google_ai_basic.py
├── tests/
│ ├── test_agentbill.py
│ └── test_tracer.py
├── README.md
├── setup.py
├── pyproject.toml
├── pytest.ini
├── Makefile
├── CHANGELOG.md
├── CONTRIBUTING.md
├── SECURITY.md
└── LICENSE
Quick Start
from agentbill import AgentBill
import openai
# Initialize AgentBill
agentbill = AgentBill.init({
"api_key": "your-api-key",
"customer_id": "customer-123",
"debug": True
})
# Wrap your OpenAI client
client = agentbill.wrap_openai(openai.OpenAI(
api_key="sk-..."
))
# Use normally - all calls are automatically tracked!
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Hello!"}]
)
⚠️ Critical: Cost Guard Error Handling
Cost Guard runs on every wrapped call; decisions come only from the company’s Cost Guard policies (company, customer, and agent daily/monthly budgets in cost_guard_policies), configured in the AgentBill app at /admin/system-configuration. The SDK raises exceptions when policy limits are exceeded. Do NOT catch and continue with direct AI calls - the blocking is intentional to prevent overspending!
# ❌ WRONG - This bypasses budget protection!
try:
response = wrapped_client.chat.completions.create(...)
except Exception as e:
print("AgentBill failed, continuing anyway...")
response = unwrapped_client.chat.completions.create(...) # BUDGET BYPASSED!
# ✅ CORRECT - Respect the block, handle gracefully
try:
response = wrapped_client.chat.completions.create(...)
except Exception as e:
if hasattr(e, 'code') and e.code == 'BUDGET_EXCEEDED':
print("Budget limit reached - please upgrade or wait")
return None # Return early, don't bypass!
raise # Re-raise other errors
Linking signals to an AI call
signal() chooses its trace in this order: explicit trace_id (traceId in
TypeScript) → active OpenTelemetry span → AgentBill’s stored context (set after
a wrapped client call) → a new trace. The active-span path covers instrument(),
agentbill_tracing() / agentbillTracing(), and your app’s own OpenTelemetry
spans. A signal linked to an AI call is a child span of that AI span.
With AGENTBILL_API_KEY and OPENAI_API_KEY set:
from agentbill import agentbill_tracing, signal
from openai import OpenAI
client = OpenAI()
with agentbill_tracing(customer_id="customer-123"):
response = client.chat.completions.create(
model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}]
)
signal("answer_delivered")
With instrument() (install openinference-instrumentation-openai first;
instrument() installs instrumentation, it is not a context manager):
from agentbill import instrument, signal
from openai import OpenAI
from opentelemetry import trace
instrument(providers=["openai"], customer_id="customer-123")
client = OpenAI()
with trace.get_tracer(__name__).start_as_current_span("answer"):
response = client.chat.completions.create(
model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}]
)
signal("answer_delivered") # Joins the active application trace.
TypeScript registers the official AsyncLocalStorage context manager when the app has none, keeping concurrent requests in separate traces.
Features
- ✅ Zero-config instrumentation
- ✅ Accurate token & cost tracking
- ✅ Multi-provider support (OpenAI, Anthropic, Bedrock, Azure OpenAI, Mistral, Google AI)
- ✅ Rich metadata capture
- ✅ OpenTelemetry-based
- ✅ Cost Guard budget enforcement (blocks requests BEFORE spending)
Supported Providers
- OpenAI - GPT-4, GPT-5, Embeddings, DALL-E, Whisper, TTS
- Anthropic - Claude Sonnet, Claude Opus
- AWS Bedrock - Claude, Titan, and other Bedrock models
- Azure OpenAI - GPT models via Azure
- Mistral AI - Mistral models
- Google AI - Gemini Pro, Gemini Flash
Provider Examples
OpenAI
from agentbill import AgentBill
import openai
agentbill = AgentBill.init({"api_key": "your-api-key"})
client = agentbill.wrap_openai(openai.OpenAI(api_key="sk-..."))
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Hello!"}]
)
Anthropic
from agentbill import AgentBill
import anthropic
agentbill = AgentBill.init({"api_key": "your-api-key"})
client = agentbill.wrap_anthropic(anthropic.Anthropic(api_key="sk-ant-..."))
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}]
)
AWS Bedrock
from agentbill import AgentBill
import boto3
agentbill = AgentBill.init({"api_key": "your-api-key"})
bedrock = agentbill.wrap_bedrock(boto3.client('bedrock-runtime'))
response = bedrock.invoke_model(
modelId='anthropic.claude-v2',
body=json.dumps({
"prompt": "Hello!",
"max_tokens_to_sample": 300
})
)
Azure OpenAI
from agentbill import AgentBill
from openai import AzureOpenAI
agentbill = AgentBill.init({"api_key": "your-api-key"})
client = agentbill.wrap_azure_openai(AzureOpenAI(
api_key="your-azure-key",
api_version="2024-02-01",
azure_endpoint="https://your-resource.openai.azure.com"
))
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Hello!"}]
)
Mistral AI
from agentbill import AgentBill
from mistralai import Mistral
agentbill = AgentBill.init({"api_key": "your-api-key"})
client = agentbill.wrap_mistral(Mistral(api_key="your-mistral-key"))
response = client.chat.complete(
model="mistral-large-latest",
messages=[{"role": "user", "content": "Hello!"}]
)
Google AI (Gemini)
from agentbill import AgentBill
import google.generativeai as genai
agentbill = AgentBill.init({"api_key": "your-api-key"})
genai.configure(api_key="your-google-key")
model = genai.GenerativeModel('gemini-pro')
wrapped_model = agentbill.wrap_google_ai(model)
response = wrapped_model.generate_content("Hello!")
Configuration
config = {
"api_key": "your-api-key", # Required
"base_url": "https://...", # Optional
"customer_id": "customer-123", # Optional
"debug": True # Optional
}
agentbill = AgentBill.init(config)
Publishing to PyPI
Prerequisites
- Create a PyPI account at https://pypi.org/account/register/
- Generate an API token at https://pypi.org/manage/account/token/
- Create
~/.pypircfile with your token:
[pypi]
username = __token__
password = pypi-YOUR_API_TOKEN_HERE
Publishing Steps
# Build the package
python setup.py sdist bdist_wheel
# Upload to PyPI
pip install twine
twine upload dist/*
GitHub Repository Setup
- Create your GitHub repository (e.g.,
agentbill-python-sdk) - Push all files (agentbill/, examples/, LICENSE, setup.py, README.md)
- Tag releases:
git tag v1.0.0 && git push origin v1.0.0 - Users can install with:
pip install agentbill-io
Idempotent Ingestion (X-Request-Id)
Every OTLP batch this SDK exports to /functions/v1/otel-collector carries an
X-Request-Id: <uuid4> header (auto-generated per export, reused across
transport-level retries within that export). The collector deduplicates on
(company_id, request_id), so a transient 5xx / network retry will not
double-write WAL rows, spans, or billing events.
- No configuration required — the header is emitted automatically by the v7.x line of this SDK.
- Server fallback: clients that cannot set custom headers may send
{"requestId": "..."}at the JSON envelope root. - Native OTLP exporters: the standard OTLP-HTTP exporter keeps headers
static across batches, so per-batch rotation is not yet wired on that path
(
PHASE3-R3-SDK-REQUESTID-NATIVE— tracked); the collector still dedupes those payloads on the natural key(company_id, trace_id, span_id).
See the OpenTelemetry Integration docs for the full request-id contract.
License
MIT
Metadata
Release files for agentbill-io 12.4.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 |
|---|---|---|---|---|
| agentbill_io-12.4.0.tar.gz | 84.6 kB | Without provenance | Details for agentbill_io-12.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| agentbill_io-12.4.0-py3-none-any.whl | Python 3 | none | any | Details for agentbill_io-12.4.0-py3-none-any.whl |
Total release size: 174.3 kB
Release files / agentbill_io-12.4.0.tar.gz
| Download URL | agentbill_io-12.4.0.tar.gz |
|---|---|
| Size | 84.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b5e4cbcebaa2d07f0f405b852dd3c0edb7ba9de1f2dc4b9883773773a0ff8b88
|
|
BLAKE2b-256 checksum How to use checksums |
db2ceb7a8f8a497ca80c4eb6139ee70239fa3e53ff65b087176d4485d1562b74
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.15
|
Release files / agentbill_io-12.4.0-py3-none-any.whl
| Download URL | agentbill_io-12.4.0-py3-none-any.whl |
|---|---|
| Size | 89.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b571d73fa288ae97cd5f5ec49484aea277b9f887487f0acf67e25cf15b786494
|
|
BLAKE2b-256 checksum How to use checksums |
cdaeb80b788a4042ddf3296c21bcfdcca258730f29f2bbedfca8810c9d598e84
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.15
|
Security for agentbill-io 12.4.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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A 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.