Back to Guides
Python SDK
AlphaComplete API reference for the Bear Lumen Python SDK. Track AI usage, manage end users, and analyze costs with full type hints.
Also available: Node.js SDK — same API surface with TypeScript support.
Installation & Configuration
Install the SDK from PyPI:
pip install bearlumenInitialize the client with your API key:
import bearlumen
client = bearlumen.Client(api_key='your_api_key')api_key is the only required parameter.
End Users
Manage end users with client.end_users.
| Method | Description |
|---|---|
| end_users.create(external_id, email=None, name=None, metadata=None) | Create a new end user |
| end_users.update(end_user_id, ...) | Update an end user |
| end_users.list(status=None, limit=None, offset=None) | List end users |
| end_users.deactivate(end_user_id) | Soft-delete an end user |
| end_users.reactivate(end_user_id) | Restore a deactivated end user |
Create an End User
result = client.end_users.create(
external_id='user_123',
name='AI Startup Inc',
metadata={'ai_provider': 'openai'}
)
print(result['endUser']['id'])Update an End User
result = client.end_users.update(
'eu_12345',
name='Updated Name',
metadata={'plan': 'enterprise'}
)List End Users
result = client.end_users.list(
status='ACTIVE', # Optional: 'ACTIVE' or 'DEACTIVATED'
limit=50, # Optional
offset=0, # Optional
)Deactivate / Reactivate
# Soft delete (usage history retained)
client.end_users.deactivate('eu_12345')
# Restore access
client.end_users.reactivate('eu_12345')Subscriptions
Manage subscriptions with client.subscriptions.
| Method | Description |
|---|---|
| subscriptions.create(organization_id, plan_id, billing_cycle, start_date, ...) | Create a new subscription |
| subscriptions.retrieve(subscription_id) | Retrieve a subscription by ID |
| subscriptions.update(subscription_id, ...) | Update a subscription |
| subscriptions.cancel(subscription_id) | Cancel a subscription |
| subscriptions.list(organization_id=None, limit=None, offset=None) | List all subscriptions |
Create a Subscription
subscription = client.subscriptions.create(
organization_id='org_123',
plan_id='plan_pro_monthly',
billing_cycle='monthly',
start_date='2024-01-01T00:00:00Z',
)Retrieve, Update, Cancel, List
# Get by ID
sub = client.subscriptions.retrieve('sub_12345')
# Update fields
updated = client.subscriptions.update('sub_12345',
plan_id='plan_enterprise',
)
# Cancel
cancelled = client.subscriptions.cancel('sub_12345')
# List with optional filters
result = client.subscriptions.list(
organization_id='org_123', # Optional
limit=20, # Optional
offset=0, # Optional
)Usage Tracking
Track and query usage with client.usage.
| Method | Description |
|---|---|
| usage.record(event_type, metric_name, quantity, ...) | Record a usage event |
| usage.record_batch(events) | Record multiple events (max 1000) |
| usage.query(subscription_id=None, ...) | Query usage events |
| usage.aggregation(subscription_id=None, ...) | Get aggregated usage by metric |
| usage.summary(subscription_id=None, ...) | Get high-level usage summary |
Record a Usage Event
Pass agent_id and workflow_id as convenience parameters for cost attribution.
result = client.usage.record(
event_type='token_usage',
metric_name='llm_tokens',
quantity=150000,
idempotency_key='invoice-001-summary',
agent_id='support-bot',
workflow_id='customer-onboarding',
metadata={
'model': 'gpt-4-turbo',
'provider': 'openai',
'provider_cost_usd': 4.50,
}
)
if not result['recorded']:
print('Duplicate event skipped')Record Batch Events
result = client.usage.record_batch([
{
'event_type': 'token_usage',
'metric_name': 'llm_tokens',
'quantity': 1000,
'idempotency_key': 'batch-1-evt-1',
},
{
'event_type': 'token_usage',
'metric_name': 'llm_tokens',
'quantity': 2000,
'idempotency_key': 'batch-1-evt-2',
},
])
print(f"Recorded: {result['recorded_count']}, Skipped: {result['skipped_count']}")Query Usage Events
events = client.usage.query(
subscription_id='sub_123',
metric_name='llm_tokens',
start_date='2024-01-01',
end_date='2024-01-31',
limit=100,
)Get Aggregated Usage
aggregation = client.usage.aggregation(
subscription_id='sub_123',
start_date='2024-01-01',
end_date='2024-01-31',
)Get Usage Summary
summary = client.usage.summary(
subscription_id='sub_123',
start_date='2024-01-01',
end_date='2024-01-31',
)Cost Attribution
Analyze costs by AI agent or workflow with client.cost_attribution.
| Method | Description |
|---|---|
| cost_attribution.by_agent(start_date, end_date) | Cost breakdown grouped by agent |
| cost_attribution.by_workflow(start_date, end_date) | Cost breakdown grouped by workflow |
| cost_attribution.list_agents(start_date, end_date) | List unique agent identifiers |
| cost_attribution.list_workflows(start_date, end_date) | List unique workflow identifiers |
Cost Breakdown by Agent
result = client.cost_attribution.by_agent(
start_date='2024-01-01T00:00:00Z',
end_date='2024-02-01T00:00:00Z',
)
for item in result['items']:
print(f"{item['attributionValue']}: ${item['totalCost']}")
print(f"Total: ${result['totalCost']}")Cost Breakdown by Workflow
result = client.cost_attribution.by_workflow(
start_date='2024-01-01T00:00:00Z',
end_date='2024-02-01T00:00:00Z',
)List Unique Agents
result = client.cost_attribution.list_agents(
start_date='2024-01-01T00:00:00Z',
end_date='2024-02-01T00:00:00Z',
)
print('Active agents:', result['values'])List Unique Workflows
result = client.cost_attribution.list_workflows(
start_date='2024-01-01T00:00:00Z',
end_date='2024-02-01T00:00:00Z',
)
print('Active workflows:', result['values'])Exception Classes
The Python SDK provides a typed exception hierarchy for precise error handling:
Exception Hierarchy
BearLumenError— Base exception class
└InvalidEmailError— Email format is invalid
└DuplicateCustomerError— End user with this external ID already exists
└InvalidRequestError— Request parameters are invalid
└AuthenticationError— API key is invalid or missing
└NotFoundError— Requested resource does not exist
└RateLimitError— Too many requests (has retry_after attribute)
└NetworkError— Network connectivity issue
Error Handling Example
from bearlumen import (
Client,
InvalidEmailError,
RateLimitError,
AuthenticationError,
BearLumenError,
)
try:
result = client.end_users.create(
external_id='user_123',
name='AI Startup Inc',
)
except InvalidEmailError:
print('Invalid email format')
except RateLimitError as e:
print(f'Rate limit hit, retry after {e.retry_after} seconds')
except AuthenticationError:
print('Invalid API key')
except BearLumenError as e:
print(f'Error: {e.message}')Import Exceptions
from bearlumen import (
Client,
InvalidEmailError,
DuplicateCustomerError,
InvalidRequestError,
AuthenticationError,
NotFoundError,
RateLimitError,
NetworkError,
BearLumenError,
)Type Hints
The SDK includes full type hints for better IDE support:
from bearlumen import Client, EndUser, Subscription, UsageRecordInput, CostBreakdownResponse
client: Client = Client(api_key='your_key')Available Types
ClientEndUserSubscriptionUsageRecordInputCostBreakdownResponseBearLumenErrorInvalidEmailErrorDuplicateCustomerErrorInvalidRequestErrorAuthenticationErrorNotFoundErrorRateLimitErrorNetworkError
Requirements
- Python
>= 3.9