import {z} from 'zod' export type StreamOptions = {include_usage?: (boolean | null) | undefined, include_internal_content?: (boolean | null) | undefined, buffer_tokens?: (number | null) | undefined, buffer_ms?: (number | null) | undefined, buffer_mode?: ('any' | 'all' | null) | undefined}; export type ResponseFormat = {type: 'json_object' | 'json_schema' | 'grammar' | 'text', schema?: ({[key: string]: unknown} | string | null) | undefined, grammar?: (string | null) | undefined, json_schema?: ({[key: string]: unknown} | string | null) | undefined}; export type ChatMessageContentImageURL = {url: string, detail?: (string | null) | undefined, max_long_side_pixel?: (number | null) | undefined}; export type ChatMessageContentVideoURL = {url: string, detail?: (string | null) | undefined, max_frames?: (number | null) | undefined, spatial_limit?: (number | null) | undefined, sample_fps?: (number | null) | undefined, fps?: (number | null) | undefined, max_long_side_pixel?: (number | null) | undefined}; export type ChatMessageContent = {type: string, text?: (string | null) | undefined, image_url?: (ChatMessageContentImageURL | null) | undefined, video_url?: (ChatMessageContentVideoURL | null) | undefined}; export type PredictedOutput = {content: string | Array, type?: 'content' | undefined}; export type ThinkingConfigEnabled = {type?: 'enabled' | undefined, budget_tokens?: (number | null) | undefined, keep?: ('all' | null) | undefined, budget_end_str?: (string | null) | undefined, effort?: ('low' | 'medium' | 'high' | 'xhigh' | 'max' | 'none' | 'adaptive' | number | boolean | null) | undefined}; export type ThinkingConfigDisabled = {type: 'disabled'}; export type ThinkingConfigAdaptive = {type: 'adaptive'}; export type CompletionRequest = {model: string, user?: (string | null) | undefined, prompt_cache_key?: (string | null) | undefined, prompt_cache_isolation_key?: (string | null) | undefined, raw_output?: (boolean | null) | undefined, perf_metrics_in_response?: (boolean | null) | undefined, stream?: (boolean | null) | undefined, stream_options?: (StreamOptions | null) | undefined, n?: number | undefined, service_tier?: ('auto' | 'default' | 'flex' | 'priority') | undefined, stop?: (string | Array | null) | undefined, max_tokens?: (number | null) | undefined, max_completion_tokens?: (number | null) | undefined, temperature?: (number | null) | undefined, top_k?: (number | null) | undefined, top_p?: (number | null) | undefined, min_p?: (number | null) | undefined, typical_p?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, presence_penalty?: (number | null) | undefined, repetition_penalty?: (number | null) | undefined, mirostat_target?: (number | null) | undefined, mirostat_lr?: (number | null) | undefined, seed?: (number | null) | undefined, logprobs?: (number | boolean | null) | undefined, top_logprobs?: (number | null) | undefined, sampling_mask?: ('count' | 'non_zero_list' | 'non_zero_buffer' | null) | undefined, echo?: (boolean | null) | undefined, echo_last?: (number | null) | undefined, ignore_eos?: boolean | undefined, context_length_exceeded_behavior?: ('error' | 'truncate') | undefined, response_format?: (ResponseFormat | null) | undefined, logit_bias?: ({[key: string]: number} | null) | undefined, speculation?: (string | Array | null) | undefined, prediction?: (PredictedOutput | string | null) | undefined, metadata?: ({[key: string]: string} | null) | undefined, reasoning_effort?: ('low' | 'medium' | 'high' | 'xhigh' | 'max' | 'none' | 'adaptive' | number | boolean | null) | undefined, reasoning_history?: ('disabled' | 'interleaved' | 'preserved' | null) | undefined, thinking?: (ThinkingConfigEnabled | ThinkingConfigDisabled | ThinkingConfigAdaptive | null) | undefined, return_token_ids?: (boolean | null) | undefined, prompt: string | Array | Array | Array>, images?: (Array | Array> | null) | undefined}; export type CreateApiV1CompletionsArgs = {body: CompletionRequest}; export type CreateApiV1CompletionsOptions = {baseUrl: string, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const logProbs = z.object({tokens: z.array(z.string()).optional(), token_logprobs: z.array(z.number()).optional(), top_logprobs: z.array(z.record(z.string(), z.number())).nullable().optional(), text_offset: z.array(z.number().int()).optional(), token_ids: z.array(z.number().int()).nullable().optional()}); export const newLogProbsContentTopLogProbs = z.object({token: z.string(), logprob: z.number(), token_id: z.number().int(), bytes: z.array(z.number().int()).optional()}); export const newLogProbsContent = z.object({token: z.string(), logprob: z.number(), sampling_logprob: z.number().nullable(), sampling_mask_count: z.number().int().nullable().optional(), sampling_mask: z.union([z.array(z.number().int()), z.string()]).nullable().optional(), bytes: z.array(z.number().int()), top_logprobs: z.array(newLogProbsContentTopLogProbs).optional(), token_id: z.number().int(), text_offset: z.number().int(), last_activation: z.string().nullable().optional(), routing_matrix: z.string().nullable().optional()}); export const newLogProbs = z.object({content: z.array(newLogProbsContent).optional()}); export const rawOutput = z.object({prompt_fragments: z.array(z.union([z.string(), z.number().int()])), prompt_token_ids: z.array(z.number().int()), completion: z.string(), completion_token_ids: z.array(z.number().int()).nullable().optional(), completion_logprobs: newLogProbs.nullable().optional(), images: z.array(z.string()).nullable().optional(), videos: z.array(z.string()).nullable().optional(), grammar: z.string().nullable().optional()}); export const choice = z.object({index: z.number().int(), text: z.string(), logprobs: z.union([logProbs, newLogProbs]).nullable().optional(), finish_reason: z.enum(["stop", "length", "error"]).nullable().optional(), raw_output: rawOutput.nullable().optional(), prompt_token_ids: z.array(z.number().int()).nullable().optional(), token_ids: z.array(z.number().int()).nullable().optional()}); export const promptTokensDetails = z.object({cached_tokens: z.number().int().nullable().optional()}); export const completionTokensDetails = z.object({reasoning_tokens: z.number().int().nullable().optional()}); export const usageInfo = z.object({prompt_tokens: z.number().int(), total_tokens: z.number().int(), completion_tokens: z.number().int().nullable().optional(), prompt_tokens_details: promptTokensDetails.nullable().optional(), completion_tokens_details: completionTokensDetails.nullable().optional(), output_tokens_details: completionTokensDetails.nullable().optional()}); export const completionResponse = z.object({id: z.string(), object: z.string().optional(), created: z.number().int(), model: z.string(), choices: z.array(choice), usage: usageInfo, perf_metrics: z.record(z.string(), z.unknown()).nullable().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 Completion * * POST /v1/completions */ export const createApiV1Completions = async (args: CreateApiV1CompletionsArgs, options: CreateApiV1CompletionsOptions) => { 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/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(completionResponse, await res.json()) };