import {z} from 'zod' export type ChatCompletionRequestOpenAI = {allow_clarification_query?: boolean | undefined, generate_related_questions?: number | undefined, inline_citations?: boolean | undefined, messages: Array<{role: 'user' | 'assistant' | 'system', content: string}>, response_format?: string | undefined, stream?: boolean | undefined, verbosity?: string | undefined}; export type CreateApiAiOpenaiChatCompletionsArgs = {body: ChatCompletionRequestOpenAI}; export type CreateApiAiOpenaiChatCompletionsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const chatCompletionResponseChoiceOpenAI = z.object({finish_reason: z.string(), index: z.number().int(), message: z.object({role: z.string(), content: z.string()})}); export const chartSource = z.record(z.string(), z.unknown()); export const standardSource = z.record(z.string(), z.unknown()); export const createApiAiOpenaiChatCompletionsResponse = z.object({choices: z.array(chatCompletionResponseChoiceOpenAI), created: z.number().int(), id: z.string(), metadata: z.object({charts: z.array(chartSource).optional(), related_questions: z.array(z.string()).optional(), sources: z.array(standardSource).optional(), status: z.string(), trace_id: z.string()}).optional(), model: z.string(), object: z.string()}); 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 }; /** * Generate chat completions in OpenAI format * * POST /ai/openai/chat/completions */ export const createApiAiOpenaiChatCompletions = async (args: CreateApiAiOpenaiChatCompletionsArgs, options?: CreateApiAiOpenaiChatCompletionsOptions) => { const {baseUrl = "https://api.messari.io", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("X-Messari-API-Key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/ai/openai/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(createApiAiOpenaiChatCompletionsResponse, await res.json()) };