Tally SDK: cost per AI agent and step, budgets, model policies, and tests of cheaper models on your own traffic
pip install tallyai==0.1.0 Copy PIP instructions
See what each AI agent costs, set budgets, let Tally choose the model per step, and test cheaper models on your own traffic.
Track usage, manage costs, and automate billing for your AI applications.
pip install tallyai Until the first release is on PyPI, install from a checkout: pip install ./sdks/python. (Not tally-sdk or tally: those names belong to unrelated projects.)
Tag each model call with the agent and step that made it. Tally then shows what every agent costs, which steps drive the bill, and runs that loop out of control.
from tallyai import TallyClient import anthropic tally = TallyClient(api_key="tally_live_...", base_url="https:// /api/v1") claude = anthropic.Anthropic() with tally.agents.run("monitor-agent") as run: # one run_id for every call inside msg = claude.messages.create(model="claude-haiku-4-5", max_tokens=200, messages=[...]) run.record(msg, step="check-prices") # model + tokens read from the response with run.step("write-alert") as s: # also records latency, and errors if it raises s.response = claude.messages.create(model="claude-haiku-4-5", max_tokens=400, messages=[...]) Works with Anthropic Messages and OpenAI Chat Completions / Responses objects (or the same shapes as dicts). For anything else: tally.agents.record_usage(model=..., agent=..., step=..., input_tokens=..., output_tokens=...).
Calls are buffered and sent in batches: every 50 calls, when a run ends if 10s have passed since the last send, on tally.agents.flush(), and at exit. In serverless functions call tally.agents.flush() before returning.
Reporting never raises into your code. Outages are retried on the next flush; calls rejected for a bad API key or invalid data are logged and dropped.
Only token counts, model names and your agent/step names are sent, never prompts or responses.
Model policies: let the dashboard choose the model per step. Pass your current model as the default and the provider your code calls; you get the policy's model if one is set, otherwise your default:
model = run.model("check-prices", default="claude-opus-5", provider="anthropic") msg = claude.messages.create(model=model, ...) Policies are cached and refreshed at most once a minute (2s timeout). If Tally is unreachable the last known policy or your default is used, and a policy for a different provider is ignored.
Test a cheaper model on your own traffic before switching. Start a test from a suggestion on the Savings page, give the SDK your provider clients once, and pass the request with each call:
tally.agents.enable_testing(anthropic=claude) # and/or openai=openai_client params = dict(model=model, max_tokens=300, messages=[...]) msg = claude.messages.create(**params) run.record(msg, step="check-prices", request=params) For a sample of calls (20% by default, until the test has 30 results), the SDK re-sends the same request to the cheaper model and asks your current model to judge the two answers blind. Only the verdict (better / same / worse) and token counts are sent to Tally; prompts, answers and the judge's reasoning stay in your process (the reasoning is logged at DEBUG). Tests run on one background thread and never block your agent. Each sample costs one call to the cheaper model plus one judging call on your current model, billed to your provider account. Plain-text requests can be tested across providers (Anthropic OpenAI); requests with tools or images are tested only on the same provider.
Budgets (set per agent in the dashboard, e.g. $3/day) alert you on Slack/email; they never block calls themselves. To have an agent stop itself: if tally.agents.over_budget("monitor-agent"): return (reflects the last send, so it can lag by one batch).
from tallyai import TallyClient # Initialize the client tally = TallyClient(api_key="your-api-key") # Log usage event = tally.log_usage( customer_id="cust_123", metric_type="tokens", quantity=2500, model="gpt-4" ) print(f"Usage logged: {event.id}") Features Usage Tracking: Log AI model usage (tokens, requests, compute time) Cost Tracking: Track provider costs for margin analysis Customer Management: Create and manage customers Invoice Generation: Create and manage invoices Pricing Configuration: Set up flexible pricing models Anomaly Detection: Create rules to detect unusual usage patterns Automatic Retries: Built-in retry logic for failed requests Type Safety: Full type hints with Pydantic models Authentication Get your API key from the Tally Dashboard.
from tallyai import TallyClient tally = TallyClient( api_key="your-api-key", base_url="https://api.tally.dev", # Optional: defaults to production timeout=30, # Optional: request timeout in seconds max_retries=3, # Optional: max retries for failed requests ) Usage Examples Tracking Usage Single Event # Log token usage event = tally.log_usage( customer_id="cust_123", metric_type="tokens", quantity=2500, model="gpt-4", metadata={"request_id": "req_xyz", "endpoint": "/chat/completions"} ) # Log API requests event = tally.log_usage( customer_id="cust_456", metric_type="requests", quantity=1, model="claude-3-opus", metadata={"user_id": "user_789"} ) # Log compute time event = tally.log_usage( customer_id="cust_789", metric_type="compute_seconds", quantity=120, model="stable-diffusion-xl" ) Batch Events from tallyai.models import UsageEvent events = [ UsageEvent(customer_id="cust_1", metric_type="tokens", quantity=1000, model="gpt-4"), UsageEvent(customer_id="cust_2", metric_type="tokens", quantity=2000, model="gpt-4"), UsageEvent(customer_id="cust_3", metric_type="tokens", quantity=500, model="claude-3"), ] results = tally.log_usage_batch(events) print(f"Logged {len(results)} events") List Usage Events # List all usage for a customer events = tally.list_usage( customer_id="cust_123", limit=100 ) print(f"Total events: {events.total}") for event in events.usage_events: print(f" {event.metric_type}: {event.quantity} ({event.model})") # Filter by date range events = tally.list_usage( customer_id="cust_123", start_date="2024-01-01", end_date="2024-01-31", metric_type="tokens" ) # Filter by model events = tally.list_usage( model="gpt-4", page=1, limit=50 ) Managing Customers Create Customer # Simple customer customer = tally.create_customer( email="john@example.com", name="John Doe" ) # With external ID and Stripe integration customer = tally.create_customer( email="jane@company.com", name="Jane Smith", external_id="user_123_from_my_db", stripe_customer_id="cus_stripe123", metadata={"plan": "enterprise", "region": "us-west"} ) print(f"Customer created: {customer.id}") Get Customer customer = tally.get_customer("550e8400-e29b-41d4-a716-446655440000") print(f"{customer.name}: {customer.email}") List Customers # List all customers customers = tally.list_customers(limit=100) # Search customers customers = tally.list_customers(search="@example.com") for customer in customers.customers: print(f"{customer.name}: {customer.email}") Update Customer customer = tally.update_customer( customer_id="550e8400-e29b-41d4-a716-446655440000", name="Jane Doe", metadata={"plan": "pro", "mrr": 299} ) Tracking Costs from decimal import Decimal # Log provider cost cost = tally.log_cost( provider="openai", model="gpt-4", amount=Decimal("45.50"), currency="USD", usage_date="2024-01-15", metadata={"invoice_id": "inv_openai_123"} ) # Track costs from multiple providers providers = [ ("openai", "gpt-4", Decimal("45.50")), ("anthropic", "claude-3-opus", Decimal("32.00")), ("replicate", "stable-diffusion-xl", Decimal("12.75")), ] for provider, model, amount in providers: tally.log_cost( provider=provider, model=model, amount=amount, usage_date="2024-01-15" ) Managing Invoices Create Invoice # Create draft invoice invoice = tally.create_invoice( customer_id="550e8400-e29b-41d4-a716-446655440000", period_start="2024-01-01", period_end="2024-01-31", status="draft", notes="January 2024 usage" ) print(f"Invoice {invoice.invoice_number}: ${invoice.total}") # Create finalized invoice invoice = tally.create_invoice( customer_id="550e8400-e29b-41d4-a716-446655440000", period_start="2024-01-01", period_end="2024-01-31", status="finalized" ) List Invoices # List all invoices invoices = tally.list_invoices() # Filter by customer invoices = tally.list_invoices( customer_id="550e8400-e29b-41d4-a716-446655440000" ) # Filter by status invoices = tally.list_invoices(status="finalized") for invoice in invoices.invoices: print(f"{invoice.invoice_number}: ${invoice.total} ({invoice.status})") Get Invoice invoice = tally.get_invoice("550e8400-e29b-41d4-a716-446655440000") print(f"Invoice: {invoice.invoice_number}") print(f"Period: {invoice.period_start} to {invoice.period_end}") print(f"Subtotal: ${invoice.subtotal}") print(f"Total: ${invoice.total}") print(f"\nLine Items:") for item in invoice.line_items: print(f" - {item['description']}: ${item['amount']}") Pricing Configuration Per-Unit Pricing pricing = tally.create_pricing_config( name="Simple Token Pricing", metric_type="tokens", pricing_model="per_unit", config={ "unit_price": 0.001 # $0.001 per token } ) Tiered Pricing pricing = tally.create_pricing_config( name="GPT-4 Tiered Pricing", metric_type="tokens", pricing_model="tiered", config={ "tiers": [ {"up_to": 1000, "unit_price": 0.01}, # First 1K tokens: $0.01/token {"up_to": 10000, "unit_price": 0.008}, # Next 9K tokens: $0.008/token {"up_to": None, "unit_price": 0.005} # Remaining: $0.005/token ] } ) Volume Pricing pricing = tally.create_pricing_config( name="Volume Discount Pricing", metric_type="tokens", pricing_model="volume", config={ "tiers": [ {"up_to": 10000, "unit_price": 0.01}, # 0-10K: all tokens at $0.01 {"up_to": 100000, "unit_price": 0.008}, # 10K-100K: all tokens at $0.008 {"up_to": None, "unit_price": 0.005} # 100K+: all tokens at $0.005 ] } ) Package Pricing pricing = tally.create_pricing_config( name="Package Pricing", metric_type="tokens", pricing_model="package", config={ "package_size": 10000, # 10K tokens per package "package_price": 50, # $50 per package "overage_price": 0.01 # $0.01 per token over package } ) Anomaly Detection # Create rule for spike detection rule = tally.create_anomaly_rule( name="High Token Usage Alert", description="Alert when token usage increases by 200%", metric_type="tokens", threshold_type="percentage_increase", threshold_value=200.0, # 200% increase time_window_hours=24, severity="high" ) # Create rule for absolute threshold rule = tally.create_anomaly_rule( name="High Request Count", metric_type="requests", threshold_type="absolute_value", threshold_value=10000.0, # More than 10K requests time_window_hours=1, severity="critical" ) Error Handling The SDK provides specific exception classes for different error types:
The main client class for interacting with the Tally API.
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
Releases go to PyPI from GitHub Actions (.github/workflows/publish-sdk.yml) using trusted publishing, so no PyPI token is stored anywhere.
git tag sdk-v0.1.0 && git push origin sdk-v0.1.0 The workflow tests on Python 3.9 and 3.13, builds, runs twine check, then publishes from the pypi environment (approve it there if the environment requires a reviewer). One-time setup: on pypi.org, add a trusted publisher for project tallyai with owner dpc2022, repository Tally, workflow publish-sdk.yml and environment pypi.
ai llm agents cost budgets anthropic openai finops
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
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 verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 28, 2026.




