带会话管理的聊天机器人组件
| 桌面版浅色 | 移动版浅色 |
|---|---|
|
|
| 桌面版深色 | 移动版深色 |
|---|---|
|
|
Chatbot 组件提供了一个具有高级会话管理功能的动态交互式聊天界面。它渲染用户和聊天机器人之间的聊天消息,包含诸如打字模拟、自动滚动、持久化聊天会话以及使用 Neo4j Needle 设计库的可折叠会话历史侧边栏等功能。
使用
要将 Chatbot 组件集成到你的应用程序中,首先需要导入组件和上下文提供程序。
import Chatbot from './path/to/Chatbot';
import { ChatSessionProvider } from './path/to/ChatSessionContext';
接下来,使用 ChatSessionProvider 包裹你的应用程序(或使用聊天机器人的部分),并渲染 Chatbot 组件。
<ChatSessionProvider>
<Chatbot messages={listMessages} />
</ChatSessionProvider>
listMessages 应为一个你想初始显示的消息对象数组。如果不提供,组件将创建一个空会话。
上下文提供程序设置
ChatSessionProvider 必须包裹任何使用 Chatbot 的组件。该提供程序处理:
-
会话状态管理
-
localStorage 持久化
-
会话 CRUD(增删改查)操作
-
会话内的消息管理
import { ChatSessionProvider } from './context/ChatSessionContext';
function App() {
return (
<ChatSessionProvider>
<Chatbot />
</ChatSessionProvider>
);
}
组件属性 (Props)
Chatbot 组件接受以下属性
| 名称 | 描述 | 必填 |
|---|---|---|
|
聊天机器人初始渲染的消息对象数组。每个消息对象应包含 |
否(默认为空数组) |
消息对象结构
messages 数组属性中的每个消息对象都应遵循此结构:
{
id: number; // Unique identifier for the message
user: string; // "user" for user messages, "chatbot" for chatbot messages
message: string; // The message text
datetime: string; // Timestamp of the message
isTyping?: boolean; // Optional, simulates typing effect for chatbot messages
src?: Array<string>; // Optional, source references for chatbot responses
}
会话对象结构
会话由 ChatSessionContext 在内部管理,并遵循此结构:
{
id: string; // Unique session identifier
title: string; // Display name for the session
messages: ChatMessage[]; // Array of messages in this session
createdAt: string; // ISO timestamp when session was created
updatedAt: string; // ISO timestamp when session was last modified
}
关键组件
示例
以下是使用带有初始消息的 Chatbot 组件的基本示例:
import { ChatSessionProvider } from './context/ChatSessionContext';
import Chatbot from './components/Chatbot';
const initialMessages = [
{
id: 1,
user: 'chatbot',
message: 'Hello! How can I assist you today?',
datetime: '01/01/2025 00:00:00',
}
];
function App() {
return (
<ChatSessionProvider>
<Chatbot messages={initialMessages} />
</ChatSessionProvider>
);
}
这将渲染一个具有会话管理功能的全屏聊天界面。如果 localStorage 中不存在会话,它将使用提供的消息创建一个初始会话。
自定义会话的高级用法
你也可以使用预定义的会话来初始化提供程序:
const predefinedSessions = [
{
id: 'session-1',
title: 'Technical Support',
messages: [/* array of messages */],
createdAt: '2024-01-01T00:00:00.000Z',
updatedAt: '2024-01-01T01:00:00.000Z',
},
{
id: 'session-2',
title: 'Product Questions',
messages: [/* array of messages */],
createdAt: '2024-01-01T02:00:00.000Z',
updatedAt: '2024-01-01T03:00:00.000Z',
},
];
<ChatSessionProvider initialSessions={predefinedSessions}>
<Chatbot />
</ChatSessionProvider>
组件集成
后端集成
以下是一个关于如何为 Chatbot 组件设置带有后端集成的本地运行演示的完整示例:
第 1 步:配置 Vite 代理
首先,更新你的 vite.config.ts,为你的后端 API 添加代理配置:
// vite.config.ts
import { defineConfig } from 'vite'
export default defineConfig({
// ... other config
server: {
proxy: {
'/ask': {
target: 'https://:8001',
changeOrigin: true,
secure: false,
},
},
},
})
此配置会将对 /ask 的所有请求代理到运行在 https://:8001 的后端服务器。
第 2 步:更新 handleSubmit 函数
将 Chatbot 组件中现有的 handleSubmit 函数替换为以下调用后端 API 的实现:
const handleSubmit = async (e: { preventDefault: () => void }) => {
e.preventDefault();
if (!inputMessage.trim() || !currentSession) {
return;
}
const date = new Date();
const datetime = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
const userMessage: ChatMessage = {
id: Date.now(),
user: 'user',
message: inputMessage,
datetime: datetime
};
addMessageToCurrentSession(userMessage);
setInputMessage('');
setIsLoading(true);
try {
// Call your backend API through the Vite proxy
const response = await fetch('/ask', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
question: inputMessage,
session_id: currentSession?.id,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const chatbotReply = {
response: data.response, // Your API should return { response: string, src: string[] }
src: data.src || [], // Sources array from your API
};
setIsLoading(false);
simulateTypingEffect(chatbotReply);
} catch (error) {
console.error("API call failed:", error);
// Fallback response in case of error
const errorReply = {
response: 'Sorry, I encountered an error while processing your request. Please try again.',
src: [],
};
setIsLoading(false);
simulateTypingEffect(errorReply);
}
};
第 3 步:增强的来源可视化(可选)
如果你想为来源集成真实的 Neo4j 数据可视化,可以更新你的 RetrievalInformation.tsx 组件:
// RetrievalInformation.tsx
import { runRAGQuery, setDriver } from '../utils/Driver';
// In your retrieveSources() function:
const retrieveSources = () => {
// Configure your Neo4j connection
setDriver('neo4j+s://your-database-url', 'username', 'password');
// Query Neo4j for actual source data
runRAGQuery(props.sources).then((nvlGraph) => {
setNodes(nvlGraph.nodes);
setRels(nvlGraph.relationships);
});
};
这将用实际的 Neo4j 查询结果替换模拟数据,用于来源可视化。
后端 API 要求
你的后端 API 端点 (/ask) 应接受包含以下结构的 POST 请求:
{
"question": "User's question text",
"session_id": "optional-session-identifier"
}
并返回以下格式的响应:
{
"response": "Chatbot's response text",
"src": ["source1", "source2", "source3"]
}
对于生产环境,请考虑为你的后端 API 调用实现适当的身份验证和授权,并使用 @tanstack/react-query 等状态管理库以实现更好的缓存和错误处理。 |
感知会话的后端集成
对于更高级的用例,你可以将会话上下文发送到后端,以维护对话历史并提供更具上下文的响应:
const fetchContextualResponse = async () => {
const requestBody = {
message: inputMessage,
sessionId: currentSession?.id,
conversationHistory: currentSession?.messages.slice(-5), // Last 5 messages for context
};
// ... API call logic
};
甚至可以将历史会话和消息存储在你的 Neo4j 数据库中。