import {z} from 'zod' export type FilterCombinator = 'and' | 'or'; export type ContentSearchOperator = 'contains' | 'equals'; export type ContentSearchFilter = {path?: (string | null) | undefined, value: string, operator?: ContentSearchOperator | undefined}; export type ContentSearchFilterGroup = {combinator?: FilterCombinator | undefined, filters?: Array | undefined}; export type ScoreOperator = 'gt' | 'gte' | 'lt' | 'lte' | 'eq'; export type ScoreFilter = {evaluator_name: string, metric: string, operator: ScoreOperator, value: number | string}; export type ScoreFilterGroup = {combinator?: FilterCombinator | undefined, filters?: Array | undefined}; export type GoalStatus = 'passed' | 'failed' | 'not_evaluated'; export type GoalStatusFilter = {evaluator_name?: (string | null) | undefined, values: Array}; export type GoalStatusFilterGroup = {combinator?: FilterCombinator | undefined, filters?: Array | undefined}; export type RecordSortField = 'created_at'; export type SortDirection = 'asc' | 'desc'; export type FieldSortInput = {kind?: 'field' | undefined, field: RecordSortField, direction?: SortDirection | undefined}; export type NumericScoreMetric = 'avg' | 'min' | 'max' | 'std'; export type ScoreSortInput = {kind?: 'score' | undefined, evaluator_name: string, metric?: NumericScoreMetric | undefined, direction?: SortDirection | undefined}; export type EvaluationRunRecordFilterInput = {input_filters?: (ContentSearchFilterGroup | null) | undefined, output_filters?: (ContentSearchFilterGroup | null) | undefined, score_filters?: (ScoreFilterGroup | null) | undefined, goal_filters?: (GoalStatusFilterGroup | null) | undefined, sort?: (FieldSortInput | ScoreSortInput | null) | undefined}; export type CreateApiV1ObservabilityEvaluationRunsV2RunIdStatisticsComputeArgs = {run_id: string, body: EvaluationRunRecordFilterInput | null}; export type CreateApiV1ObservabilityEvaluationRunsV2RunIdStatisticsComputeOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const scalarStatisticValue = z.object({type: z.literal("scalar").optional(), id: z.string(), value: z.number().nullable().optional()}); export const numericStatistics = z.object({type: z.literal("numeric").optional(), values: z.array(scalarStatisticValue).nullable().optional(), sample_count: z.number().int().optional(), avg: z.number().nullable().optional(), min: z.number().nullable().optional(), max: z.number().nullable().optional(), std: z.number().nullable().optional(), count: z.number().int().optional()}); export const confusionMatrix = z.object({labels: z.array(z.string()), matrix: z.array(z.array(z.number().int()))}); export const categoricalStatistics = z.object({type: z.literal("categorical").optional(), frequencies: z.record(z.string(), z.number().int()), mode: z.array(z.string()), count: z.number().int(), values: z.array(scalarStatisticValue).nullable().optional(), excluded_count: z.number().int().optional(), confusion_matrix: confusionMatrix.nullable().optional()}); export const unsupportedStatistics = z.object({type: z.literal("unsupported").optional(), count: z.number().int()}); export const evaluatorStatistics = z.union([numericStatistics, categoricalStatistics, unsupportedStatistics]); export const goalResultItem = z.object({metric: z.string(), operator: z.string(), target: z.number().nullable().optional(), target_min: z.number().nullable().optional(), target_max: z.number().nullable().optional(), actual: z.number(), passed: z.boolean(), direction: z.enum(["higher_is_better", "lower_is_better"]).nullable().optional()}); export const goalResult = z.object({passed: z.boolean().nullable(), results: z.array(goalResultItem)}); export const runStatisticsResponse = z.object({run_id: z.string(), statistics: z.record(z.string(), evaluatorStatistics), goal_results: z.record(z.string(), goalResult).optional(), passed: z.boolean().nullable().optional()}); 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 }; /** * Compute statistics for a specific evaluation run with optional filters * * POST /v1/observability/evaluation-runs_v2/{run_id}/statistics/compute */ export const createApiV1ObservabilityEvaluationRunsV2RunIdStatisticsCompute = async (args: CreateApiV1ObservabilityEvaluationRunsV2RunIdStatisticsComputeArgs, options?: CreateApiV1ObservabilityEvaluationRunsV2RunIdStatisticsComputeOptions) => { const {baseUrl = "https://api.mistral.ai", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Bearer ${ApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/observability/evaluation-runs_v2/${encodeURIComponent(String(args.run_id))}/statistics/compute${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(runStatisticsResponse, await res.json()) };