import {z} from 'zod' export type ChatCompletionSystemMessageParam = {content: string | Array<{type: 'text' | 'image_url', text?: string | undefined, image_url?: string | undefined}>, role: 'system' | 'user' | 'assistant' | 'tool'}; export type FunctionDefinition = {name: string, description?: string | undefined, parameters?: {[key: string]: unknown} | undefined}; export type ChatCompletionToolParam = {type: 'function', function: FunctionDefinition}; export type BucketIds = {bucket_ids: Array, max_num_results?: number | undefined}; export type Retrieval = {type: 'retrieval', retrieval: BucketIds}; export type ResponseFormatText = {type: 'text'}; export type ResponseFormatJsonObject = {type: 'json_object'}; export type ResponseFormatJsonSchema = {name: string, description?: string | undefined, schema?: {[key: string]: unknown} | undefined, strict?: boolean | undefined}; export type ResponseFormatJsonSchemaParam = {type: 'json_schema', json_schema: ResponseFormatJsonSchema}; export type ChatCompletionResponseFormatParam = ResponseFormatText | ResponseFormatJsonObject | ResponseFormatJsonSchemaParam; export type ChatCompletionRequest = {messages: Array, model?: string | undefined, service_tier?: string | undefined, region?: ('USA' | 'EU' | 'AUS' | 'UAE') | undefined, mode?: ('preferred' | 'strict') | undefined, api_key_ref?: string | undefined, stream?: boolean | undefined, temperature?: number | undefined, max_tokens?: (number | null) | undefined, tools?: (Array) | undefined, tool_choice?: ('none' | 'auto' | 'required') | undefined, response_format?: ChatCompletionResponseFormatParam | undefined, min_p?: number | undefined, n?: number | undefined, use_beam_search?: boolean | undefined, best_of?: number | undefined, length_penalty?: number | undefined, early_stopping?: boolean | undefined, logprobs?: boolean | undefined, top_logprobs?: number | undefined, frequency_penalty?: number | undefined, presence_penalty?: number | undefined, top_p?: number | undefined, stop?: (string | Array) | undefined, seed?: number | undefined, enable_thinking?: boolean | undefined, reasoning_effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max') | undefined}; export type CreateApiAiChatCompletionsArgs = {body: ChatCompletionRequest}; export type CreateApiAiChatCompletionsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiAiChatCompletionsResponse = z.record(z.string(), 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 }; /** * Create a chat completion * * POST /ai/chat/completions */ export const createApiAiChatCompletions = async (args: CreateApiAiChatCompletionsArgs, options?: CreateApiAiChatCompletionsOptions) => { const {baseUrl = "https://api.telnyx.com/v2", 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(/\/+$/, '')}/ai/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(createApiAiChatCompletionsResponse, await res.json()) };