import {z} from 'zod' export type Checkpoint = 'input' | 'output'; export type CheckContext = {checkpoint: Checkpoint, user_prompt?: (string | null) | undefined}; export type GuardrailImage = {search_store_id: string, file_id: string}; export type CheckRequest = {application_id?: (string | null) | undefined, check_type: Checkpoint, input: string, context?: (CheckContext | null) | undefined, images?: Array | undefined, unreferenced_image_count?: number | undefined, if_unconfigured?: ('error' | 'allow') | undefined}; export type CreateApiV1CheckArgs = {body: CheckRequest}; export type CreateApiV1CheckOptions = {baseUrl?: string | undefined, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const violation = z.object({category: z.string(), provider: z.string(), stage: z.string(), step: z.number().int(), reason: z.string().nullable().optional()}); export const guardrailAction = z.enum(["allow", "label", "block"]); export const checkpoint = z.enum(["input", "output"]); export const checkResponse = z.object({safe: z.boolean(), violations: z.array(violation), action: guardrailAction.optional(), evaluated: z.boolean().optional(), configured_checkpoints: z.array(checkpoint).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 }; /** * Post Check Endpoint * * POST /v1/check */ export const createApiV1Check = async (args: CreateApiV1CheckArgs, options?: CreateApiV1CheckOptions) => { const {baseUrl = "https://api.pharia.example.com", fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/check${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(checkResponse, await res.json()) };