Skip to main content

TokenTally Python SDK

Track your AI API usage with TokenTally. Get real-time analytics, cost tracking, and usage insights for Claude, OpenAI, and other AI providers.

Installation

pip install tokentally

Quick Start

from tokentally import TokenTally

# Initialize the client with your API key
tt = TokenTally(api_key="tt_your_api_key")

# Track usage manually
response = tt.track(
    tokens_in=150,
    tokens_out=300,
    model="claude-3-sonnet-20240229",
    provider="anthropic",
    metadata={
        "feature": "chat",
        "user_id": "user123",
    }
)

print(f"Recorded! Cost: ${response.cost_usd:.6f}")

Usage with Context Manager

The context manager automatically tracks timing:

from tokentally import TokenTally
import anthropic

tt = TokenTally(api_key="tt_your_api_key")
client = anthropic.Anthropic()

with tt.track_usage(
    model="claude-3-sonnet-20240229",
    metadata={"feature": "summarization"}
) as ctx:
    # Make your API call
    response = client.messages.create(
        model="claude-3-sonnet-20240229",
        max_tokens=1000,
        messages=[{"role": "user", "content": "Summarize this..."}]
    )

    # Set the usage from the response
    ctx.set_usage(
        tokens_in=response.usage.input_tokens,
        tokens_out=response.usage.output_tokens,
        stop_reason=response.stop_reason,
    )

# Usage is automatically sent when the context exits
print(f"Cost: ${ctx.response.cost_usd:.6f}")

Configuration

tt = TokenTally(
    api_key="tt_your_api_key",
    base_url="https://api.tokentally.cloud",  # Optional custom URL
    timeout=30.0,  # Request timeout in seconds
)

Error Handling

from tokentally import TokenTally, RateLimitError, AuthenticationError, TokenTallyError

tt = TokenTally(api_key="tt_your_api_key")

try:
    tt.track(tokens_in=100, tokens_out=200, model="claude-3-sonnet")
except RateLimitError:
    print("Rate limit exceeded. Upgrade your plan for unlimited usage.")
except AuthenticationError:
    print("Invalid API key. Check your credentials.")
except TokenTallyError as e:
    print(f"Error tracking usage: {e}")

Metadata

Add custom metadata to categorize your usage. The application and feature keys are special -- they appear as filterable dropdowns in the TokenTally dashboard, making it easy to break down usage by app or feature.

tt.track(
    tokens_in=100,
    tokens_out=200,
    model="claude-3-sonnet-20240229",
    metadata={
        "application": "my-app",        # Filterable in dashboard
        "feature": "chat_completion",    # Filterable in dashboard
        "user_id": "user123",
        "environment": "production",
        "request_id": "abc-123",
    }
)

You can add any other key-value pairs to metadata for your own tracking purposes.

Image Generation

Track image generation APIs like Leonardo, DALL-E, and Midjourney using credits, resolution, and quality parameters:

# Leonardo AI
tt.track(
    model="leonardo-phoenix",
    provider="leonardo",
    credits=15,
    resolution="1024x1024",
    quality="high",
)

# OpenAI DALL-E
tt.track(
    model="dall-e-3",
    provider="openai",
    resolution="1024x1024",
    quality="hd",
)

# With context manager
with tt.track_usage(model="leonardo-phoenix", provider="leonardo") as ctx:
    response = leonardo.generate(prompt="A sunset over mountains")

    ctx.set_usage(
        credits=response.credits_used,
        resolution="1024x1024",
        quality="high",
    )

License

MIT License - see LICENSE for details.

Metadata

Release files for tokentally 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tokentally 0.4.0
File Size Uploaded Provenance
tokentally-0.4.0.tar.gz 8.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for tokentally 0.4.0
File Interpreter ABI Platform
tokentally-0.4.0-py3-none-any.whl Python 3 none any Details

Total release size: 16.3 kB

Release files / tokentally-0.4.0.tar.gz

Download URL tokentally-0.4.0.tar.gz
Size 8.5 kB
Tags Source
SHA-256 checksum
How to use checksums
e9040fc635a6c6e9070f91563f133a37f200f46a2cb33c7d211eaa3c2eed53c0
BLAKE2b-256 checksum
How to use checksums
cfdbcca5c84e5f7d35d9ec3b3db590632aa7108214a009245cf5895e0fd93cbd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / tokentally-0.4.0-py3-none-any.whl

Download URL tokentally-0.4.0-py3-none-any.whl
Size 7.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8d258f15e83581cd6648b00fb659d4b2f8a701ff2120f4ee876e1a064ea89125
BLAKE2b-256 checksum
How to use checksums
cdab64fabfaa8d494d77b4277c4edf06c2c990367b2e5386f49aeee46e71accc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Security for tokentally 0.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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page