import {z} from 'zod' export type TraceStructuredFilter = {field: string, operator: string, value: unknown, nested_key?: string | undefined}; export type TraceStructuredFilterGroup = {logic?: ('AND' | 'OR' | 'SPAN_AND' | 'SPAN_OR') | undefined, filters: Array}; export type TraceCustomChartSpec = {id: string, title?: string | undefined, chartType: 'bar' | 'line' | 'area' | 'pie' | 'donut' | 'histogram' | 'heatmap' | 'treemap' | 'sunburst', metric?: ('count' | 'sum' | 'avg' | 'min' | 'max' | 'percentile') | undefined, metricField?: ('trace_duration_ms' | 'trace_total_cost_usd' | 'trace_total_tokens' | 'trace_input_tokens' | 'trace_output_tokens' | 'trace_span_count' | 'trace_depth' | 'span_duration_ms' | 'span_cost_usd' | 'span_tokens' | 'span_input_tokens' | 'span_output_tokens') | undefined, percentile?: number | undefined, groupByField?: ('trace_status' | 'trace_name' | 'trace_models_used' | 'trace_prompt_ids' | 'trace_workflow_ids' | 'trace_tool_names' | 'span_tool_name' | 'span_name' | 'span_type' | 'span_kind' | 'span_status') | undefined, secondaryGroupByField?: ('trace_status' | 'trace_name' | 'trace_models_used' | 'trace_prompt_ids' | 'trace_workflow_ids' | 'trace_tool_names' | 'span_tool_name' | 'span_name' | 'span_type' | 'span_kind' | 'span_status') | undefined, histogramField?: ('trace_duration_ms' | 'trace_total_cost_usd' | 'trace_total_tokens' | 'trace_input_tokens' | 'trace_output_tokens' | 'trace_span_count' | 'trace_depth' | 'span_duration_ms' | 'span_cost_usd' | 'span_tokens' | 'span_input_tokens' | 'span_output_tokens') | undefined, histogramInterval?: number | undefined, hierarchyFields?: (Array<'trace_status' | 'trace_name' | 'trace_models_used' | 'trace_prompt_ids' | 'trace_workflow_ids' | 'trace_tool_names' | 'span_tool_name' | 'span_name' | 'span_type' | 'span_kind' | 'span_status'>) | undefined, timeSeries?: boolean | undefined, timeBucket?: ('auto' | 'day' | 'week' | 'month') | undefined, limit?: number | undefined, series?: (Array<{key: string, label: string, metric: 'sum' | 'avg' | 'min' | 'max' | 'percentile', metricField: 'trace_duration_ms' | 'trace_total_cost_usd' | 'trace_total_tokens' | 'trace_input_tokens' | 'trace_output_tokens' | 'trace_span_count' | 'trace_depth' | 'span_duration_ms' | 'span_cost_usd' | 'span_tokens' | 'span_input_tokens' | 'span_output_tokens', percentile?: number | undefined}>) | undefined}; export type TraceAnalyticsCustomAnalyticsQuery = {filter_group?: TraceStructuredFilterGroup | undefined, customCharts: Array}; export type CreateApiApiPublicV2TracesAnalyticsCustomAnalyticsArgs = {body: TraceAnalyticsCustomAnalyticsQuery}; export type CreateApiApiPublicV2TracesAnalyticsCustomAnalyticsOptions = {baseUrl: string, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const customAnalyticsSeriesMeta = z.object({key: z.string().optional(), label: z.string().optional(), unit: z.enum(["count", "tokens", "currency", "duration_seconds", "number"]).optional()}); export const derivedRatioInsightResult = z.object({type: z.literal("ratio").optional(), label: z.string().optional(), numeratorSeriesKey: z.string().optional(), denominatorSeriesKey: z.string().optional(), value: z.number().optional()}); export const customAnalyticsResult = z.object({id: z.string().optional(), title: z.string().optional(), chartType: z.enum(["bar", "line", "area"]).optional(), series: z.array(customAnalyticsSeriesMeta).optional(), data: z.array(z.record(z.string(), z.unknown())).optional(), derivedInsights: z.array(derivedRatioInsightResult).nullable().optional()}); export const requestAnalyticsCustomAnalyticsResponse = z.object({success: z.literal(true), customCharts: z.array(customAnalyticsResult)}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Trace Analytics Custom Queries * * POST /api/public/v2/traces/analytics/custom-analytics */ export const createApiApiPublicV2TracesAnalyticsCustomAnalytics = async (args: CreateApiApiPublicV2TracesAnalyticsCustomAnalyticsArgs, options: CreateApiApiPublicV2TracesAnalyticsCustomAnalyticsOptions) => { const {baseUrl, fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set("X-API-KEY", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/api/public/v2/traces/analytics/custom-analytics${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(requestAnalyticsCustomAnalyticsResponse, await res.json()) };