教程: 提供可下载的对话抄本
您可以定制 Web 交谈以向客户提供下载对话历史记录记录的选项。
要获取本教程中描述的示例的完整工作版本,请参阅 Download history for watsonx Assistant web chat。
为支持下载对话文字记录,此示例将定制菜单选项添加到交谈窗口标题中的溢出菜单:

单击此菜单选项将开始下载包含逗号分隔值 (CSV) 格式的完整对话历史记录的文件。
-
为
send
和receive
事件创建处理程序。 在此处理程序中,将每个入局或出局消息保存在列表 (messages
) 中以维护对话的历史记录。const messages = []; function saveMessage(event) { messages.push(event.data); }
-
为
history:begin
事件创建处理程序,此处理程序在从会话历史记录重新装入 Web 聊天时触发。 在此处理程序中,将任何重新装入的会话历史记录保存到列表中。function saveHistory(event) { messages.push(...event.messages); }
-
在
onLoad
事件处理程序中,使用on()
实例方法来预订send
,receive
和history:begin
事件,并将相应的处理程序注册为回调。instance.on({ type: 'send', handler: saveMessage }); instance.on({ type: 'receive', handler: saveMessage }); instance.on({ type: 'history:begin', handler: saveHistory });
-
创建一个函数,用于将保存在
messages
列表中的消息转换为要在下载的文件中提供的格式。 此转换需要适应对话可能包含的任何响应类型 (例如,文本,图像,选项或到人员代理的传输)。在此示例中,我们将消息转换为 CSV 文件格式,可以使用 Microsoft Excel 之类的应用程序打开这些文件。 每行中的第一列是一个标签,用于指示消息是源自客户 (
You
) 还是源自助手 (Lendyr
)。此函数依赖于用于格式化每行文本的帮助程序函数 (
createDownloadText
)。 您可以在 完整示例中查看此帮助程序函数的实现。function createDownload() { const downloadLines = [createDownloadText('From', 'Message')]; messages.forEach(message => { if (message.input?.text) { // This is a message that came from the user. downloadLines.push(createDownloadText('You', message.input.text)); } else if (message.output?.generic?.length) { // This is a message that came from the assistant. It can contain an array of individual message items. message.output?.generic.forEach(messageItem => { // This is only handling a text response but you can handle other types of responses here as well as // custom responses. if (messageItem?.text) { downloadLines.push(createDownloadText('Lendyr', messageItem.text)); } }); } }); return downloadLines.join('\n'); }
-
创建用于启动对话历史记录文件下载的函数。 此函数调用
createDownload()
函数以生成要下载的内容。 然后,通过使用从当前日期生成的文件名,模拟单击链接以启动下载。function doDownload() { const downloadContent = createDownload(); const blob = new Blob([downloadContent], { type: 'text/csv' }); const url = URL.createObjectURL(blob); // To automatically trigger a download, we have to create a fake "a" element and then click it. const timestamp = new Date().toISOString().replace(/[_:]/g, '-').replace(/.[0-9][0-9][0-9]Z/, ''); const a = document.createElement('a'); a.setAttribute('href', url); a.setAttribute('download', `Chat History ${timestamp}.csv`); a.click(); }
-
在
onLoad
事件处理程序中,使用updateCustomMenuOptions()
实例方法来添加客户可用于下载对话历史记录的定制菜单选项。 在调用render()
实例方法之前立即添加此行。instance.updateCustomMenuOptions('bot', [{ text: 'Download history', handler: doDownload }]);
有关完整的工作代码,请参阅 Download history for watsonx Assistant web chat 示例。