import {z} from 'zod' export type ChatCompletionContentPartTextParam = {type: 'text', text: string}; export type ImageURL = {url: string, detail?: ('auto' | 'low' | 'high') | undefined}; export type ChatCompletionContentPartImageParam = {type: 'image_url', image_url: ImageURL}; export type InputAudio = {data: string, format: 'wav' | 'mp3'}; export type ChatCompletionContentPartInputAudioParam = {type: 'input_audio', input_audio: InputAudio}; export type Function = {arguments: string | {[key: string]: unknown}, name: string}; export type ChatCompletionMessageToolCallParam = {id: string, index?: number | undefined, function: Function, type: 'function'}; export type ChatCompletionMessage = {role: 'system' | 'user' | 'assistant' | 'tool', content?: (string | Array) | undefined, name?: string | undefined, tool_calls?: Array | undefined, tool_call_id?: string | undefined}; export type ResponseFormatText = {type: 'text'}; export type JsonSchema = {name: string, description?: string | undefined, schema: {[key: string]: unknown}, strict?: true | undefined}; export type ResponseFormatJson = {type: 'json_schema', json_schema: JsonSchema}; export type ResponseFormatJsonObject = {type: 'json_object'}; export type ResponseFormatGrammar = {type: 'grammar', grammar: string}; export type ResponseFormatStructuralTag = {type: 'structural_tag', structural_tag: string}; export type StreamOptions = {include_usage?: boolean | undefined, continuous_usage_stats?: boolean | undefined}; export type FunctionDefinition = {name: string, description?: string | undefined, parameters?: {[key: string]: unknown} | undefined, strict?: boolean | undefined}; export type ChatCompletionToolsParam = {type?: 'function' | undefined, function: FunctionDefinition}; export type ChatCompletionNamedFunction = {name: string}; export type ChatCompletionNamedToolChoiceParam = {function: ChatCompletionNamedFunction, type?: 'function' | undefined}; export type DisaggregatedParams = {request_type: string, first_gen_tokens?: Array | undefined, ctx_request_id?: number | undefined, opaque_state?: string | undefined, draft_tokens?: Array | undefined, multimodal_embedding_handles?: Array<{[key: string]: unknown}> | undefined, multimodal_hashes?: Array> | undefined}; export type ChatCompletionRequest = {messages: Array, model: string, frequency_penalty?: number | undefined, logit_bias?: {[key: string]: number} | undefined, logprobs?: boolean | undefined, top_logprobs?: number | undefined, max_tokens?: number | undefined, n?: number | undefined, presence_penalty?: number | undefined, response_format?: (ResponseFormatText | ResponseFormatJson | ResponseFormatJsonObject | ResponseFormatGrammar | ResponseFormatStructuralTag) | undefined, seed?: number | undefined, stop?: (string | Array) | undefined, stream?: boolean | undefined, stream_options?: StreamOptions | undefined, temperature?: number | undefined, top_p?: number | undefined, tools?: Array | undefined, tool_choice?: ('none' | 'required' | 'auto' | ChatCompletionNamedToolChoiceParam) | undefined, parallel_tool_calls?: boolean | undefined, user?: string | undefined, best_of?: number | undefined, top_k?: number | undefined, top_p_min?: number | undefined, min_p?: number | undefined, repetition_penalty?: number | undefined, length_penalty?: number | undefined, early_stopping?: boolean | undefined, bad?: (string | Array) | undefined, bad_token_ids?: Array | undefined, stop_token_ids?: Array | undefined, include_stop_str_in_output?: boolean | undefined, ignore_eos?: boolean | undefined, min_tokens?: number | undefined, skip_special_tokens?: boolean | undefined, spaces_between_special_tokens?: boolean | undefined, truncate_prompt_tokens?: number | undefined, echo?: boolean | undefined, add_generation_prompt?: boolean | undefined, add_special_tokens?: boolean | undefined, documents?: Array<{[key: string]: string}> | undefined, chat_template?: string | undefined, chat_template_args?: {[key: string]: unknown} | undefined, disaggregated_params?: DisaggregatedParams | undefined}; export type CreateApiV1ChatCompletionsArgs = {body: ChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl: string, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const functionCall = z.object({name: z.string().optional(), arguments: z.string()}); export const toolCall = z.object({index: z.number().int(), id: z.string().optional(), type: z.literal("function").optional(), function: functionCall}); export const deltaMessage = z.object({role: z.string().optional(), content: z.string().optional(), tool_calls: z.array(toolCall).optional()}); export const chatCompletionLogProb = z.object({token: z.string(), logprob: z.number().optional(), bytes: z.array(z.number().int()).optional()}); export const chatCompletionLogProbsContent = z.object({token: z.string(), logprob: z.number().optional(), bytes: z.array(z.number().int()).optional(), top_logprobs: z.array(chatCompletionLogProb).optional()}); export const chatCompletionLogProbs = z.object({content: z.array(chatCompletionLogProbsContent).optional()}); export const chatCompletionResponseStreamChoice = z.object({index: z.number().int(), delta: deltaMessage, logprobs: chatCompletionLogProbs.optional(), finish_reason: z.string().optional(), stop_reason: z.union([z.number().int(), z.string()]).optional()}); export const completionTokensDetails = z.object({accepted_prediction_tokens: z.number().int().optional(), audio_tokens: z.number().int().optional(), reasoning_tokens: z.number().int().optional(), rejected_prediction_tokens: z.number().int().optional()}); export const promptTokensDetails = z.object({audio_tokens: z.number().int().optional(), cached_tokens: z.number().int().optional()}); export const usageInfo = z.object({completion_tokens: z.number().int().optional(), prompt_tokens: z.number().int().optional(), total_tokens: z.number().int().optional(), completion_tokens_details: completionTokensDetails.optional(), prompt_tokens_details: promptTokensDetails.optional()}); export const chatCompletionResponse = 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.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 a chat completion * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options: CreateApiV1ChatCompletionsOptions) => { const {baseUrl, 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()) };