import {z} from 'zod' export type ChatMessage = {role: string, content: string, name?: (string | null) | undefined, tool_calls?: (Array<{[key: string]: unknown}> | null) | undefined}; export type ChatCompletionRequest = {model: string, messages: Array, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, n?: (number | null) | undefined, stream?: (boolean | null) | undefined, stop?: (string | Array | null) | undefined, max_tokens?: (number | null) | undefined, presence_penalty?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, logit_bias?: ({[key: string]: number} | null) | undefined, user?: (string | null) | undefined}; export type CreateApiApiV1ArbitersChatCompletionsArgs = {authorization?: (string | null) | undefined, modaic_session?: (string | null) | undefined, body: ChatCompletionRequest}; export type CreateApiApiV1ArbitersChatCompletionsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const chatMessage = z.object({role: z.string(), content: z.string(), name: z.string().nullable().optional(), tool_calls: z.array(z.record(z.string(), z.unknown())).nullable().optional()}); export const chatCompletionChoice = z.object({index: z.number().int(), message: chatMessage, finish_reason: z.string().nullable().optional()}); export const completionUsage = z.object({prompt_tokens: z.number().int().nullable(), completion_tokens: z.number().int().nullable(), total_tokens: z.number().int().nullable()}); export const chatCompletionResponse = z.object({id: z.string().optional(), object: z.string().optional(), created: z.number().int().optional(), model: z.string(), choices: z.array(chatCompletionChoice), usage: completionUsage, system_fingerprint: z.string().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 }; /** * Create Chat Completion * * POST /api/v1/arbiters/chat/completions */ export const createApiApiV1ArbitersChatCompletions = async (args: CreateApiApiV1ArbitersChatCompletionsArgs, options: CreateApiApiV1ArbitersChatCompletionsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() const cookies: string[] = [] headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.authorization != null) headers.set("authorization", String(args.authorization)) if (args.modaic_session != null) cookies.push("modaic_session=" + encodeURIComponent(String(args.modaic_session))) if (cookies.length > 0) headers.set('cookie', cookies.join('; ')) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/arbiters/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()) };