import {z} from 'zod' export type Message = {role: string, content: string}; export type AIAdvisorRequest = {message: string, conversationHistory?: Array | undefined, dateRangeOverride?: ({[key: string]: string} | null) | undefined, userId?: (string | null) | undefined, programId?: (string | null) | undefined, transactionSummary?: ({[key: string]: unknown} | null) | undefined, transactionDetails?: (Array<{[key: string]: unknown}> | null) | undefined, currencyCode?: string | undefined, currencySymbol?: string | undefined}; export type CreateApiApiAiAdvisorArgs = {authorization?: (string | null) | undefined, body: AIAdvisorRequest}; export type CreateApiApiAiAdvisorOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const aIAdvisorResponse = z.object({response: z.string(), transactionCount: z.number().int(), transactionSummary: z.record(z.string(), z.unknown()), dateRange: z.record(z.string(), z.string()), warning: z.string().nullable().optional(), timestamp: z.string()}); 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 Advisor * * POST /api/ai-advisor */ export const createApiApiAiAdvisor = async (args: CreateApiApiAiAdvisorArgs, options?: CreateApiApiAiAdvisorOptions) => { const {baseUrl = "https://api.loyalty.dog", 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.authorization != null) headers.set("authorization", String(args.authorization)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/ai-advisor${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(aIAdvisorResponse, await res.json()) };