import {z} from 'zod' export type ProviderRoutingObject = {order?: Array | undefined, only?: Array | undefined, ignore?: Array | undefined, sort?: ('speed' | 'throughput' | 'latency' | 'price' | 'auto' | 'none' | 'default' | {by: 'speed' | 'throughput' | 'latency' | 'price' | 'auto' | 'none' | 'default', partition?: ('model' | 'none') | undefined}) | undefined, quantizations?: (Array<'int4' | 'fp4' | 'fp6' | 'int8' | 'fp8' | 'fp16' | 'bf16' | 'fp32' | 'unknown'>) | undefined, min_quantization?: ('int4' | 'fp4' | 'fp6' | 'int8' | 'fp8' | 'fp16' | 'bf16' | 'fp32') | undefined, max_price?: ({prompt?: number | undefined, completion?: number | undefined}) | undefined, preferred_max_latency?: (number | {p50?: number | undefined, p75?: number | undefined, p90?: number | undefined, p99?: number | undefined}) | undefined, preferred_min_throughput?: (number | {p50?: number | undefined, p75?: number | undefined, p90?: number | undefined, p99?: number | undefined}) | undefined, allow_fallbacks?: boolean | undefined, require_parameters?: boolean | undefined}; export type CompletionRequest = {model: string, billing_mode?: string | undefined, billingMode?: string | undefined, provider?: (string | ProviderRoutingObject) | undefined, prompt: string, max_tokens?: number | undefined, temperature?: number | undefined, top_p?: number | undefined, stream?: boolean | undefined, stop?: (string | Array) | undefined, frequency_penalty?: number | undefined, presence_penalty?: number | undefined, repetition_penalty?: number | undefined, top_k?: number | undefined, top_a?: number | undefined, min_p?: number | undefined, tfs?: number | undefined, eta_cutoff?: number | undefined, epsilon_cutoff?: number | undefined, typical_p?: number | undefined, mirostat_mode?: (0 | 1 | 2) | undefined, mirostat_tau?: number | undefined, mirostat_eta?: number | undefined, min_tokens?: number | undefined, stop_token_ids?: Array | undefined, include_stop_str_in_output?: boolean | undefined, ignore_eos?: boolean | undefined, no_repeat_ngram_size?: number | undefined, custom_token_bans?: Array | undefined, logit_bias?: {[key: string]: number} | undefined, logprobs?: (boolean | number) | undefined, prompt_logprobs?: boolean | undefined, seed?: number | undefined}; export type CreateApiV1CompletionsArgs = {'X-Provider'?: string | undefined, 'X-Billing-Mode'?: string | undefined, body: CompletionRequest}; export type CreateApiV1CompletionsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const completionResponse = z.object({id: z.string().optional(), object: z.string().optional(), created: z.number().int().optional(), model: z.string().optional(), choices: z.array(z.object({text: z.string().optional(), index: z.number().int().optional(), logprobs: z.object({}).nullable().optional(), finish_reason: z.enum(["stop", "length", "content_filter"]).optional()})).optional(), usage: z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional()}).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 }; /** * Creates a completion for the provided prompt. This endpoint is available on a best-effort basis for legacy compatibility, and performance may be less consistent than /v1/chat/completions because not all upstream providers support the legacy completions API. * * POST /v1/completions */ export const createApiV1Completions = async (args: CreateApiV1CompletionsArgs, options?: CreateApiV1CompletionsOptions) => { const {baseUrl = "https://api.nano-gpt.com/api", 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 (args['X-Provider'] != null) headers.set("X-Provider", String(args['X-Provider'])) if (args['X-Billing-Mode'] != null) headers.set("X-Billing-Mode", String(args['X-Billing-Mode'])) 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()) };