@devries-cameron20 / composio Mirror · read-only
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 120 lines 4.01 KB
Raw
1 /**
2 * @fileoverview `composio.experimental.usage`: project-scoped metering.
3 * **Experimental — shape may change in future releases.**
4 *
5 * @module Usage
6 */
7 import ComposioClient from '@composio/client';
8 import {
9 UsageBreakdownParams,
10 UsageBreakdownParamsSchema,
11 UsageBreakdownResponse,
12 UsageSummaryParams,
13 UsageSummaryParamsSchema,
14 UsageSummaryResponse,
15 } from '../types/usage.types';
16 import { ComposioRequestOptions } from '../types/requestOptions.types';
17 import { ValidationError } from '../errors/ValidationErrors';
18 import { telemetry } from '../telemetry/Telemetry';
19 import { withCancellation } from '../utils/cancellation';
20 import {
21 transformUsageBreakdownParams,
22 transformUsageBreakdownResponse,
23 transformUsageSummaryParams,
24 transformUsageSummaryResponse,
25 } from '../utils/transformers/usage';
26
27 /**
28 * `composio.experimental.usage` — metering for the project the API key
29 * belongs to. **Experimental — shape may change in future releases.**
30 *
31 * @example
32 * ```typescript
33 * const summary = await composio.experimental.usage.summary();
34 * console.log(summary.entities.tool_calls?.totalQuantity);
35 * console.log(summary.instantCharge); // exact USD string
36 *
37 * const byTool = await composio.experimental.usage.breakdown('tool_calls', {
38 * groupBy: 'tool_slug',
39 * limit: 10,
40 * });
41 * ```
42 */
43 export class Usage {
44 private client: ComposioClient;
45
46 constructor(client: ComposioClient) {
47 this.client = client;
48 telemetry.instrument(this, 'Usage');
49 }
50
51 /**
52 * Usage totals per metering entity type for a time range.
53 * **Experimental — shape may change in future releases.**
54 *
55 * @param {UsageSummaryParams} [params] - Optional range, `entityTypes` and filters
56 * @returns {Promise<UsageSummaryResponse>} Totals keyed by entity type and the exact USD Instant charge
57 * @throws {ValidationError} If the params fail validation
58 *
59 * @example
60 * ```typescript
61 * const summary = await composio.experimental.usage.summary({
62 * from: Date.now() - 7 * 24 * 60 * 60 * 1000,
63 * filters: { userId: ['user_123'] },
64 * });
65 * ```
66 */
67 async summary(
68 params?: UsageSummaryParams,
69 requestOptions?: ComposioRequestOptions
70 ): Promise<UsageSummaryResponse> {
71 const parsedParams = UsageSummaryParamsSchema.safeParse(params ?? {});
72 if (!parsedParams.success) {
73 throw new ValidationError('Failed to parse usage summary params', {
74 cause: parsedParams.error,
75 });
76 }
77 const body = transformUsageSummaryParams(parsedParams.data);
78 const result = await withCancellation(
79 () => this.client.project.usage.retrieveSummary(body, requestOptions),
80 requestOptions?.signal
81 );
82 return transformUsageSummaryResponse(result);
83 }
84
85 /**
86 * Usage for one metering entity type, grouped by a dimension.
87 * **Experimental — shape may change in future releases.**
88 *
89 * @param {string} entityType - Entity type to break down (e.g. `tool_calls`, `sessions`)
90 * @param {UsageBreakdownParams} [params] - Optional range, `groupBy`, ordering, `limit` and filters
91 * @returns {Promise<UsageBreakdownResponse>} Totals plus per-group rows
92 * @throws {ValidationError} If the params fail validation
93 *
94 * @example
95 * ```typescript
96 * const byUser = await composio.experimental.usage.breakdown('sessions', {
97 * groupBy: 'user_id',
98 * orderBy: 'event_count',
99 * });
100 * ```
101 */
102 async breakdown(
103 entityType: string,
104 params?: UsageBreakdownParams,
105 requestOptions?: ComposioRequestOptions
106 ): Promise<UsageBreakdownResponse> {
107 const parsedParams = UsageBreakdownParamsSchema.safeParse(params ?? {});
108 if (!parsedParams.success) {
109 throw new ValidationError('Failed to parse usage breakdown params', {
110 cause: parsedParams.error,
111 });
112 }
113 const body = transformUsageBreakdownParams(parsedParams.data);
114 const result = await withCancellation(
115 () => this.client.project.usage.retrieve(entityType, body, requestOptions),
116 requestOptions?.signal
117 );
118 return transformUsageBreakdownResponse(result);
119 }
120 }