Skip to main content

venice_ai.resources.billing

Venice AI Billing and Usage Analytics Resource Module.

This module provides comprehensive billing and usage tracking functionality for Venice AI services. It enables users to retrieve detailed usage analytics, cost breakdowns, and billing information in multiple formats to support various integration and reporting needs.

The module supports both structured JSON responses for programmatic integration and CSV exports for data analysis, reporting, and external system integration. All operations are designed to work seamlessly with asynchronous workflows and provide flexible filtering options for precise usage analysis.

Key Features: - Detailed usage analytics with flexible filtering - Multi-format support (JSON and CSV) - Comprehensive cost tracking and billing summaries - Aggregated usage analytics with breakdowns by date, model, and API key (Beta) - Pagination support for large datasets - Real-time usage monitoring and reporting

Classes: Billing: Asynchronous resource for billing and usage data operations

Billing Objects

class Billing(APIResource["VeniceClient"])

Asynchronous resource for comprehensive billing and usage analytics operations.

This class provides a complete interface for retrieving and analyzing Venice AI usage data, billing information, and cost analytics. It supports multiple output formats and flexible filtering options to accommodate various reporting and integration needs.

The class automatically handles format-specific request headers, response parsing, and data type conversions based on the requested output format. All operations are fully asynchronous and integrate seamlessly with async/await patterns.

Key Capabilities:

  • Usage data retrieval with flexible date range filtering
  • Multiple output formats (JSON for APIs, CSV for analytics)
  • Pagination support for large datasets
  • Currency-specific cost reporting
  • Detailed usage breakdowns by model and service type

Arguments:

  • client - The Venice AI client instance for making authenticated API requests.

Example:

Basic usage analytics:

.. code-block:: python

async with VeniceClient() as client:

Get recent usage data

usage = await client.billing.get_usage( startDate="2025-01-01T00:00:00Z", endDate="2025-02-01T00:00:00Z" )

Export to CSV for analysis

csv_data = await client.billing.get_usage( format=BillingFormatEnum.CSV, startDate="2025-01-01T00:00:00Z" )

Billing.get_usage

async def get_usage(
*,
format: BillingFormatEnum = BillingFormatEnum.JSON,
currency: str | None = None,
startDate: str | None = None,
endDate: str | None = None,
limit: int | None = None,
page: int | None = None,
sortOrder: str | None = None) -> BillingUsageResponse | bytes

Retrieve comprehensive billing and usage data with flexible filtering options.

Fetches detailed usage analytics from Venice AI services with support for multiple output formats, date range filtering, pagination, and currency-specific reporting. The response format is automatically determined by the Content-Type header based on the requested format parameter.

Arguments:

  • format - Output format for the response. Defaults to JSON for programmatic use.
  • currency - Filter results by currency type. Supported values are "USD", "DIEM", "VCU", and "BUNDLED_CREDITS" (matching BillingUsageEntry.currency).
  • startDate - Start date for filtering in ISO 8601 format (e.g., "2025-01-01T00:00:00Z").
  • endDate - End date for filtering in ISO 8601 format.
  • limit - Maximum number of records per page (1-500, default 200).
  • page - Page number for pagination (1-based indexing, default 1).
  • sortOrder - Sort order for timestamps ("asc" or "desc", default "desc").

Returns:

For JSON format: Structured usage data with detailed metrics and metadata. For CSV format: Raw byte data ready for file writing or stream processing.

Raises:

  • BillingTimeoutError - If the request times out (10s limit). This often occurs with small date ranges (< 15 min) or queries that return empty results.
  • InvalidRequestError - If any parameter values are invalid or out of range.
  • AuthenticationError - If the API key is invalid or expired.
  • PermissionDeniedError - If the account lacks billing data access.
  • RateLimitError - If API rate limits are exceeded.
  • APIError - For other API-related errors or service issues.

Notes:

The billing API uses an aggressive 10-second timeout because the Venice billing endpoint is known to hang indefinitely on certain query conditions (small date ranges, empty results). If you receive a BillingTimeoutError, try using a larger date range (at least 1 day).

Example:

Structured usage analysis:

.. code-block:: python

from venice_ai import VeniceClient from venice_ai.types.enums import BillingFormatEnum

async def analyze_usage(): async with VeniceClient() as client:

Get detailed JSON usage data

usage = await client.billing.get_usage( startDate="2025-01-01T00:00:00Z", endDate="2025-02-01T00:00:00Z", currency="USD", limit=100 )

Analyze usage patterns

