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"

Programmatic Configuration

from costgov import CostGov

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

Test Your Setup

After installation, verify everything works with the built-in test CLI:

# Set environment variables first
export COSTGOV_API_KEY="cg_prod_xxxxx"
export COSTGOV_PROJECT_ID="proj_xxxxx"
export COSTGOV_API_URL="https://ingest.costgov.com"

# Run the test
costgov-test
# Or: python -m costgov.test

You should see:

🔍 CostGov SDK Test

API Key: cg_prod_xxxx...xxxx
Project: proj_xxxxxxxxxxxxx
API URL: https://ingest.costgov.com

📤 Sending test event...

✅ Test event sent successfully!

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.2.0.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.

costgov-0.2.0-py3-none-any.whl (11.1 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for costgov-0.2.0.tar.gz
Algorithm Hash digest
SHA256 9027f0c650d6799c6e5669a9246404ace1195c2311bb4305faa7938f585be17a
MD5 c05cf3375651a880a2b8cec01f216bb5
BLAKE2b-256 d946846e4cf4888e3f8f934dbe4ffc6d8c915e0edfe9ed2bc5c77837055e4971

See more details on using hashes here.

File details

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

File metadata

  • Download URL: costgov-0.2.0-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.9.6

File hashes

Hashes for costgov-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 17b9699552f12a45b7f0d103417cd4e5b2a9952cde5c4c643063e02cd974d373
MD5 60c919eae17fa49da4cbe8d3a538e90a
BLAKE2b-256 b22ea020e3fe42b8f22199e9d7003cef70e69ef3a3fb1755a3ff30ba9ac519c9

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