import {z} from 'zod' export type RespondChatRequest = {conversation_id: string, message?: string | undefined}; export type CreateApiVersionAccountIdProjectIdChatRespondArgs = {'X-API-KEY': string, 'X-TOKEN': string, version: string, account_id: string, project_id: string, body: RespondChatRequest}; export type CreateApiVersionAccountIdProjectIdChatRespondOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const respondChatResponse = z.object({conversation_id: z.string(), response: z.string(), end_conversation: z.boolean(), handoff: z.object({destination: z.string().optional(), reason: z.string().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 }; /** * Send a message to an existing chat conversation * * POST /{version}/{account_id}/{project_id}/chat/respond * * Also accepts auth: TokenAuth */ export const createApiVersionAccountIdProjectIdChatRespond = async (args: CreateApiVersionAccountIdProjectIdChatRespondArgs, options?: CreateApiVersionAccountIdProjectIdChatRespondOptions) => { const {baseUrl = "https://api.us.poly.ai", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-API-KEY'] != null) headers.set("X-API-KEY", String(args['X-API-KEY'])) if (args['X-TOKEN'] != null) headers.set("X-TOKEN", String(args['X-TOKEN'])) if (ApiKeyAuth !== undefined) headers.set("x-api-key", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/${encodeURIComponent(String(args.version))}/${encodeURIComponent(String(args.account_id))}/${encodeURIComponent(String(args.project_id))}/chat/respond${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(respondChatResponse, await res.json()) };