import {z} from 'zod' export type JsonValue = string; export type NoulQuestion = {type: 'noul', instructions?: (string | Record | Array | number | boolean | null) | undefined, criteria?: ({true?: (string | null) | undefined, false?: (string | null) | undefined}) | undefined}; export type ChoiceQuestion = {type: 'choice', instructions?: (string | Record | Array | number | boolean | null) | undefined, criteria: {[key: string]: string | null}}; export type ScoreQuestion = {type: 'score', instructions?: (string | Record | Array | number | boolean | null) | undefined, criteria: Array}; export type Question = NoulQuestion | ChoiceQuestion | ScoreQuestion; export type SystemOneRequest = {state: JsonValue, questions: {[key: string]: Question}, model?: string | undefined, images?: (Array) | undefined}; export type CreateApiV1SystemoneArgs = {'X-Nace-Legend'?: ('array' | 'object') | undefined, body: SystemOneRequest}; export type CreateApiV1SystemoneOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const noulAnswer = z.object({type: z.literal("noul"), noul: z.number().gte(0).lte(1), confidence: z.number().gte(0.5).lte(1)}); export const choiceAnswer = z.object({type: z.literal("choice"), choice: z.string(), confidence: z.number(), probabilities: z.record(z.string(), z.number())}); export const scoreAnswer = z.object({type: z.literal("score"), score: z.number(), legend: z.union([z.array(z.string()), z.record(z.string(), z.string())]), probabilities: z.record(z.string(), z.number()), confidence: z.number()}); export const answer = z.discriminatedUnion("type", [noulAnswer, choiceAnswer, scoreAnswer]); export const requestId = z.string(); export const systemOneResponse = z.object({model: z.enum(["drex-v1.5", "drex-v2.0", "drex-max", "drex-max-v1.1", "drex-max-finance"]), answers: z.record(z.string(), answer), usage: z.object({input_tokens: z.number().int().gte(0), output_tokens: z.number().int().gte(0), image_tokens: z.number().int().gte(0).optional()}), evaluation_time_ms: z.number(), request_id: requestId}); 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 questions * * POST /v1/systemone */ export const createApiV1Systemone = async (args: CreateApiV1SystemoneArgs, options?: CreateApiV1SystemoneOptions) => { const {baseUrl = "https://console.nace.ai", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Nace-Legend'] != null) headers.set("X-Nace-Legend", String(args['X-Nace-Legend'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) 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()) };