import {z} from 'zod' export type CreateApiCygnalV1MessagesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const contentBlockOutput = z.object({type: z.literal("text"), text: z.string()}); 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 toolUseBlock = z.object({type: z.literal("tool_use"), id: z.string(), name: z.string(), input: z.record(z.string(), jSONValueOutput)}); export const anthropicUsage = z.object({input_tokens: z.number().int(), output_tokens: z.number().int()}); export const apiTypesResponsesAnthropicResponseCreateChatCompletionResponse = z.object({id: z.string(), type: z.literal("message"), role: z.literal("assistant"), content: z.array(z.union([contentBlockOutput, toolUseBlock])), model: z.string(), stop_reason: z.enum(["end_turn", "max_tokens", "stop_sequence", "tool_use", "content_filter"]).nullable().optional(), usage: anthropicUsage.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 }; /** * Cygnal Anthropic Messages * * POST /cygnal/v1/messages */ export const createApiCygnalV1Messages = async (options?: CreateApiCygnalV1MessagesOptions) => { const {baseUrl = "https://api.grayswan.ai", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/cygnal/v1/messages${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(apiTypesResponsesAnthropicResponseCreateChatCompletionResponse, await res.json()) };