get_metrics
Query aggregated metrics like costs, tokens, and counts from Langfuse analytics with flexible filtering and grouping options to analyze usage data.
Instructions
Query aggregated metrics (costs, tokens, counts) with flexible filtering and dimensions.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| from | Yes | Start timestamp (ISO 8601) | |
| to | Yes | End timestamp (ISO 8601) | |
| view | No | Data view to query (default: traces) | |
| metrics | No | Metrics to aggregate | |
| dimensions | No | Dimensions to group by | |
| environment | No | Optional environment filter |
Input Schema (JSON Schema)
{
"properties": {
"dimensions": {
"description": "Dimensions to group by",
"items": {
"properties": {
"field": {
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"environment": {
"description": "Optional environment filter",
"type": "string"
},
"from": {
"description": "Start timestamp (ISO 8601)",
"format": "date-time",
"type": "string"
},
"metrics": {
"description": "Metrics to aggregate",
"items": {
"properties": {
"aggregation": {
"type": "string"
},
"measure": {
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"to": {
"description": "End timestamp (ISO 8601)",
"format": "date-time",
"type": "string"
},
"view": {
"description": "Data view to query (default: traces)",
"enum": [
"traces",
"observations"
],
"type": "string"
}
},
"required": [
"from",
"to"
],
"type": "object"
}
Implementation Reference
- src/tools/get-metrics.ts:29-117 (handler)The core handler function that executes the get_metrics tool: validates args, calls Langfuse client.getMetrics, processes and aggregates the response data, and returns formatted JSON.export async function getMetrics( client: LangfuseAnalyticsClient, args: z.infer<typeof getMetricsSchema> ) { const filters: any[] = args.filters || []; // Add environment filter if specified if (args.environment) { filters.push({ column: 'environment', operator: 'equals', value: args.environment, type: 'string', }); } const response = await client.getMetrics({ view: args.view, from: args.from, to: args.to, metrics: args.metrics, dimensions: args.dimensions, filters, }); // Process the response into a structured format const metricsResult: MetricsResponse = { projectId: client.getProjectId(), from: args.from, to: args.to, view: args.view, metrics: [], dimensions: [], }; // Parse metrics data from response if (response.data && Array.isArray(response.data)) { // Aggregate metrics across all rows const aggregatedMetrics: Record<string, number> = {}; response.data.forEach((row: any) => { args.metrics.forEach(metric => { const key = `${metric.measure}_${metric.aggregation}`; // Metrics API returns aggregated field names like 'totalCost_sum', 'count_count' const aggregatedFieldName = `${metric.measure}_${metric.aggregation}`; if (row[aggregatedFieldName] !== undefined) { if (metric.aggregation === 'sum' || metric.aggregation === 'count') { aggregatedMetrics[key] = (aggregatedMetrics[key] || 0) + (row[aggregatedFieldName] || 0); } else if (metric.aggregation === 'avg') { // For average, we'll need to handle this differently aggregatedMetrics[key] = row[aggregatedFieldName] || 0; } } }); }); // Convert aggregated metrics to result format metricsResult.metrics = Object.entries(aggregatedMetrics).map(([key, value]) => { const [measure, aggregation] = key.split('_'); return { measure, aggregation, value }; }); // Extract dimension data if present if (args.dimensions && response.data.length > 0) { const dimensions = new Set<string>(); response.data.forEach((row: any) => { args.dimensions?.forEach(dim => { if (row[dim.field] !== undefined) { dimensions.add(`${dim.field}:${row[dim.field]}`); } }); }); metricsResult.dimensions = Array.from(dimensions).map(dimStr => { const [field, value] = dimStr.split(':'); return { field, value }; }); } } return { content: [ { type: 'text' as const, text: JSON.stringify(metricsResult, null, 2), }, ], }; }
- src/tools/get-metrics.ts:5-27 (schema)Zod schema defining the input parameters for the get_metrics tool, used for validation in the handler and dispatcher.export const getMetricsSchema = z.object({ from: z.string().datetime(), to: z.string().datetime(), view: z.enum(['traces', 'observations']).default('traces'), metrics: z.array(z.object({ measure: z.string(), aggregation: z.string(), })).default([ { measure: 'totalCost', aggregation: 'sum' }, { measure: 'totalTokens', aggregation: 'sum' }, { measure: 'count', aggregation: 'count' }, ]), dimensions: z.array(z.object({ field: z.string(), })).optional(), filters: z.array(z.object({ column: z.string(), operator: z.string(), value: z.any(), type: z.string().optional(), })).optional(), environment: z.string().optional(), });
- src/index.ts:1036-1039 (registration)Tool registration in the main switch dispatcher: parses arguments with schema and invokes the getMetrics handler.case 'get_metrics': { const args = getMetricsSchema.parse(request.params.arguments); return await getMetrics(this.client, args); }
- src/index.ts:298-346 (registration)Tool metadata registration including name, description, and JSON inputSchema in the listTools response.{ name: 'get_metrics', description: 'Query aggregated metrics (costs, tokens, counts) with flexible filtering and dimensions.', inputSchema: { type: 'object', properties: { from: { type: 'string', format: 'date-time', description: 'Start timestamp (ISO 8601)', }, to: { type: 'string', format: 'date-time', description: 'End timestamp (ISO 8601)', }, view: { type: 'string', enum: ['traces', 'observations'], description: 'Data view to query (default: traces)', }, metrics: { type: 'array', items: { type: 'object', properties: { measure: { type: 'string' }, aggregation: { type: 'string' }, }, }, description: 'Metrics to aggregate', }, dimensions: { type: 'array', items: { type: 'object', properties: { field: { type: 'string' }, }, }, description: 'Dimensions to group by', }, environment: { type: 'string', description: 'Optional environment filter', }, }, required: ['from', 'to'], },
- src/index.ts:59-59 (registration)Import statement bringing in the getMetrics handler and schema from the tool module.import { getMetrics, getMetricsSchema } from './tools/get-metrics.js';