import {z} from 'zod' export type FunctionParameters = {type?: string | undefined, properties: {[key: string]: Record}, required: Array | null}; export type ToolFunctionDetail = {name: string, description?: (string | null) | undefined, parameters: FunctionParameters}; export type ToolFunctionInput = {type?: 'function' | undefined, function: ToolFunctionDetail}; export type ToolChoiceFunction = {name: string}; export type ToolChoice = {type?: ('function' | 'json_object' | null) | undefined, function?: (ToolChoiceFunction | null) | undefined}; export type RequestResponseFormat = {type: 'text' | 'json_object'}; export type RoleContentChatChoiceContentImageUrl = {url: string}; export type RoleContentChatChoiceContent = {type: 'text' | 'image_url', text?: (string | null) | undefined, image_url?: (RoleContentChatChoiceContentImageUrl | null) | undefined}; export type FunctionCallArguments = {arguments: string, name: string}; export type ToolCall = {function: FunctionCallArguments, id: string, type?: 'function' | undefined}; export type RoleContentChatChoiceInput = {role: 'user' | 'assistant' | 'system', content: string | Array | null, tool_calls?: (Array | null) | undefined}; export type ChatCompletionRequestPayload = {model?: (string | null) | undefined, max_tokens?: (number | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, tools?: (Array | null) | undefined, tool_choice?: ('none' | 'auto' | ToolChoice) | undefined, n?: (number | null) | undefined, stream?: (boolean | null) | undefined, logprobs?: (number | null) | undefined, stop?: (string | Array | null) | undefined, presence_penalty?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, best_of?: (number | null) | undefined, logit_bias?: (Record | null) | undefined, response_format?: (RequestResponseFormat | null) | undefined, messages: Array, plugins?: Array | undefined}; export type CreateApiV1ChatCompletionsArgs = {body: ChatCompletionRequestPayload}; export type CreateApiV1ChatCompletionsOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const roleContentChatChoiceContentImageUrl = z.object({url: z.string()}); export const roleContentChatChoiceContent = z.object({type: z.enum(["text", "image_url"]), text: z.string().nullable().optional(), image_url: roleContentChatChoiceContentImageUrl.nullable().optional()}); export const functionCallArguments = z.object({arguments: z.string(), name: z.string()}); export const toolCall = z.object({function: functionCallArguments, id: z.string(), type: z.literal("function").optional()}); export const roleContentChatChoiceOutput = z.object({role: z.enum(["user", "assistant", "system"]), content: z.union([z.string(), z.array(roleContentChatChoiceContent)]).nullable(), tool_calls: z.array(toolCall).nullable().optional()}); export const responseCompletionChatChoice = z.object({index: z.number().int(), finish_reason: z.string().nullable().optional(), message: roleContentChatChoiceOutput}); export const modelParts = z.object({model: z.string(), provider: z.string().nullable().optional(), owner: z.string().nullable().optional(), namespace: z.string(), at: z.string().nullable().optional()}); export const pulzeEngineTokens = z.object({total_tokens: z.number().optional(), prompt_tokens: z.number().optional(), completion_tokens: z.number().optional()}); export const pulzeGeneratedArtifacts = z.object({items: z.array(z.object({})).optional()}); export const pulzeSearchResults = z.object({items: z.array(z.object({})).optional()}); export const rankedScoringModels = z.object({best_models: z.array(z.record(z.string(), z.number())).optional(), candidates: z.array(z.record(z.string(), z.number())).nullable().optional()}); export const pulzeEngineResponseMetadata = z.object({app_id: z.string().optional(), model: modelParts.nullable().optional(), costs: pulzeEngineTokens.optional(), cost_savings: pulzeEngineTokens.optional(), generated_artifacts: pulzeGeneratedArtifacts.optional(), search_results: pulzeSearchResults.optional(), latency: z.number().nullable().optional(), labels: z.record(z.string(), z.string()).nullable().optional(), error: z.string().nullable().optional(), scores: rankedScoringModels.nullable().optional(), score: z.number().nullable().optional(), temperature: z.union([z.number(), z.number().int()]).nullable().optional(), max_tokens: z.number().int().gte(-1).nullable().optional(), status_code: z.number().int().nullable().optional(), retries: z.number().int().optional(), extra: z.object({}).nullable().optional(), warning: z.string().nullable().optional()}); export const pulzeEngineResponseChatCompletion = z.object({choices: z.array(responseCompletionChatChoice), created: z.number().int().optional(), metadata: pulzeEngineResponseMetadata.optional(), id: z.string().optional(), usage: pulzeEngineTokens.optional(), model: z.string(), object: z.enum(["text_completion", "chat.completion"])}).and(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 }; /** * Chat Completions * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options: CreateApiV1ChatCompletionsOptions) => { const {baseUrl, 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 (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/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(pulzeEngineResponseChatCompletion, await res.json()) };