import {z} from 'zod' export type MessageContentPartImageUrl = {detail?: (string | null) | undefined, url: string}; export type MessageContentPart = {text: string, type: string} | {image_url: MessageContentPartImageUrl, type: string}; export type MessageContent = string | Array; export type ToolCallFunction = {arguments: string, name: string}; export type ToolCall = {function: ToolCallFunction, id: string, type: string}; export type ChatCompletionMessage = {content?: (MessageContent | null) | undefined, name?: (string | null) | undefined, role: 'system'} | {content?: (MessageContent | null) | undefined, name?: (string | null) | undefined, role: 'user'} | {content?: (MessageContent | null) | undefined, name?: (string | null) | undefined, refusal?: (string | null) | undefined, role: 'assistant', tool_calls?: Array | undefined} | {content?: (MessageContent | null) | undefined, role: 'tool', tool_call_id?: string | undefined}; export type JsonSchemaResponseFormat = {description?: (string | null) | undefined, name: string, schema: unknown, strict?: (boolean | null) | undefined}; export type ResponseFormatType = 'text' | 'json_object' | 'json_schema'; export type ResponseFormat = {json_schema?: (JsonSchemaResponseFormat | null) | undefined, type: ResponseFormatType}; export type StreamOptions = {include_usage?: (boolean | null) | undefined}; export type ToolChoiceLiteral = 'none' | 'auto'; export type ChatCompletionNamedFunction = {name: string}; export type ChatCompletionNamedToolChoiceParam = {function: ChatCompletionNamedFunction, type: string}; export type ToolChoice = ToolChoiceLiteral | ChatCompletionNamedToolChoiceParam; export type ChatCompletionToolFunctionParam = {description?: (string | null) | undefined, name: string, parameters?: ({[key: string]: unknown} | null) | undefined, strict?: (boolean | null) | undefined}; export type ChatCompletionToolsParam = {function: ChatCompletionToolFunctionParam, type: string}; export type CreateChatCompletionRequest = {frequency_penalty?: (number | null) | undefined, function_call: unknown, functions?: (Array | null) | undefined, logit_bias?: ({[key: string]: number} | null) | undefined, max_completion_tokens?: (number | null) | undefined, max_tokens?: (number | null) | undefined, messages: Array, model: string, n?: (number | null) | undefined, parallel_tool_calls?: (boolean | null) | undefined, presence_penalty?: (number | null) | undefined, response_format?: (ResponseFormat | null) | undefined, seed?: (number | null) | undefined, service_tier?: (string | null) | undefined, stop?: (Array | null) | undefined, stream?: (boolean | null) | undefined, stream_options?: (StreamOptions | null) | undefined, temperature?: (number | null) | undefined, tool_choice?: (ToolChoice | null) | undefined, tools?: (Array | null) | undefined, top_logprobs?: (number | null) | undefined, top_p?: (number | null) | undefined, user?: (string | null) | undefined}; export type CreateApiV1ChatCompletionsArgs = {body: CreateChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const chatCompletionLogProb = z.object({bytes: z.array(z.number().int()).nullable().optional(), logprob: z.number(), token: z.string()}); export const chatCompletionLogProbsContent = z.object({top_logprobs: z.array(chatCompletionLogProb)}); export const chatCompletionLogProbs = z.object({content: z.array(chatCompletionLogProbsContent).nullable().optional()}); export const messageContentPartImageUrl = z.object({detail: z.string().nullable().optional(), url: z.string()}); export const messageContentPart = z.union([z.object({text: z.string(), type: z.string()}), z.object({image_url: messageContentPartImageUrl, type: z.string()})]); export const messageContent = z.union([z.string(), z.array(messageContentPart)]); export const toolCallFunction = z.object({arguments: z.string(), name: z.string()}); export const toolCall = z.object({function: toolCallFunction, id: z.string(), type: z.string()}); export const chatCompletionMessage = z.union([z.object({content: messageContent.nullable().optional(), name: z.string().nullable().optional(), role: z.literal("system")}), z.object({content: messageContent.nullable().optional(), name: z.string().nullable().optional(), role: z.literal("user")}), z.object({content: messageContent.nullable().optional(), name: z.string().nullable().optional(), refusal: z.string().nullable().optional(), role: z.literal("assistant"), tool_calls: z.array(toolCall).optional()}), z.object({content: messageContent.nullable().optional(), role: z.literal("tool"), tool_call_id: z.string().optional()})]); export const chatCompletionChoice = z.object({finish_reason: z.string().nullable().optional(), index: z.number().int(), logprobs: chatCompletionLogProbs.nullable().optional(), message: chatCompletionMessage}); export const promptTokensDetails = z.object({audio_tokens: z.number().int().gte(0), cached_tokens: z.number().int().gte(0)}); export const completionUsage = z.object({completion_tokens: z.number().int(), prompt_tokens: z.number().int(), prompt_tokens_details: promptTokensDetails.nullable().optional(), total_tokens: z.number().int()}); export const chatCompletionResponse = z.object({choices: z.array(chatCompletionChoice), created: z.number().int(), id: z.string(), model: z.string(), object: z.string(), service_tier: z.string().nullable().optional(), 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 }; /** * Create chat completions * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "https://api.atoma.network", 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(chatCompletionResponse, await res.json()) };