import {z} from 'zod' export type AIModel = 'gpt-oss-120b' | 'gpt-oss-20b' | 'gpt-5.2' | 'gpt-5.5' | 'gpt-5.6-terra' | 'gpt-6-luna' | 'gpt-6.1-sol' | 'gpt-6.1-terra' | 'claude-opus-5-5' | 'claude-sonnet-5-5' | 'claude-haiku-5-5' | 'gemini-2.5-pro' | 'gemini-3-flash' | 'gemini-3.1-flash-lite' | 'gemini-3.1-pro' | 'gemini-3.5-flash-lite' | 'gemini-3.6-flash' | 'gemini-3.8-flash' | 'grok-4.7' | 'DeepSeek-V3.1' | 'DeepSeek-R1' | 'DeepSeek-V4-Flash' | 'DeepSeek-V4.1-Flash' | 'kimi-k2.6' | 'mistral-medium-3.5' | 'mistral-small-2603' | 'glm-5.2' | 'glm-5.3-flash' | 'auto'; export type CreateApiChatArgs = {body: {chatbotId: string, messages: Array<{role: 'user' | 'assistant', content: string}>, conversationId?: string | undefined, contactId?: string | undefined, model?: AIModel | undefined, temperature?: number | undefined, stream?: boolean | undefined}}; export type CreateApiChatOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiChatResponse = z.object({text: z.string().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 }; /** * Chat with a chatbot * * POST /chat */ export const createApiChat = async (args: CreateApiChatArgs, options?: CreateApiChatOptions) => { const {baseUrl = "https://www.chatbase.co/api/v1", 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 (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/chat${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(createApiChatResponse, await res.json()) };