import {z} from 'zod' export type ChatCompletionRequest = {message: string, file_ids?: Array | undefined, playbook_ids?: Array | undefined, playbook_id?: string | undefined, skill_ids?: Array | undefined, blocked_tools?: Array | undefined, auto_accept?: boolean | undefined, chat_id?: string | undefined, project_id?: string | undefined, materialize?: boolean | undefined, company_id?: string | undefined, vault_id?: string | undefined}; export type CreateApiChatCompletionsArgs = {wait?: (number | null) | undefined, Prefer?: string | undefined, body: ChatCompletionRequest}; export type CreateApiChatCompletionsOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const apiDocument = z.object({file_id: z.string(), original_file_id: z.string().optional(), filename: z.string(), original_filename: z.string().optional(), signed_url: z.string(), download_url: z.string()}); export const apiEmail = z.object({to: z.string(), cc: z.string().optional(), bcc: z.string().optional(), subject: z.string(), body: z.string(), plaintext_body: z.string()}); export const apiDiagram = z.object({title: z.string(), diagram_type: z.string(), mermaid: z.string()}); export const chatCompletionResult = z.object({result: z.string(), chat_id: z.string(), chat_url: z.string().optional(), documents: z.array(apiDocument).optional(), emails: z.array(apiEmail).optional(), diagrams: z.array(apiDiagram).optional(), judge_approved_steps: z.array(z.string()).optional(), skipped_steps: z.array(z.string()).optional()}).nullable(); export const chatCompletionResponse = z.object({job_id: z.string(), kind: z.literal("chat/completions"), status: z.enum(["pending", "running", "succeeded", "failed", "canceled"]), result: chatCompletionResult, error: z.object({code: z.string(), message: z.string()}).nullable(), created_at: z.string(), completed_at: z.string().nullable()}); 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 }; /** * Create chat completion * * POST /chat/completions */ export const createApiChatCompletions = async (args: CreateApiChatCompletionsArgs, options?: CreateApiChatCompletionsOptions) => { const {baseUrl = "https://app.gc.ai/api/external/v1", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.wait != null) query.append("wait", String(args.wait)) if (args.Prefer != null) headers.set("Prefer", String(args.Prefer)) if (ApiKeyAuth !== undefined) headers.set("Authorization", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/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(chatCompletionResponse, await res.json()) };