import {z} from 'zod' export type ContentPart = {type: 'text' | 'image_url', text?: string | undefined, image_url?: ({url?: string | undefined}) | undefined}; export type ChatMessage = {role: 'system' | 'user' | 'assistant', content: string | Array}; export type ChatRequest = {messages: Array, model?: string | undefined, stream?: boolean | undefined, temperature?: number | undefined, max_tokens?: number | undefined}; export type CreateApiV1ChatCompletionsArgs = {body: ChatRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const chatResponse = z.object({id: z.string().optional(), object: z.literal("chat.completion").optional(), created: z.number().int().optional(), model: z.string().optional(), choices: z.array(z.object({index: z.number().int().optional(), message: z.object({role: z.literal("assistant").optional(), content: z.string().optional()}).optional(), finish_reason: z.literal("stop").optional()})).optional(), usage: z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional()}).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 }; /** * Chat (POST) * * POST /v1/chat/completions * * Also accepts auth: ApiKeyHeader, ApiKeyQuery */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "https://search.elixpo.com", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/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(chatResponse, await res.json()) };