import {z} from 'zod' export type StopConfiguration = string | null | Array | null; export type ChatCompletionStreamOptions = {include_usage?: boolean | undefined, include_obfuscation?: boolean | undefined} | null; export type CreateCompletionRequest = {model: string | 'gpt-3.5-turbo-instruct' | 'davinci-002' | 'babbage-002', prompt: string | Array | Array | Array> | null, best_of?: (number | null) | undefined, echo?: (boolean | null) | undefined, frequency_penalty?: (number | null) | undefined, logit_bias?: ({[key: string]: number} | null) | undefined, logprobs?: (number | null) | undefined, max_tokens?: (number | null) | undefined, n?: (number | null) | undefined, presence_penalty?: (number | null) | undefined, seed?: (number | null) | undefined, stop?: StopConfiguration | undefined, stream?: (boolean | null) | undefined, stream_options?: ChatCompletionStreamOptions | undefined, suffix?: (string | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, user?: string | undefined}; export type CreateApiV1CompletionsArgs = {body: CreateCompletionRequest}; export type CreateApiV1CompletionsOptions = {baseUrl?: string | undefined, gatewayBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const completionUsage = z.object({completion_tokens: z.number().int(), prompt_tokens: z.number().int(), total_tokens: z.number().int(), completion_tokens_details: z.object({accepted_prediction_tokens: z.number().int().optional(), audio_tokens: z.number().int().optional(), reasoning_tokens: z.number().int().optional(), rejected_prediction_tokens: z.number().int().optional()}).optional(), prompt_tokens_details: z.object({audio_tokens: z.number().int().optional(), cached_tokens: z.number().int().optional(), cache_write_tokens: z.number().int().optional()}).optional()}); export const createCompletionResponse = z.object({id: z.string(), choices: z.array(z.object({finish_reason: z.enum(["stop", "length", "content_filter"]), index: z.number().int(), logprobs: z.object({text_offset: z.array(z.number().int()).optional(), token_logprobs: z.array(z.number()).optional(), tokens: z.array(z.string()).optional(), top_logprobs: z.array(z.record(z.string(), z.number())).optional()}).nullable(), text: z.string()})), created: z.number().int(), model: z.string(), system_fingerprint: z.string().optional(), object: z.literal("text_completion"), usage: completionUsage.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 }; /** * /v1/completions * * POST /v1/completions */ export const createApiV1Completions = async (args: CreateApiV1CompletionsArgs, options?: CreateApiV1CompletionsOptions) => { const {baseUrl = "https://aihubmix.com", fetch: fetchFn = fetch, gatewayBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (gatewayBearer !== undefined) headers.set('authorization', `Bearer ${gatewayBearer}`) 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(createCompletionResponse, await res.json()) };