Skip to main content

Python SDK for AI agents to track LLM usage and forward billing data to TokenVault

Project description

TokenVault SDK

PyPI version Python versions License: MIT

A lightweight Python SDK for AI agents to track LLM usage and manage billing with TokenVault.

Features

  • Credit balance checking with Redis caching
  • Usage tracking and forwarding to TokenVault
  • Async/await support with automatic retries
  • Fail-open mode for resilience
  • Groq API integration

Installation

pip install tokenvault-sdk

Requirements

  • Python 3.11+
  • Redis server
  • TokenVault API access

Quick Start

Set environment variables:

export TOKENVAULT_REDIS_URL="redis://localhost:6379"
export TOKENVAULT_API_URL="https://api.tokenvault.io"

Basic usage:

import asyncio
from tokenvault_sdk import SDKConfig, UsageTracker
from groq import AsyncGroq

async def main():
    config = SDKConfig.from_env()
    tracker = UsageTracker(
        redis_url=config.redis_url,
        tokenvault_api_url=config.tokenvault_api_url,
    )
    
    groq_client = AsyncGroq(api_key="your-api-key")
    
    try:
        # Check credit balance
        credit_balance = await tracker.check_credit_balance(organization_id="org_123")
        print(f"Credit balance: {credit_balance:.2f} credits")
        
        # Make LLM call
        response = await groq_client.chat.completions.create(
            model="llama-3.1-70b-versatile",
            messages=[{"role": "user", "content": "Hello"}]
        )
        
        # Track usage (fire-and-forget)
        asyncio.create_task(
            tracker.track_usage(
                groq_response=response.model_dump(),
                organization_id="org_123",
                profile_id="agent_456",
            )
        )
        
        print(response.choices[0].message.content)
    finally:
        await tracker.close()

asyncio.run(main())

Configuration

Environment variables:

Variable Required Default
TOKENVAULT_REDIS_URL Yes -
TOKENVAULT_API_URL Yes -
TOKENVAULT_STREAM_NAME No usage_records
TOKENVAULT_BALANCE_THRESHOLD No 0.0
TOKENVAULT_CACHE_TTL No 60
TOKENVAULT_FAIL_OPEN No true
TOKENVAULT_MAX_RETRIES No 3
TOKENVAULT_RETRY_BACKOFF_MS No 100

Or configure programmatically:

from tokenvault_sdk import SDKConfig, UsageTracker

config = SDKConfig(
    redis_url="redis://localhost:6379",
    tokenvault_api_url="https://api.tokenvault.io",
    balance_threshold=0.0,
    cache_ttl=60,
    fail_open=True,
)

tracker = UsageTracker(
    redis_url=config.redis_url,
    wallet_api_url=config.wallet_api_url,
    balance_threshold=config.balance_threshold,
    cache_ttl=config.cache_ttl,
    fail_open=config.fail_open,
)

API Reference

UsageTracker

Methods:

check_credit_balance(organization_id: str, force_refresh: bool = False) -> float

  • Check organization credit balance with optional cache bypass
  • Returns credit balance as float
  • Raises InsufficientBalanceError if below threshold

track_usage(groq_response: Dict, organization_id: str, profile_id: str, user_id: str = "", metadata: Optional[Dict] = None)

  • Track LLM usage and publish to Redis Stream
  • Designed for fire-and-forget usage with asyncio.create_task()

close()

  • Close all connections gracefully

Exceptions

  • SDKConfigurationError: Invalid configuration
  • InsufficientBalanceError: Balance below threshold
  • TrackingError: Usage tracking failed (fail-closed mode)

Error Handling

from tokenvault_sdk import (
    UsageTracker,
    InsufficientBalanceError,
    SDKConfigurationError,
)

try:
    config = SDKConfig.from_env()
except SDKConfigurationError as e:
    print(f"Configuration error: {e}")
    exit(1)

tracker = UsageTracker(
    redis_url=config.redis_url,
    tokenvault_api_url=config.tokenvault_api_url,
)

try:
    credit_balance = await tracker.check_credit_balance("org_123")
except InsufficientBalanceError as e:
    print(f"Insufficient credit balance: {e}")

Modes

Fail-Open (default): Allows requests when services are unavailable

tracker = UsageTracker(..., fail_open=True)

Fail-Closed: Rejects requests when services are unavailable

tracker = UsageTracker(..., fail_open=False)

License

MIT License - see LICENSE file for details

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tokenvault_sdk-0.1.5.tar.gz (11.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tokenvault_sdk-0.1.5-py3-none-any.whl (11.1 kB view details)

Uploaded Python 3

File details

Details for the file tokenvault_sdk-0.1.5.tar.gz.

File metadata

  • Download URL: tokenvault_sdk-0.1.5.tar.gz
  • Upload date:
  • Size: 11.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for tokenvault_sdk-0.1.5.tar.gz
Algorithm Hash digest
SHA256 b5801d9dc245eb5e345687f5549815b2f9b48c7f375b4f9bafd3f63a94346472
MD5 5d649d5389cf0cd94ad5f9ca7d3e4903
BLAKE2b-256 20164a78621ec9e498bc5e34a307421b862f27af981f02e086282ef61d8f8acf

See more details on using hashes here.

File details

Details for the file tokenvault_sdk-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: tokenvault_sdk-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 11.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for tokenvault_sdk-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 822ee9eeb0b803274f8ab3e3be1b2c1cbb536d9e6a4126ccb42e10e000c8c54f
MD5 9b9218e12b57df3f04f80bd51888f7cd
BLAKE2b-256 2ee8339cbb85394e78a9049836ca80526678e386809b97a248c1c59c59a9d007

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page