import {z} from 'zod' export type ChatCompletionCachedContent = {type: 'ephemeral', ttl?: ('5m' | '1h') | undefined}; export type ChatCompletionTextObject = {type: 'text', text: string, cache_control?: ChatCompletionCachedContent | undefined}; export type ChatCompletionImageUrlObject = {url: string, detail?: string | undefined, format?: string | undefined}; export type ChatCompletionImageObject = {type: 'image_url', image_url: string | ChatCompletionImageUrlObject}; export type InputAudio = {data: string, format: 'wav' | 'mp3'}; export type ChatCompletionAudioObject = {input_audio: InputAudio, type: 'input_audio'}; export type DocumentObject = {type: 'text', media_type: string, data: string}; export type CitationsObject = {enabled: boolean}; export type ChatCompletionDocumentObject = {type: 'document', source: DocumentObject, title: string, context: string, citations: CitationsObject | null}; export type ChatCompletionVideoUrlObject = {url: string, detail?: string | undefined}; export type ChatCompletionVideoObject = {type: 'video_url', video_url: string | ChatCompletionVideoUrlObject}; export type ChatCompletionFileObjectFile = {file_data?: string | undefined, file_id?: string | undefined, filename?: string | undefined, format?: string | undefined, detail?: string | undefined, video_metadata?: {[key: string]: unknown} | undefined}; export type ChatCompletionFileObject = {type: 'file', file: ChatCompletionFileObjectFile}; export type ChatCompletionUserMessage = {role: 'user', content: string | Array, cache_control?: ChatCompletionCachedContent | undefined}; export type ChatCompletionThinkingBlock = {type: 'thinking', thinking?: string | undefined, signature?: (string | null) | undefined, cache_control?: ({[key: string]: unknown} | ChatCompletionCachedContent | null) | undefined}; export type ChatCompletionRedactedThinkingBlock = {type: 'redacted_thinking', data?: string | undefined, cache_control?: ({[key: string]: unknown} | ChatCompletionCachedContent | null) | undefined}; export type ChatCompletionToolCallFunctionChunk = {name?: (string | null) | undefined, arguments?: string | undefined, provider_specific_fields?: ({[key: string]: unknown} | null) | undefined}; export type ChatCompletionAssistantToolCall = {id: string | null, type: 'function', function: ChatCompletionToolCallFunctionChunk}; export type ChatCompletionReasoningSummaryTextBlock = {type: 'summary_text', text?: string | undefined}; export type ChatCompletionReasoningItem = {type: 'reasoning', id?: string | undefined, encrypted_content?: (string | null) | undefined, summary?: Array | undefined}; export type ChatCompletionAssistantMessage = {role: 'assistant', content?: (string | Array | null) | undefined, name?: (string | null) | undefined, tool_calls?: (Array | null) | undefined, function_call?: (ChatCompletionToolCallFunctionChunk | null) | undefined, reasoning_content?: (string | null) | undefined, cache_control?: ChatCompletionCachedContent | undefined, thinking_blocks?: (Array | null) | undefined, reasoning_items?: (Array | null) | undefined}; export type ChatCompletionToolReferenceObject = {type: 'tool_reference', tool_name: string}; export type ChatCompletionToolMessage = {role: 'tool', content: string | Array, tool_call_id: string}; export type ChatCompletionSystemMessage = {role: 'system', content: string | Array, name?: string | undefined, cache_control?: ChatCompletionCachedContent | undefined}; export type ChatCompletionFunctionMessage = {role: 'function', content: string | Array | null, name: string, tool_call_id: string | null}; export type ChatCompletionDeveloperMessage = {role: 'developer', content: string | Array, name?: string | undefined, cache_control?: ChatCompletionCachedContent | undefined}; export type CreateApiChatCompletionsArgs = {body: {model: string, messages: Array, 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?: ({[key: string]: unknown} | null) | undefined, seed?: (number | null) | undefined, service_tier?: (string | null) | undefined, stop?: (string | Array | null) | undefined, stream_options?: ({[key: string]: unknown} | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, tools?: (Array<{[key: string]: unknown}> | null) | undefined, tool_choice?: (string | {[key: string]: unknown} | null) | undefined, parallel_tool_calls?: (boolean | null) | undefined, function_call?: (string | {[key: string]: unknown} | null) | undefined, functions?: (Array<{[key: string]: unknown}> | null) | undefined, user?: (string | null) | undefined, stream?: (boolean | null) | undefined, metadata?: ({[key: string]: unknown} | null) | undefined, guardrails?: (Array | null) | undefined, caching?: (boolean | null) | undefined, num_retries?: (number | null) | undefined, context_window_fallback_dict?: ({[key: string]: string} | null) | undefined, fallbacks?: (Array | null) | undefined}}; export type CreateApiChatCompletionsOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiChatCompletionsResponse = z.unknown(); 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 }; /** * Chat Completion * * POST /chat/completions */ export const createApiChatCompletions = async (args: CreateApiChatCompletionsArgs, options: CreateApiChatCompletionsOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (APIKeyHeader !== undefined) headers.set("x-litellm-api-key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/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(createApiChatCompletionsResponse, await res.json()) };