import {z} from 'zod' export type RoutingStrategyWire = 'reliability' | 'balanced' | 'latency' | 'throughput' | 'cache'; export type ChatImageDetail = 'low' | 'high' | 'auto'; export type ImageUrl = {url: string, detail?: ChatImageDetail | undefined}; export type File = {filename?: (string | null) | undefined, file_data?: (string | null) | undefined, file_url?: (string | null) | undefined, file_id?: (string | null) | undefined}; export type InputAudioFormat = 'wav' | 'mp3' | 'aiff' | 'aac' | 'ogg' | 'flac' | 'm4a' | 'pcm16' | 'pcm24'; export type InputAudio = {data: string, format: InputAudioFormat}; export type ChatContentPart = {text: string, type: 'text'} | {image_url: ImageUrl, type: 'image_url'} | {file: File, type: 'file'} | {input_audio: InputAudio, type: 'input_audio'} | {refusal: string, type: 'refusal'}; export type ImageContentPart = {image_url: ImageUrl, signature?: (string | null) | undefined, format?: (string | null) | undefined, type: 'image_url'}; export type ReasoningDetailUnion = {id?: (string | null) | undefined, format?: (string | null) | undefined, index?: (number | null) | undefined, summary: string, type: 'reasoning.summary'} | {id?: (string | null) | undefined, format?: (string | null) | undefined, index?: (number | null) | undefined, data: string, type: 'reasoning.encrypted'} | {id?: (string | null) | undefined, format?: (string | null) | undefined, index?: (number | null) | undefined, text?: (string | null) | undefined, signature?: (string | null) | undefined, type: 'reasoning.text'}; export type ChatMessage = {role: string, content?: (Array | string | null) | undefined, images?: (Array | null) | undefined, reasoning_details?: (Array | null) | undefined, reasoning_content?: (string | null) | undefined, reasoning?: (string | null) | undefined, name?: (string | null) | undefined, tool_call_id?: (string | null) | undefined, tool_calls?: (Array | null) | undefined, function_call?: ({[key: string]: unknown} | null) | undefined}; export type FunctionDefinition = {name: string, description?: (string | null) | undefined, parameters?: ({[key: string]: unknown} | null) | undefined, strict?: (boolean | null) | undefined}; export type ChatTool = {function: FunctionDefinition, type: 'function'} | {type: 'custom'}; export type ChatToolChoice = {[key: string]: unknown} | string; export type JsonSchemaConfig = {name: string, description?: (string | null) | undefined, schema?: ({[key: string]: unknown} | null) | undefined, strict?: (boolean | null) | undefined}; export type WebSearchLocationType = 'approximate'; export type WebSearchLocation = {country?: (string | null) | undefined, region?: (string | null) | undefined, city?: (string | null) | undefined, timezone?: (string | null) | undefined}; export type ChatCompletions = {model: string, messages: Array, routing?: ({strategy: RoutingStrategyWire} | null) | undefined, models?: (Array | null) | undefined, tools?: (Array | null) | undefined, functions?: (Array | null) | undefined, tool_choice?: ChatToolChoice | undefined, response_format?: ({type: 'text'} | {type: 'json_object'} | {json_schema: JsonSchemaConfig, type: 'json_schema'} | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, stream?: (boolean | null) | undefined, stream_options?: ({include_usage?: boolean | undefined} | null) | undefined, stop?: (Array | string | null) | undefined, max_completion_tokens?: (number | null) | undefined, max_tokens?: (number | null) | undefined, reasoning_effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | null) | undefined, presence_penalty?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, parallel_tool_calls?: (boolean | null) | undefined, web_search_options?: ({search_context_size?: ('low' | 'medium' | 'high' | null) | undefined, user_location?: ({type?: WebSearchLocationType | undefined, approximate: WebSearchLocation} | null) | undefined} | null) | undefined}; export type CreateApiV1ChatCompletionsArgs = {'x-naga-routing-strategy'?: RoutingStrategyWire | undefined, body: ChatCompletions}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const chatToolCallFunction = z.object({name: z.string(), arguments: z.string()}); export const chatToolCall = z.object({id: z.string(), type: z.string(), function: chatToolCallFunction}); export const chatImageUrl = z.object({url: z.string()}); export const chatImageEntry = z.object({type: z.string(), image_url: chatImageUrl, signature: z.string().nullable().optional(), format: z.string().nullable().optional()}); export const chatUrlCitation = z.object({start_index: z.number().int(), end_index: z.number().int(), url: z.string(), title: z.string()}); export const chatAnnotation = z.object({type: z.string(), url_citation: chatUrlCitation}); export const chatResponseMessage = z.object({role: z.string(), content: z.string().nullable(), refusal: z.string().nullable(), reasoning_content: z.string().nullable().optional(), reasoning_details: z.array(z.unknown()).nullable().optional(), tool_calls: z.array(chatToolCall).nullable().optional(), images: z.array(chatImageEntry).nullable().optional(), annotations: z.array(chatAnnotation).nullable().optional()}); export const chatChoice = z.object({index: z.number().int(), message: chatResponseMessage, finish_reason: z.string(), logprobs: z.unknown()}); export const chatPromptTokensDetails = z.object({cached_tokens: z.number().int(), audio_tokens: z.number().int().nullable().optional()}); export const chatCompletionTokensDetails = z.object({reasoning_tokens: z.number().int(), image_tokens: z.number().int().nullable().optional()}); export const chatCompletionResponse = z.object({id: z.string(), object: z.string(), created: z.number().int(), model: z.string(), choices: z.array(chatChoice), usage: z.object({prompt_tokens: z.number().int(), completion_tokens: z.number().int(), total_tokens: z.number().int(), prompt_tokens_details: chatPromptTokensDetails, completion_tokens_details: chatCompletionTokensDetails}).nullable().optional()}); export const chatCompletionToolCallResponseType = z.literal("function"); export const chatCompletionFunctionCallResponse = z.object({name: z.string().nullable().optional(), arguments: z.string().optional()}); export const chatCompletionToolCallResponse = z.object({id: z.string().nullable().optional(), type: chatCompletionToolCallResponseType.optional(), function: chatCompletionFunctionCallResponse}); export const chatReasoningSummaryResponseType = z.literal("reasoning.summary"); export const chatReasoningEncryptedResponseType = z.literal("reasoning.encrypted"); export const chatReasoningTextResponseType = z.literal("reasoning.text"); export const chatReasoningDetailResponse = z.union([z.object({id: z.string().nullable().optional(), format: z.string().nullable().optional(), index: z.number().int().nullable().optional(), type: chatReasoningSummaryResponseType, summary: z.string()}), z.object({id: z.string().nullable().optional(), format: z.string().nullable().optional(), index: z.number().int().nullable().optional(), type: chatReasoningEncryptedResponseType, data: z.string()}), z.object({id: z.string().nullable().optional(), format: z.string().nullable().optional(), index: z.number().int().nullable().optional(), type: chatReasoningTextResponseType, text: z.string().nullable().optional(), signature: z.string().nullable().optional()})]); export const chatCompletionMessageResponse = z.object({role: z.string(), content: z.union([z.string(), z.array(z.unknown())]).nullable().optional(), refusal: z.string().nullable().optional(), tool_calls: z.array(chatCompletionToolCallResponse).nullable().optional(), annotations: z.array(z.unknown()).nullable().optional(), reasoning_content: z.string().nullable().optional(), reasoning_details: z.array(chatReasoningDetailResponse).nullable().optional(), images: z.array(z.unknown()).nullable().optional(), name: z.string().nullable().optional(), tool_call_id: z.string().nullable().optional()}); export const chatCompletionChoiceResponse = z.object({index: z.number().int().optional(), message: chatCompletionMessageResponse, finish_reason: z.string().nullable().optional(), logprobs: z.unknown()}); export const chatCompletionModelObject = z.literal("chat.completion"); export const chatCompletionModel = z.object({id: z.string(), created: z.number().int(), model: z.string(), choices: z.array(chatCompletionChoiceResponse).nullable(), usage: z.object({prompt_tokens: z.number().int(), completion_tokens: z.number().int(), total_tokens: z.number().int(), prompt_tokens_details: z.object({cached_tokens: z.number().int().nullable().optional()}).nullable().optional(), completion_tokens_details: z.object({image_tokens: z.number().int().nullable().optional()}).nullable().optional()}).nullable(), object: chatCompletionModelObject.optional()}); export const createApiV1ChatCompletionsResponse = z.union([chatCompletionResponse, chatCompletionModel]); 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 a chat completion * * POST /v1/chat/completions * * Also accepts auth: xApiKeyAuth */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "https://api.naga.ac", 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 (args['x-naga-routing-strategy'] != null) headers.set("x-naga-routing-strategy", String(args['x-naga-routing-strategy'])) 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(createApiV1ChatCompletionsResponse, await res.json()) };