Skip to main content

Python SDK for CostGov - Track and govern billable events in your application

Project description

CostGov Python SDK

Drop-in cost governance for your Python applications. Track, limit, and optimize billable events in real-time.

PyPI version Python Versions License

Installation

pip install costgov

Quick Start

import os
from costgov import CostGov

# Initialize the client
client = CostGov(
    api_key=os.getenv("COSTGOV_API_KEY"),
    project_id=os.getenv("COSTGOV_PROJECT_ID"),
)

# Track billable events
client.track("ai.openai.gpt4", 1500)  # Track 1500 tokens
client.track("email.send", 1)         # Track 1 email
client.track("sms.send", 1, metadata={"provider": "twilio"})

# Shutdown when done (flushes remaining events)
client.shutdown()

Features

  • Simple API - Track events with one line of code
  • Automatic Batching - Events are batched for efficiency
  • Auto-flush - Events are sent automatically at intervals
  • Context Manager - Use with statement for automatic cleanup
  • Type Hints - Full type hint support for better IDE experience
  • Zero Dependencies - Only requires requests library

Configuration

Environment Variables

export COSTGOV_API_KEY="cg_prod_xxxxxxxxxxxxx"
export COSTGOV_PROJECT_ID="proj_xxxxxxxxxxxxx"
export COSTGOV_API_URL="https://ingest.costgov.com"  # Optional

Programmatic Configuration

from costgov import CostGov

client = CostGov(
    api_key="cg_prod_xxxxx",
    project_id="proj_xxxxx",
    api_url="https://ingest.costgov.com",  # Optional
    batch_size=100,        # Events to batch before sending
    flush_interval=5.0,    # Seconds between auto-flushes
)

Usage Examples

Basic Tracking

from costgov import CostGov

client = CostGov()

# Track OpenAI API usage
client.track("ai.openai.gpt4", token_count)

# Track email sends
client.track("email.send", 1)

# Track with metadata
client.track("storage.s3.put", 1, metadata={
    "bucket": "my-bucket",
    "size_bytes": 1024
})

Context Manager (Recommended)

from costgov import CostGov

with CostGov() as client:
    client.track("ai.openai.gpt4", 1500)
    client.track("email.send", 1)
    # Automatically flushes and shuts down on exit

Manual Flush

client = CostGov()

# Queue events
client.track("ai.openai.gpt4", 1000)
client.track("ai.openai.gpt4", 500)

# Force immediate send
client.flush()

Error Handling

from costgov import CostGov, APIError, ConfigError

try:
    client = CostGov()
    client.track("ai.openai.gpt4", 1500)
except ConfigError as e:
    print(f"Configuration error: {e}")
except APIError as e:
    print(f"API error: {e} (status: {e.status_code})")

API Reference

CostGov(api_key, project_id, api_url, batch_size, flush_interval)

Initialize the CostGov client.

Parameters:

  • api_key (str, optional): Your API key. Defaults to COSTGOV_API_KEY env var
  • project_id (str, optional): Your project ID. Defaults to COSTGOV_PROJECT_ID env var
  • api_url (str, optional): API endpoint. Defaults to COSTGOV_API_URL or http://localhost:3001
  • batch_size (int, optional): Max events to batch. Default: 100
  • flush_interval (float, optional): Seconds between flushes. Default: 5.0

track(metric, units, metadata=None)

Track a billable event.

Parameters:

  • metric (str): Event metric name (e.g., "ai.openai.gpt4")
  • units (float): Number of units consumed
  • metadata (dict, optional): Additional event metadata

Returns: bool - True if event was queued successfully

flush()

Flush all queued events immediately.

Returns: bool - True if flush was successful

Raises: APIError if the request fails

shutdown()

Flush remaining events and clean up resources. Called automatically on exit.

Best Practices

  1. Use Context Manager

    with CostGov() as client:
        client.track("ai.openai.gpt4", tokens)
    
  2. Handle Errors Gracefully

    try:
        client.track("ai.openai.gpt4", tokens)
    except APIError:
        # Log error but don't break your app
        pass
    
  3. Set Environment Variables

    # Don't hardcode credentials
    client = CostGov()  # Uses env vars
    
  4. Call Shutdown on Exit

    import atexit
    
    client = CostGov()
    atexit.register(client.shutdown)
    

Requirements

  • Python 3.7+
  • requests library

License

MIT License - see LICENSE file for details

Support

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

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

costgov-0.1.0.tar.gz (6.3 kB view details)

Uploaded Source

Built Distribution

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

costgov-0.1.0-py3-none-any.whl (6.7 kB view details)

Uploaded Python 3

File details

Details for the file costgov-0.1.0.tar.gz.

File metadata

  • Download URL: costgov-0.1.0.tar.gz
  • Upload date:
  • Size: 6.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for costgov-0.1.0.tar.gz
Algorithm Hash digest
SHA256 830b824774fb54116459ddcde18bc2cf5c1b9871251c4df2c367b566b38b1187
MD5 814f7c82d608213450f7f68795f8870a
BLAKE2b-256 d9456e16efe6178451249bd2202a4ef12f7bbd88e1fda90ecf7d29ccbabb4d80

See more details on using hashes here.

File details

Details for the file costgov-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: costgov-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for costgov-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7be77ee1ab530b0b9adbc04ba03c6944a6a3e38b4afad18f9ac0dfb0185d3ea7
MD5 fa24d68cc5682920cb70a14ce65115a3
BLAKE2b-256 24ad2ecb8706821cf586545750df17f2ae8daaaa6fa08cbb0afc27935a17db61

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