mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: add LLM memory extraction functionality with OpenAI support
- Implemented a new test script for LLM memory extraction in `test_llm_extraction.py`. - Created LLM client module with base class `LLMClient` and OpenAI-specific implementation. - Added fact extraction prompt template for structured memory extraction. - Integrated memory management with retrieval and intention extraction capabilities.
This commit is contained in:
parent
9d0a1f7a13
commit
0b4d5f594a
16 changed files with 999 additions and 7 deletions
3
aipet/__init__.py
Normal file
3
aipet/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
from .aipet import MemoryProvider
|
||||||
|
|
||||||
|
__all__ = ['MemoryProvider']
|
||||||
126
aipet/aipet.py
Normal file
126
aipet/aipet.py
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
import asyncio
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from ..base import MemoryProviderBase, logger
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
|
||||||
|
# 添加 xiaozhi-memory 路径
|
||||||
|
XIAOZHI_MEMORY_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../../xiaozhi-memory"))
|
||||||
|
if os.path.exists(XIAOZHI_MEMORY_PATH):
|
||||||
|
sys.path.insert(0, XIAOZHI_MEMORY_PATH)
|
||||||
|
|
||||||
|
|
||||||
|
class MemoryProvider(MemoryProviderBase):
|
||||||
|
def __init__(self, config, summary_memory=None):
|
||||||
|
super().__init__(config)
|
||||||
|
self.db_path = config.get("db_path", "./data/xiaozhi_memory.db")
|
||||||
|
self.manager = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
from core import MemoryManager
|
||||||
|
cfg = {
|
||||||
|
"retrieval_mode": config.get("retrieval_mode", "fts5"),
|
||||||
|
"sqlite": {"path": self.db_path},
|
||||||
|
# TODO: 临时写死 LLM 配置用于测试
|
||||||
|
"llm": {
|
||||||
|
"provider": "openai",
|
||||||
|
"api_key": "6202d63d-377b-4bd7-a2ad-c162ed977c24",
|
||||||
|
"model": "doubao-seed-2-0-lite-260428",
|
||||||
|
"base_url": "https://ark.cn-beijing.volces.com/api/v3"
|
||||||
|
},
|
||||||
|
"extraction": {
|
||||||
|
"enabled": True,
|
||||||
|
"max_retrieved_memories": 20,
|
||||||
|
"max_recent_memories": 10,
|
||||||
|
"observation_date_delta": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.manager = MemoryManager(cfg)
|
||||||
|
logger.bind(tag=TAG).info(f"成功初始化 aipet 记忆服务: {self.db_path}")
|
||||||
|
logger.bind(tag=TAG).info(f"LLM 提取已启用: {cfg['llm']['model']}")
|
||||||
|
except ImportError as e:
|
||||||
|
logger.bind(tag=TAG).error(f"xiaozhi-memory 未安装: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"初始化 aipet 记忆服务失败: {e}")
|
||||||
|
|
||||||
|
async def save_memory(self, msgs, session_id=None):
|
||||||
|
"""保存记忆"""
|
||||||
|
if not self.manager or not self.role_id:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 格式化消息
|
||||||
|
messages = []
|
||||||
|
for msg in msgs:
|
||||||
|
if msg.role in ("system", "tool"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
content = msg.content
|
||||||
|
if not content:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 处理 JSON 格式(ASR 情感标签)
|
||||||
|
try:
|
||||||
|
if content.strip().startswith("{"):
|
||||||
|
data = json.loads(content)
|
||||||
|
if "content" in data:
|
||||||
|
content = data["content"]
|
||||||
|
except (json.JSONDecodeError, KeyError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
messages.append({"role": msg.role, "content": content})
|
||||||
|
|
||||||
|
if messages:
|
||||||
|
result = await self.manager.add_memory(messages, self.role_id)
|
||||||
|
logger.bind(tag=TAG).debug(f"保存记忆结果: {result}")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def query_memory(self, query: str) -> str:
|
||||||
|
"""查询记忆"""
|
||||||
|
if not self.manager or not self.role_id:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
search_query = query
|
||||||
|
# 处理 JSON 格式
|
||||||
|
try:
|
||||||
|
if query.strip().startswith("{"):
|
||||||
|
data = json.loads(query)
|
||||||
|
if "content" in data:
|
||||||
|
search_query = data["content"]
|
||||||
|
except (json.JSONDecodeError, KeyError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
results = await self.manager.search(search_query, self.role_id, top_k=30)
|
||||||
|
|
||||||
|
if not results:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# 格式化记忆
|
||||||
|
memories = []
|
||||||
|
for m in results:
|
||||||
|
timestamp = m.created_at.strftime("%Y-%m-%d %H:%M") if m.created_at else ""
|
||||||
|
content = m.content
|
||||||
|
if timestamp and content:
|
||||||
|
memories.append((timestamp, f"[{timestamp}] {content}"))
|
||||||
|
|
||||||
|
# 按时间排序
|
||||||
|
memories.sort(key=lambda x: x[0], reverse=True)
|
||||||
|
return "\n".join(f"- {m[1]}" for m in memories)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"查询记忆失败: {e}")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
"""关闭连接"""
|
||||||
|
if self.manager:
|
||||||
|
self.manager.close()
|
||||||
319
xiaozhi-memory/LLM_EXTRACTION_DESIGN.md
Normal file
319
xiaozhi-memory/LLM_EXTRACTION_DESIGN.md
Normal file
|
|
@ -0,0 +1,319 @@
|
||||||
|
# xiaozhi-memory LLM 记忆提取方案
|
||||||
|
|
||||||
|
## 设计理念
|
||||||
|
|
||||||
|
结合 **mem0ai V3** 和 **PowerMem** 的优点,设计适合小智 ESP32 服务器的 LLM 记忆提取方案。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心策略选择
|
||||||
|
|
||||||
|
| 特性 | mem0ai V3 | PowerMem | **本方案** |
|
||||||
|
|------|-----------|----------|-----------|
|
||||||
|
| **操作策略** | Add-only | 完整 CRUD | **Add-only + 链接** |
|
||||||
|
| **LLM 调用** | 单次 | 两次(提取+决策) | **单次提取** |
|
||||||
|
| **时间处理** | Observation Date | Critical Rule #1 | **Critical Rule #1** |
|
||||||
|
| **意图提取** | 隐式 | Critical Rule #4 | **Critical Rule #4** |
|
||||||
|
| **多语言** | 未强调 | Critical Rule #5 | **Critical Rule #5** |
|
||||||
|
| **记忆链接** | ✅ linked_memory_ids | ❌ | **✅ linked_memory_ids** |
|
||||||
|
| **上下文丰富度** | 15-80词 | 中等 | **15-80词** |
|
||||||
|
|
||||||
|
**选择理由**:
|
||||||
|
- **Add-only**:简单高效,适合嵌入式设备,通过检索算法解决质量问题
|
||||||
|
- **记忆链接**:建立记忆间关联,提升检索相关性
|
||||||
|
- **Critical Rules**:保留 PowerMem 的核心规则(时间、意图、多语言)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 提示词设计
|
||||||
|
|
||||||
|
### FACT_EXTRACTION_PROMPT
|
||||||
|
|
||||||
|
```python
|
||||||
|
FACT_EXTRACTION_PROMPT = """你是一个个人信息提取助手。从对话中提取相关事实、记忆、偏好和意图。
|
||||||
|
|
||||||
|
CRITICAL 规则(按优先级):
|
||||||
|
1. TEMPORAL (时间): 始终提取时间信息。将相对时间转换为绝对时间,同时保留原始时间描述
|
||||||
|
- 例如: "两天后" → "2025-05-22 (两天后)"
|
||||||
|
- 使用 Observation Date 解析相对时间
|
||||||
|
|
||||||
|
2. INTENTIONS (意图): 始终提取用户的意图、需求和请求,即使没有时间信息
|
||||||
|
- 例如: "我想约个心脏科医生" → 意图记忆
|
||||||
|
- "明天要去开会" → 意图记忆
|
||||||
|
|
||||||
|
3. LANGUAGE (语言): 不要翻译!保持原文语言
|
||||||
|
- 中文输入 → 中文输出
|
||||||
|
- 英文输入 → 英文输出
|
||||||
|
- 混合输入 → 分别保持
|
||||||
|
|
||||||
|
4. COMPLETE (完整): 提取完整的事实,包含谁/什么/何时/何地
|
||||||
|
- 15-80词,上下文丰富
|
||||||
|
- 包含情感反应、动机
|
||||||
|
|
||||||
|
5. SEPARATE (分离): 不同时间段的事实用分开提取
|
||||||
|
- 不同主题分别提取
|
||||||
|
|
||||||
|
6. ATTRIBUTION (归属): 正确归属信息来源
|
||||||
|
- 用户陈述 → "User ..."
|
||||||
|
- 助手推荐 → "User was recommended ..."
|
||||||
|
|
||||||
|
记忆类型:
|
||||||
|
- FACT: 已发生的事实("昨天去了北京")
|
||||||
|
- INTENTION: 未来的计划和意图("明天要去开会")
|
||||||
|
- PREFERENCE: 偏好("喜欢喝咖啡")
|
||||||
|
|
||||||
|
输出格式:
|
||||||
|
{
|
||||||
|
"facts": [
|
||||||
|
{
|
||||||
|
"content": "记忆内容(保持原文语言,15-80词,上下文丰富)",
|
||||||
|
"type": "FACT|INTENTION|PREFERENCE",
|
||||||
|
"time_info": {"absolute": "2025-05-22", "relative": "两天后"},
|
||||||
|
"intention_type": "meeting|travel|task|purchase|appointment|...",
|
||||||
|
"linked_memory_ids": ["uuid1", "uuid2"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
如果提取到与现有记忆相关的新记忆,在 linked_memory_ids 中添加相关记忆的ID。
|
||||||
|
|
||||||
|
今天的日期: {current_date}
|
||||||
|
观察日期(用于解析相对时间): {observation_date}
|
||||||
|
|
||||||
|
最近提取的记忆:
|
||||||
|
{recently_extracted}
|
||||||
|
|
||||||
|
现有记忆:
|
||||||
|
{existing_memories}
|
||||||
|
|
||||||
|
从以下对话中提取信息:
|
||||||
|
{conversation}
|
||||||
|
|
||||||
|
只返回 JSON,不要其他内容。"""
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 处理流程
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ add_memory(messages, user_id) │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 1. 格式化消息 │
|
||||||
|
│ - 过滤 system 消息 │
|
||||||
|
│ - 处理 JSON 格式(ASR 情感标签) │
|
||||||
|
│ - 构建 conversation 字符串 │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 2. 获取上下文 │
|
||||||
|
│ - recently_extracted: 本会话最近提取的记忆(20条) │
|
||||||
|
│ - existing_memories: 相关的现有记忆(FTS5 检索) │
|
||||||
|
│ - current_date: 今天日期 │
|
||||||
|
│ - observation_date: 对话发生日期 │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 3. LLM 提取(单次调用) │
|
||||||
|
│ - 使用 FACT_EXTRACTION_PROMPT │
|
||||||
|
│ - 返回结构化的 facts 列表 │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 4. 去重与链接 │
|
||||||
|
│ - 与 recently_extracted 去重 │
|
||||||
|
│ - 检查与 existing_memories 的相似性 │
|
||||||
|
│ - 建立 linked_memory_ids │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 5. 存储记忆 │
|
||||||
|
│ - 创建 Memory 对象(FactMemory/IntentionMemory) │
|
||||||
|
│ - 保存到 SQLite │
|
||||||
|
│ - FTS5 索引自动更新 │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
返回 {"added": n, "updated": 0, "skipped": m}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 记忆对象映射
|
||||||
|
|
||||||
|
### LLM 输出 → Memory 对象
|
||||||
|
|
||||||
|
```python
|
||||||
|
def llm_output_to_memory(fact: dict, user_id: str) -> BaseMemory:
|
||||||
|
"""将 LLM 输出转换为 Memory 对象"""
|
||||||
|
|
||||||
|
fact_type = fact.get("type", "FACT")
|
||||||
|
|
||||||
|
common_data = {
|
||||||
|
"id": str(uuid.uuid4()),
|
||||||
|
"user_id": user_id,
|
||||||
|
"content": fact["content"],
|
||||||
|
"type": MemoryType.FACT if fact_type == "FACT" else MemoryType.INTENTION,
|
||||||
|
"created_at": datetime.now(),
|
||||||
|
"updated_at": datetime.now(),
|
||||||
|
"related_ids": fact.get("linked_memory_ids", []),
|
||||||
|
"time_info": fact.get("time_info"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if fact_type == "INTENTION":
|
||||||
|
common_data.update({
|
||||||
|
"intention_status": IntentionStatus.PLANNED,
|
||||||
|
"planned_time": parse_absolute_time(fact.get("time_info", {}).get("absolute")),
|
||||||
|
"time_description": fact.get("time_info", {}).get("relative"),
|
||||||
|
"intention_type": fact.get("intention_type"),
|
||||||
|
})
|
||||||
|
return IntentionMemory(**common_data)
|
||||||
|
|
||||||
|
return FactMemory(**common_data)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## LLM 客户端接口
|
||||||
|
|
||||||
|
```python
|
||||||
|
class LLMClient(ABC):
|
||||||
|
"""LLM 客户端基类"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def extract_facts(
|
||||||
|
self,
|
||||||
|
conversation: str,
|
||||||
|
context: dict
|
||||||
|
) -> List[dict]:
|
||||||
|
"""提取事实"""
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
### OpenAI 实现
|
||||||
|
|
||||||
|
```python
|
||||||
|
class OpenAIClient(LLMClient):
|
||||||
|
def __init__(self, api_key: str, model: str = "gpt-4o-mini"):
|
||||||
|
self.api_key = api_key
|
||||||
|
self.model = model
|
||||||
|
self.client = AsyncOpenAI(api_key=api_key)
|
||||||
|
|
||||||
|
async def extract_facts(self, conversation: str, context: dict) -> List[dict]:
|
||||||
|
prompt = FACT_EXTRACTION_PROMPT.format(**context, conversation=conversation)
|
||||||
|
|
||||||
|
response = await self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": "你是一个专业的个人信息提取助手。"},
|
||||||
|
{"role": "user", "content": prompt}
|
||||||
|
],
|
||||||
|
response_format={"type": "json_object"}
|
||||||
|
)
|
||||||
|
|
||||||
|
result = json.loads(response.choices[0].message.content)
|
||||||
|
return result.get("facts", [])
|
||||||
|
```
|
||||||
|
|
||||||
|
### Ollama 实现(本地免费)
|
||||||
|
|
||||||
|
```python
|
||||||
|
class OllamaClient(LLMClient):
|
||||||
|
def __init__(self, model: str = "qwen2:7b", base_url: str = "http://localhost:11434"):
|
||||||
|
self.model = model
|
||||||
|
self.base_url = base_url
|
||||||
|
|
||||||
|
async def extract_facts(self, conversation: str, context: dict) -> List[dict]:
|
||||||
|
prompt = FACT_EXTRACTION_PROMPT.format(**context, conversation=conversation)
|
||||||
|
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.post(
|
||||||
|
f"{self.base_url}/api/chat",
|
||||||
|
json={
|
||||||
|
"model": self.model,
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": "你是一个专业的个人信息提取助手。"},
|
||||||
|
{"role": "user", "content": prompt}
|
||||||
|
],
|
||||||
|
"format": "json",
|
||||||
|
"stream": False
|
||||||
|
}
|
||||||
|
) as resp:
|
||||||
|
result = await resp.json()
|
||||||
|
facts = json.loads(result["message"]["content"])
|
||||||
|
return facts.get("facts", [])
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 配置示例
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
memory:
|
||||||
|
retrieval_mode: fts5
|
||||||
|
|
||||||
|
sqlite:
|
||||||
|
path: ./data/xiaozhi_memory.db
|
||||||
|
|
||||||
|
# LLM 配置
|
||||||
|
llm:
|
||||||
|
provider: ollama # openai, ollama, zhipu
|
||||||
|
model: qwen2:7b
|
||||||
|
base_url: http://localhost:11434 # Ollama
|
||||||
|
api_key: xxx # OpenAI/智谱
|
||||||
|
|
||||||
|
# 提取配置
|
||||||
|
extraction:
|
||||||
|
enabled: true
|
||||||
|
max_retrieved_memories: 20 # 传入 LLM 的现有记忆数量
|
||||||
|
max_recent_memories: 10 # 最近提取的记忆数量
|
||||||
|
observation_date_delta: 0 # 对话日期偏移(天)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 关键优势
|
||||||
|
|
||||||
|
| 特性 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| **单次 LLM 调用** | mem0ai V3 策略,延迟低 |
|
||||||
|
| **记忆链接** | 建立记忆间关联,提升检索 |
|
||||||
|
| **Critical Rules** | PowerMem 的核心规则 |
|
||||||
|
| **上下文丰富** | 15-80词,保留完整信息 |
|
||||||
|
| **Add-only** | 简单高效,通过检索排序 |
|
||||||
|
| **时间感知** | Observation Date 解析相对时间 |
|
||||||
|
| **多语言保持** | 禁止翻译,保持原文 |
|
||||||
|
| **意图强调** | 即使没有时间也提取意图 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 实现优先级
|
||||||
|
|
||||||
|
### Phase 1: 基础 LLM 提取
|
||||||
|
- [ ] LLM 客户端基类和 OpenAI 实现
|
||||||
|
- [ ] FACT_EXTRACTION_PROMPT
|
||||||
|
- [ ] 修改 add_memory 使用 LLM 提取
|
||||||
|
- [ ] 去重机制
|
||||||
|
|
||||||
|
### Phase 2: 记忆链接
|
||||||
|
- [ ] linked_memory_ids 支持
|
||||||
|
- [ ] 相关记忆检索(用于链接)
|
||||||
|
- [ ] 链接关系存储
|
||||||
|
|
||||||
|
### Phase 3: 多 LLM 支持
|
||||||
|
- [ ] Ollama 客户端(本地免费)
|
||||||
|
- [ ] 智谱 AI 客户端
|
||||||
|
- [ ] 其他兼容 OpenAI API 的服务
|
||||||
|
|
||||||
|
### Phase 4: 优化
|
||||||
|
- [ ] 提取缓存
|
||||||
|
- [ ] 批量提取
|
||||||
|
- [ ] 错误重试
|
||||||
|
|
@ -7,6 +7,7 @@ from .memories import (
|
||||||
BaseMemory, FactMemory, IntentionMemory, PreferenceMemory,
|
BaseMemory, FactMemory, IntentionMemory, PreferenceMemory,
|
||||||
MemoryType, MemoryStatus, IntentionStatus
|
MemoryType, MemoryStatus, IntentionStatus
|
||||||
)
|
)
|
||||||
|
from .llm import LLMClient, OpenAIClient
|
||||||
|
|
||||||
__version__ = "0.1.0"
|
__version__ = "0.1.0"
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
|
@ -19,5 +20,7 @@ __all__ = [
|
||||||
'PreferenceMemory',
|
'PreferenceMemory',
|
||||||
'MemoryType',
|
'MemoryType',
|
||||||
'MemoryStatus',
|
'MemoryStatus',
|
||||||
'IntentionStatus'
|
'IntentionStatus',
|
||||||
|
'LLMClient',
|
||||||
|
'OpenAIClient'
|
||||||
]
|
]
|
||||||
|
|
|
||||||
40
xiaozhi-memory/config.example.yaml
Normal file
40
xiaozhi-memory/config.example.yaml
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
# xiaozhi-memory 配置示例
|
||||||
|
|
||||||
|
memory:
|
||||||
|
# 检索模式: fts5, embedding, hybrid
|
||||||
|
retrieval_mode: fts5
|
||||||
|
|
||||||
|
# SQLite 配置
|
||||||
|
sqlite:
|
||||||
|
path: ./data/xiaozhi_memory.db
|
||||||
|
|
||||||
|
# LLM 配置(用于智能记忆提取)
|
||||||
|
llm:
|
||||||
|
# 提供商: openai(兼容 OpenAI API 格式的服务)
|
||||||
|
provider: openai
|
||||||
|
|
||||||
|
# 火山引擎豆包配置
|
||||||
|
api_key: 6202d63d-377b-4bd7-a2ad-c162ed977c24
|
||||||
|
model: ep-20250513073203-wjddv
|
||||||
|
base_url: https://ark.cn-beijing.volces.com/api/v3
|
||||||
|
|
||||||
|
# OpenAI 官方配置示例
|
||||||
|
# api_key: ${OPENAI_API_KEY}
|
||||||
|
# model: gpt-4o-mini
|
||||||
|
# base_url: https://api.openai.com/v1
|
||||||
|
|
||||||
|
# Ollama 配置示例(本地免费)
|
||||||
|
# provider: ollama
|
||||||
|
# model: qwen2:7b
|
||||||
|
# base_url: http://localhost:11434
|
||||||
|
|
||||||
|
# 记忆提取配置
|
||||||
|
extraction:
|
||||||
|
# 是否启用 LLM 提取(false 时使用规则匹配)
|
||||||
|
enabled: true
|
||||||
|
# 传入 LLM 的现有记忆数量
|
||||||
|
max_retrieved_memories: 20
|
||||||
|
# 最近提取的记忆数量(用于去重)
|
||||||
|
max_recent_memories: 10
|
||||||
|
# 对话日期偏移(天)
|
||||||
|
observation_date_delta: 0
|
||||||
|
|
@ -38,8 +38,34 @@ class MemoryManager:
|
||||||
from core.retriever.fts import FTS5Retriever
|
from core.retriever.fts import FTS5Retriever
|
||||||
self.retriever = FTS5Retriever(self.store)
|
self.retriever = FTS5Retriever(self.store)
|
||||||
|
|
||||||
# LLM配置(暂时不实现,预留接口)
|
# LLM 客户端
|
||||||
self.llm_config = config.get("llm", {})
|
self.llm_client = self._init_llm_client(config.get("llm", {}))
|
||||||
|
self.extraction_config = config.get("extraction", {
|
||||||
|
"enabled": False,
|
||||||
|
"max_retrieved_memories": 20,
|
||||||
|
"max_recent_memories": 10,
|
||||||
|
"observation_date_delta": 0
|
||||||
|
})
|
||||||
|
|
||||||
|
# 会话级别的最近提取记忆(用于去重)
|
||||||
|
self._session_extracted: List[str] = []
|
||||||
|
|
||||||
|
def _init_llm_client(self, llm_config: dict):
|
||||||
|
"""初始化 LLM 客户端"""
|
||||||
|
if not llm_config.get("provider"):
|
||||||
|
return None
|
||||||
|
|
||||||
|
provider = llm_config["provider"]
|
||||||
|
|
||||||
|
if provider == "openai":
|
||||||
|
from llm.openai_client import OpenAIClient
|
||||||
|
return OpenAIClient(
|
||||||
|
api_key=llm_config["api_key"],
|
||||||
|
model=llm_config.get("model", "gpt-4o-mini"),
|
||||||
|
base_url=llm_config.get("base_url")
|
||||||
|
)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
async def add_memory(
|
async def add_memory(
|
||||||
self,
|
self,
|
||||||
|
|
@ -56,9 +82,20 @@ class MemoryManager:
|
||||||
Returns:
|
Returns:
|
||||||
{"added": 0, "updated": 0, "skipped": 0}
|
{"added": 0, "updated": 0, "skipped": 0}
|
||||||
"""
|
"""
|
||||||
results = {"added": 0, "updated": 0, "skipped": 0}
|
# 格式化消息
|
||||||
|
formatted_messages = self._format_messages(messages)
|
||||||
|
if not formatted_messages:
|
||||||
|
return {"added": 0, "updated": 0, "skipped": 0}
|
||||||
|
|
||||||
# 提取消息内容
|
# 判断是否使用 LLM 提取
|
||||||
|
if self.llm_client and self.extraction_config.get("enabled", False):
|
||||||
|
return await self._add_memory_with_llm(formatted_messages, user_id)
|
||||||
|
else:
|
||||||
|
return await self._add_memory_with_rules(formatted_messages, user_id)
|
||||||
|
|
||||||
|
def _format_messages(self, messages: List[Dict[str, str]]) -> List[Dict[str, str]]:
|
||||||
|
"""格式化消息,过滤系统消息和空内容"""
|
||||||
|
formatted = []
|
||||||
for msg in messages:
|
for msg in messages:
|
||||||
if msg.get("role") == "system":
|
if msg.get("role") == "system":
|
||||||
continue
|
continue
|
||||||
|
|
@ -67,6 +104,74 @@ class MemoryManager:
|
||||||
if not content:
|
if not content:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# 处理 JSON 格式(ASR 情感标签等)
|
||||||
|
if content.startswith("{") and content.endswith("}"):
|
||||||
|
import json
|
||||||
|
try:
|
||||||
|
data = json.loads(content)
|
||||||
|
if "text" in data:
|
||||||
|
content = data["text"]
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
formatted.append({"role": msg.get("role", "user"), "content": content})
|
||||||
|
|
||||||
|
return formatted
|
||||||
|
|
||||||
|
async def _add_memory_with_llm(
|
||||||
|
self,
|
||||||
|
messages: List[Dict[str, str]],
|
||||||
|
user_id: str
|
||||||
|
) -> Dict[str, int]:
|
||||||
|
"""使用 LLM 提取记忆"""
|
||||||
|
results = {"added": 0, "updated": 0, "skipped": 0}
|
||||||
|
|
||||||
|
# 1. 获取上下文
|
||||||
|
context = await self._build_extraction_context(user_id, messages)
|
||||||
|
|
||||||
|
# 2. 构建对话文本
|
||||||
|
conversation = self._build_conversation_text(messages)
|
||||||
|
|
||||||
|
# 3. LLM 提取
|
||||||
|
try:
|
||||||
|
facts = await self.llm_client.extract_facts(conversation, context)
|
||||||
|
except Exception as e:
|
||||||
|
# LLM 失败时回退到规则提取
|
||||||
|
print(f"LLM extraction failed, falling back to rule-based: {e}")
|
||||||
|
return await self._add_memory_with_rules(messages, user_id)
|
||||||
|
|
||||||
|
# 4. 处理提取的事实
|
||||||
|
for fact in facts:
|
||||||
|
# 去重检查
|
||||||
|
existing = await self._find_duplicate(fact.get("content", ""), user_id)
|
||||||
|
|
||||||
|
if existing:
|
||||||
|
results["updated"] += 1
|
||||||
|
else:
|
||||||
|
# 创建记忆对象
|
||||||
|
memory = self._fact_to_memory(fact, user_id)
|
||||||
|
self.store.add(memory)
|
||||||
|
|
||||||
|
# 记录到会话提取列表
|
||||||
|
self._session_extracted.append(fact.get("content", ""))
|
||||||
|
|
||||||
|
results["added"] += 1
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
async def _add_memory_with_rules(
|
||||||
|
self,
|
||||||
|
messages: List[Dict[str, str]],
|
||||||
|
user_id: str
|
||||||
|
) -> Dict[str, int]:
|
||||||
|
"""使用规则匹配提取记忆(原有逻辑)"""
|
||||||
|
results = {"added": 0, "updated": 0, "skipped": 0}
|
||||||
|
|
||||||
|
for msg in messages:
|
||||||
|
content = msg.get("content", "")
|
||||||
|
if not content:
|
||||||
|
continue
|
||||||
|
|
||||||
# 解析时间信息
|
# 解析时间信息
|
||||||
time_info = TimeParser.parse(content)
|
time_info = TimeParser.parse(content)
|
||||||
|
|
||||||
|
|
@ -95,16 +200,103 @@ class MemoryManager:
|
||||||
existing = await self._find_similar(memory.content, user_id)
|
existing = await self._find_similar(memory.content, user_id)
|
||||||
|
|
||||||
if existing:
|
if existing:
|
||||||
# 更新
|
|
||||||
await self._update_memory(existing.id, memory)
|
await self._update_memory(existing.id, memory)
|
||||||
results["updated"] += 1
|
results["updated"] += 1
|
||||||
else:
|
else:
|
||||||
# 添加
|
|
||||||
self.store.add(memory)
|
self.store.add(memory)
|
||||||
results["added"] += 1
|
results["added"] += 1
|
||||||
|
|
||||||
return results
|
return results
|
||||||
|
|
||||||
|
async def _build_extraction_context(
|
||||||
|
self,
|
||||||
|
user_id: str,
|
||||||
|
messages: List[Dict]
|
||||||
|
) -> dict:
|
||||||
|
"""构建 LLM 提取的上下文"""
|
||||||
|
config = self.extraction_config
|
||||||
|
current_date = datetime.now()
|
||||||
|
observation_date = current_date + timedelta(days=config.get("observation_date_delta", 0))
|
||||||
|
|
||||||
|
# 获取最近提取的记忆(用于去重)
|
||||||
|
recently_extracted = self._session_extracted[:config.get("max_recent_memories", 10)]
|
||||||
|
|
||||||
|
# 获取相关现有记忆(用于链接)
|
||||||
|
query_text = " ".join([m.get("content", "") for m in messages[-3:]])
|
||||||
|
existing_memories = self.store.search_fts(query_text, user_id, top_k=config.get("max_retrieved_memories", 20))
|
||||||
|
existing_formatted = [
|
||||||
|
{"id": m[0].id, "text": m[0].content}
|
||||||
|
for m in existing_memories
|
||||||
|
]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"current_date": current_date.strftime("%Y-%m-%d"),
|
||||||
|
"observation_date": observation_date.strftime("%Y-%m-%d"),
|
||||||
|
"recently_extracted": "\n".join(f"- {r}" for r in recently_extracted) if recently_extracted else "无",
|
||||||
|
"existing_memories": "\n".join(f"[{e['id']}] {e['text']}" for e in existing_formatted) if existing_formatted else "无"
|
||||||
|
}
|
||||||
|
|
||||||
|
def _build_conversation_text(self, messages: List[Dict]) -> str:
|
||||||
|
"""构建对话文本"""
|
||||||
|
lines = []
|
||||||
|
for msg in messages:
|
||||||
|
role = msg.get("role", "user")
|
||||||
|
content = msg.get("content", "")
|
||||||
|
role_name = "User" if role == "user" else "Assistant"
|
||||||
|
lines.append(f"{role_name}: {content}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
async def _find_duplicate(
|
||||||
|
self,
|
||||||
|
content: str,
|
||||||
|
user_id: str,
|
||||||
|
threshold: float = 0.85
|
||||||
|
) -> Optional[BaseMemory]:
|
||||||
|
"""查找重复记忆"""
|
||||||
|
results = self.store.search_fts(content, user_id, top_k=5)
|
||||||
|
|
||||||
|
for memory, score in results:
|
||||||
|
if self._string_similarity(content, memory.content) > threshold:
|
||||||
|
return memory
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _fact_to_memory(self, fact: dict, user_id: str) -> BaseMemory:
|
||||||
|
"""将 LLM 提取的事实转换为记忆对象"""
|
||||||
|
fact_type = fact.get("type", "FACT")
|
||||||
|
|
||||||
|
common_data = {
|
||||||
|
"id": str(uuid.uuid4()),
|
||||||
|
"user_id": user_id,
|
||||||
|
"content": fact["content"],
|
||||||
|
"time_info": fact.get("time_info"),
|
||||||
|
"related_ids": fact.get("linked_memory_ids", []),
|
||||||
|
}
|
||||||
|
|
||||||
|
if fact_type == "INTENTION":
|
||||||
|
common_data.update({
|
||||||
|
"intention_status": IntentionStatus.PLANNED,
|
||||||
|
"intention_type": fact.get("intention_type"),
|
||||||
|
})
|
||||||
|
|
||||||
|
# 解析时间
|
||||||
|
time_info = fact.get("time_info", {})
|
||||||
|
if time_info and time_info.get("absolute"):
|
||||||
|
try:
|
||||||
|
common_data["planned_time"] = datetime.fromisoformat(time_info["absolute"])
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if time_info and time_info.get("relative"):
|
||||||
|
common_data["time_description"] = time_info["relative"]
|
||||||
|
|
||||||
|
return IntentionMemory(**common_data)
|
||||||
|
|
||||||
|
elif fact_type == "PREFERENCE":
|
||||||
|
return PreferenceMemory(**common_data)
|
||||||
|
|
||||||
|
return FactMemory(**common_data)
|
||||||
|
|
||||||
async def search(
|
async def search(
|
||||||
self,
|
self,
|
||||||
query: str,
|
query: str,
|
||||||
|
|
|
||||||
BIN
xiaozhi-memory/data/test.db
Normal file
BIN
xiaozhi-memory/data/test.db
Normal file
Binary file not shown.
Binary file not shown.
BIN
xiaozhi-memory/examples/data/test.db
Normal file
BIN
xiaozhi-memory/examples/data/test.db
Normal file
Binary file not shown.
BIN
xiaozhi-memory/examples/data/test_llm_memory.db
Normal file
BIN
xiaozhi-memory/examples/data/test_llm_memory.db
Normal file
Binary file not shown.
108
xiaozhi-memory/examples/test_llm_extraction.py
Normal file
108
xiaozhi-memory/examples/test_llm_extraction.py
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
"""
|
||||||
|
LLM 记忆提取测试
|
||||||
|
|
||||||
|
支持火山引擎豆包、OpenAI 等兼容 OpenAI API 格式的服务
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# 添加父目录到路径
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
from core.memory_manager import MemoryManager
|
||||||
|
|
||||||
|
|
||||||
|
async def test_llm_extraction():
|
||||||
|
"""测试 LLM 记忆提取功能"""
|
||||||
|
|
||||||
|
# 默认使用火山引擎豆包配置
|
||||||
|
config = {
|
||||||
|
"retrieval_mode": "fts5",
|
||||||
|
"sqlite": {"path": "./data/test_llm_memory.db"},
|
||||||
|
"llm": {
|
||||||
|
"provider": "openai",
|
||||||
|
# 火山引擎豆包(默认)
|
||||||
|
"api_key": os.getenv("ARK_API_KEY", "6202d63d-377b-4bd7-a2ad-c162ed977c24"),
|
||||||
|
"model": os.getenv("ARK_MODEL", "doubao-seed-2-0-lite-260428"),
|
||||||
|
"base_url": os.getenv("ARK_BASE_URL", "https://ark.cn-beijing.volces.com/api/v3"),
|
||||||
|
|
||||||
|
# OpenAI 官方(取消注释使用)
|
||||||
|
# "api_key": os.getenv("OPENAI_API_KEY", ""),
|
||||||
|
# "model": "gpt-4o-mini",
|
||||||
|
# "base_url": os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1"),
|
||||||
|
},
|
||||||
|
"extraction": {
|
||||||
|
"enabled": True,
|
||||||
|
"max_retrieved_memories": 20,
|
||||||
|
"max_recent_memories": 10,
|
||||||
|
"observation_date_delta": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if not config["llm"]["api_key"]:
|
||||||
|
print("错误: 请设置 API Key")
|
||||||
|
print("火山引擎: export ARK_API_KEY=your-api-key")
|
||||||
|
print("OpenAI: export OPENAI_API_KEY=your-api-key")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 创建管理器
|
||||||
|
manager = MemoryManager(config)
|
||||||
|
|
||||||
|
print("=== 测试 LLM 记忆提取 ===\n")
|
||||||
|
|
||||||
|
# 测试对话
|
||||||
|
messages = [
|
||||||
|
{"role": "user", "content": "我叫张三,是一名软件工程师,住在北京"},
|
||||||
|
{"role": "assistant", "content": "你好张三!很高兴认识你。"},
|
||||||
|
{"role": "user", "content": "我明天下午3点要和客户李四开会,讨论新项目的技术方案"},
|
||||||
|
{"role": "user", "content": "我喜欢喝咖啡,每天早上都要来一杯拿铁"},
|
||||||
|
]
|
||||||
|
|
||||||
|
print("输入对话:")
|
||||||
|
for msg in messages:
|
||||||
|
print(f" {msg['role']}: {msg['content']}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 添加记忆
|
||||||
|
result = await manager.add_memory(messages, "test_user_llm")
|
||||||
|
print(f"提取结果: {result}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 查看提取的记忆
|
||||||
|
memories = await manager.get_all_memories("test_user_llm")
|
||||||
|
print(f"共提取了 {len(memories)} 条记忆:\n")
|
||||||
|
for m in memories:
|
||||||
|
print(f"- [{m.type.value}] {m.content}")
|
||||||
|
if hasattr(m, 'planned_time') and m.planned_time:
|
||||||
|
print(f" 计划时间: {m.planned_time}")
|
||||||
|
if m.time_info:
|
||||||
|
print(f" 时间信息: {m.time_info}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 测试搜索
|
||||||
|
print("=== 测试搜索 ===")
|
||||||
|
query = "开会"
|
||||||
|
results = await manager.search(query, "test_user_llm", top_k=3)
|
||||||
|
print(f"搜索 '{query}' 的结果:")
|
||||||
|
for m in results:
|
||||||
|
print(f"- {m.content}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 测试即将到来的意图
|
||||||
|
print("=== 测试即将到来的意图 ===")
|
||||||
|
intentions = await manager.get_upcoming_intentions("test_user_llm", days=7)
|
||||||
|
print(f"未来7天的意图:")
|
||||||
|
for intent in intentions:
|
||||||
|
print(f"- {intent.content}")
|
||||||
|
if intent.planned_time:
|
||||||
|
print(f" 计划时间: {intent.planned_time}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 关闭
|
||||||
|
manager.close()
|
||||||
|
print("测试完成!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(test_llm_extraction())
|
||||||
7
xiaozhi-memory/llm/__init__.py
Normal file
7
xiaozhi-memory/llm/__init__.py
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
"""
|
||||||
|
LLM 客户端模块
|
||||||
|
"""
|
||||||
|
from .base import LLMClient
|
||||||
|
from .openai_client import OpenAIClient
|
||||||
|
|
||||||
|
__all__ = ['LLMClient', 'OpenAIClient']
|
||||||
31
xiaozhi-memory/llm/base.py
Normal file
31
xiaozhi-memory/llm/base.py
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
"""
|
||||||
|
LLM 客户端基类
|
||||||
|
"""
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import List, Dict, Any
|
||||||
|
|
||||||
|
|
||||||
|
class LLMClient(ABC):
|
||||||
|
"""LLM 客户端基类"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def extract_facts(
|
||||||
|
self,
|
||||||
|
conversation: str,
|
||||||
|
context: Dict[str, Any]
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
从对话中提取事实
|
||||||
|
|
||||||
|
Args:
|
||||||
|
conversation: 对话文本
|
||||||
|
context: 上下文信息
|
||||||
|
- current_date: 当前日期
|
||||||
|
- observation_date: 观察日期(用于解析相对时间)
|
||||||
|
- recently_extracted: 最近提取的记忆(用于去重)
|
||||||
|
- existing_memories: 现有相关记忆
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
[{"content": "...", "type": "FACT|INTENTION|PREFERENCE", ...}]
|
||||||
|
"""
|
||||||
|
pass
|
||||||
93
xiaozhi-memory/llm/openai_client.py
Normal file
93
xiaozhi-memory/llm/openai_client.py
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
"""
|
||||||
|
OpenAI LLM 客户端
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import List, Dict, Any
|
||||||
|
|
||||||
|
try:
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
OPENAI_AVAILABLE = True
|
||||||
|
except ImportError:
|
||||||
|
OPENAI_AVAILABLE = False
|
||||||
|
|
||||||
|
from .base import LLMClient
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class OpenAIClient(LLMClient):
|
||||||
|
"""OpenAI API 客户端"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
api_key: str,
|
||||||
|
model: str = "gpt-4o-mini",
|
||||||
|
base_url: str = None,
|
||||||
|
use_json_mode: bool = None
|
||||||
|
):
|
||||||
|
if not OPENAI_AVAILABLE:
|
||||||
|
raise ImportError("openai package is required. Install with: pip install openai")
|
||||||
|
|
||||||
|
self.api_key = api_key
|
||||||
|
self.model = model
|
||||||
|
self.client = AsyncOpenAI(api_key=api_key, base_url=base_url)
|
||||||
|
# 自动检测是否使用 JSON 模式(豆包等模型不支持)
|
||||||
|
self.use_json_mode = use_json_mode if use_json_mode is not None else self._supports_json_mode()
|
||||||
|
|
||||||
|
def _supports_json_mode(self) -> bool:
|
||||||
|
"""检测模型是否支持 JSON 模式"""
|
||||||
|
# 豆包模型不支持 JSON 模式
|
||||||
|
if "doubao" in self.model.lower() or self.model.startswith("ep-"):
|
||||||
|
return False
|
||||||
|
# gpt-4o-mini, gpt-4o, gpt-3.5-turbo 等支持
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def extract_facts(
|
||||||
|
self,
|
||||||
|
conversation: str,
|
||||||
|
context: Dict[str, Any]
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
从对话中提取事实
|
||||||
|
|
||||||
|
Args:
|
||||||
|
conversation: 对话文本
|
||||||
|
context: 上下文信息
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
提取的事实列表
|
||||||
|
"""
|
||||||
|
from prompts.fact_extraction import FACT_EXTRACTION_PROMPT
|
||||||
|
|
||||||
|
prompt = FACT_EXTRACTION_PROMPT.format(**context, conversation=conversation)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 构建请求参数
|
||||||
|
request_params = {
|
||||||
|
"model": self.model,
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": "你是一个专业的个人信息提取助手。"},
|
||||||
|
{"role": "user", "content": prompt}
|
||||||
|
],
|
||||||
|
"temperature": 0.3,
|
||||||
|
}
|
||||||
|
|
||||||
|
# 只有支持的模型才使用 JSON 模式
|
||||||
|
if self.use_json_mode:
|
||||||
|
request_params["response_format"] = {"type": "json_object"}
|
||||||
|
|
||||||
|
response = await self.client.chat.completions.create(**request_params)
|
||||||
|
|
||||||
|
result = json.loads(response.choices[0].message.content)
|
||||||
|
facts = result.get("facts", [])
|
||||||
|
|
||||||
|
logger.info(f"Extracted {len(facts)} facts from conversation")
|
||||||
|
return facts
|
||||||
|
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
logger.error(f"Failed to parse LLM response as JSON: {e}")
|
||||||
|
return []
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to extract facts: {e}")
|
||||||
|
raise
|
||||||
6
xiaozhi-memory/prompts/__init__.py
Normal file
6
xiaozhi-memory/prompts/__init__.py
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
"""
|
||||||
|
提示词模块
|
||||||
|
"""
|
||||||
|
from .fact_extraction import FACT_EXTRACTION_PROMPT
|
||||||
|
|
||||||
|
__all__ = ['FACT_EXTRACTION_PROMPT']
|
||||||
64
xiaozhi-memory/prompts/fact_extraction.py
Normal file
64
xiaozhi-memory/prompts/fact_extraction.py
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
"""
|
||||||
|
事实提取提示词模板
|
||||||
|
"""
|
||||||
|
|
||||||
|
FACT_EXTRACTION_PROMPT = """你是一个个人信息提取助手。从对话中提取相关事实、记忆、偏好和意图。
|
||||||
|
|
||||||
|
CRITICAL 规则(按优先级):
|
||||||
|
1. TEMPORAL (时间): 始终提取时间信息。将相对时间转换为绝对时间,同时保留原始时间描述
|
||||||
|
- 例如: "两天后" → "2026-05-28 (两天后)"
|
||||||
|
- 使用 Observation Date 解析相对时间
|
||||||
|
|
||||||
|
2. INTENTIONS (意图): 始终提取用户的意图、需求和请求,即使没有时间信息
|
||||||
|
- 例如: "我想约个心脏科医生" → 意图记忆
|
||||||
|
- "明天要去开会" → 意图记忆
|
||||||
|
|
||||||
|
3. LANGUAGE (语言): 不要翻译!保持原文语言
|
||||||
|
- 中文输入 → 中文输出
|
||||||
|
- 英文输入 → 英文输出
|
||||||
|
- 混合输入 → 分别保持
|
||||||
|
|
||||||
|
4. COMPLETE (完整): 提取完整的事实,包含谁/什么/何时/何地
|
||||||
|
- 15-80词,上下文丰富
|
||||||
|
- 包含情感反应、动机
|
||||||
|
|
||||||
|
5. SEPARATE (分离): 不同时间段的事实用分开提取
|
||||||
|
- 不同主题分别提取
|
||||||
|
|
||||||
|
6. ATTRIBUTION (归属): 正确归属信息来源
|
||||||
|
- 用户陈述 → "User ..."
|
||||||
|
- 助手推荐 → "User was recommended ..."
|
||||||
|
|
||||||
|
记忆类型:
|
||||||
|
- FACT: 已发生的事实("昨天去了北京")
|
||||||
|
- INTENTION: 未来的计划和意图("明天要去开会")
|
||||||
|
- PREFERENCE: 偏好("喜欢喝咖啡")
|
||||||
|
|
||||||
|
输出格式:
|
||||||
|
{{
|
||||||
|
"facts": [
|
||||||
|
{{
|
||||||
|
"content": "记忆内容(保持原文语言,15-80词,上下文丰富)",
|
||||||
|
"type": "FACT|INTENTION|PREFERENCE",
|
||||||
|
"time_info": {{"absolute": "2026-05-28", "relative": "两天后"}},
|
||||||
|
"intention_type": "meeting|travel|task|purchase|appointment|...",
|
||||||
|
"linked_memory_ids": ["uuid1", "uuid2"]
|
||||||
|
}}
|
||||||
|
]
|
||||||
|
}}
|
||||||
|
|
||||||
|
如果提取到与现有记忆相关的新记忆,在 linked_memory_ids 中添加相关记忆的ID。
|
||||||
|
|
||||||
|
今天的日期: {current_date}
|
||||||
|
观察日期(用于解析相对时间): {observation_date}
|
||||||
|
|
||||||
|
最近提取的记忆:
|
||||||
|
{recently_extracted}
|
||||||
|
|
||||||
|
现有记忆:
|
||||||
|
{existing_memories}
|
||||||
|
|
||||||
|
从以下对话中提取信息:
|
||||||
|
{conversation}
|
||||||
|
|
||||||
|
只返回 JSON,不要其他内容。"""
|
||||||
Loading…
Reference in a new issue