Files
AIclinicalresearch/frontend-v2/src/shared/components/Chat
HaHafeng af325348b8 feat(dc): Complete Tool C Day 5 - AI Chat + Ant Design X Integration
Summary:
- Upgrade to Ant Design 6.0.1 + install Ant Design X (2.1.0) + X SDK (2.1.0)
- Develop frontend common capability layer: Chat component library (~968 lines)
  * ChatContainer.tsx - Core container component
  * MessageRenderer.tsx - Message renderer
  * CodeBlockRenderer.tsx - Code block renderer with syntax highlighting
  * Complete TypeScript types and documentation
- Integrate ChatContainer into Tool C
- Fix 7 critical UI issues:
  * AG Grid module registration error
  * UI refinement (borders, shadows, gradients)
  * Add AI welcome message
  * Auto-clear input field after sending
  * Remove page scrollbars
  * Manual code execution (not auto-run)
  * Support simple Q&A (new /ai/chat API)
- Complete end-to-end testing
- Update all documentation (4 status docs + 6 dev logs)

Technical Stack:
- Frontend: React 19 + Ant Design 6.0 + Ant Design X 2.1
- Components: Bubble, Sender from @ant-design/x
- Total code: ~5418 lines

Status: Tool C MVP completed, production ready
2025-12-07 22:02:14 +08:00
..

Chat 通用组件库

基于 Ant Design X 构建的 AI 对话通用组件,支持多场景复用

📚 技术栈

  • @ant-design/x (2.1.0) - UI 组件Bubble, Sender
  • @ant-design/x-sdk (2.1.0) - 数据流管理(可选)
  • React 19 + TypeScript 5
  • Prism.js - 代码语法高亮

特性

  • 多场景支持AIA、PKB个人知识库、Tool C 等
  • 开箱即用:基于 Ant Design X无需复杂配置
  • 类型安全:完整的 TypeScript 类型定义
  • 高度可定制:支持自定义消息渲染、样式配置
  • 代码执行Tool C 专用,支持代码块展示和执行

📦 安装

组件已内置在项目中,无需额外安装。如需单独使用,确保安装以下依赖:

npm install @ant-design/x @ant-design/x-sdk prismjs

🚀 快速开始

基础用法

import { ChatContainer } from '@/shared/components/Chat';

<ChatContainer
  conversationType="aia"
  providerConfig={{
    apiEndpoint: '/api/chat',
  }}
/>

Tool C 集成(完整示例)

import { ChatContainer, MessageRenderer } from '@/shared/components/Chat';

<ChatContainer
  conversationType="tool-c"
  conversationKey={sessionId}
  providerConfig={{
    apiEndpoint: `/api/dc/tool-c/process`,
    requestFn: async (message: string) => {
      const response = await fetch(`/api/dc/tool-c/process`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sessionId, userMessage: message }),
      });
      return await response.json();
    },
  }}
  customMessageRenderer={(msgInfo) => (
    <MessageRenderer
      messageInfo={msgInfo}
      onExecuteCode={handleExecuteCode}
      isExecuting={isExecuting}
    />
  )}
  onMessageReceived={(msg) => {
    if (msg.metadata?.newDataPreview) {
      updateDataGrid(msg.metadata.newDataPreview);
    }
  }}
/>

📖 API 文档

ChatContainer Props

参数 类型 必填 默认值 说明
conversationType ConversationType - 对话类型('aia' | 'pkb' | 'tool-c'
conversationKey string - 会话 ID用于多会话管理
providerConfig ChatProviderConfig - API 配置
defaultMessages ChatMessage[] [] 初始消息列表
customMessageRenderer Function - 自定义消息渲染器
senderProps SenderProps {} Sender 组件配置
onMessageSent Function - 消息发送回调
onMessageReceived Function - 消息接收回调
onError Function - 错误回调

ChatProviderConfig

interface ChatProviderConfig {
  apiEndpoint: string;                    // API 端点
  method?: 'GET' | 'POST';                // 请求方法
  headers?: Record<string, string>;       // 请求头
  requestFn?: (message: string, context?: any) => Promise<any>;  // 自定义请求函数
}

ChatMessage

interface ChatMessage {
  id: string | number;
  role: 'user' | 'assistant' | 'system';
  content: string;
  status?: 'local' | 'loading' | 'success' | 'error';
  code?: string;              // Tool C 专用
  explanation?: string;       // Tool C 专用
  timestamp?: number;
  metadata?: Record<string, any>;
}

🎨 自定义渲染

MessageRenderer默认渲染器

import { MessageRenderer } from '@/shared/components/Chat';

<MessageRenderer
  messageInfo={msgInfo}
  onExecuteCode={(code) => console.log('Execute:', code)}
  isExecuting={false}
/>

CodeBlockRenderer代码块渲染器

import { CodeBlockRenderer } from '@/shared/components/Chat';

<CodeBlockRenderer
  code="df['age'].fillna(df['age'].mean(), inplace=True)"
  language="python"
  onExecute={handleExecute}
  isExecuting={false}
  executionResult={{ success: true }}
/>

🔧 高级用法

自定义消息渲染

<ChatContainer
  conversationType="custom"
  providerConfig={{ apiEndpoint: '/api/custom' }}
  customMessageRenderer={(msgInfo) => {
    const msg = msgInfo.message;
    return (
      <div>
        <strong>{msg.role}:</strong> {msg.content}
        {msg.code && <pre>{msg.code}</pre>}
      </div>
    );
  }}
/>

处理后端响应

后端 API 应返回以下格式:

{
  "messageId": "xxx",
  "explanation": "好的,我将帮您...",
  "code": "df['sex'].fillna(df['sex'].mode()[0], inplace=True)",
  "success": true,
  "metadata": {
    "newDataPreview": [...]
  }
}

📁 文件结构

shared/components/Chat/
├── types.ts                 # TypeScript 类型定义
├── ChatContainer.tsx        # 核心容器组件
├── MessageRenderer.tsx      # 默认消息渲染器
├── CodeBlockRenderer.tsx    # 代码块渲染器
├── styles/
│   └── chat.css            # 样式文件
├── index.ts                # 统一导出
└── README.md               # 本文档

🎯 使用场景

1. AIAAI智能问答

<ChatContainer
  conversationType="aia"
  providerConfig={{
    apiEndpoint: '/api/aia/chat',
  }}
/>

2. PKB个人知识库

<ChatContainer
  conversationType="pkb"
  conversationKey={knowledgeBaseId}
  providerConfig={{
    apiEndpoint: '/api/pkb/query',
  }}
/>

3. Tool C数据清洗

<ChatContainer
  conversationType="tool-c"
  conversationKey={sessionId}
  providerConfig={{
    apiEndpoint: '/api/dc/tool-c/process',
  }}
  customMessageRenderer={(msgInfo) => (
    <MessageRenderer
      messageInfo={msgInfo}
      onExecuteCode={handleExecuteCode}
    />
  )}
/>

🐛 常见问题

Q1: 如何自定义样式?

通过 classNamestyle 属性:

<ChatContainer
  className="my-custom-chat"
  style={{ height: '600px' }}
  // ...
/>

或修改 styles/chat.css

Q2: 如何处理流式响应?

当前版本暂不支持流式响应,计划在后续版本中支持。

Q3: 如何添加新的对话类型?

  1. types.ts 中扩展 ConversationType
  2. 根据需要自定义 customMessageRenderer

📝 开发记录

  • 2025-12-07: 初始版本,基于 Ant Design X 2.1.0 重构
  • 完整开发记录:docs/03-业务模块/DC-数据清洗整理/06-开发记录/

📚 参考资料