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.
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
withstatement for automatic cleanup - Type Hints - Full type hint support for better IDE experience
- Zero Dependencies - Only requires
requestslibrary
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 toCOSTGOV_API_KEYenv varproject_id(str, optional): Your project ID. Defaults toCOSTGOV_PROJECT_IDenv varapi_url(str, optional): API endpoint. Defaults toCOSTGOV_API_URLorhttp://localhost:3001batch_size(int, optional): Max events to batch. Default: 100flush_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 consumedmetadata(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
-
Use Context Manager
with CostGov() as client: client.track("ai.openai.gpt4", tokens)
-
Handle Errors Gracefully
try: client.track("ai.openai.gpt4", tokens) except APIError: # Log error but don't break your app pass
-
Set Environment Variables
# Don't hardcode credentials client = CostGov() # Uses env vars
-
Call Shutdown on Exit
import atexit client = CostGov() atexit.register(client.shutdown)
Requirements
- Python 3.7+
requestslibrary
License
MIT License - see LICENSE file for details
Support
- Documentation: https://docs.costgov.com
- Issues: https://github.com/costgov/costgov/issues
- Email: hello@costgov.com
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
28012588680d204de857dc27bcf24b13963350c25f444154e4798c9cdd45ea98
|
|
| MD5 |
0f792960106b83bba6eac7f40ad60520
|
|
| BLAKE2b-256 |
d0f8e4eb0a11e2d8dc226264b14ba227986248964e710acd041244558ba55da2
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8e3a88458bba2f504b9e3982ebe78341674a59801920efc0ac93abe4f463a07c
|
|
| MD5 |
e2c74abf9854884414f38c69d5c2a096
|
|
| BLAKE2b-256 |
633291d32e5f0d105a9498e39da103a4b243db0bd756a9d1b026e6f5a52539df
|