import {z} from 'zod' export type Role = 'assistant' | 'user' | 'system' | 'tool' | 'function'; export type NIMVLMChatCompletionContentPartImage = {image: string, type: 'image'}; export type NIMVLMChatCompletionContentPartText = {text: string, type: 'text'}; export type NIMVLMChatCompletionContentPartVideo = {video?: string | undefined, start_offset?: (number | null) | undefined, duration?: (number | null) | undefined, type?: 'video' | undefined} | {[key: string]: unknown}; export type NIMVLMChatCompletionContentPartVideoStreaming = {video_url?: unknown, connect_timeout?: (number | null) | undefined, duration?: number | undefined, fps?: (number | null) | undefined, type?: 'rtsp' | undefined}; export type FunctionCall = {name?: (string | null) | undefined, arguments?: (string | null) | undefined}; export type ToolCall = {index?: (number | null) | undefined, id?: string | undefined, type?: 'function' | undefined, function: FunctionCall}; export type NIMLLMChatCompletionMessage = {role: Role, content: string | Array, tool_call_id?: (string | null) | undefined, name?: (string | null) | undefined, tool_calls?: (Array | null) | undefined}; export type ResponseFormat = {type: 'text' | 'json_object'}; export type StreamOptions = {include_usage?: (boolean | null) | undefined, continuous_usage_stats?: (boolean | null) | undefined}; export type FunctionDefinition = {name: string, description?: (string | null) | undefined, parameters?: (Record | null) | undefined}; export type ChatCompletionToolsParam = {type?: 'function' | undefined, function: FunctionDefinition}; export type ChatCompletionNamedFunction = {name: string}; export type ChatCompletionNamedToolChoiceParam = {function: ChatCompletionNamedFunction, type?: 'function' | undefined}; export type BaseModel = Record; export type NVExt = {ignore_eos?: (boolean | null) | undefined, repetition_penalty?: (number | null) | undefined, top_k?: number | undefined, guided_choice?: (Array | null) | undefined, guided_json?: (string | Record | BaseModel | null) | undefined, guided_regex?: (string | null) | undefined, guided_grammar?: (string | null) | undefined}; export type NIMLLMChatCompletionRequest = {messages: Array, model: string, frequency_penalty?: (number | null) | undefined, logit_bias?: ({[key: string]: number} | null) | undefined, logprobs?: (boolean | null) | undefined, top_logprobs?: (number | null) | undefined, max_tokens?: (number | null) | undefined, n?: (number | null) | undefined, presence_penalty?: (number | null) | undefined, response_format?: (ResponseFormat | null) | undefined, seed?: (number | null) | undefined, stop?: (string | Array | null) | undefined, stream?: (boolean | null) | undefined, stream_options?: (StreamOptions | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, tools?: (Array | null) | undefined, tool_choice?: ('none' | 'auto' | 'required' | ChatCompletionNamedToolChoiceParam | null) | undefined, parallel_tool_calls?: (boolean | null) | undefined, user?: (string | null) | undefined, min_p?: number | undefined, prompt_logprobs?: (number | null) | undefined, echo?: (boolean | null) | undefined, add_special_tokens?: boolean | undefined, documents?: (Array<{[key: string]: string}> | null) | undefined, chat_template?: (string | null) | undefined, chat_template_kwargs?: (Record | null) | undefined, guided_whitespace_pattern?: (string | null) | undefined, image?: (string | null) | undefined, nvext?: (NVExt | null) | undefined, num_frames_per_inference?: (number | null) | undefined, media_response_type?: ('none' | 'image' | 'video' | null) | undefined}; export type CreateApiV1ChatCompletionsArgs = {'content-type'?: (string | null) | undefined, body: NIMLLMChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const functionCall = z.object({name: z.string().nullable().optional(), arguments: z.string().nullable().optional()}); export const toolCall = z.object({index: z.number().int().nullable().optional(), id: z.string().optional(), type: z.literal("function").optional(), function: functionCall}); export const chatMessage = z.object({role: z.string(), content: z.string().nullable().optional(), tool_calls: z.array(toolCall).nullable().optional()}); export const chatCompletionLogProb = z.object({token: z.string(), logprob: z.number().optional(), bytes: z.array(z.number().int()).nullable().optional()}); export const chatCompletionLogProbsContent = z.object({token: z.string(), logprob: z.number().optional(), bytes: z.array(z.number().int()).nullable().optional(), top_logprobs: z.array(chatCompletionLogProb).optional()}); export const chatCompletionLogProbs = z.object({content: z.array(chatCompletionLogProbsContent).nullable().optional()}); export const chatCompletionResponseChoice = z.object({index: z.number().int(), message: chatMessage, logprobs: chatCompletionLogProbs.nullable().optional(), finish_reason: z.enum(["stop", "length", "tool_calls"]).nullable().optional(), stop_reason: z.union([z.number().int(), z.string()]).nullable().optional()}); export const usageInfo = z.object({prompt_tokens: z.number().int().optional(), total_tokens: z.number().int().optional(), completion_tokens: z.number().int().nullable().optional()}); export const logprob = z.object({logprob: z.number(), rank: z.number().int().nullable().optional(), decoded_token: z.string().nullable().optional()}); export const nIMLLMMediaObject = z.object({type: z.string(), b64_json: z.string().nullable().optional(), url: z.string().nullable().optional(), revised_prompt: z.string().nullable().optional()}); export const nIMLLMChatCompletionResponse = z.object({id: z.string().optional(), object: z.literal("chat.completion").optional(), created: z.number().int().optional(), model: z.string(), choices: z.array(chatCompletionResponseChoice), usage: usageInfo, prompt_logprobs: z.array(z.record(z.string(), logprob).nullable()).nullable().optional(), data: z.array(nIMLLMMediaObject).nullable().optional()}); export const deltaMessage = z.object({role: z.string().nullable().optional(), content: z.string().nullable().optional(), tool_calls: z.array(toolCall).nullable().optional()}); export const chatCompletionResponseStreamChoice = z.object({index: z.number().int(), delta: deltaMessage, logprobs: chatCompletionLogProbs.nullable().optional(), finish_reason: z.enum(["stop", "length", "tool_calls"]).nullable().optional(), stop_reason: z.union([z.number().int(), z.string()]).nullable().optional()}); export const nIMLLMChatCompletionStreamResponse = z.object({id: z.string().optional(), object: z.literal("chat.completion.chunk").optional(), created: z.number().int().optional(), model: z.string(), choices: z.array(chatCompletionResponseStreamChoice), usage: usageInfo.nullable().optional(), data: z.array(nIMLLMMediaObject).nullable().optional()}); export const createApiV1ChatCompletionsResponse = z.union([nIMLLMChatCompletionResponse, nIMLLMChatCompletionStreamResponse]); 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 }; /** * OpenAI-compatible chat endpoint * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options: CreateApiV1ChatCompletionsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['content-type'] != null) headers.set("content-type", String(args['content-type'])) 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()) };