import {z} from 'zod' export type ServiceTier = 'auto' | 'default' | 'over-limit' | 'flex' | 'no-limit'; export type CompletionRequest = {model: string, prompt: string | Array | Array, stream?: (boolean | null) | undefined, stream_options?: ({[key: string]: boolean} | null) | undefined, max_tokens?: (number | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, n?: (number | null) | undefined, logprobs?: (number | null) | undefined, echo?: (boolean | null) | undefined, stop?: (string | Array | null) | undefined, presence_penalty?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, logit_bias?: ({[key: string]: number} | null) | undefined, user?: (string | null) | undefined, extra_body?: ({[key: string]: unknown} | null) | undefined, service_tier?: ServiceTier | undefined} | {[key: string]: unknown}; export type CreateApiV1CompletionsArgs = {ai_project_id?: (string | null) | undefined, body: CompletionRequest}; export type CreateApiV1CompletionsOptions = {baseUrl?: string | undefined, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const completionFinishReason = z.enum(["stop", "length", "content_filter"]); export const completionChoice = z.object({index: z.number().int(), text: z.string(), finish_reason: completionFinishReason}); 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 usage = z.object({completion_tokens: z.number().int(), prompt_tokens: z.number().int(), total_tokens: z.number().int(), prompt_tokens_details: promptTokensDetails.nullable().optional(), completion_tokens_details: completionTokensDetails.nullable().optional()}); export const serviceTier = z.enum(["auto", "default", "over-limit", "flex", "no-limit"]); export const completionResponse = z.object({id: z.string(), object: z.string(), created: z.number().int(), model: z.string(), choices: z.array(completionChoice), usage: usage, service_tier: serviceTier}); 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 = "https://api.tokenfactory.nebius.com", fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.ai_project_id != null) query.append("ai_project_id", String(args.ai_project_id)) if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) 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()) };