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.1.tar.gz (8.0 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.1-py3-none-any.whl (8.4 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for costgov-0.1.1.tar.gz
Algorithm Hash digest
SHA256 28012588680d204de857dc27bcf24b13963350c25f444154e4798c9cdd45ea98
MD5 0f792960106b83bba6eac7f40ad60520
BLAKE2b-256 d0f8e4eb0a11e2d8dc226264b14ba227986248964e710acd041244558ba55da2

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for costgov-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 8e3a88458bba2f504b9e3982ebe78341674a59801920efc0ac93abe4f463a07c
MD5 e2c74abf9854884414f38c69d5c2a096
BLAKE2b-256 633291d32e5f0d105a9498e39da103a4b243db0bd756a9d1b026e6f5a52539df

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