add chat type
This commit is contained in:
parent
f21da37f51
commit
65892036c1
@ -1,180 +0,0 @@
|
|||||||
# AI聊天功能使用说明
|
|
||||||
|
|
||||||
## 概述
|
|
||||||
|
|
||||||
AI聊天模块为徵象防伪验证平台提供智能客服功能,基于Moonshot Kimi K2 API实现。
|
|
||||||
|
|
||||||
## 文件结构
|
|
||||||
|
|
||||||
```
|
|
||||||
api/products/
|
|
||||||
├── aichat.py # 核心AI聊天库
|
|
||||||
├── management/
|
|
||||||
│ └── commands/
|
|
||||||
│ └── chat.py # Django管理命令
|
|
||||||
└── README_AI_CHAT.md # 本文档
|
|
||||||
```
|
|
||||||
|
|
||||||
## 使用方法
|
|
||||||
|
|
||||||
### 1. 作为Django管理命令运行(推荐)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 进入Django项目目录
|
|
||||||
cd api
|
|
||||||
|
|
||||||
# 启动AI聊天
|
|
||||||
python manage.py chat
|
|
||||||
|
|
||||||
# 使用自定义参数
|
|
||||||
python manage.py chat --api-key "your_key" --history-file "~/.custom_history"
|
|
||||||
```
|
|
||||||
|
|
||||||
**可用参数:**
|
|
||||||
- `--history-file`: 指定历史文件路径 (默认: ~/.aichat_history)
|
|
||||||
|
|
||||||
**注意:** API密钥和URL现在从Django设置中自动获取,无需命令行参数
|
|
||||||
|
|
||||||
### 2. 作为Python库导入
|
|
||||||
|
|
||||||
```python
|
|
||||||
from products.aichat import AIChatService
|
|
||||||
|
|
||||||
# 创建服务实例
|
|
||||||
service = AIChatService()
|
|
||||||
|
|
||||||
# 发送消息
|
|
||||||
response = service.chat("你好,请介绍一下徵象平台")
|
|
||||||
|
|
||||||
# 查看对话历史
|
|
||||||
history = service.get_conversation_history()
|
|
||||||
|
|
||||||
# 清空历史
|
|
||||||
service.clear_history()
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. 直接运行库文件(测试模式)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python api/products/aichat.py
|
|
||||||
```
|
|
||||||
|
|
||||||
## 功能特性
|
|
||||||
|
|
||||||
### 核心功能
|
|
||||||
- **智能对话**: 基于Kimi K2的AI客服
|
|
||||||
- **工具调用**: 支持二维码扫描等工具
|
|
||||||
- **多轮对话**: 完整的对话历史管理
|
|
||||||
- **品牌定制**: 徵象平台专属系统提示词
|
|
||||||
|
|
||||||
### 控制台功能
|
|
||||||
- **Readline支持**: 完整的命令行体验
|
|
||||||
- **历史记录**: 持久化的输入历史
|
|
||||||
- **智能补全**: Tab键命令补全
|
|
||||||
- **快捷键**: Emacs风格的编辑快捷键
|
|
||||||
|
|
||||||
## 可用命令
|
|
||||||
|
|
||||||
在聊天界面中,可以使用以下命令:
|
|
||||||
|
|
||||||
- `help` - 显示帮助信息
|
|
||||||
- `history` - 查看AI对话历史
|
|
||||||
- `clear` - 清空对话历史
|
|
||||||
- `readline-help` - 显示快捷键帮助
|
|
||||||
- `stats` - 显示readline统计信息
|
|
||||||
- `quit/exit/q` - 退出系统
|
|
||||||
|
|
||||||
## 快捷键
|
|
||||||
|
|
||||||
### 导航
|
|
||||||
- `↑/↓` - 浏览历史记录
|
|
||||||
- `Ctrl+A` - 跳转到行首
|
|
||||||
- `Ctrl+E` - 跳转到行尾
|
|
||||||
|
|
||||||
### 编辑
|
|
||||||
- `Ctrl+U` - 删除到行首
|
|
||||||
- `Ctrl+K` - 删除到行尾
|
|
||||||
- `Ctrl+W` - 删除单词
|
|
||||||
|
|
||||||
### 搜索
|
|
||||||
- `Ctrl+R` - 反向搜索历史
|
|
||||||
- `Ctrl+S` - 正向搜索历史
|
|
||||||
|
|
||||||
### 补全
|
|
||||||
- `Tab` - 自动补全命令
|
|
||||||
|
|
||||||
## 配置说明
|
|
||||||
|
|
||||||
### 环境变量
|
|
||||||
- `KIMI_API_KEY`: Moonshot API密钥(在Django设置中配置)
|
|
||||||
- `KIMI_API_URL`: Moonshot API基础URL(在Django设置中配置)
|
|
||||||
|
|
||||||
### Django设置配置
|
|
||||||
API凭证在 `emblemapi/settings.py` 中配置:
|
|
||||||
```python
|
|
||||||
KIMI_API_KEY = "your_api_key_here"
|
|
||||||
KIMI_API_URL = "https://api.moonshot.cn/v1"
|
|
||||||
```
|
|
||||||
|
|
||||||
### 历史文件
|
|
||||||
- 默认位置: `~/.aichat_history`
|
|
||||||
- 最大记录数: 1000条
|
|
||||||
- 自动保存: 退出时自动保存
|
|
||||||
|
|
||||||
## 开发说明
|
|
||||||
|
|
||||||
### 扩展工具
|
|
||||||
在`AIChatService._define_tools()`中添加新工具:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def _define_tools(self):
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
"type": "function",
|
|
||||||
"function": {
|
|
||||||
"name": "your_tool_name",
|
|
||||||
"description": "工具描述",
|
|
||||||
"parameters": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {},
|
|
||||||
"required": []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
### 自定义系统提示词
|
|
||||||
修改`_add_system_message()`方法中的`system_prompt`变量。
|
|
||||||
|
|
||||||
## 故障排除
|
|
||||||
|
|
||||||
### 常见问题
|
|
||||||
|
|
||||||
1. **API调用失败**
|
|
||||||
- 检查API密钥是否正确
|
|
||||||
- 确认网络连接正常
|
|
||||||
- 查看错误日志
|
|
||||||
|
|
||||||
2. **Readline功能异常**
|
|
||||||
- 确认终端支持readline
|
|
||||||
- 检查历史文件权限
|
|
||||||
- 尝试重新创建历史文件
|
|
||||||
|
|
||||||
3. **导入错误**
|
|
||||||
- 确认Django环境已激活
|
|
||||||
- 检查Python路径设置
|
|
||||||
- 验证依赖包安装
|
|
||||||
|
|
||||||
### 调试模式
|
|
||||||
使用`--verbosity=2`参数获取详细日志:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python manage.py chat --verbosity=2
|
|
||||||
```
|
|
||||||
|
|
||||||
## 更新日志
|
|
||||||
|
|
||||||
- **v1.0**: 初始版本,支持基础AI聊天和工具调用
|
|
||||||
- **v1.1**: 添加readline支持和Django管理命令
|
|
||||||
- **v1.2**: 重构为库模块,分离界面和核心功能
|
|
||||||
@ -31,12 +31,14 @@ class ToolResult:
|
|||||||
class AIChatService:
|
class AIChatService:
|
||||||
"""AI聊天服务主类"""
|
"""AI聊天服务主类"""
|
||||||
|
|
||||||
def __init__(self, api_key: str = None, base_url: str = None):
|
def __init__(self, api_key: str = None, base_url: str = None, chat_type: str = 'platform', product_id: int = None):
|
||||||
"""初始化AI聊天服务
|
"""初始化AI聊天服务
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
api_key: Moonshot API密钥
|
api_key: Moonshot API密钥
|
||||||
base_url: API基础URL
|
base_url: API基础URL
|
||||||
|
chat_type: 聊天类型 ('platform' 或 'product')
|
||||||
|
product_id: 产品ID,当chat_type为'product'时使用
|
||||||
"""
|
"""
|
||||||
self.api_key = api_key or getattr(settings, 'KIMI_API_KEY', None)
|
self.api_key = api_key or getattr(settings, 'KIMI_API_KEY', None)
|
||||||
self.base_url = base_url or getattr(settings, 'KIMI_API_URL', None)
|
self.base_url = base_url or getattr(settings, 'KIMI_API_URL', None)
|
||||||
@ -44,6 +46,14 @@ class AIChatService:
|
|||||||
if not self.api_key:
|
if not self.api_key:
|
||||||
raise ValueError("KIMI_API_KEY is required")
|
raise ValueError("KIMI_API_KEY is required")
|
||||||
|
|
||||||
|
# 聊天类型和产品ID
|
||||||
|
self.chat_type = chat_type
|
||||||
|
self.product_id = product_id
|
||||||
|
|
||||||
|
# 验证参数
|
||||||
|
if chat_type == 'product' and not product_id:
|
||||||
|
raise ValueError("当chat_type为'product'时,必须提供product_id")
|
||||||
|
|
||||||
self.client = OpenAI(
|
self.client = OpenAI(
|
||||||
api_key=self.api_key,
|
api_key=self.api_key,
|
||||||
base_url=self.base_url
|
base_url=self.base_url
|
||||||
@ -75,7 +85,8 @@ class AIChatService:
|
|||||||
|
|
||||||
def _add_system_message(self):
|
def _add_system_message(self):
|
||||||
"""添加系统提示词"""
|
"""添加系统提示词"""
|
||||||
system_prompt = """你是一个专业的徵象防伪验证平台AI客服助手。
|
if self.chat_type == 'platform':
|
||||||
|
system_prompt = """你是一个专业的徵象防伪验证平台AI客服助手。
|
||||||
|
|
||||||
平台介绍:
|
平台介绍:
|
||||||
徵象是由广州市诚投科技有限公司开发的AI驱动的智能防伪平台,通过多模态特征识别构建新一代防伪验证体系,实现从物理防伪到数字认证的全链路保护。系统采用ISO 12931国际防伪标准,已获取国家发明专利(证书编号:CN 115222000 B)。
|
徵象是由广州市诚投科技有限公司开发的AI驱动的智能防伪平台,通过多模态特征识别构建新一代防伪验证体系,实现从物理防伪到数字认证的全链路保护。系统采用ISO 12931国际防伪标准,已获取国家发明专利(证书编号:CN 115222000 B)。
|
||||||
@ -96,6 +107,28 @@ class AIChatService:
|
|||||||
可用工具:
|
可用工具:
|
||||||
- start_qr_scan: 启动二维码扫描功能,用于产品防伪验证
|
- start_qr_scan: 启动二维码扫描功能,用于产品防伪验证
|
||||||
|
|
||||||
|
请根据用户问题提供准确、有用的回答。如果用户需要验证产品,请使用二维码扫描工具。"""
|
||||||
|
|
||||||
|
elif self.chat_type == 'product':
|
||||||
|
system_prompt = f"""你是一个专业的徵象防伪验证平台产品客服助手,专门为产品ID {self.product_id} 提供客服服务。
|
||||||
|
|
||||||
|
平台介绍:
|
||||||
|
徵象是由广州市诚投科技有限公司开发的AI驱动的智能防伪平台,通过多模态特征识别构建新一代防伪验证体系,实现从物理防伪到数字认证的全链路保护。
|
||||||
|
|
||||||
|
当前服务产品:
|
||||||
|
- 产品ID: {self.product_id}
|
||||||
|
- 服务类型: 产品专属客服
|
||||||
|
|
||||||
|
服务原则:
|
||||||
|
1. 专业、友好、准确回答用户关于该产品的问题
|
||||||
|
2. 优先使用产品相关信息回答
|
||||||
|
3. 对于不确定的信息,明确告知用户
|
||||||
|
4. 引导用户使用相关功能和服务
|
||||||
|
5. 当用户需要验证产品真伪时,主动提供二维码扫描功能
|
||||||
|
|
||||||
|
可用工具:
|
||||||
|
- start_qr_scan: 启动二维码扫描功能,用于产品防伪验证
|
||||||
|
|
||||||
请根据用户问题提供准确、有用的回答。如果用户需要验证产品,请使用二维码扫描工具。"""
|
请根据用户问题提供准确、有用的回答。如果用户需要验证产品,请使用二维码扫描工具。"""
|
||||||
|
|
||||||
self.conversation_history.append({
|
self.conversation_history.append({
|
||||||
|
|||||||
@ -99,11 +99,36 @@ class Command(BaseCommand):
|
|||||||
type=str,
|
type=str,
|
||||||
help='指定历史文件路径 (默认: ~/.aichat_history)'
|
help='指定历史文件路径 (默认: ~/.aichat_history)'
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
'--chat-type',
|
||||||
|
type=str,
|
||||||
|
choices=['platform', 'product'],
|
||||||
|
default='platform',
|
||||||
|
help='聊天类型: platform(平台客服) 或 product(产品客服) (默认: platform)'
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
'--product-id',
|
||||||
|
type=int,
|
||||||
|
help='产品ID,当chat-type为product时必须提供'
|
||||||
|
)
|
||||||
|
|
||||||
def handle(self, *args, **options):
|
def handle(self, *args, **options):
|
||||||
"""执行命令"""
|
"""执行命令"""
|
||||||
|
# 参数验证
|
||||||
|
chat_type = options.get('chat_type')
|
||||||
|
product_id = options.get('product_id')
|
||||||
|
|
||||||
|
if chat_type == 'product' and not product_id:
|
||||||
|
self.stderr.write("❌ 错误: 当chat-type为product时,必须提供--product-id参数")
|
||||||
|
self.stderr.write("示例: python manage.py chat --chat-type product --product-id 12345")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 显示系统信息
|
||||||
self.stdout.write("🚀 徵象防伪验证平台 AI客服系统")
|
self.stdout.write("🚀 徵象防伪验证平台 AI客服系统")
|
||||||
self.stdout.write("=" * 50)
|
self.stdout.write("=" * 50)
|
||||||
|
self.stdout.write(f"聊天类型: {chat_type.upper()}")
|
||||||
|
if product_id:
|
||||||
|
self.stdout.write(f"产品ID: {product_id}")
|
||||||
self.stdout.write("输入 'help' 查看帮助信息")
|
self.stdout.write("输入 'help' 查看帮助信息")
|
||||||
self.stdout.write("输入 'history' 查看对话历史")
|
self.stdout.write("输入 'history' 查看对话历史")
|
||||||
self.stdout.write("输入 'clear' 清空对话历史")
|
self.stdout.write("输入 'clear' 清空对话历史")
|
||||||
@ -116,8 +141,11 @@ class Command(BaseCommand):
|
|||||||
# 初始化readline
|
# 初始化readline
|
||||||
readline_config = ReadlineConfig(options.get('history_file'))
|
readline_config = ReadlineConfig(options.get('history_file'))
|
||||||
|
|
||||||
# 初始化AI服务
|
# 初始化AI服务,传递聊天类型和产品ID
|
||||||
ai_service = AIChatService()
|
ai_service = AIChatService(
|
||||||
|
chat_type=chat_type,
|
||||||
|
product_id=product_id
|
||||||
|
)
|
||||||
self.stdout.write("✅ AI服务初始化成功!")
|
self.stdout.write("✅ AI服务初始化成功!")
|
||||||
self.stdout.write("")
|
self.stdout.write("")
|
||||||
|
|
||||||
|
|||||||
618
doc/ai-chat.md
618
doc/ai-chat.md
@ -77,18 +77,306 @@ class AIChatService:
|
|||||||
- **工具执行**: 模拟5秒扫描过程,返回验证结果
|
- **工具执行**: 模拟5秒扫描过程,返回验证结果
|
||||||
- **工具集成**: 完整的工具调用流程,支持多轮对话
|
- **工具集成**: 完整的工具调用流程,支持多轮对话
|
||||||
|
|
||||||
#### 4.1.4 智能能力调度系统(简化版)
|
#### 4.1.4 智能能力调度系统
|
||||||
- **能力分类**: RAG知识检索、平台服务、一般问答
|
- **架构选择**: 直接以Tool形式接入Kimi K2,无需复杂路由
|
||||||
- **优先级策略**: 平台服务 > RAG知识 > 一般问答
|
- **能力分类**: 知识库检索工具、二维码扫描工具、一般问答
|
||||||
- **智能路由**: 基于规则的快速路由策略
|
- **调度策略**: 依赖Kimi K2的智能判断,自动选择合适的工具
|
||||||
- **降级机制**: 简单的能力降级和回退
|
- **优势**: 实现简单、维护成本低、Kimi K2原生支持
|
||||||
- **后续扩展**: 工具执行、网络搜索等高级功能
|
- **扩展性**: 后续可轻松添加更多工具,无需修改路由逻辑
|
||||||
|
|
||||||
#### 4.1.5 RAG框架集成(简化版)
|
#### 4.1.5 本地知识库系统
|
||||||
- **框架选择**: LangChain基础功能
|
- **存储方案**: 向量数据库 + 文件存储
|
||||||
- **文档处理**: 基础分块、简单向量化、相似度检索
|
- **内容类型**: 文字、图片、视频、文档
|
||||||
- **上下文优化**: 基础分层策略(摘要、完整)
|
- **检索策略**: 语义搜索 + 关键词匹配
|
||||||
- **检索策略**: 向量相似度检索,关键词匹配作为备选
|
- **更新机制**: 支持实时更新和版本控制
|
||||||
|
- **成本优化**: 本地处理,减少API调用
|
||||||
|
|
||||||
|
#### 4.1.6 RAG架构设计
|
||||||
|
```python
|
||||||
|
class AIChatService:
|
||||||
|
def __init__(self):
|
||||||
|
self.client = OpenAI(api_key=KIMI_API_KEY, base_url=KIMI_API_URL)
|
||||||
|
self.knowledge_base = LocalKnowledgeBase() # 本地知识库
|
||||||
|
self.tools = self._define_tools()
|
||||||
|
|
||||||
|
def chat(self, message: str) -> str:
|
||||||
|
# 步骤1:从本地知识库检索相关信息
|
||||||
|
relevant_docs = self.knowledge_base.search(message, k=3)
|
||||||
|
|
||||||
|
# 步骤2:构建增强的上下文
|
||||||
|
enhanced_context = self._build_enhanced_context(message, relevant_docs)
|
||||||
|
|
||||||
|
# 步骤3:使用Kimi K2生成回答(基于检索到的信息)
|
||||||
|
response = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": self.system_prompt + enhanced_context},
|
||||||
|
{"role": "user", "content": message}
|
||||||
|
],
|
||||||
|
tools=self.tools,
|
||||||
|
tool_choice="auto"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 步骤4:处理工具调用(如果需要)
|
||||||
|
if response.choices[0].message.tool_calls:
|
||||||
|
# 执行工具调用逻辑...
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 步骤5:将问答对保存到知识库(可选)
|
||||||
|
self.knowledge_base.add_qa_pair(message, response.choices[0].message.content)
|
||||||
|
|
||||||
|
return response.choices[0].message.content
|
||||||
|
|
||||||
|
def _build_enhanced_context(self, query: str, docs: List[Document]) -> str:
|
||||||
|
"""构建增强的上下文信息"""
|
||||||
|
if not docs:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
context = "\n\n相关参考信息:\n"
|
||||||
|
for i, doc in enumerate(docs, 1):
|
||||||
|
context += f"{i}. {doc.page_content}\n"
|
||||||
|
|
||||||
|
context += f"\n请基于以上信息回答用户问题:{query}"
|
||||||
|
return context
|
||||||
|
```
|
||||||
|
|
||||||
|
**RAG流程**:
|
||||||
|
- **检索(Retrieval)**:从本地知识库找到相关信息
|
||||||
|
- **增强(Augmentation)**:将检索到的信息作为上下文
|
||||||
|
- **生成(Generation)**:Kimi K2基于增强的上下文生成回答
|
||||||
|
|
||||||
|
#### 4.1.7 本地知识库实现
|
||||||
|
```python
|
||||||
|
class LocalKnowledgeBase:
|
||||||
|
def __init__(self):
|
||||||
|
# 使用轻量级向量数据库
|
||||||
|
self.vector_store = Chroma(
|
||||||
|
embedding_function=OpenAIEmbeddings(api_key=KIMI_API_KEY),
|
||||||
|
persist_directory="./knowledge_base"
|
||||||
|
)
|
||||||
|
self.file_storage = FileStorage() # 文件存储
|
||||||
|
|
||||||
|
def search(self, query: str, k: int = 3, threshold: float = 0.5) -> List[Document]:
|
||||||
|
"""搜索本地知识库,返回相关文档列表"""
|
||||||
|
# 语义搜索
|
||||||
|
results = self.vector_store.similarity_search_with_score(query, k=k)
|
||||||
|
|
||||||
|
# 过滤低置信度结果,但保留更多候选
|
||||||
|
filtered_results = [r for r in results if r[1] > threshold]
|
||||||
|
|
||||||
|
# 转换为Document对象列表
|
||||||
|
documents = []
|
||||||
|
for doc, score in filtered_results:
|
||||||
|
documents.append(Document(
|
||||||
|
page_content=doc.page_content,
|
||||||
|
metadata={
|
||||||
|
**doc.metadata,
|
||||||
|
'similarity_score': score
|
||||||
|
}
|
||||||
|
))
|
||||||
|
|
||||||
|
return documents
|
||||||
|
|
||||||
|
def add_content(self, content: str, content_type: str, metadata: dict):
|
||||||
|
"""添加内容到知识库"""
|
||||||
|
# 文本内容直接向量化
|
||||||
|
if content_type == 'text':
|
||||||
|
self.vector_store.add_texts([content], [metadata])
|
||||||
|
|
||||||
|
# 图片内容使用OCR提取文本
|
||||||
|
elif content_type == 'image':
|
||||||
|
text = self._extract_text_from_image(content)
|
||||||
|
self.vector_store.add_texts([text], [metadata])
|
||||||
|
|
||||||
|
# 视频内容提取关键帧和音频
|
||||||
|
elif content_type == 'video':
|
||||||
|
frames = self._extract_key_frames(content)
|
||||||
|
audio_text = self._extract_audio_text(content)
|
||||||
|
self.vector_store.add_texts([audio_text], [metadata])
|
||||||
|
|
||||||
|
def add_qa_pair(self, question: str, answer: str):
|
||||||
|
"""添加问答对到知识库"""
|
||||||
|
qa_text = f"问题:{question}\n答案:{answer}"
|
||||||
|
metadata = {
|
||||||
|
'type': 'qa_pair',
|
||||||
|
'question': question,
|
||||||
|
'answer': answer,
|
||||||
|
'created_at': datetime.now().isoformat()
|
||||||
|
}
|
||||||
|
self.vector_store.add_texts([qa_text], [metadata])
|
||||||
|
```
|
||||||
|
|
||||||
|
**技术特点**:
|
||||||
|
- **轻量级**:使用Chroma向量数据库,无需复杂部署
|
||||||
|
- **多模态**:支持文字、图片、视频内容
|
||||||
|
- **实时更新**:支持动态添加和更新内容
|
||||||
|
- **成本优化**:本地处理,减少API调用
|
||||||
|
|
||||||
|
#### 4.1.8 完整RAG实现示例
|
||||||
|
```python
|
||||||
|
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
||||||
|
from langchain.embeddings import OpenAIEmbeddings
|
||||||
|
from langchain.vectorstores import Chroma
|
||||||
|
from langchain.document_loaders import TextLoader, ImageLoader, VideoLoader
|
||||||
|
|
||||||
|
class RAGService:
|
||||||
|
def __init__(self):
|
||||||
|
self.embeddings = OpenAIEmbeddings(api_key=KIMI_API_KEY)
|
||||||
|
self.text_splitter = RecursiveCharacterTextSplitter(
|
||||||
|
chunk_size=1000,
|
||||||
|
chunk_overlap=200
|
||||||
|
)
|
||||||
|
self.vector_store = Chroma(
|
||||||
|
embedding_function=self.embeddings,
|
||||||
|
persist_directory="./knowledge_base"
|
||||||
|
)
|
||||||
|
|
||||||
|
def add_document(self, file_path: str, content_type: str):
|
||||||
|
"""添加文档到知识库"""
|
||||||
|
if content_type == 'text':
|
||||||
|
loader = TextLoader(file_path)
|
||||||
|
elif content_type == 'image':
|
||||||
|
loader = ImageLoader(file_path)
|
||||||
|
elif content_type == 'video':
|
||||||
|
loader = VideoLoader(file_path)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"不支持的内容类型: {content_type}")
|
||||||
|
|
||||||
|
documents = loader.load()
|
||||||
|
# 分块处理
|
||||||
|
chunks = self.text_splitter.split_documents(documents)
|
||||||
|
# 添加到向量数据库
|
||||||
|
self.vector_store.add_documents(chunks)
|
||||||
|
|
||||||
|
def retrieve_context(self, query: str, k: int = 3) -> str:
|
||||||
|
"""检索相关上下文"""
|
||||||
|
docs = self.vector_store.similarity_search(query, k=k)
|
||||||
|
context = "\n\n".join([doc.page_content for doc in docs])
|
||||||
|
return context
|
||||||
|
|
||||||
|
def generate_answer(self, query: str, context: str) -> str:
|
||||||
|
"""使用Kimi K2生成回答"""
|
||||||
|
enhanced_prompt = f"""
|
||||||
|
基于以下参考信息回答用户问题:
|
||||||
|
|
||||||
|
参考信息:
|
||||||
|
{context}
|
||||||
|
|
||||||
|
用户问题:{query}
|
||||||
|
|
||||||
|
请基于参考信息提供准确、详细的回答。如果参考信息不足以回答问题,请明确说明。
|
||||||
|
"""
|
||||||
|
|
||||||
|
response = self.client.chat.completions.create(
|
||||||
|
model="kimi-k2-0711-preview",
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": "你是徵象防伪验证平台的AI助手,请基于提供的参考信息回答问题。"},
|
||||||
|
{"role": "user", "content": enhanced_prompt}
|
||||||
|
],
|
||||||
|
temperature=0.7,
|
||||||
|
max_tokens=2000
|
||||||
|
)
|
||||||
|
|
||||||
|
return response.choices[0].message.content
|
||||||
|
|
||||||
|
# 使用示例
|
||||||
|
rag_service = RAGService()
|
||||||
|
|
||||||
|
# 添加文档
|
||||||
|
rag_service.add_document("产品说明.txt", "text")
|
||||||
|
rag_service.add_document("防伪标识.jpg", "image")
|
||||||
|
rag_service.add_document("操作演示.mp4", "video")
|
||||||
|
|
||||||
|
# 问答流程
|
||||||
|
query = "如何验证产品真伪?"
|
||||||
|
context = rag_service.retrieve_context(query)
|
||||||
|
answer = rag_service.generate_answer(query, context)
|
||||||
|
```
|
||||||
|
|
||||||
|
**RAG优势**:
|
||||||
|
- **信息可控**:检索到的信息来自平台知识库
|
||||||
|
- **回答质量**:Kimi K2基于准确信息生成高质量回答
|
||||||
|
- **成本优化**:避免重复的API调用,知识库一次构建多次使用
|
||||||
|
- **专业性强**:平台专业知识 + AI生成能力
|
||||||
|
|
||||||
|
#### 4.1.9 架构选择说明
|
||||||
|
|
||||||
|
**为什么选择直接以Tool形式接入Kimi K2?**
|
||||||
|
|
||||||
|
1. **符合Kimi K2设计理念**
|
||||||
|
- Kimi K2本身就是为工具调用设计的
|
||||||
|
- 原生支持Function Calling,无需额外路由层
|
||||||
|
- AI能根据上下文智能选择合适的工具
|
||||||
|
|
||||||
|
2. **实现简单,维护成本低**
|
||||||
|
- 代码逻辑清晰,易于理解和维护
|
||||||
|
- 避免复杂的if-else路由规则
|
||||||
|
- 减少系统复杂度,降低出错概率
|
||||||
|
|
||||||
|
3. **足够灵活,扩展性好**
|
||||||
|
- 可以轻松添加新的工具
|
||||||
|
- 工具优先级通过描述和系统提示词控制
|
||||||
|
- 支持复杂的工具组合调用
|
||||||
|
|
||||||
|
4. **性能优势**
|
||||||
|
- 减少额外的路由判断逻辑
|
||||||
|
- 直接利用Kimi K2的智能判断能力
|
||||||
|
- 避免不必要的中间层处理
|
||||||
|
|
||||||
|
**具体实现方式**:
|
||||||
|
```python
|
||||||
|
def _define_tools(self):
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "search_knowledge_base",
|
||||||
|
"description": "搜索徵象平台知识库,获取产品信息、防伪验证方法、技术文档等相关内容。当用户询问平台相关问题时,优先使用此工具。",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"query": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "搜索查询,支持中文关键词"
|
||||||
|
},
|
||||||
|
"content_type": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["all", "text", "image", "video"],
|
||||||
|
"description": "内容类型过滤"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["query"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "start_qr_scan",
|
||||||
|
"description": "启动二维码扫描功能,用于产品防伪验证。当用户需要验证产品真伪时使用。",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {},
|
||||||
|
"required": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
**系统提示词优化**:
|
||||||
|
```python
|
||||||
|
system_prompt = """你是一个专业的徵象防伪验证平台AI客服助手。
|
||||||
|
|
||||||
|
使用策略:
|
||||||
|
1. 当用户询问平台相关问题时,优先使用search_knowledge_base工具搜索知识库
|
||||||
|
2. 当用户需要验证产品真伪时,使用start_qr_scan工具启动扫描
|
||||||
|
3. 基于检索到的信息,结合你的知识,提供准确、详细的回答
|
||||||
|
4. 如果知识库信息不足,可以结合你的通用知识回答,但要明确说明信息来源
|
||||||
|
|
||||||
|
工具优先级:知识库搜索 > 二维码扫描 > 一般问答
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
|
||||||
### 4.2 数据模型扩展
|
### 4.2 数据模型扩展
|
||||||
|
|
||||||
@ -161,6 +449,11 @@ class Tenant(models.Model):
|
|||||||
ai_brand_name = models.CharField(max_length=100, null=True, blank=True, verbose_name="AI品牌名称")
|
ai_brand_name = models.CharField(max_length=100, null=True, blank=True, verbose_name="AI品牌名称")
|
||||||
ai_welcome_message = models.TextField(null=True, blank=True, verbose_name="AI欢迎语")
|
ai_welcome_message = models.TextField(null=True, blank=True, verbose_name="AI欢迎语")
|
||||||
ai_theme_colors = models.JSONField(null=True, blank=True, verbose_name="AI主题色彩")
|
ai_theme_colors = models.JSONField(null=True, blank=True, verbose_name="AI主题色彩")
|
||||||
|
|
||||||
|
# TODO: 在MiniProgramContent模型中添加enable_ai_chat字段
|
||||||
|
# class MiniProgramContent(models.Model):
|
||||||
|
# # ... 现有字段 ...
|
||||||
|
# enable_ai_chat = models.BooleanField(default=False, verbose_name="启用AI客服")
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4.3 后端API设计
|
### 4.3 后端API设计
|
||||||
@ -413,6 +706,12 @@ Page({
|
|||||||
- 头像和图标上传
|
- 头像和图标上传
|
||||||
- 回答风格调整
|
- 回答风格调整
|
||||||
|
|
||||||
|
#### 4.5.3 首页AI客服开关
|
||||||
|
- TODO: 在MiniProgramContent中添加enable_ai_chat字段
|
||||||
|
- 后台管理:简单的on/off开关
|
||||||
|
- 小程序端:判断bool值,如果为true则跳转到chat页面
|
||||||
|
- 实现方式:几行代码即可完成
|
||||||
|
|
||||||
#### 4.5.3 平台知识库管理(简化版)
|
#### 4.5.3 平台知识库管理(简化版)
|
||||||
- 平台介绍内容(4000字)的基础分块
|
- 平台介绍内容(4000字)的基础分块
|
||||||
- 分层内容策略:摘要、完整两个层次
|
- 分层内容策略:摘要、完整两个层次
|
||||||
@ -427,74 +726,6 @@ Page({
|
|||||||
|
|
||||||
## 5. 技术实现细节
|
## 5. 技术实现细节
|
||||||
|
|
||||||
### 5.1 AI Prompt工程
|
|
||||||
|
|
||||||
#### 5.1.1 系统Prompt模板 ✅ **已实现**
|
|
||||||
```
|
|
||||||
你是一个专业的徵象防伪验证平台AI客服助手。
|
|
||||||
|
|
||||||
平台介绍:
|
|
||||||
徵象是由广州市诚投科技有限公司开发的AI驱动的智能防伪平台,通过多模态特征识别构建新一代防伪验证体系,实现从物理防伪到数字认证的全链路保护。系统采用ISO 12931国际防伪标准,已获取国家发明专利(证书编号:CN 115222000 B)。
|
|
||||||
|
|
||||||
服务范围:
|
|
||||||
1. 商品防伪验证
|
|
||||||
2. 证件安全验证
|
|
||||||
3. 工业品防伪
|
|
||||||
4. 品牌数字化服务
|
|
||||||
|
|
||||||
服务原则:
|
|
||||||
1. 专业、友好、准确回答用户问题
|
|
||||||
2. 优先使用官方信息回答
|
|
||||||
3. 对于不确定的信息,明确告知用户
|
|
||||||
4. 引导用户使用相关功能和服务
|
|
||||||
5. 当用户需要验证产品真伪时,主动提供二维码扫描功能
|
|
||||||
|
|
||||||
可用工具:
|
|
||||||
- start_qr_scan: 启动二维码扫描功能,用于产品防伪验证
|
|
||||||
|
|
||||||
请根据用户问题提供准确、有用的回答。如果用户需要验证产品,请使用二维码扫描工具。
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 5.1.2 平台客服Prompt模板
|
|
||||||
```
|
|
||||||
你是一个专业的徵象防伪验证平台客服助手。
|
|
||||||
|
|
||||||
平台介绍:
|
|
||||||
徵象是由广州市诚投科技有限公司开发的AI驱动的智能防伪平台,通过多模态特征识别构建新一代防伪验证体系,实现从物理防伪到数字认证的全链路保护。系统采用ISO 12931国际防伪标准,已获取国家发明专利(证书编号:CN 115222000 B)。
|
|
||||||
|
|
||||||
服务范围:
|
|
||||||
1. 商品防伪验证
|
|
||||||
2. 证件安全验证
|
|
||||||
3. 工业品防伪
|
|
||||||
4. 品牌数字化服务
|
|
||||||
|
|
||||||
服务原则:
|
|
||||||
1. 专业、友好、准确回答用户问题
|
|
||||||
2. 优先使用官方信息回答
|
|
||||||
3. 对于不确定的信息,明确告知用户
|
|
||||||
4. 引导用户使用相关功能和服务
|
|
||||||
|
|
||||||
请根据用户问题提供准确、有用的回答。
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 5.1.2 动态Prompt构建
|
|
||||||
```python
|
|
||||||
def build_dynamic_prompt(self, message, context, tenant_context):
|
|
||||||
# 获取品牌知识
|
|
||||||
knowledge = self._get_relevant_knowledge(message, tenant_context)
|
|
||||||
|
|
||||||
# 获取产品信息
|
|
||||||
product_info = self._get_product_info(context.get('serial_code'))
|
|
||||||
|
|
||||||
# 构建完整prompt
|
|
||||||
prompt = self._get_system_prompt(tenant_context)
|
|
||||||
prompt += f"\n\n相关产品信息:{product_info}"
|
|
||||||
prompt += f"\n\n品牌知识:{knowledge}"
|
|
||||||
prompt += f"\n\n用户问题:{message}"
|
|
||||||
|
|
||||||
return prompt
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 5.1.3 智能能力路由(简化版)
|
#### 5.1.3 智能能力路由(简化版)
|
||||||
```python
|
```python
|
||||||
def route_capability(self, query, context):
|
def route_capability(self, query, context):
|
||||||
@ -566,30 +797,106 @@ function renderContent(content, type) {
|
|||||||
- 简单性能监控
|
- 简单性能监控
|
||||||
- 后续版本支持高级功能
|
- 后续版本支持高级功能
|
||||||
|
|
||||||
## 6. 部署和运维
|
### 5.5 上下文长度管理
|
||||||
|
|
||||||
### 6.1 环境配置 ✅ **已实现**
|
#### 5.5.1 当前问题
|
||||||
```bash
|
- **无限累积**:对话历史无限制增长
|
||||||
# Django设置配置 (emblemapi/settings.py)
|
- **Token超限**:可能超出API的token限制
|
||||||
KIMI_API_KEY = "sk-IKA7ZnDrv44mfaorjF5UZjSsml66yaBNdcrASJsV90hCSdgn"
|
- **内存占用**:长时间对话占用大量内存
|
||||||
KIMI_API_URL = "https://api.moonshot.cn/v1"
|
- **API失败**:超长历史可能导致API调用失败
|
||||||
|
|
||||||
# 环境变量支持
|
#### 5.5.2 优化策略
|
||||||
KIMI_API_KEY = os.environ.get("KIMI_API_KEY", "default_key")
|
```python
|
||||||
KIMI_API_URL = os.environ.get("KIMI_API_URL", "https://api.moonshot.cn/v1")
|
class AIChatService:
|
||||||
|
def __init__(self, api_key: str = None, base_url: str = None):
|
||||||
|
# ... 现有代码 ...
|
||||||
|
self.max_history_length = 20 # 最大历史记录数
|
||||||
|
self.max_tokens_per_message = 1000 # 每条消息最大token数
|
||||||
|
|
||||||
|
def _truncate_history(self):
|
||||||
|
"""截断对话历史,保持上下文长度"""
|
||||||
|
if len(self.conversation_history) > self.max_history_length:
|
||||||
|
# 保留系统提示词和最近的对话
|
||||||
|
system_message = self.conversation_history[0] # 系统提示词
|
||||||
|
recent_messages = self.conversation_history[-self.max_history_length+1:]
|
||||||
|
self.conversation_history = [system_message] + recent_messages
|
||||||
|
|
||||||
|
def _estimate_tokens(self, text: str) -> int:
|
||||||
|
"""估算文本的token数量(简化版)"""
|
||||||
|
# 中文约1.5字符=1token,英文约4字符=1token
|
||||||
|
chinese_chars = len([c for c in text if '\u4e00' <= c <= '\u9fff'])
|
||||||
|
english_chars = len(text) - chinese_chars
|
||||||
|
return int(chinese_chars / 1.5 + english_chars / 4)
|
||||||
|
|
||||||
|
def _smart_truncate(self):
|
||||||
|
"""智能截断:基于token数量而非消息数量"""
|
||||||
|
total_tokens = sum(self._estimate_tokens(msg['content']) for msg in self.conversation_history)
|
||||||
|
max_total_tokens = 4000 # 预留1000token给AI回复
|
||||||
|
|
||||||
|
if total_tokens > max_total_tokens:
|
||||||
|
# 保留系统提示词和最近的对话,直到token数合适
|
||||||
|
system_message = self.conversation_history[0]
|
||||||
|
truncated_history = [system_message]
|
||||||
|
|
||||||
|
for msg in reversed(self.conversation_history[1:]):
|
||||||
|
truncated_history.insert(1, msg)
|
||||||
|
current_tokens = sum(self._estimate_tokens(m['content']) for m in truncated_history)
|
||||||
|
if current_tokens > max_total_tokens:
|
||||||
|
truncated_history.pop(1) # 移除刚添加的消息
|
||||||
|
break
|
||||||
|
|
||||||
|
self.conversation_history = truncated_history
|
||||||
```
|
```
|
||||||
|
|
||||||
### 6.2 监控和日志
|
#### 5.5.3 分层历史策略
|
||||||
- AI API调用监控
|
```python
|
||||||
- 响应时间统计
|
def _build_context_aware_history(self, user_message: str) -> List[Dict]:
|
||||||
- 错误率监控
|
"""构建上下文感知的对话历史"""
|
||||||
- 用户满意度反馈
|
# 策略1:保留最近的N轮对话
|
||||||
|
recent_messages = self.conversation_history[-10:] # 最近10轮
|
||||||
|
|
||||||
|
# 策略2:保留关键信息(如工具调用结果)
|
||||||
|
important_messages = [msg for msg in self.conversation_history
|
||||||
|
if msg.get('role') == 'tool' or '重要' in msg.get('content', '')]
|
||||||
|
|
||||||
|
# 策略3:动态调整:根据用户问题复杂度决定保留多少历史
|
||||||
|
if '刚才' in user_message or '之前' in user_message:
|
||||||
|
# 用户引用之前内容,保留更多历史
|
||||||
|
context_messages = self.conversation_history[-15:]
|
||||||
|
else:
|
||||||
|
# 新话题,保留较少历史
|
||||||
|
context_messages = self.conversation_history[-5:]
|
||||||
|
|
||||||
|
return [self.conversation_history[0]] + context_messages # 系统提示词 + 上下文
|
||||||
|
```
|
||||||
|
|
||||||
### 6.3 性能优化
|
#### 5.5.4 错误处理和降级
|
||||||
- 响应缓存
|
```python
|
||||||
- 异步处理
|
def chat(self, user_message: str) -> str:
|
||||||
- 负载均衡
|
try:
|
||||||
- 数据库优化
|
# 智能截断历史
|
||||||
|
self._smart_truncate()
|
||||||
|
|
||||||
|
# 调用API
|
||||||
|
response = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=self.conversation_history,
|
||||||
|
tools=self.tools,
|
||||||
|
tool_choice="auto",
|
||||||
|
temperature=0.7,
|
||||||
|
max_tokens=2000
|
||||||
|
)
|
||||||
|
|
||||||
|
# ... 处理响应 ...
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
if "context_length_exceeded" in str(e) or "token_limit" in str(e):
|
||||||
|
# Token超限,截断历史重试
|
||||||
|
self._truncate_history()
|
||||||
|
return self.chat(user_message) # 递归重试
|
||||||
|
else:
|
||||||
|
return f"AI服务调用失败: {str(e)}"
|
||||||
|
```
|
||||||
|
|
||||||
## 7. 安全考虑
|
## 7. 安全考虑
|
||||||
|
|
||||||
@ -600,30 +907,9 @@ KIMI_API_URL = os.environ.get("KIMI_API_URL", "https://api.moonshot.cn/v1")
|
|||||||
- 访问权限控制
|
- 访问权限控制
|
||||||
|
|
||||||
### 7.2 系统安全
|
### 7.2 系统安全
|
||||||
- 防SQL注入
|
|
||||||
- 防XSS攻击
|
|
||||||
- 请求频率限制
|
- 请求频率限制
|
||||||
- 异常监控告警
|
- 异常监控告警
|
||||||
|
|
||||||
## 8. 测试策略
|
|
||||||
|
|
||||||
### 8.1 功能测试
|
|
||||||
- AI对话准确性测试
|
|
||||||
- 多模态内容展示测试
|
|
||||||
- 品牌定制功能测试
|
|
||||||
- 异常情况处理测试
|
|
||||||
|
|
||||||
### 8.2 性能测试
|
|
||||||
- 并发用户测试
|
|
||||||
- 响应时间测试
|
|
||||||
- 内存使用测试
|
|
||||||
- 数据库性能测试
|
|
||||||
|
|
||||||
### 8.3 集成测试
|
|
||||||
- 与现有系统集成测试
|
|
||||||
- 第三方API集成测试
|
|
||||||
- 端到端流程测试
|
|
||||||
|
|
||||||
## 9. 项目计划
|
## 9. 项目计划
|
||||||
|
|
||||||
### 9.1 开发阶段
|
### 9.1 开发阶段
|
||||||
@ -634,12 +920,12 @@ KIMI_API_URL = os.environ.get("KIMI_API_URL", "https://api.moonshot.cn/v1")
|
|||||||
- 工具调用系统 ✅
|
- 工具调用系统 ✅
|
||||||
- Django管理命令 ✅
|
- Django管理命令 ✅
|
||||||
2. **第二阶段 (1周)**: AI能力扩展
|
2. **第二阶段 (1周)**: AI能力扩展
|
||||||
- LangChain RAG基础集成
|
- 知识库检索工具集成
|
||||||
- 平台知识库(简化版)
|
- 平台知识库(简化版)
|
||||||
- 智能路由基础功能
|
- 工具调用优化和扩展
|
||||||
3. **第三阶段 (1周)**: 前端界面和内容管理
|
3. **第三阶段 (1周)**: 小程序集成和内容管理
|
||||||
- 小程序AI聊天界面(核心功能)
|
- 小程序AI聊天界面(核心功能)
|
||||||
- Web管理端(基础配置)
|
- 小程序与AI服务的集成
|
||||||
- 内容管理基础功能
|
- 内容管理基础功能
|
||||||
4. **第四阶段 (1周)**: 集成测试和部署
|
4. **第四阶段 (1周)**: 集成测试和部署
|
||||||
- 功能测试和bug修复
|
- 功能测试和bug修复
|
||||||
@ -648,78 +934,36 @@ KIMI_API_URL = os.environ.get("KIMI_API_URL", "https://api.moonshot.cn/v1")
|
|||||||
|
|
||||||
### 9.2 里程碑
|
### 9.2 里程碑
|
||||||
- Week 1: 完成核心架构和基础AI聊天功能 ✅ **已完成**
|
- Week 1: 完成核心架构和基础AI聊天功能 ✅ **已完成**
|
||||||
- Week 2: 完成RAG系统和智能路由基础功能
|
- Week 2: 完成知识库检索工具和RAG系统基础功能
|
||||||
- Week 3: 完成前端界面和内容管理
|
- Week 3: 完成小程序AI聊天集成和内容管理
|
||||||
- Week 4: 完成测试、优化和上线
|
- Week 4: 完成测试、优化和上线
|
||||||
|
|
||||||
## 10. 风险评估
|
### 10.3 Backup
|
||||||
|
|
||||||
### 10.1 技术风险
|
|
||||||
- AI API稳定性风险
|
|
||||||
- 多模态内容处理复杂度
|
|
||||||
- 性能瓶颈风险
|
|
||||||
- 开发时间压缩导致的代码质量风险
|
|
||||||
- 功能简化可能影响用户体验
|
|
||||||
- 测试时间不足的风险
|
|
||||||
|
|
||||||
### 10.2 业务风险
|
|
||||||
- 用户接受度风险
|
|
||||||
- 内容管理复杂度
|
|
||||||
- 成本控制风险
|
|
||||||
|
|
||||||
### 10.3 缓解措施
|
|
||||||
- 多AI服务商备选方案
|
- 多AI服务商备选方案
|
||||||
- 渐进式功能发布
|
|
||||||
- 用户反馈快速迭代
|
|
||||||
- 功能优先级排序,核心功能优先
|
|
||||||
- 代码复用和模板化开发
|
|
||||||
- 自动化测试和部署
|
|
||||||
|
|
||||||
## 11. 总结
|
|
||||||
|
|
||||||
本技术方案基于现有徵象系统架构,通过AI服务集成、数据模型扩展、前后端界面开发,实现品牌专属AI客服功能。方案考虑了技术可行性、系统集成、用户体验和运维管理等各个方面,为项目的成功实施提供了全面的技术指导。
|
|
||||||
|
|
||||||
### 11.1 技术亮点
|
|
||||||
- **智能能力调度**: 基于优先级的多能力协调系统,支持RAG、平台服务、一般问答
|
|
||||||
- **RAG框架集成**: 基于LangChain的智能文档处理和向量检索
|
|
||||||
- **分层内容策略**: 4000字平台介绍的基础分块和内容选择
|
|
||||||
- **检索策略**: 向量相似度检索,关键词匹配作为备选
|
|
||||||
- **MVP策略**: 核心功能先行,后续版本迭代优化
|
|
||||||
|
|
||||||
### 11.2 开发周期
|
### 11.2 开发周期
|
||||||
- **总周期**: 4周(压缩版)
|
- **总周期**: 4周(压缩版)
|
||||||
- **核心功能**: AI聊天、RAG知识检索、智能路由、基础内容管理
|
- **核心功能**: AI聊天、RAG知识检索、工具调用、小程序集成、基础内容管理
|
||||||
- **技术栈**: Django + Kimi K2 + LangChain(简化版)+ 基础向量存储
|
- **技术栈**: Django + Kimi K2 + LangChain(知识库管理)+ 微信小程序 + 基础向量存储
|
||||||
- **开发策略**: MVP优先,核心功能先行,后续迭代优化
|
- **开发策略**: MVP优先,核心功能先行,小程序集成优先,后续迭代优化
|
||||||
|
|
||||||
### 11.3 当前实现状态 ✅ **已完成功能**
|
### 11.3 架构设计总结
|
||||||
|
|
||||||
#### **核心AI聊天系统**
|
**核心架构选择:直接以Tool形式接入Kimi K2**
|
||||||
- ✅ AIChatService 类实现
|
|
||||||
- ✅ Kimi K2 API 集成
|
|
||||||
- ✅ 工具调用系统(start_qr_scan)
|
|
||||||
- ✅ 对话历史管理
|
|
||||||
- ✅ 系统提示词配置
|
|
||||||
|
|
||||||
#### **Django管理命令**
|
1. **简化设计**:避免复杂的能力调度和路由逻辑
|
||||||
- ✅ `python manage.py chat` 命令
|
2. **原生支持**:充分利用Kimi K2的Function Calling能力
|
||||||
- ✅ 完整的readline支持
|
3. **易于维护**:代码结构清晰,逻辑简单
|
||||||
- ✅ 历史记录持久化
|
4. **扩展性好**:后续可以轻松添加更多工具
|
||||||
- ✅ 快捷键和补全功能
|
|
||||||
|
|
||||||
#### **文件结构**
|
**RAG实现方式**:
|
||||||
```
|
- 知识库检索作为工具提供给Kimi K2
|
||||||
api/products/
|
- AI根据用户问题自动选择是否使用知识库
|
||||||
├── aichat.py # 核心AI聊天库 ✅
|
- 基于检索结果生成高质量回答
|
||||||
├── management/
|
- 无需手动路由,完全依赖AI智能判断
|
||||||
│ └── commands/
|
|
||||||
│ └── chat.py # Django管理命令 ✅
|
|
||||||
└── README_AI_CHAT.md # 使用文档 ✅
|
|
||||||
```
|
|
||||||
|
|
||||||
#### **配置管理**
|
**技术优势**:
|
||||||
- ✅ Django settings.py 集成
|
- 减少系统复杂度
|
||||||
- ✅ 环境变量支持
|
- 降低维护成本
|
||||||
- ✅ 默认配置值
|
- 提高系统稳定性
|
||||||
|
- 保持架构简洁性
|
||||||
通过分阶段开发和迭代优化,可以确保系统稳定性和用户满意度,同时为后续功能扩展奠定良好基础。第一阶段的核心功能已经完成,为后续开发提供了坚实的基础。
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user