Charges
Smarter.apps.dashboard.views.api.charges.
Overview
It provides endpoints and utilities for summarizing per-user or per-resource usage costs, intended for display within frontend dashboard components. The module’s main responsibilities are:
Aggregated Charges Querying: Defines functions to efficiently query and aggregate usage charge metrics (e.g., tokens, cost) across various time intervals including hour, day, week, month, and year, supporting dynamic data visualization in dashboard charts.
Periodicity Logic: Encapsulates business logic to compute time boundaries and grouping fields for different reporting periods, used for accurate and flexible charting.
API Endpoint: Exposes an authenticated Django view class (MyResourcesView) which serves data to frontend React components via a JSON API, supporting POST requests that specify desired aggregation periodicity.
Caching
Resource-intensive queries (e.g., charge aggregation) leverage a cache layer to minimize repeated expensive computations and database load. The @cache_results decorator is used, with a default timeout of one hour.
Usage
To expose the API endpoint, wire up MyResourcesView in your Django application’s URL configuration. The endpoint expects POST requests containing a valid periodicity value and returns aggregated charge statistics as JSON. Use these endpoints to drive dashboard visualizations of account or organization usage.
Note
Function signatures and argument details are documented via Sphinx’s automodule directive. For deeper API
reference, see the generated developer docs or inline function docstrings.
- class smarter.apps.dashboard.views.views.api.charges.AggregatedChargesPeriod[source]
Bases:
objectAPI view to provide aggregated usage charge data for the dashboard’s “Aggregated Charges Chart”.
React component.
This view responds to authenticated POST requests, returning per-user usage summaries (e.g., tokens and cost) for a requested aggregation period as part of the dashboard experience.
Inherits from
SmarterAuthenticatedWebView, which enforces user authentication.- formatted_class_name
Returns the class name and instance identifier as a formatted string, helpful for logging and debugging.
- Type:
- post(request, periodicity, \*args, \*\*kwargs)
Handle POST requests and return aggregated charge data as JSON for the specified periodicity.
Examples
Usage in Django’s URL configuration:
from smarter.apps.dashboard.views.api.charges import MyResourcesView urlpatterns = [ path("api/charges/<str:periodicity>/", MyResourcesView.as_view(), name="api-charges"), ]
- DAY = '24_hours'
- HALF_DAY = '12_hours'
- HOUR = '1_hour'
- MONTH = '1_month'
- WEEK = '7_days'
- YEAR = '1_year'
- classmethod delta(periodicity, tz=None)[source]
Compute the UTC datetime cutoff for the beginning of a given aggregation period.
Determines the lower (older) time boundary to use when aggregating charge data, based on a specified periodicity key. The returned datetime represents “now minus the length of the interval,” in the given timezone.
- Return type:
- Parameters:
periodicity (str) – The aggregation period key. Must be one of:
"1_hour","12_hours","24_hours","7_days","1_month", or"1_year".tz (ZoneInfo or None, optional) – Timezone to use for the calculation (defaults to the system local time zone if None).
- Returns:
The datetime value representing the start of the aggregation window.
- Return type:
datetime
- Raises:
ValueError – If an unknown periodicity key is provided.
Examples
# Get start of the last 7 days in UTC from zoneinfo import ZoneInfo cutoff = AggregatedChargesPeriod.delta("7_days", tz=ZoneInfo("UTC"))
- classmethod grouping_fields(periodicity)[source]
Retrieve the list of model fields used to group charge data for a given periodicity.
This method assists in dynamically determining how database records should be grouped for aggregation, based on the reporting interval requested. It enables flexible aggregation (hourly, daily, monthly, etc.) for charge summaries.
- Return type:
- Parameters:
periodicity (str) – Aggregation period key. Must be one of the constants defined in
AggregatedChargesPeriod(e.g.,"1_hour","12_hours","24_hours","7_days","1_month","1_year").- Returns:
List of model field names that should be used to group charge records for the requested periodicity.
- Return type:
- Raises:
KeyError – If the supplied periodicity value is not recognized.
Examples
fields = AggregatedChargesPeriod.grouping_fields("1_month") # May return: ['year', 'month', 'day']
- class smarter.apps.dashboard.views.views.api.charges.ChargesView(**kwargs)[source]
Bases:
SmarterAuthenticatedWebViewAPI view for the Aggregated Charges Chart React component on the dashboard.
- property formatted_class_name: str
Returns the class name in a formatted string along with the name of this view.
- smarter.apps.dashboard.views.views.api.charges.get_aggregated_charges(user_profile, periodicity='1_hour', invalidate=False)[source]
Query and aggregate resource usage charges for a user over a specified reporting interval.
This function collects and summarizes charge records (e.g., tokens, cost) associated with a user’s resource locator, grouping by the appropriate fields for the requested periodicity (hourly, daily, weekly, etc.). The result is suitable for data visualization on usage charts. Results are cached to improve performance on repeated requests.
- Return type:
- Parameters:
user_profile (UserProfile) – The user profile whose charges should be aggregated.
periodicity (str, optional) – Key for aggregation period, accepted values are constants defined in
AggregatedChargesPeriod(default isAggregatedChargesPeriod.HOUR).invalidate (bool, optional) – If True, bypass and invalidate any cached value before recomputing the result (default is False).
- Returns:
A list of dictionaries representing aggregated charge data. Each dict contains groupby fields (year, month, day, etc.), resource_locator, and aggregated metrics:
records,prompt_tokens,completion_tokens,total_tokens, andtotal_cost.- Return type:
- Raises:
ValueError – If the supplied periodicity value is unrecognized.
Examples
data = get_aggregated_charges(user_profile, periodicity="1_month") for entry in data: print(entry["total_cost"])