import {z} from 'zod' export type CreateChatCompletionRequest = {model: string, messages: Array<{role?: ('system' | 'user' | 'assistant') | undefined, content?: string | undefined}>, temperature?: number | undefined, mcp_servers?: Array<{name: string, type: string}> | undefined, router?: ({name: string, type: string, script?: string | undefined}) | undefined, extra?: ({guards?: Array | undefined, user?: ({id?: string | undefined, name?: string | undefined, tags?: Array | undefined}) | undefined}) | undefined}; export type CreateApiV1ChatCompletionsArgs = {'X-Project-Id': string, body: CreateChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const createChatCompletionResponse = z.object({id: z.string(), choices: z.array(z.object({finish_reason: z.enum(["stop", "length", "tool_calls", "content_filter", "function_call"]), index: z.number().int(), message: z.object({role: z.literal("assistant"), content: z.string()}), logprobs: z.object({content: z.array(z.object({token: z.string().optional(), logprob: z.number().optional()})).nullable(), refusal: z.array(z.object({token: z.string().optional(), logprob: z.number().optional()})).nullable()}).nullable()})), created: z.number().int(), model: z.string(), service_tier: z.enum(["scale", "default"]).nullable().optional(), system_fingerprint: z.string().optional(), object: z.literal("chat.completion"), usage: z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional(), prompt_tokens_details: z.object({cached_tokens: z.number().int().optional()}).optional(), completion_tokens_details: z.object({reasoning_tokens: z.number().int().optional(), accepted_prediction_tokens: z.number().int().optional(), rejected_prediction_tokens: z.number().int().optional()}).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 }; /** * Create chat completion * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "https://api.us-east-1.langdb.ai", 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-Project-Id'] != null) headers.set("X-Project-Id", String(args['X-Project-Id'])) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) 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(createChatCompletionResponse, await res.json()) };