带会话管理的聊天机器人组件

桌面版浅色 移动版浅色
DesktopChatbotLight
MobileChatbotLight
桌面版深色 移动版深色
DesktopChatbotDark
MobileChatbotDark

Chatbot 组件提供了一个具有高级会话管理功能的动态交互式聊天界面。它渲染用户和聊天机器人之间的聊天消息,包含诸如打字模拟、自动滚动、持久化聊天会话以及使用 Neo4j Needle 设计库的可折叠会话历史侧边栏等功能。

核心功能

  • 会话管理:创建、切换、编辑和删除多个聊天会话

  • 持久化存储:会话会自动保存到 localStorage,并在页面重载时恢复

  • 交互式 UI:带有会话历史记录的可折叠侧边栏及直观的悬停效果

  • 打字模拟:为聊天机器人响应提供逼真的逐字输入效果

  • 来源集成:支持消息来源和检索信息显示

  • 响应式设计:针对桌面和移动设备优化的全屏布局

  • Neo4j Needle 集成:使用官方 Neo4j Needle 设计库组件

先决条件

确保你的项目中安装了 @neo4j-ndl 库以使用此 Chatbot 组件。

你还需要设置 ChatSessionContext 提供程序以启用会话管理功能。

使用

要将 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

聊天机器人初始渲染的消息对象数组。每个消息对象应包含 idusermessagedatetime 以及可选的 isTypingsrc 字段。如果 localStorage 中不存在会话,这些消息将用于填充第一个会话。

否(默认为空数组)

会话管理功能

聊天会话

该组件自动管理多个聊天会话,具备以下功能:

  • 创建新会话:开始一段全新的对话

  • 切换会话:在不同的聊天历史记录之间导航

  • 编辑会话标题:重命名会话以便更好地组织

  • 删除会话:移除不需要的对话

  • 持久化存储:所有会话都保存到 localStorage 并可在页面加载时恢复

消息对象结构

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
}

关键组件

会话管理上下文

该组件使用 useChatSession 钩子来访问会话管理功能:

  • sessions:所有可用聊天会话的数组

  • currentSession:当前活动的会话

  • createNewSession():创建新的聊天会话

  • switchSession(id):切换到不同的会话

  • deleteSession(id):删除会话

  • updateSessionTitle(id, title):重命名会话

  • addMessageToCurrentSession(message):向当前活动会话添加消息

会话持久化

所有会话都会自动通过以下键持久化到 localStorage:

  • neo4j-chat-sessions:存储所有会话的数组

  • neo4j-current-session:存储当前活动会话的 ID

应用程序加载时会恢复会话,从而在浏览器会话之间提供无缝的用户体验。

示例

以下是使用带有初始消息的 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 数据库中。

© . This site is unofficial and not affiliated with Neo4j, Inc.