total_cost = sum(record.amount for record in usage.data) print(f"Total cost: ${total_cost:.2f}")

Export for external analysis

csv_data = await client.billing.get_usage( format=BillingFormatEnum.CSV, startDate="2025-01-01T00:00:00Z", endDate="2025-02-01T00:00:00Z" )

Save to file

with open("venice_usage.csv", "wb") as f: f.write(csv_data)

Billing.iter_usage

def iter_usage(*,
page_size: int = DEFAULT_PAGE_SIZE,
max_items: int | None = None,
currency: str | None = None,
startDate: str | None = None,
endDate: str | None = None,
sortOrder: str | None = None) -> Paginator[BillingUsageEntry]

Lazily iterate every billing usage entry matching the filters.

Wraps :meth:get_usage (JSON form only) for unbounded enumeration. Termination uses the response's pagination.totalPages field. Date and currency filters are passed to every per-page call so the server-side query is consistent across pages.

Arguments:

  • page_size: Server page size (default 100; server max 500).
  • max_items: Optional cap on total items yielded.
  • currency: Filter by currency type.
  • startDate: Start date (ISO 8601).
  • endDate: End date (ISO 8601).
  • sortOrder: "asc" or "desc" (default "desc"). Example:
async for entry in client.billing.iter_usage(currency="USD"):
print(entry.timestamp, entry.amount)

Billing.get_balance

async def get_balance() -> BillingBalanceResponse

Get current balance information (GET /billing/balance).

Returns the authenticated user's remaining DIEM and USD balances along with the total DIEM epoch allocation.

Returns:

:class:BillingBalanceResponse with DIEM/USD balances.

Raises:

  • AuthenticationError - If the API key is invalid or expired.
  • APIError - If the request fails or returns an error response.
  • APIConnectionError - If unable to connect to the API.

Example:

.. code-block:: python

balance = await client.billing.get_balance() print(f"Can consume: {balance.can_consume}") if balance.balances:

  • print(f"DIEM - {balance.balances.diem}")
  • print(f"USD - {balance.balances.usd}")

Billing.get_usage_analytics

async def get_usage_analytics(
*,
lookback: str | None = None,
startDate: str | None = None,
endDate: str | None = None) -> UsageAnalyticsResponse

Get aggregated usage analytics with breakdowns by date, model, and API key.

.. beta:

This method wraps a **beta** API endpoint (``GET /billing/usage-analytics``).
The request/response schema and behaviour may change without notice.

Provides summary views of your API usage data, ideal for building dashboards
and monitoring consumption. Data is cached server-side for 10 minutes.

You can specify the time period using either:

* **lookback**: A relative period like ``"7d"`` (7 days), ``"30d"`` (30 days),
up to ``"90d"`` (90 days).
* **startDate** and **endDate**: A custom date range in ``YYYY-MM-DD`` format.
Both are required if either is provided.

If no parameters are specified, the default lookback period is 7 days.

Arguments:

  • lookback - Relative lookback period (e.g., "7d", "30d", up to "90d"). Cannot be combined with startDate/endDate.
  • startDate - Start date in YYYY-MM-DD format. Required if endDate is provided.
  • endDate - End date in YYYY-MM-DD format. Required if startDate is provided.

Returns:

:class:~venice_ai.types.api.billing.UsageAnalyticsResponse containing aggregated analytics with byDate, byModel, byKey, and chart data.

Raises:

  • InvalidRequestError - If parameter values are invalid (e.g., lookback > 90d, mismatched startDate/endDate, or combining lookback with date range).
  • AuthenticationError - If the API key is invalid or expired.
  • BillingTimeoutError - If the request times out (10s limit).
  • APIError - For other API-related errors or service issues.

Warnings:

This endpoint is currently in beta and may be unstable. Request/response schemas and behaviour may change without notice in future API versions.

Example:

.. code-block:: python

from venice_ai import VeniceClient

async def check_analytics(): async with VeniceClient() as client:

Default: last 7 days

analytics = await client.billing.get_usage_analytics()

Last 30 days

analytics = await client.billing.get_usage_analytics(lookback="30d")

Custom date range

analytics = await client.billing.get_usage_analytics( startDate="2025-01-01", endDate="2025-01-31", )

Inspect results

for day in analytics.byDate:

  • print(f"{day.date} - ${day.USD:.2f} / {day.DIEM:.2f} DIEM")

    for model in analytics.byModel:

  • print(f"{model.modelName} - ${model.totalUsd:.4f}")