# iConsulting - 香港移民在线咨询系统开发指导 ## 项目概述 iConsulting 是一个基于 Claude Agent SDK 的智能在线客服系统,专注于提供香港移民咨询服务。系统具备自我进化能力,能够从用户对话中学习经验,并根据管理员意图持续优化服务。 ### 核心特性 - **智能咨询**: 基于 Claude Agent SDK 的自然语言对话 - **付费评估**: 移民资格评估服务,支持多种支付方式 - **知识增强**: RAG + 知识图谱,提供准确专业的回答 - **自我进化**: 从对话中学习,根据管理员指令调整 - **长期记忆**: 基于时间线的知识图谱记录 --- ## 技术架构 ### 整体架构图 ``` ┌─────────────────────────────────────────────────────────────────────┐ │ 客户端层 (Client Layer) │ ├─────────────────────────────────────────────────────────────────────┤ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │ │ │ PC Web │ │ H5 Mobile │ │ Admin Dashboard │ │ │ │ (React+TS) │ │ (React+TS) │ │ (React+TS) │ │ │ └──────────────┘ └──────────────┘ └──────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────┐ │ API 网关层 (API Gateway) │ ├─────────────────────────────────────────────────────────────────────┤ │ - 路由分发 - 认证授权 - 限流熔断 - 日志追踪 │ │ - WebSocket 代理 - 请求聚合 │ └─────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────┐ │ 微服务层 (Microservices) │ ├─────────────────────────────────────────────────────────────────────┤ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │ │ User │ │ Conversation│ │ Knowledge │ │ Payment │ │ │ │ Service │ │ Service │ │ Service │ │ Service │ │ │ │ │ │ │ │ │ │ │ │ │ │ - 匿名用户 │ │ - Claude │ │ - RAG引擎 │ │ - 支付宝 │ │ │ │ - 手机验证 │ │ Agent │ │ - 向量检索 │ │ - 微信支付 │ │ │ │ - 会话管理 │ │ - 对话管理 │ │ - 知识图谱 │ │ - 信用卡 │ │ │ │ - 用户画像 │ │ - 流式输出 │ │ - 长期记忆 │ │ - 订单管理 │ │ │ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ │ │ │ ┌────────────┐ ┌────────────┐ │ │ │ Admin │ │ Evolution │ │ │ │ Service │ │ Service │ │ │ │ │ │ │ │ │ │ - 后台管理 │ │ - 经验提取 │ │ │ │ - 角色权限 │ │ - 模式识别 │ │ │ │ - 系统配置 │ │ - 自我调整 │ │ │ │ - 数据统计 │ │ - 管理员交互│ │ │ └────────────┘ └────────────┘ │ └─────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────┐ │ 基础设施层 (Infrastructure) │ ├─────────────────────────────────────────────────────────────────────┤ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │ │ PostgreSQL │ │ Neo4j │ │ Redis │ │ Kafka │ │ │ │ │ │ │ │ │ │ │ │ │ │ - 用户数据 │ │ - 知识图谱 │ │ - 会话缓存 │ │ - 事件驱动 │ │ │ │ - 订单数据 │ │ - 长期记忆 │ │ - 分布式锁 │ │ - Outbox │ │ │ │ - 配置数据 │ │ - 关系网络 │ │ - 限流计数 │ │ - 消息队列 │ │ │ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ │ │ │ ┌────────────┐ ┌────────────┐ │ │ │ Anthropic │ │ 向量数据库 │ │ │ │ Claude API │ │ (pgvector) │ │ │ └────────────┘ └────────────┘ │ └─────────────────────────────────────────────────────────────────────┘ ``` ### 技术栈详情 | 层次 | 技术选型 | 说明 | |------|---------|------| | 前端 | React 18 + TypeScript | Clean Architecture | | 前端UI | TailwindCSS + Radix UI | 响应式设计 | | 前端状态 | Zustand + React Query | 轻量高效 | | 后端框架 | NestJS | DDD + Hexagonal Architecture | | API协议 | REST + WebSocket | 实时对话支持 | | 主数据库 | PostgreSQL 15 | 结构化数据存储 | | 向量数据库 | pgvector | RAG 向量检索 | | 图数据库 | Neo4j | 知识图谱 + 长期记忆 | | 缓存 | Redis | 会话 + 缓存 | | 消息队列 | Kafka | 事件驱动 + Outbox模式 | | AI引擎 | Claude Agent SDK | 对话 + 推理 | --- ## 项目目录结构 ``` iconsulting/ ├── docs/ # 项目文档 │ ├── architecture/ # 架构设计文档 │ ├── api/ # API 文档 │ └── deployment/ # 部署文档 │ ├── packages/ # Monorepo 包管理 │ ├── shared/ # 共享代码 │ │ ├── types/ # TypeScript 类型定义 │ │ ├── utils/ # 工具函数 │ │ └── constants/ # 常量定义 │ │ │ ├── web-client/ # 用户端 Web 应用 (PC/H5) │ │ ├── src/ │ │ │ ├── app/ # 应用层 │ │ │ │ ├── providers/ # Context Providers │ │ │ │ ├── routes/ # 路由配置 │ │ │ │ └── App.tsx │ │ │ ├── features/ # 功能模块 (Clean Architecture) │ │ │ │ ├── chat/ # 聊天功能 │ │ │ │ │ ├── domain/ # 领域层 │ │ │ │ │ ├── data/ # 数据层 │ │ │ │ │ └── presentation/# 表现层 │ │ │ │ ├── payment/ # 支付功能 │ │ │ │ └── user/ # 用户功能 │ │ │ ├── shared/ # 共享组件 │ │ │ │ ├── components/ # UI 组件 │ │ │ │ ├── hooks/ # 自定义 Hooks │ │ │ │ └── utils/ # 工具函数 │ │ │ └── main.tsx │ │ ├── package.json │ │ └── vite.config.ts │ │ │ ├── admin-client/ # 管理端 Web 应用 │ │ ├── src/ │ │ │ ├── app/ │ │ │ ├── features/ │ │ │ │ ├── dashboard/ # 仪表盘 │ │ │ │ ├── knowledge/ # 知识库管理 │ │ │ │ ├── evolution/ # 进化管理 │ │ │ │ ├── users/ # 用户管理 │ │ │ │ ├── orders/ # 订单管理 │ │ │ │ └── settings/ # 系统设置 │ │ │ └── shared/ │ │ └── package.json │ │ │ └── services/ # 后端微服务 │ ├── api-gateway/ # API 网关 │ │ ├── src/ │ │ │ ├── main.ts │ │ │ ├── gateway.module.ts │ │ │ └── middleware/ │ │ └── package.json │ │ │ ├── user-service/ # 用户服务 │ │ ├── src/ │ │ │ ├── domain/ # 领域层 │ │ │ │ ├── entities/ │ │ │ │ ├── value-objects/ │ │ │ │ ├── repositories/ │ │ │ │ └── services/ │ │ │ ├── application/ # 应用层 │ │ │ │ ├── commands/ │ │ │ │ ├── queries/ │ │ │ │ └── services/ │ │ │ ├── infrastructure/ # 基础设施层 │ │ │ │ ├── persistence/ │ │ │ │ ├── messaging/ │ │ │ │ └── external/ │ │ │ └── interfaces/ # 接口层 │ │ │ ├── http/ │ │ │ └── grpc/ │ │ └── package.json │ │ │ ├── conversation-service/ # 对话服务 (核心) │ │ ├── src/ │ │ │ ├── domain/ │ │ │ │ ├── entities/ │ │ │ │ │ ├── conversation.entity.ts │ │ │ │ │ ├── message.entity.ts │ │ │ │ │ └── session.entity.ts │ │ │ │ ├── value-objects/ │ │ │ │ ├── repositories/ │ │ │ │ └── services/ │ │ │ │ └── claude-agent.service.ts │ │ │ ├── application/ │ │ │ │ ├── commands/ │ │ │ │ │ ├── send-message.command.ts │ │ │ │ │ └── start-conversation.command.ts │ │ │ │ └── services/ │ │ │ │ └── conversation.service.ts │ │ │ ├── infrastructure/ │ │ │ │ ├── claude/ # Claude Agent SDK 集成 │ │ │ │ │ ├── claude-client.ts │ │ │ │ │ ├── tools/ # Agent Tools │ │ │ │ │ └── prompts/ │ │ │ │ └── persistence/ │ │ │ └── interfaces/ │ │ │ ├── http/ │ │ │ └── websocket/ │ │ └── package.json │ │ │ ├── knowledge-service/ # 知识服务 │ │ ├── src/ │ │ │ ├── domain/ │ │ │ │ ├── entities/ │ │ │ │ │ ├── document.entity.ts │ │ │ │ │ ├── knowledge-node.entity.ts │ │ │ │ │ └── memory.entity.ts │ │ │ │ └── services/ │ │ │ │ ├── rag.service.ts │ │ │ │ └── graph.service.ts │ │ │ ├── application/ │ │ │ ├── infrastructure/ │ │ │ │ ├── vector-store/ # pgvector │ │ │ │ ├── graph-db/ # Neo4j │ │ │ │ └── embedding/ # 向量化 │ │ │ └── interfaces/ │ │ └── package.json │ │ │ ├── payment-service/ # 支付服务 │ │ ├── src/ │ │ │ ├── domain/ │ │ │ │ ├── entities/ │ │ │ │ │ ├── order.entity.ts │ │ │ │ │ └── payment.entity.ts │ │ │ │ └── services/ │ │ │ ├── application/ │ │ │ ├── infrastructure/ │ │ │ │ ├── alipay/ # 支付宝 │ │ │ │ ├── wechat-pay/ # 微信支付 │ │ │ │ └── stripe/ # 信用卡(Stripe) │ │ │ └── interfaces/ │ │ └── package.json │ │ │ ├── admin-service/ # 管理服务 │ │ ├── src/ │ │ │ ├── domain/ │ │ │ │ ├── entities/ │ │ │ │ │ ├── admin-user.entity.ts │ │ │ │ │ ├── role.entity.ts │ │ │ │ │ └── system-config.entity.ts │ │ │ │ └── services/ │ │ │ ├── application/ │ │ │ ├── infrastructure/ │ │ │ └── interfaces/ │ │ └── package.json │ │ │ └── evolution-service/ # 进化服务 (核心) │ ├── src/ │ │ ├── domain/ │ │ │ ├── entities/ │ │ │ │ ├── experience.entity.ts │ │ │ │ ├── pattern.entity.ts │ │ │ │ └── evolution-log.entity.ts │ │ │ └── services/ │ │ │ ├── experience-extractor.service.ts │ │ │ ├── pattern-recognizer.service.ts │ │ │ └── evolution-engine.service.ts │ │ ├── application/ │ │ │ ├── commands/ │ │ │ │ ├── extract-experience.command.ts │ │ │ │ └── apply-evolution.command.ts │ │ │ └── services/ │ │ ├── infrastructure/ │ │ │ ├── analyzers/ # 分析器 │ │ │ └── adapters/ # 适配器 │ │ └── interfaces/ │ └── package.json │ ├── infrastructure/ # 基础设施配置 │ ├── docker/ │ │ ├── docker-compose.yml │ │ ├── docker-compose.dev.yml │ │ └── services/ │ │ ├── postgres/ │ │ ├── neo4j/ │ │ ├── redis/ │ │ └── kafka/ │ ├── k8s/ # Kubernetes 配置 (可选) │ └── scripts/ # 部署脚本 │ ├── package.json # Root package.json ├── pnpm-workspace.yaml # pnpm workspace 配置 ├── turbo.json # Turborepo 配置 ├── tsconfig.base.json # TypeScript 基础配置 ├── .env.example # 环境变量示例 └── README.md # 项目说明 ``` --- ## 核心模块设计 ### 1. 对话服务 (Conversation Service) #### Claude Agent SDK 集成 ```typescript // conversation-service/src/infrastructure/claude/claude-client.ts import Anthropic from '@anthropic-ai/sdk'; import { Injectable } from '@nestjs/common'; @Injectable() export class ClaudeAgentClient { private client: Anthropic; constructor(private configService: ConfigService) { this.client = new Anthropic({ apiKey: this.configService.get('ANTHROPIC_API_KEY'), }); } async createConversation( systemPrompt: string, tools: Tool[], ): Promise { // 创建带有工具的对话会话 } async sendMessage( sessionId: string, message: string, context: ConversationContext, ): AsyncGenerator { // 流式发送消息并获取响应 } } ``` #### 对话工具定义 系统需要定义以下 Agent Tools: 1. **知识检索工具** - 从 RAG 系统检索相关知识 2. **评估工具** - 收集用户信息进行移民评估 3. **支付工具** - 生成支付二维码 4. **记忆工具** - 读写长期记忆 ```typescript // conversation-service/src/infrastructure/claude/tools/index.ts export const immigrationTools = [ { name: 'search_knowledge', description: '搜索香港移民相关知识库', input_schema: { type: 'object', properties: { query: { type: 'string', description: '搜索查询' }, category: { type: 'string', enum: ['优才计划', '专才计划', '留学IANG', '高才通', '投资移民', '科技人才'], description: '移民类别' } }, required: ['query'] } }, { name: 'start_assessment', description: '开始移民资格评估(付费服务)', input_schema: { type: 'object', properties: { category: { type: 'string', description: '评估的移民类别' }, user_info: { type: 'object', description: '用户基本信息' } }, required: ['category'] } }, { name: 'generate_payment', description: '生成支付二维码', input_schema: { type: 'object', properties: { amount: { type: 'number', description: '支付金额' }, service_type: { type: 'string', description: '服务类型' }, payment_method: { type: 'string', enum: ['alipay', 'wechat', 'credit_card'], description: '支付方式' } }, required: ['amount', 'service_type', 'payment_method'] } }, { name: 'check_off_topic', description: '检查问题是否与移民相关', input_schema: { type: 'object', properties: { question: { type: 'string', description: '用户问题' } }, required: ['question'] } } ]; ``` #### 系统提示词设计 ```typescript // conversation-service/src/infrastructure/claude/prompts/system-prompt.ts export const buildSystemPrompt = (config: SystemConfig): string => ` 你是 iConsulting 的香港移民咨询顾问,专门为用户提供香港各类移民政策的咨询服务。 ## 身份定位 ${config.identity || '专业、友善、耐心的移民顾问'} ## 服务范围 你只回答与香港移民相关的问题,包括以下6大类别: ### 1. 优才计划 (QMAS - Quality Migrant Admission Scheme) - **目的**: 吸纳优秀人才来港定居 - **审核标准**: 年龄、教育经历、工作经验、语言能力、年收入证明、良好品格、是否持有公司等 - **人才类型**: 行业翘楚、精英人士 - **名额**: 暂无名额限制 - **申请要点**: 年龄、教育经历、工作经验、年收入证明、良好品格,是否符合等方面的要求(共12项),满足其中6项为基本门槛,择优批准 ### 2. 专才计划 (GEP - General Employment Policy) - **目的**: 吸引专业人才来港就业 - **审核标准**: 雇佣企业的行业背景、行业内的地位、政策扶持力度、所属行业经济地位 - **人才类型**: 专业人士(≥200万年薪,属于人才清单) - **名额**: 无配额限制(不限行业) - **申请要点**: 必须有雇主担保、要保持工作连续性(被裁3个月内)、工作和居住在非粤港澳、申请前至少有一年半社保记录、提供所在公司配套宣传图 ### 3. 留学IANG (Immigration Arrangements for Non-local Graduates) - **目的**: 吸引优秀学生人才来港续读 - **审核标准**: 有无完成学业、是否有雇主担保 - **人才类型**: 成绩优异、拥有国际化视野的学生 - **名额**: 扩展到本港大学大湾区校区毕业生,为期2年、1年后续签 - **申请要点**: 必须有雇主担保、要保持工作连续性 ### 4. 高才通计划 (TTPS - Top Talent Pass Scheme) - **目的**: 吸引高端人才来港 - **审核标准**: - A类: 年薪≥250万港币 - B类: 毕业于世界前100名大学,5年内有3年以上工作经验 - C类: 毕业于世界前100名大学,5年内有少于3年工作经验(年度限额10,000名) - **人才类型**: 顶尖人才 - **名额**: 无限期计划(推出后制一进行检讨) ### 5. 投资移民 (新资本投资者入境计划) - **目的**: 吸引投资者 - **审核标准**: 投资不少于3,000万港币(或等值外币)净资产于其指定对实益拥有者的许可投资 - **人才类型**: 投资者 - **名额**: 无名额限制 - **申请要点**: 资产审查新政3月1日起,申请人只须证明在提出申请六个月前已期限内持有该资产(1,000万元额度可获考虑) ### 6. 科技人才入境计划 (TechTAS) - **目的**: 吸引科技人才来港就业 - **审核标准**: 申请人主要从事先进通讯技术、人工智能、生物科技、网络安全、数据分析、数码娱乐、金融科技、绿色科技、集成电路设计、物联网、材料科学、微电子、量子科技、机械人技术等研究工作;申请薪酬应不低于香港特区该业务的市场薪酬水平 - **人才类型**: 科技人才 - **名额**: 需用公司高新创新科技营配出有效配额 - **申请要点**: 由符合创新科技署发出的获配证出有效配额 ## 行为准则 1. 如果用户询问与移民无关的问题,礼貌地引导回移民话题 2. 对于复杂的评估需求,建议使用付费评估服务 3. 提供信息时注明信息来源和更新时间 4. 不做任何法律承诺或申请成功率的保证 ## 付费服务 当用户需要个性化移民评估时,介绍付费评估服务: - 说明服务内容和价值 - 确认用户意愿后生成支付码 ## 对话风格 ${config.conversationStyle || '专业但不生硬,用简洁明了的语言解答'} ## 已积累的经验 ${config.accumulatedExperience || '暂无'} ## 管理员特别指示 ${config.adminInstructions || '暂无'} `; ``` ### 2. 知识服务 (Knowledge Service) #### RAG 架构 ```typescript // knowledge-service/src/domain/services/rag.service.ts @Injectable() export class RAGService { constructor( private vectorStore: VectorStoreRepository, private embeddingService: EmbeddingService, private graphService: GraphService, ) {} async search(query: string, options: SearchOptions): Promise { // 1. 向量相似度搜索 const embedding = await this.embeddingService.embed(query); const vectorResults = await this.vectorStore.search(embedding, options.limit); // 2. 图谱增强(可选) if (options.useGraph) { const graphContext = await this.graphService.getRelatedNodes( vectorResults.map(r => r.nodeId) ); return this.mergeResults(vectorResults, graphContext); } return vectorResults; } async addDocument(doc: Document): Promise { // 1. 文档分块 const chunks = await this.chunkDocument(doc); // 2. 向量化并存储 for (const chunk of chunks) { const embedding = await this.embeddingService.embed(chunk.content); await this.vectorStore.insert({ content: chunk.content, embedding, metadata: chunk.metadata, }); } // 3. 更新知识图谱 await this.graphService.addDocumentNodes(doc, chunks); } } ``` #### 知识图谱 (Neo4j) ```typescript // knowledge-service/src/infrastructure/graph-db/neo4j.repository.ts @Injectable() export class Neo4jRepository { constructor(private neo4jService: Neo4jService) {} // 添加用户记忆节点 async addMemory(memory: Memory): Promise { await this.neo4jService.write(` MERGE (u:User {id: $userId}) CREATE (m:Memory { id: $memoryId, content: $content, timestamp: datetime($timestamp), type: $type }) CREATE (u)-[:HAS_MEMORY {timestamp: datetime($timestamp)}]->(m) `, { userId: memory.userId, memoryId: memory.id, content: memory.content, timestamp: memory.timestamp.toISOString(), type: memory.type, }); } // 获取用户时间线记忆 async getUserTimeline(userId: string, limit: number = 50): Promise { const result = await this.neo4jService.read(` MATCH (u:User {id: $userId})-[r:HAS_MEMORY]->(m:Memory) RETURN m ORDER BY m.timestamp DESC LIMIT $limit `, { userId, limit }); return result.records.map(r => this.mapToMemory(r.get('m'))); } // 知识关联查询 async getRelatedKnowledge(topic: string): Promise { const result = await this.neo4jService.read(` MATCH (n:Knowledge)-[r:RELATED_TO*1..2]-(related) WHERE n.topic CONTAINS $topic RETURN n, related, r `, { topic }); return this.mapToKnowledgeNodes(result); } } ``` ### 3. 进化服务 (Evolution Service) 这是系统的核心创新点,实现自我学习和进化。 #### 经验提取器 ```typescript // evolution-service/src/domain/services/experience-extractor.service.ts @Injectable() export class ExperienceExtractorService { constructor( private claudeClient: ClaudeAgentClient, private experienceRepo: ExperienceRepository, ) {} // 从对话中提取经验 async extractFromConversation(conversation: Conversation): Promise { const prompt = ` 分析以下对话,提取有价值的经验: 1. 用户常见问题模式 2. 有效的回答策略 3. 用户满意度信号 4. 需要改进的地方 对话内容: ${JSON.stringify(conversation.messages)} 请以JSON格式返回经验列表。 `; const response = await this.claudeClient.analyze(prompt); return this.parseExperiences(response); } // 定期批量分析 async batchAnalyze(): Promise { const conversations = await this.getRecentConversations(); const prompt = ` 分析以下 ${conversations.length} 个对话,总结: 1. 高频问题 TOP 10 2. 用户最关心的移民类别 3. 转化率较高的话术 4. 常见的用户困惑点 5. 建议的系统改进方向 请生成详细的分析报告。 `; return await this.claudeClient.analyze(prompt); } } ``` #### 进化引擎 ```typescript // evolution-service/src/domain/services/evolution-engine.service.ts @Injectable() export class EvolutionEngineService { constructor( private experienceRepo: ExperienceRepository, private configService: SystemConfigService, private claudeClient: ClaudeAgentClient, ) {} // 与管理员对话,理解意图 async interactWithAdmin( adminMessage: string, context: AdminContext, ): Promise { const experiences = await this.experienceRepo.getRecentExperiences(); const currentConfig = await this.configService.getCurrentConfig(); const prompt = ` 你是 iConsulting 系统的进化引擎。 ## 当前系统配置 ${JSON.stringify(currentConfig)} ## 近期积累的经验 ${JSON.stringify(experiences)} ## 管理员指令 ${adminMessage} ## 任务 1. 理解管理员的意图 2. 基于积累的经验,提出具体的调整方案 3. 生成新的配置或行为规则 请返回: - 对管理员意图的理解 - 建议的调整方案 - 需要确认的事项(如有) `; return await this.claudeClient.analyze(prompt); } // 应用进化 async applyEvolution(evolution: Evolution): Promise { // 更新系统提示词 if (evolution.promptChanges) { await this.configService.updatePrompt(evolution.promptChanges); } // 更新知识库 if (evolution.knowledgeChanges) { await this.knowledgeService.applyChanges(evolution.knowledgeChanges); } // 更新业务规则 if (evolution.ruleChanges) { await this.configService.updateRules(evolution.ruleChanges); } // 记录进化日志 await this.evolutionLogRepo.save({ timestamp: new Date(), changes: evolution, triggeredBy: evolution.adminId, }); } } ``` ### 4. 支付服务 (Payment Service) ```typescript // payment-service/src/infrastructure/alipay/alipay.adapter.ts @Injectable() export class AlipayAdapter implements PaymentGateway { constructor(private configService: ConfigService) { this.alipay = new AlipaySdk({ appId: this.configService.get('ALIPAY_APP_ID'), privateKey: this.configService.get('ALIPAY_PRIVATE_KEY'), // ... }); } async createPayment(order: Order): Promise { const result = await this.alipay.exec('alipay.trade.precreate', { bizContent: { out_trade_no: order.id, total_amount: order.amount.toString(), subject: order.subject, } }); return { qrCode: result.qrCode, orderId: order.id, expireAt: new Date(Date.now() + 30 * 60 * 1000), // 30分钟有效 }; } async handleCallback(payload: AlipayCallback): Promise { // 验签并处理回调 } } ``` ### 5. 用户服务 (User Service) #### 匿名用户处理 ```typescript // user-service/src/domain/entities/user.entity.ts export class User extends AggregateRoot { id: UserId; type: UserType; // ANONYMOUS | REGISTERED fingerprint?: string; phone?: string; createdAt: Date; lastActiveAt: Date; static createAnonymous(fingerprint: string): User { return new User({ id: UserId.generate(), type: UserType.ANONYMOUS, fingerprint, createdAt: new Date(), lastActiveAt: new Date(), }); } upgradeToRegistered(phone: string): void { this.phone = phone; this.type = UserType.REGISTERED; this.addDomainEvent(new UserUpgradedEvent(this.id, phone)); } } ``` --- ## 数据模型设计 ### PostgreSQL 表结构 ```sql -- 用户表 CREATE TABLE users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), type VARCHAR(20) NOT NULL DEFAULT 'ANONYMOUS', fingerprint VARCHAR(255), phone VARCHAR(20), created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), last_active_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- 对话表 CREATE TABLE conversations ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES users(id), status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE', created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), ended_at TIMESTAMP WITH TIME ZONE ); -- 消息表 CREATE TABLE messages ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), conversation_id UUID REFERENCES conversations(id), role VARCHAR(20) NOT NULL, -- user, assistant, system content TEXT NOT NULL, metadata JSONB, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- 订单表 CREATE TABLE orders ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES users(id), service_type VARCHAR(50) NOT NULL, amount DECIMAL(10, 2) NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'PENDING', payment_method VARCHAR(20), paid_at TIMESTAMP WITH TIME ZONE, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- 发件箱表 (Outbox Pattern) CREATE TABLE outbox ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), aggregate_type VARCHAR(100) NOT NULL, aggregate_id UUID NOT NULL, event_type VARCHAR(100) NOT NULL, payload JSONB NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), processed_at TIMESTAMP WITH TIME ZONE ); -- 知识文档表 CREATE TABLE documents ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), title VARCHAR(255) NOT NULL, content TEXT NOT NULL, category VARCHAR(50), metadata JSONB, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- 向量存储表 (pgvector) CREATE TABLE document_embeddings ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), document_id UUID REFERENCES documents(id), chunk_index INT NOT NULL, content TEXT NOT NULL, embedding vector(1536), metadata JSONB, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- 系统配置表 CREATE TABLE system_configs ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), key VARCHAR(100) UNIQUE NOT NULL, value JSONB NOT NULL, updated_by UUID, updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- 管理员表 CREATE TABLE admin_users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), username VARCHAR(100) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, role VARCHAR(50) NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- 进化日志表 CREATE TABLE evolution_logs ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), triggered_by UUID REFERENCES admin_users(id), change_type VARCHAR(50) NOT NULL, changes JSONB NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); ``` ### Neo4j 图模型 ```cypher // 用户节点 (:User { id: string, type: string, createdAt: datetime }) // 记忆节点 (:Memory { id: string, content: string, type: string, // FACT, PREFERENCE, INTERACTION timestamp: datetime }) // 知识节点 (:Knowledge { id: string, topic: string, content: string, category: string, updatedAt: datetime }) // 经验节点 (:Experience { id: string, pattern: string, insight: string, frequency: int, createdAt: datetime }) // 关系定义 (User)-[:HAS_MEMORY {timestamp}]->(Memory) (User)-[:ASKED_ABOUT]->(Knowledge) (Knowledge)-[:RELATED_TO {weight}]->(Knowledge) (Experience)-[:DERIVED_FROM]->(Conversation) (Experience)-[:INFLUENCES]->(SystemConfig) ``` --- ## API 设计 ### REST API ```yaml # 用户端 API /api/v1: /auth: /anonymous: POST: 创建匿名会话 /verify-phone: POST: 发送验证码 /login: POST: 手机号登录 /conversations: POST: 创建新对话 GET: 获取对话列表 /{id}: GET: 获取对话详情 /messages: POST: 发送消息 (HTTP) /payments: POST: 创建支付订单 /{id}/status: GET: 查询支付状态 # 管理端 API /admin/api/v1: /auth: /login: POST: 管理员登录 /knowledge: GET: 获取知识列表 POST: 添加知识 /{id}: PUT: 更新知识 DELETE: 删除知识 /upload: POST: 上传文档 /evolution: /chat: POST: 与系统进化引擎对话 /experiences: GET: 获取经验总结 /apply: POST: 应用进化变更 /configs: GET: 获取配置 PUT: 更新配置 /analytics: /dashboard: GET: 获取仪表盘数据 /conversations: GET: 对话统计 /payments: GET: 支付统计 ``` ### WebSocket API ```typescript // 对话 WebSocket ws://host/ws/conversation // 客户端 -> 服务端 { type: 'message', conversationId: 'uuid', content: '用户消息' } // 服务端 -> 客户端 (流式) { type: 'stream_start', messageId: 'uuid' } { type: 'stream_chunk', messageId: 'uuid', content: '部分内容', index: 0 } { type: 'stream_end', messageId: 'uuid' } { type: 'tool_call', tool: 'generate_payment', result: { qrCode: '...', orderId: '...' } } ``` --- ## 前端架构 (Clean Architecture) ### 目录结构详解 ``` features/chat/ ├── domain/ # 领域层 │ ├── entities/ │ │ ├── Message.ts # 消息实体 │ │ └── Conversation.ts # 对话实体 │ ├── repositories/ │ │ └── IChatRepository.ts # 仓储接口 │ └── usecases/ │ ├── SendMessageUseCase.ts │ └── GetConversationUseCase.ts │ ├── data/ # 数据层 │ ├── repositories/ │ │ └── ChatRepositoryImpl.ts │ ├── datasources/ │ │ ├── ChatApiDataSource.ts │ │ └── ChatWebSocketDataSource.ts │ └── models/ │ ├── MessageModel.ts │ └── ConversationModel.ts │ └── presentation/ # 表现层 ├── components/ │ ├── ChatWindow.tsx │ ├── MessageBubble.tsx │ ├── InputArea.tsx │ └── PaymentModal.tsx ├── hooks/ │ ├── useChat.ts │ └── useWebSocket.ts ├── stores/ │ └── chatStore.ts └── pages/ └── ChatPage.tsx ``` ### 核心组件示例 ```tsx // features/chat/presentation/components/ChatWindow.tsx import { useChat } from '../hooks/useChat'; import { MessageBubble } from './MessageBubble'; import { InputArea } from './InputArea'; export const ChatWindow: React.FC = () => { const { messages, isStreaming, sendMessage, currentStreamContent } = useChat(); return (
{messages.map((msg) => ( ))} {isStreaming && ( )}
); }; ``` --- ## 部署方案 ### Docker Compose (开发环境) ```yaml # infrastructure/docker/docker-compose.dev.yml version: '3.8' services: postgres: image: pgvector/pgvector:pg15 environment: POSTGRES_USER: iconsulting POSTGRES_PASSWORD: dev_password POSTGRES_DB: iconsulting ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data neo4j: image: neo4j:5 environment: NEO4J_AUTH: neo4j/dev_password ports: - "7474:7474" - "7687:7687" volumes: - neo4j_data:/data redis: image: redis:7-alpine ports: - "6379:6379" zookeeper: image: confluentinc/cp-zookeeper:7.4.0 environment: ZOOKEEPER_CLIENT_PORT: 2181 ports: - "2181:2181" kafka: image: confluentinc/cp-kafka:7.4.0 depends_on: - zookeeper ports: - "9092:9092" environment: KAFKA_BROKER_ID: 1 KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 volumes: postgres_data: neo4j_data: ``` --- ## 开发计划 ### Phase 1: 基础架构 (核心) 1. 项目初始化和工程配置 2. 数据库 Schema 和连接 3. 基础微服务框架搭建 4. API 网关配置 ### Phase 2: 核心对话功能 1. Claude Agent SDK 集成 2. 对话服务完整实现 3. WebSocket 实时通信 4. 基础知识检索 (RAG) ### Phase 3: 支付和用户 1. 支付服务对接 2. 用户认证体系 3. 订单管理 ### Phase 4: 知识和记忆 1. Neo4j 知识图谱 2. 长期记忆系统 3. RAG 优化 ### Phase 5: 进化系统 1. 经验提取引擎 2. 管理员交互界面 3. 自动进化机制 ### Phase 6: 管理后台 1. 管理员认证 2. 知识库管理 3. 系统配置 4. 数据统计 ### Phase 7: 前端完善 1. 用户端 UI 完善 2. 管理端 UI 完善 3. 移动端适配 ### Phase 8: 测试和优化 1. 单元测试 2. 集成测试 3. 性能优化 4. 安全审计 --- ## 环境变量配置 ```env # .env.example # Anthropic ANTHROPIC_API_KEY=sk-ant-xxx # PostgreSQL POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_USER=iconsulting POSTGRES_PASSWORD=your_password POSTGRES_DB=iconsulting # Neo4j NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=your_password # Redis REDIS_HOST=localhost REDIS_PORT=6379 # Kafka KAFKA_BROKERS=localhost:9092 # 支付宝 ALIPAY_APP_ID=your_app_id ALIPAY_PRIVATE_KEY=your_private_key ALIPAY_PUBLIC_KEY=alipay_public_key # 微信支付 WECHAT_APP_ID=your_app_id WECHAT_MCH_ID=your_mch_id WECHAT_API_KEY=your_api_key # JWT JWT_SECRET=your_jwt_secret JWT_EXPIRES_IN=7d # 服务端口 API_GATEWAY_PORT=3000 USER_SERVICE_PORT=3001 CONVERSATION_SERVICE_PORT=3002 KNOWLEDGE_SERVICE_PORT=3003 PAYMENT_SERVICE_PORT=3004 ADMIN_SERVICE_PORT=3005 EVOLUTION_SERVICE_PORT=3006 ``` --- ## 安全考虑 1. **API 安全** - JWT 认证 - 请求限流 - 输入验证 - SQL 注入防护 2. **支付安全** - 签名验证 - 回调白名单 - 金额校验 3. **数据安全** - 敏感数据加密 - 日志脱敏 - 定期备份 4. **Claude API 安全** - API Key 安全存储 - 输入内容过滤 - 输出内容审核 --- ## 下一步行动 1. 确认移民类别列表(等待图片) 2. 创建项目目录结构 3. 初始化 Monorepo 配置 4. 搭建基础微服务框架 5. 集成 Claude Agent SDK 准备好后请告知,我将开始创建项目结构!