import {z} from 'zod' export type JsonValue = unknown; export type NoulCriteria = {true?: (string | null) | undefined, false?: (string | null) | undefined}; export type NoulQuestion = {type: 'noul', instructions?: (string | null) | undefined, criteria?: (NoulCriteria | null) | undefined}; export type ChoiceQuestion = {type: 'choice', instructions?: (string | null) | undefined, criteria: {[key: string]: string | null}}; export type ScoreQuestion = {type: 'score', instructions?: (string | null) | undefined, criteria: Array}; export type SystemOneRequest = {state: JsonValue, questions: {[key: string]: NoulQuestion | ChoiceQuestion | ScoreQuestion}}; export type CreateApiV1SystemoneArgs = {body: SystemOneRequest}; export type CreateApiV1SystemoneOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const noulAnswer = z.object({type: z.literal("noul").optional(), noul: z.number()}); export const choiceAnswer = z.object({type: z.literal("choice").optional(), choice: z.string(), confidence: z.number(), probabilities: z.record(z.string(), z.number())}); export const scoreAnswer = z.object({type: z.literal("score").optional(), score: z.number(), legend: z.array(z.string()), probabilities: z.record(z.string(), z.number()), confidence: z.number()}); export const systemOneUsage = z.object({input_tokens: z.number().int().nullable(), output_tokens: z.number().int().nullable()}); export const systemOneResponse = z.object({model: z.string(), answers: z.record(z.string(), z.discriminatedUnion("type", [noulAnswer, choiceAnswer, scoreAnswer])), usage: systemOneUsage, evaluation_time_ms: z.number(), request_id: z.string().nullable()}); 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 }; /** * evaluate_systemone * * POST /v1/systemone */ export const createApiV1Systemone = async (args: CreateApiV1SystemoneArgs, options: CreateApiV1SystemoneOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (APIKeyHeader !== undefined) headers.set("X-API-Key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/systemone${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(systemOneResponse, await res.json()) };