import {z} from 'zod' export type Function = {arguments: string, name: string} | {[key: string]: unknown}; export type ChatCompletionMessageFunctionToolCall = {id: string, function: Function, type: 'function'} | {[key: string]: unknown}; export type ChatCompletionRequestMessage = {role: 'system' | 'user' | 'assistant' | 'tool' | 'function' | 'developer', content?: (string | null) | undefined, tool_calls?: (Array | null) | undefined, tool_call_id?: (string | null) | undefined}; export type ApiTypesRequestsOpenaiRequestToolFunction = {name: string, description: string, parameters: {[key: string]: unknown}, required?: (Array | null) | undefined}; export type Tool = {type: string, function: ApiTypesRequestsOpenaiRequestToolFunction}; export type ToolChoiceName = {name: string}; export type ToolChoice = {type: string, function: ToolChoiceName}; export type CreateChatCompletionRequest = {messages: Array, model: string, metadata?: ({[key: string]: unknown} | null) | undefined, frequency_penalty?: (number | null) | undefined, logit_bias?: ({[key: string]: number} | null) | undefined, logprobs?: (boolean | null) | undefined, top_logprobs?: (number | null) | undefined, max_tokens?: (number | null) | undefined, max_completion_tokens?: (number | null) | undefined, modalities?: (Array | null) | undefined, n?: number | undefined, prediction: unknown, audio: unknown, presence_penalty?: (number | null) | undefined, response_format: unknown, seed?: (number | null) | undefined, service_tier?: (string | null) | undefined, stop?: (Array | string | null) | undefined, store?: (boolean | null) | undefined, stream?: (boolean | null) | undefined, stream_options: unknown, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, tools?: (Array<{[key: string]: unknown}> | Array | null) | undefined, tool_choice?: ('none' | 'auto' | 'required' | ToolChoice) | undefined, parallel_tool_calls?: (boolean | null) | undefined, user?: (string | null) | undefined, monitor_details?: (boolean | null) | undefined, policy_id?: (string | null) | undefined, function_call?: (string | {[key: string]: unknown} | null) | undefined, functions?: (Array | null) | undefined, moderate_before?: (boolean | null) | undefined}; export type CreateApiCygnalChatCompletionsArgs = {body: CreateChatCompletionRequest}; export type CreateApiCygnalChatCompletionsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const function = z.object({arguments: z.string(), name: z.string()}).and(z.record(z.string(), z.unknown())); export const chatCompletionMessageFunctionToolCall = z.object({id: z.string(), function: function, type: z.literal("function")}).and(z.record(z.string(), z.unknown())); export const chatCompletionResponseMessage = z.object({content: z.string().nullable().optional(), role: z.literal("assistant"), tool_calls: z.array(chatCompletionMessageFunctionToolCall).nullable().optional()}); export const chatCompletionChoice = z.object({finish_reason: z.enum(["stop", "length", "content_filter", "tool_calls", "violation"]), index: z.number().int(), message: chatCompletionResponseMessage, logprobs: z.string().nullable().optional()}); export const completionTokensDetails = z.object({accepted_prediction_tokens: z.number().int().nullable().optional(), audio_tokens: z.number().int().nullable().optional(), reasoning_tokens: z.number().int().nullable().optional(), rejected_prediction_tokens: z.number().int().nullable().optional()}).and(z.record(z.string(), z.unknown())); export const promptTokensDetails = z.object({audio_tokens: z.number().int().nullable().optional(), cached_tokens: z.number().int().nullable().optional()}).and(z.record(z.string(), z.unknown())); export const completionUsage = z.object({completion_tokens: z.number().int(), prompt_tokens: z.number().int(), total_tokens: z.number().int(), completion_tokens_details: completionTokensDetails.nullable().optional(), prompt_tokens_details: promptTokensDetails.nullable().optional()}).and(z.record(z.string(), z.unknown())); export const apiTypesResponsesOpenaiResponseCreateChatCompletionResponse = z.object({id: z.string(), choices: z.array(chatCompletionChoice), created: z.number().int(), model: z.string(), object: z.literal("chat.completion"), system_fingerprint: z.string().nullable().optional(), usage: completionUsage.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 Completions * * POST /cygnal/chat/completions */ export const createApiCygnalChatCompletions = async (args: CreateApiCygnalChatCompletionsArgs, options?: CreateApiCygnalChatCompletionsOptions) => { 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/chat/completions${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(apiTypesResponsesOpenaiResponseCreateChatCompletionResponse, await res.json()) };