import {z} from 'zod' export type JSONPrimitive = string | number | number | boolean | null; export type JSONValueInput = JSONPrimitive | Array | {[key: string]: JSONValueInput}; export type Conversation = {id: string}; export type Prompt = {id: string, variables?: ({[key: string]: unknown} | null) | undefined, version?: (string | null) | undefined}; export type ResponsesToolChoice = 'none' | 'auto' | 'required' | {[key: string]: JSONValueInput}; export type CreateResponseRequest = {background?: boolean | undefined, context_management?: (Array<{[key: string]: JSONValueInput}> | null) | undefined, conversation?: (string | Conversation | null) | undefined, include?: (Array | null) | undefined, input?: (string | Array | null) | undefined, instructions?: (string | null) | undefined, max_output_tokens?: (number | null) | undefined, max_tool_calls?: (number | null) | undefined, metadata?: ({[key: string]: unknown} | null) | undefined, model?: (string | null) | undefined, moderation?: ({[key: string]: JSONValueInput} | null) | undefined, parallel_tool_calls?: (boolean | null) | undefined, previous_response_id?: (string | null) | undefined, prompt?: (Prompt | null) | undefined, prompt_cache_key?: (string | null) | undefined, prompt_cache_options?: ({[key: string]: JSONValueInput} | null) | undefined, prompt_cache_retention?: ('in_memory' | 'in-memory' | '24h' | null) | undefined, reasoning?: ({[key: string]: unknown} | null) | undefined, safety_identifier?: (string | null) | undefined, service_tier?: ('auto' | 'default' | 'flex' | 'scale' | 'priority' | null) | undefined, store?: (boolean | null) | undefined, stream?: (boolean | null) | undefined, stream_options: unknown, temperature?: (number | null) | undefined, text: unknown, tool_choice?: ResponsesToolChoice | undefined, tools?: (Array | null) | undefined, top_logprobs?: (number | null) | undefined, top_p?: (number | null) | undefined, truncation?: ('auto' | 'disabled' | null) | undefined, user?: (string | null) | undefined, monitor_details?: (boolean | null) | undefined, policy_id?: (string | null) | undefined}; export type CreateApiCygnalResponsesArgs = {body: CreateResponseRequest}; export type CreateApiCygnalResponsesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const jSONPrimitive = z.union([z.string(), z.number().int(), z.number(), z.boolean()]).nullable(); export const jSONValueOutput: z.ZodType = z.union([jSONPrimitive, z.array(z.lazy(() => jSONValueOutput)), z.record(z.string(), z.lazy(() => jSONValueOutput))]); export const responseMessage = z.object({role: z.string().nullable().optional(), content: z.string().nullable().optional()}).and(z.record(z.string(), z.unknown())); export const responseChoice = z.object({index: z.number().int().nullable().optional(), finish_reason: z.string().nullable().optional(), message: responseMessage.nullable().optional()}).and(z.record(z.string(), z.unknown())); export const responseUsage = z.object({prompt_tokens: z.number().int().nullable().optional(), completion_tokens: z.number().int().nullable().optional(), total_tokens: z.number().int().nullable().optional(), input_tokens: z.number().int().nullable().optional(), output_tokens: z.number().int().nullable().optional()}).and(z.record(z.string(), z.unknown())); export const responseError = z.object({message: z.string().nullable().optional(), type: z.string().nullable().optional(), code: z.string().nullable().optional(), param: z.string().nullable().optional()}).and(z.record(z.string(), z.unknown())); export const responsesEndpointResponse = z.object({id: z.string().nullable().optional(), object: z.string().nullable().optional(), model: z.string().nullable().optional(), output: z.array(jSONValueOutput).nullable().optional(), choices: z.array(responseChoice).nullable().optional(), usage: responseUsage.nullable().optional(), error: responseError.nullable().optional()}).and(z.record(z.string(), z.unknown())); 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 }; /** * Cygnal Responses * * POST /cygnal/responses */ export const createApiCygnalResponses = async (args: CreateApiCygnalResponsesArgs, options?: CreateApiCygnalResponsesOptions) => { const {baseUrl = "https://api.grayswan.ai", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/cygnal/responses${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(responsesEndpointResponse, await res.json()) };