import {z} from 'zod' export type ChatImageAttachment = {bucket: string, path: string, title?: (string | null) | undefined}; export type SendChatUserMessage = {id?: (string | null) | undefined, text?: string | undefined, attachments?: Array | undefined}; export type SendMessageRequest = {message: SendChatUserMessage, population_id?: (string | null) | undefined, persona_id?: (string | null) | undefined, title?: (string | null) | undefined, chat_name?: (string | null) | undefined, demographic_filter?: ({[key: string]: Array} | null) | undefined, stream?: boolean | undefined}; export type CreateApiWorkspacesWorkspaceIdChatArchiveChatIdMessagesArgs = {chat_id: string, workspace_id: string, body: SendMessageRequest}; export type CreateApiWorkspacesWorkspaceIdChatArchiveChatIdMessagesOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const archivedChatMessageCustom = z.object({demographicFilter: z.record(z.string(), z.unknown())}); export const archivedChatMessageMetadata = z.object({chatId: z.string(), custom: archivedChatMessageCustom.nullable().optional()}); export const textPart = z.object({type: z.literal("text").optional(), text: z.string()}); export const filePart = z.object({type: z.literal("file").optional(), url: z.string(), mediaType: z.string(), filename: z.string().nullable().optional()}); export const progressToolOutput = z.object({status: z.enum(["done", "skipped", "error"]), summary: z.record(z.string(), z.unknown()).nullable().optional()}); export const progressToolPart = z.object({type: z.literal("dynamic-tool").optional(), toolName: z.string(), toolCallId: z.string(), title: z.string(), providerExecuted: z.literal(true).optional(), state: z.literal("output-available").optional(), input: z.record(z.string(), z.unknown()).optional(), output: progressToolOutput}); export const responseClusterSkew = z.object({group: z.string().optional(), label: z.string().optional(), share: z.number().optional()}); export const responseClusterQuote = z.object({persona: z.string().optional(), text: z.string().optional()}); export const responseClusterExample = z.object({persona_id: z.string().optional(), persona: z.string().optional(), text: z.string().optional()}); export const responseClusterCode = z.object({id: z.string().optional(), title: z.string().optional(), summary: z.string().optional(), count: z.number().int().optional(), share: z.number().optional(), primary_count: z.number().int().optional(), sentiment: z.enum(["positive", "neutral", "mixed", "negative"]).optional(), member_persona_ids: z.array(z.string()).optional(), primary_persona_ids: z.array(z.string()).optional(), skew: z.array(responseClusterSkew).optional(), quotes: z.array(responseClusterQuote).optional(), examples: z.array(responseClusterExample).optional()}); export const populationClusters = z.object({question: z.string().optional(), headline: z.string().optional(), total: z.number().int().optional(), codes: z.array(responseClusterCode).optional()}); export const responseClustersPart = z.object({type: z.literal("data-responseClusters").optional(), data: populationClusters}); export const archivedChatMessage = z.object({id: z.string(), role: z.enum(["user", "assistant"]), metadata: archivedChatMessageMetadata, parts: z.array(z.discriminatedUnion("type", [textPart, filePart, progressToolPart, responseClustersPart])).optional()}); export const sendMessageResponse = z.object({status: z.literal("completed"), chat_id: z.string(), message: archivedChatMessage, answer: 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 }; /** * Send Archived Chat Message * * POST /workspaces/{workspace_id}/chat-archive/{chat_id}/messages */ export const createApiWorkspacesWorkspaceIdChatArchiveChatIdMessages = async (args: CreateApiWorkspacesWorkspaceIdChatArchiveChatIdMessagesArgs, options: CreateApiWorkspacesWorkspaceIdChatArchiveChatIdMessagesOptions) => { 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(/\/+$/, '')}/workspaces/${encodeURIComponent(String(args.workspace_id))}/chat-archive/${encodeURIComponent(String(args.chat_id))}/messages${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(sendMessageResponse, await res.json()) };