import {z} from 'zod' export type StructuredFilter = {field: 'pl_id' | 'prompt_id' | 'engine' | 'provider_type' | 'input_text' | 'output_text' | 'prompt_version_number' | 'input_tokens' | 'output_tokens' | 'cost' | 'latency_ms' | 'request_start_time' | 'request_end_time' | 'status' | 'is_json' | 'is_tool_call' | 'is_plain_text' | 'tags' | 'metadata_keys' | 'metadata' | 'tool_names' | 'output' | 'output_keys' | 'input_variables' | 'input_variable_keys' | 'user_intent' | 'agent_intent', operator: 'is' | 'is_not' | 'in' | 'not_in' | 'contains' | 'not_contains' | 'starts_with' | 'ends_with' | 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'between' | 'before' | 'after' | 'is_true' | 'is_false' | 'is_empty' | 'is_not_empty' | 'is_null' | 'is_not_null' | 'key_equals' | 'key_not_equals' | 'key_contains', value?: (string | number | boolean | Array | null) | undefined, nested_key?: (string | null) | undefined}; export type StructuredFilterGroup = {logic?: ('AND' | 'OR') | undefined, filters: Array}; export type CustomAnalyticsSeriesSpec = {key: string, label: string, metric: 'sum' | 'avg' | 'min' | 'max' | 'percentile', metricField: 'input_tokens' | 'output_tokens' | 'cost' | 'latency_ms' | 'prompt_version_number' | 'turn_count' | 'tool_call_count' | 'cached_tokens' | 'thinking_tokens', percentile?: (number | null) | undefined}; export type DerivedRatioInsightSpec = {type?: 'ratio' | undefined, label: string, numeratorSeriesKey: string, denominatorSeriesKey: string}; export type CustomAnalyticsSpec = {id: string, title?: (string | null) | undefined, chartType: 'bar' | 'line' | 'area', metric?: ('count' | 'sum' | 'avg' | 'min' | 'max' | 'percentile' | null) | undefined, metricField?: ('input_tokens' | 'output_tokens' | 'cost' | 'latency_ms' | 'prompt_version_number' | 'turn_count' | 'tool_call_count' | 'cached_tokens' | 'thinking_tokens' | null) | undefined, percentile?: (number | null) | undefined, series?: (Array | null) | undefined, derivedInsights?: (Array | null) | undefined, groupByField?: ('engine' | 'provider_type' | 'prompt_id' | 'prompt_version_number' | 'status' | 'error_type' | 'tags' | 'metadata_keys' | 'output_keys' | 'input_variable_keys' | 'tool_names' | null) | undefined, groupByMetadataKey?: (string | null) | undefined, timeSeries?: boolean | undefined, limit?: number | undefined}; export type RequestAnalyticsCustomAnalyticsQuery = {filter_group?: StructuredFilterGroup | undefined, q?: (string | null) | undefined, sort_by?: ('request_start_time' | 'input_tokens' | 'output_tokens' | 'cost' | 'latency_ms' | 'status' | null) | undefined, sort_order?: ('asc' | 'desc' | null) | undefined, customCharts: Array}; export type CreateApiApiPublicV2RequestsAnalyticsCustomAnalyticsArgs = {body: RequestAnalyticsCustomAnalyticsQuery}; export type CreateApiApiPublicV2RequestsAnalyticsCustomAnalyticsOptions = {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 }; /** * Request Analytics Custom Analytics * * POST /api/public/v2/requests/analytics/custom-analytics */ export const createApiApiPublicV2RequestsAnalyticsCustomAnalytics = async (args: CreateApiApiPublicV2RequestsAnalyticsCustomAnalyticsArgs, options: CreateApiApiPublicV2RequestsAnalyticsCustomAnalyticsOptions) => { 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/requests/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()) };