mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge pull request #1 from SerenNoble/feat/llm-cache-control
feat: LLM缓存控制与对话分层优化
This commit is contained in:
commit
f8222c8461
13 changed files with 482 additions and 43 deletions
|
|
@ -0,0 +1,32 @@
|
||||||
|
-- 1. 给 openai LLM provider 添加 cache 字段(千问显式缓存配置)
|
||||||
|
-- 在现有 fields 末尾追加 cache 字段,类型为 dict(JSON 文本框)
|
||||||
|
UPDATE `ai_model_provider` SET `fields` = JSON_ARRAY_APPEND(
|
||||||
|
`fields`,
|
||||||
|
'$',
|
||||||
|
JSON_OBJECT('key', 'cache', 'label', '缓存配置(JSON)', 'type', 'dict')
|
||||||
|
) WHERE `id` = 'SYSTEM_LLM_openai' AND JSON_CONTAINS(
|
||||||
|
`fields`,
|
||||||
|
JSON_OBJECT('key', 'cache'),
|
||||||
|
'$'
|
||||||
|
) = 0;
|
||||||
|
|
||||||
|
-- 2. 新增 doubao_cache LLM provider(豆包 Session 缓存)
|
||||||
|
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `is_custom`, `created_at`, `updated_at`)
|
||||||
|
VALUES (
|
||||||
|
'SYSTEM_LLM_doubao_cache',
|
||||||
|
'LLM',
|
||||||
|
'doubao_cache',
|
||||||
|
'豆包(Session缓存)',
|
||||||
|
'[
|
||||||
|
{"key": "base_url", "label": "基础URL", "type": "string"},
|
||||||
|
{"key": "model_name", "label": "模型名称", "type": "string"},
|
||||||
|
{"key": "api_key", "label": "API密钥", "type": "string"},
|
||||||
|
{"key": "temperature", "label": "温度", "type": "number"},
|
||||||
|
{"key": "max_tokens", "label": "最大令牌数", "type": "number"},
|
||||||
|
{"key": "cache", "label": "缓存配置(JSON)", "type": "dict"}
|
||||||
|
]',
|
||||||
|
50,
|
||||||
|
0,
|
||||||
|
NOW(),
|
||||||
|
NOW()
|
||||||
|
);
|
||||||
|
|
@ -641,3 +641,10 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202604300930.sql
|
path: classpath:db/changelog/202604300930.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202606120930
|
||||||
|
author: cache
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202606120930.sql
|
||||||
|
|
|
||||||
|
|
@ -103,6 +103,9 @@
|
||||||
"></el-input>
|
"></el-input>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<el-switch v-else-if="field.type === 'boolean'" v-model="form.configJson[field.prop]"
|
||||||
|
:active-value="true" :inactive-value="false" class="custom-switch"></el-switch>
|
||||||
|
|
||||||
<el-input v-else v-model="form.configJson[field.prop]" :placeholder="field.placeholder" :type="field.type"
|
<el-input v-else v-model="form.configJson[field.prop]" :placeholder="field.placeholder" :type="field.type"
|
||||||
class="custom-input-bg" :show-password="field.type === 'password'" @focus="
|
class="custom-input-bg" :show-password="field.type === 'password'" @focus="
|
||||||
isSensitiveField(field.prop)
|
isSensitiveField(field.prop)
|
||||||
|
|
@ -327,6 +330,8 @@ export default {
|
||||||
type:
|
type:
|
||||||
f.type === "dict"
|
f.type === "dict"
|
||||||
? "json-textarea"
|
? "json-textarea"
|
||||||
|
: f.type === "boolean"
|
||||||
|
? "boolean"
|
||||||
: f.type === "password"
|
: f.type === "password"
|
||||||
? "password"
|
? "password"
|
||||||
: "text",
|
: "text",
|
||||||
|
|
@ -353,6 +358,9 @@ export default {
|
||||||
this.formatJson(configJson[field.prop])
|
this.formatJson(configJson[field.prop])
|
||||||
);
|
);
|
||||||
configJson[field.prop] = this.ensureObject(configJson[field.prop]);
|
configJson[field.prop] = this.ensureObject(configJson[field.prop]);
|
||||||
|
} else if (field.type === "boolean") {
|
||||||
|
// 保持布尔类型,不转为字符串
|
||||||
|
configJson[field.prop] = !!configJson[field.prop];
|
||||||
} else if (typeof configJson[field.prop] !== "string") {
|
} else if (typeof configJson[field.prop] !== "string") {
|
||||||
configJson[field.prop] = String(configJson[field.prop]);
|
configJson[field.prop] = String(configJson[field.prop]);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -808,6 +808,7 @@ class ConnectionHandler:
|
||||||
self.memory = modules["memory"]
|
self.memory = modules["memory"]
|
||||||
|
|
||||||
def _initialize_memory(self):
|
def _initialize_memory(self):
|
||||||
|
self.logger.bind(tag=TAG).info(f"[DEBUG] _initialize_memory called, self.memory={self.memory is not None}")
|
||||||
if self.memory is None:
|
if self.memory is None:
|
||||||
return
|
return
|
||||||
"""初始化记忆模块"""
|
"""初始化记忆模块"""
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,293 @@
|
||||||
|
"""
|
||||||
|
豆包(火山方舟)Session 缓存 LLM Provider
|
||||||
|
|
||||||
|
混合模式设计:
|
||||||
|
- 普通对话:使用 Responses API + previous_response_id,享受 Session 缓存
|
||||||
|
- 工具调用:使用 Chat Completions API,稳定支持 tools + streaming
|
||||||
|
|
||||||
|
Session 缓存原理:
|
||||||
|
首轮请求通过 Chat Completions API 发送完整对话,获取 response_id。
|
||||||
|
后续轮次通过 Responses API + previous_response_id 发送,
|
||||||
|
服务端自动复用已缓存的上下文,减少重复计算和 Token 传输。
|
||||||
|
|
||||||
|
配置示例:
|
||||||
|
DoubaoCacheLLM:
|
||||||
|
type: doubao_cache
|
||||||
|
base_url: https://ark.cn-beijing.volces.com/api/v3
|
||||||
|
model_name: doubao-seed-2-0-lite-260215
|
||||||
|
api_key: xxx
|
||||||
|
cache:
|
||||||
|
enabled: true
|
||||||
|
expire_seconds: 86400 # 缓存过期时间(秒),最长 7 天
|
||||||
|
"""
|
||||||
|
import httpx
|
||||||
|
import openai
|
||||||
|
from openai.types import CompletionUsage
|
||||||
|
from config.logger import setup_logging
|
||||||
|
from core.utils.util import check_model_key
|
||||||
|
from core.providers.llm.base import LLMProviderBase
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
|
class LLMProvider(LLMProviderBase):
|
||||||
|
def __init__(self, config):
|
||||||
|
self.model_name = config.get("model_name")
|
||||||
|
self.api_key = config.get("api_key")
|
||||||
|
if "base_url" in config:
|
||||||
|
self.base_url = config.get("base_url")
|
||||||
|
else:
|
||||||
|
self.base_url = config.get("url", "https://ark.cn-beijing.volces.com/api/v3")
|
||||||
|
|
||||||
|
timeout_config = config.get("timeout")
|
||||||
|
if isinstance(timeout_config, dict):
|
||||||
|
custom_timeout = httpx.Timeout(
|
||||||
|
pool=timeout_config.get("pool", 2.0),
|
||||||
|
connect=timeout_config.get("connect", 3.0),
|
||||||
|
write=timeout_config.get("write", 5.0),
|
||||||
|
read=timeout_config.get("read", 60.0)
|
||||||
|
)
|
||||||
|
elif isinstance(timeout_config, (int, float)) and timeout_config > 0:
|
||||||
|
custom_timeout = httpx.Timeout(timeout_config)
|
||||||
|
else:
|
||||||
|
custom_timeout = httpx.Timeout(300)
|
||||||
|
|
||||||
|
param_defaults = {
|
||||||
|
"max_tokens": int,
|
||||||
|
"temperature": lambda x: round(float(x), 1),
|
||||||
|
"top_p": lambda x: round(float(x), 1),
|
||||||
|
"frequency_penalty": lambda x: round(float(x), 1),
|
||||||
|
}
|
||||||
|
for param, converter in param_defaults.items():
|
||||||
|
value = config.get(param)
|
||||||
|
try:
|
||||||
|
setattr(
|
||||||
|
self, param,
|
||||||
|
converter(value) if value not in (None, "") else None,
|
||||||
|
)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
setattr(self, param, None)
|
||||||
|
|
||||||
|
model_key_msg = check_model_key("LLM", self.api_key)
|
||||||
|
if model_key_msg:
|
||||||
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
||||||
|
self.client = openai.OpenAI(
|
||||||
|
api_key=self.api_key,
|
||||||
|
base_url=self.base_url,
|
||||||
|
timeout=custom_timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 缓存配置(支持 boolean 开关和 dict 详细配置)
|
||||||
|
self._cache_config = config.get("cache", {})
|
||||||
|
if isinstance(self._cache_config, bool):
|
||||||
|
self._cache_enabled = self._cache_config
|
||||||
|
elif isinstance(self._cache_config, dict):
|
||||||
|
self._cache_enabled = self._cache_config.get("enabled", True)
|
||||||
|
else:
|
||||||
|
self._cache_enabled = True
|
||||||
|
|
||||||
|
# Session 状态:session_id -> response_id
|
||||||
|
self._session_response_ids: Dict[str, str] = {}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def normalize_dialogue(dialogue):
|
||||||
|
"""自动修复 dialogue 中缺失 content 的消息"""
|
||||||
|
for msg in dialogue:
|
||||||
|
if "role" in msg and "content" not in msg:
|
||||||
|
msg["content"] = ""
|
||||||
|
return dialogue
|
||||||
|
|
||||||
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
|
"""普通对话:优先使用 Responses API Session 缓存,失败回退到 Chat Completions"""
|
||||||
|
dialogue = self.normalize_dialogue(dialogue)
|
||||||
|
|
||||||
|
if self._cache_enabled:
|
||||||
|
prev_id = self._session_response_ids.get(session_id)
|
||||||
|
if prev_id:
|
||||||
|
try:
|
||||||
|
yield from self._stream_with_session(session_id, dialogue, prev_id, **kwargs)
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(
|
||||||
|
f"Session 缓存请求失败,回退到 Chat Completions: {e}"
|
||||||
|
)
|
||||||
|
self._session_response_ids.pop(session_id, None)
|
||||||
|
|
||||||
|
# 首轮或缓存失效/关闭:使用 Chat Completions API
|
||||||
|
yield from self._stream_chat_completions(session_id, dialogue, **kwargs)
|
||||||
|
|
||||||
|
def response_with_functions(self, session_id, dialogue, functions=None, **kwargs):
|
||||||
|
"""工具调用:始终使用 Chat Completions API(稳定支持 tools + streaming)"""
|
||||||
|
dialogue = self.normalize_dialogue(dialogue)
|
||||||
|
|
||||||
|
request_params = {
|
||||||
|
"model": self.model_name,
|
||||||
|
"messages": dialogue,
|
||||||
|
"stream": True,
|
||||||
|
"tools": functions,
|
||||||
|
}
|
||||||
|
|
||||||
|
optional_params = {
|
||||||
|
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
|
||||||
|
"temperature": kwargs.get("temperature", self.temperature),
|
||||||
|
"top_p": kwargs.get("top_p", self.top_p),
|
||||||
|
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
|
||||||
|
}
|
||||||
|
for key, value in optional_params.items():
|
||||||
|
if value is not None:
|
||||||
|
request_params[key] = value
|
||||||
|
|
||||||
|
# 禁用思考模式
|
||||||
|
request_params.setdefault("extra_body", {}).update(
|
||||||
|
{"thinking": {"type": "disabled"}}
|
||||||
|
)
|
||||||
|
|
||||||
|
stream = self.client.chat.completions.create(**request_params)
|
||||||
|
|
||||||
|
try:
|
||||||
|
for chunk in stream:
|
||||||
|
if getattr(chunk, "choices", None):
|
||||||
|
delta = chunk.choices[0].delta
|
||||||
|
content = getattr(delta, "content", "")
|
||||||
|
tool_calls = getattr(delta, "tool_calls", None)
|
||||||
|
yield content, tool_calls
|
||||||
|
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
|
||||||
|
self._log_usage(getattr(chunk, "usage", None))
|
||||||
|
finally:
|
||||||
|
stream.close()
|
||||||
|
|
||||||
|
def _stream_with_session(self, session_id, dialogue, prev_id, **kwargs):
|
||||||
|
"""使用 Responses API + previous_response_id 进行 Session 缓存流式对话"""
|
||||||
|
# 提取最新用户消息
|
||||||
|
last_user_msg = None
|
||||||
|
for msg in reversed(dialogue):
|
||||||
|
if msg.get("role") == "user":
|
||||||
|
last_user_msg = msg.get("content", "")
|
||||||
|
break
|
||||||
|
|
||||||
|
if not last_user_msg:
|
||||||
|
raise ValueError("未找到用户消息")
|
||||||
|
|
||||||
|
logger.bind(tag=TAG).info(
|
||||||
|
f"使用 Session 缓存: session_id={session_id}, prev_response_id={prev_id[:20]}..."
|
||||||
|
)
|
||||||
|
|
||||||
|
stream = self.client.responses.create(
|
||||||
|
model=self.model_name,
|
||||||
|
input=[{"role": "user", "content": last_user_msg}],
|
||||||
|
previous_response_id=prev_id,
|
||||||
|
stream=True,
|
||||||
|
store=True,
|
||||||
|
extra_body={
|
||||||
|
"caching": {"type": "enabled"},
|
||||||
|
"thinking": {"type": "disabled"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
response_id = None
|
||||||
|
try:
|
||||||
|
for event in stream:
|
||||||
|
# 捕获 response ID
|
||||||
|
if hasattr(event, "id") and event.id:
|
||||||
|
response_id = event.id
|
||||||
|
|
||||||
|
# 解析流式输出事件
|
||||||
|
text = self._parse_responses_stream_event(event)
|
||||||
|
if text:
|
||||||
|
# 过滤思考标签
|
||||||
|
yield text
|
||||||
|
finally:
|
||||||
|
if response_id:
|
||||||
|
self._session_response_ids[session_id] = response_id
|
||||||
|
logger.bind(tag=TAG).info(
|
||||||
|
f"Session 缓存已更新: session_id={session_id}, "
|
||||||
|
f"new_response_id={response_id[:20]}..."
|
||||||
|
)
|
||||||
|
stream.close()
|
||||||
|
|
||||||
|
def _stream_chat_completions(self, session_id, dialogue, **kwargs):
|
||||||
|
"""标准 Chat Completions API 流式对话(首轮或回退路径)"""
|
||||||
|
request_params = {"model": self.model_name, "messages": dialogue, "stream": True}
|
||||||
|
optional_params = {
|
||||||
|
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
|
||||||
|
"temperature": kwargs.get("temperature", self.temperature),
|
||||||
|
"top_p": kwargs.get("top_p", self.top_p),
|
||||||
|
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
|
||||||
|
}
|
||||||
|
for key, value in optional_params.items():
|
||||||
|
if value is not None:
|
||||||
|
request_params[key] = value
|
||||||
|
request_params.setdefault("extra_body", {}).update({"thinking": {"type": "disabled"}})
|
||||||
|
responses = self.client.chat.completions.create(**request_params)
|
||||||
|
try:
|
||||||
|
for chunk in responses:
|
||||||
|
try:
|
||||||
|
delta = chunk.choices[0].delta if getattr(chunk, "choices", None) else None
|
||||||
|
content = getattr(delta, "content", "") if delta else ""
|
||||||
|
except IndexError:
|
||||||
|
content = ""
|
||||||
|
if content:
|
||||||
|
yield content
|
||||||
|
finally:
|
||||||
|
responses.close()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_responses_stream_event(event):
|
||||||
|
"""解析 Responses API 流式事件,提取文本内容
|
||||||
|
|
||||||
|
Responses API 的流式事件格式与 Chat Completions 不同,
|
||||||
|
需要根据事件类型提取 output 中的 text content。
|
||||||
|
"""
|
||||||
|
# 处理 response.output_text.delta 类型事件
|
||||||
|
if hasattr(event, "type") and event.type == "response.output_text.delta":
|
||||||
|
return getattr(event, "delta", "")
|
||||||
|
# 处理 response.completed 事件中的完整输出
|
||||||
|
if hasattr(event, "type") and event.type == "response.completed":
|
||||||
|
return None
|
||||||
|
# 兼容:尝试从 output 提取
|
||||||
|
output = getattr(event, "output", None)
|
||||||
|
if output:
|
||||||
|
for item in (output if isinstance(output, list) else [output]):
|
||||||
|
content_list = getattr(item, "content", None)
|
||||||
|
if content_list:
|
||||||
|
for c in (content_list if isinstance(content_list, list) else [content_list]):
|
||||||
|
text = getattr(c, "text", None)
|
||||||
|
if text:
|
||||||
|
return text
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _log_usage(self, usage_info):
|
||||||
|
"""记录 Token 使用量,包含缓存命中信息"""
|
||||||
|
prompt_tokens = getattr(usage_info, "prompt_tokens", "未知")
|
||||||
|
completion_tokens = getattr(usage_info, "completion_tokens", "未知")
|
||||||
|
total_tokens = getattr(usage_info, "total_tokens", "未知")
|
||||||
|
|
||||||
|
# Chat Completions API 的缓存信息
|
||||||
|
details = getattr(usage_info, "prompt_tokens_details", None)
|
||||||
|
cached_tokens = getattr(details, "cached_tokens", 0) if details else 0
|
||||||
|
cache_created = getattr(details, "cache_creation_input_tokens", 0) if details else 0
|
||||||
|
|
||||||
|
# Responses API 的缓存信息
|
||||||
|
input_details = getattr(usage_info, "input_tokens_details", None)
|
||||||
|
if input_details and not cached_tokens:
|
||||||
|
cached_tokens = getattr(input_details, "cached_tokens", 0)
|
||||||
|
|
||||||
|
cache_log = ""
|
||||||
|
if cached_tokens or cache_created:
|
||||||
|
cache_log = f",缓存命中 {cached_tokens},缓存创建 {cache_created}"
|
||||||
|
|
||||||
|
logger.bind(tag=TAG).info(
|
||||||
|
f"Token 消耗:输入 {prompt_tokens},输出 {completion_tokens},"
|
||||||
|
f"共计 {total_tokens}{cache_log}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def clear_session(self, session_id):
|
||||||
|
"""清理指定会话的缓存状态"""
|
||||||
|
removed = self._session_response_ids.pop(session_id, None)
|
||||||
|
if removed:
|
||||||
|
logger.bind(tag=TAG).info(f"已清理 Session 缓存: session_id={session_id}")
|
||||||
|
|
@ -70,6 +70,10 @@ class LLMProvider(LLMProviderBase):
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=custom_timeout)
|
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=custom_timeout)
|
||||||
|
|
||||||
|
# 缓存控制(千问显式缓存)
|
||||||
|
self._cache_config = config.get("cache", {})
|
||||||
|
self._cache_enabled = self._detect_cache_enabled()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def normalize_dialogue(dialogue):
|
def normalize_dialogue(dialogue):
|
||||||
"""自动修复 dialogue 中缺失 content 的消息"""
|
"""自动修复 dialogue 中缺失 content 的消息"""
|
||||||
|
|
@ -78,6 +82,50 @@ class LLMProvider(LLMProviderBase):
|
||||||
msg["content"] = ""
|
msg["content"] = ""
|
||||||
return dialogue
|
return dialogue
|
||||||
|
|
||||||
|
def _detect_cache_enabled(self):
|
||||||
|
"""检测是否启用显式缓存(千问 cache_control)
|
||||||
|
|
||||||
|
支持两种配置方式:
|
||||||
|
- boolean: cache: true/false(智控台开关)
|
||||||
|
- dict: cache: {enabled: true/false}(YAML 手动配置)
|
||||||
|
"""
|
||||||
|
cache = self._cache_config
|
||||||
|
# boolean 直传:cache: true
|
||||||
|
if isinstance(cache, bool):
|
||||||
|
return cache
|
||||||
|
# dict 格式:cache: {enabled: true}
|
||||||
|
if isinstance(cache, dict) and "enabled" in cache:
|
||||||
|
return cache["enabled"]
|
||||||
|
# 自动检测:DashScope 域名默认开启
|
||||||
|
if self.base_url and "aliyuncs.com" in self.base_url:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _apply_cache_control(self, dialogue):
|
||||||
|
"""为静态 system 消息添加 cache_control 标记(千问显式缓存)
|
||||||
|
|
||||||
|
将第一条 system 消息的 content 从字符串转为数组格式,
|
||||||
|
加入 cache_control: {"type": "ephemeral"} 标记,
|
||||||
|
使该静态前缀在千问 API 端被缓存,5 分钟内命中后按 10% 输入价计费。
|
||||||
|
"""
|
||||||
|
if not self._cache_enabled:
|
||||||
|
return dialogue
|
||||||
|
if not dialogue or dialogue[0].get("role") != "system":
|
||||||
|
return dialogue
|
||||||
|
|
||||||
|
dialogue = [dict(m) for m in dialogue] # 浅拷贝,不污染原始数据
|
||||||
|
content = dialogue[0].get("content", "")
|
||||||
|
if isinstance(content, str) and content:
|
||||||
|
dialogue[0] = {
|
||||||
|
"role": "system",
|
||||||
|
"content": [{
|
||||||
|
"type": "text",
|
||||||
|
"text": content,
|
||||||
|
"cache_control": {"type": "ephemeral"}
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
return dialogue
|
||||||
|
|
||||||
def _apply_thinking_disabled(self, request_params: dict):
|
def _apply_thinking_disabled(self, request_params: dict):
|
||||||
"""根据域名自动禁用思考模式"""
|
"""根据域名自动禁用思考模式"""
|
||||||
parsed_url = urlparse(self.base_url)
|
parsed_url = urlparse(self.base_url)
|
||||||
|
|
@ -90,6 +138,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
dialogue = self.normalize_dialogue(dialogue)
|
dialogue = self.normalize_dialogue(dialogue)
|
||||||
|
dialogue = self._apply_cache_control(dialogue)
|
||||||
|
|
||||||
request_params = {
|
request_params = {
|
||||||
"model": self.model_name,
|
"model": self.model_name,
|
||||||
|
|
@ -136,6 +185,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None, **kwargs):
|
def response_with_functions(self, session_id, dialogue, functions=None, **kwargs):
|
||||||
dialogue = self.normalize_dialogue(dialogue)
|
dialogue = self.normalize_dialogue(dialogue)
|
||||||
|
dialogue = self._apply_cache_control(dialogue)
|
||||||
|
|
||||||
request_params = {
|
request_params = {
|
||||||
"model": self.model_name,
|
"model": self.model_name,
|
||||||
|
|
@ -169,10 +219,19 @@ class LLMProvider(LLMProviderBase):
|
||||||
yield content, tool_calls
|
yield content, tool_calls
|
||||||
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
|
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
|
||||||
usage_info = getattr(chunk, "usage", None)
|
usage_info = getattr(chunk, "usage", None)
|
||||||
|
prompt_tokens = getattr(usage_info, 'prompt_tokens', '未知')
|
||||||
|
completion_tokens = getattr(usage_info, 'completion_tokens', '未知')
|
||||||
|
total_tokens = getattr(usage_info, 'total_tokens', '未知')
|
||||||
|
# 提取缓存命中信息
|
||||||
|
details = getattr(usage_info, 'prompt_tokens_details', None)
|
||||||
|
cached_tokens = getattr(details, 'cached_tokens', 0) if details else 0
|
||||||
|
cache_created = getattr(details, 'cache_creation_input_tokens', 0) if details else 0
|
||||||
|
cache_log = ""
|
||||||
|
if cached_tokens or cache_created:
|
||||||
|
cache_log = f",缓存命中 {cached_tokens},缓存创建 {cache_created}"
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
|
f"Token 消耗:输入 {prompt_tokens},输出 {completion_tokens},"
|
||||||
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
|
f"共计 {total_tokens}{cache_log}"
|
||||||
f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
|
|
||||||
)
|
)
|
||||||
finally:
|
finally:
|
||||||
stream.close()
|
stream.close()
|
||||||
|
|
|
||||||
|
|
@ -276,6 +276,8 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
if not self.manager or not self.role_id:
|
if not self.manager or not self.role_id:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
logger.bind(tag=TAG).info(f"[DEBUG] save_memory called, llm_client={self.manager.llm_client is not None}, extraction_enabled={self.manager.extraction_config.get('enabled', False)}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 格式化消息
|
# 格式化消息
|
||||||
messages = []
|
messages = []
|
||||||
|
|
@ -300,7 +302,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
|
|
||||||
messages.append({"role": msg.role, "content": content})
|
messages.append({"role": msg.role, "content": content})
|
||||||
|
|
||||||
result = self.manager.add_memory(messages, user_id=self.role_id)
|
result = await self.manager.add_memory(messages, user_id=self.role_id)
|
||||||
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
|
||||||
|
|
@ -324,17 +326,17 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
except (json.JSONDecodeError, KeyError):
|
except (json.JSONDecodeError, KeyError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
memories = self.manager.retrieve_memories(
|
memories = await self.manager.search(
|
||||||
query=search_query,
|
query=search_query,
|
||||||
user_id=self.role_id,
|
user_id=self.role_id,
|
||||||
limit=5
|
top_k=5
|
||||||
)
|
)
|
||||||
|
|
||||||
if not memories:
|
if not memories:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
# Format each memory entry
|
# Format each memory entry
|
||||||
memories_str = "\n".join([f"- {m}" for m in memories])
|
memories_str = "\n".join([f"- {m.content}" for m in memories])
|
||||||
logger.bind(tag=TAG).debug(f"Query results: {memories_str}")
|
logger.bind(tag=TAG).debug(f"Query results: {memories_str}")
|
||||||
return memories_str
|
return memories_str
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
||||||
|
|
@ -118,35 +118,32 @@ class Dialogue:
|
||||||
# 第一段:静态 system prompt(前缀缓存可命中)
|
# 第一段:静态 system prompt(前缀缓存可命中)
|
||||||
dialogue.append({"role": "system", "content": static_part})
|
dialogue.append({"role": "system", "content": static_part})
|
||||||
|
|
||||||
# 第二段:few-shot 示例(会话内不变,也是缓存前缀的一部分)
|
# 第二段:few-shot 示例(会话内不变,也是缓存前缀的一部分,可命中缓存)
|
||||||
non_system_messages = [m for m in self.dialogue if m.role != "system"]
|
non_system_messages = [m for m in self.dialogue if m.role != "system"]
|
||||||
fewshot_messages = [m for m in non_system_messages if m.is_temporary]
|
fewshot_messages = [m for m in non_system_messages if m.is_temporary]
|
||||||
complete_fewshot = self._ensure_tool_calls_complete(fewshot_messages)
|
complete_fewshot = self._ensure_tool_calls_complete(fewshot_messages)
|
||||||
for m in complete_fewshot:
|
for m in complete_fewshot:
|
||||||
self.getMessages(m, dialogue)
|
self.getMessages(m, dialogue)
|
||||||
|
|
||||||
# 第三段:动态上下文 system prompt(时间、记忆、说话人等)
|
# 第三段 + 第四段:将动态上下文拆分为半稳定和实时两部分
|
||||||
# 保持 system 角色以确保模型权威性,不降级为 user
|
# 半稳定部分(system 角色):日期、农历、位置、天气、dynamic_context — 同一天内不变
|
||||||
|
# 实时部分(user 角色):当前时间、记忆、说话人 — 每次调用都可能变
|
||||||
|
# 拆分目的:半稳定的 system 消息可以被缓存前缀覆盖,实时变化不影响缓存
|
||||||
if system_message and dynamic_part:
|
if system_message and dynamic_part:
|
||||||
# 替换时间占位符
|
# 构建实时变化内容(每次调用都不同)
|
||||||
dynamic_part = dynamic_part.replace(
|
realtime_parts = []
|
||||||
"{{current_time}}", datetime.now().strftime("%H:%M")
|
current_time = datetime.now().strftime("%H:%M")
|
||||||
)
|
realtime_parts.append(f"当前时间:{current_time}")
|
||||||
|
|
||||||
# 填充记忆
|
# 填充记忆到实时部分
|
||||||
if memory_str is not None:
|
if memory_str is not None:
|
||||||
dynamic_part = re.sub(
|
realtime_parts.append(f"<memory>\n{memory_str}\n</memory>")
|
||||||
r"<memory>.*?</memory>",
|
|
||||||
f"<memory>\n{memory_str}\n</memory>",
|
|
||||||
dynamic_part,
|
|
||||||
flags=re.DOTALL,
|
|
||||||
)
|
|
||||||
|
|
||||||
# 追加说话人信息
|
# 追加说话人信息到实时部分
|
||||||
try:
|
try:
|
||||||
speakers = voiceprint_config.get("speakers", [])
|
speakers = voiceprint_config.get("speakers", [])
|
||||||
if speakers:
|
if speakers:
|
||||||
dynamic_part += "\n<speakers_info>"
|
speakers_text = "<speakers_info>"
|
||||||
for speaker_str in speakers:
|
for speaker_str in speakers:
|
||||||
try:
|
try:
|
||||||
parts = speaker_str.split(",", 2)
|
parts = speaker_str.split(",", 2)
|
||||||
|
|
@ -155,16 +152,36 @@ class Dialogue:
|
||||||
description = (
|
description = (
|
||||||
parts[2].strip() if len(parts) >= 3 else ""
|
parts[2].strip() if len(parts) >= 3 else ""
|
||||||
)
|
)
|
||||||
dynamic_part += f"\n- {name}:{description}"
|
speakers_text += f"\n- {name}:{description}"
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
dynamic_part += "\n</speakers_info>"
|
speakers_text += "\n</speakers_info>"
|
||||||
|
realtime_parts.append(speakers_text)
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
dialogue.append({"role": "system", "content": dynamic_part})
|
# 从 dynamic_part 中移除已提取到实时部分的占位符
|
||||||
|
# 注意:模板中 {{current_time}} 已被 prompt_manager 渲染为实际时间值
|
||||||
|
# 移除当前时间行(当前时间已移到实时 user 消息)
|
||||||
|
semi_stable_part = re.sub(
|
||||||
|
r"- 当前时间:[^\n]+\n?", "", dynamic_part
|
||||||
|
)
|
||||||
|
# 移除 <memory> 块(记忆已移到实时 user 消息)
|
||||||
|
semi_stable_part = re.sub(
|
||||||
|
r"<memory>.*?</memory>", "", semi_stable_part, flags=re.DOTALL
|
||||||
|
)
|
||||||
|
# 清理多余空行
|
||||||
|
semi_stable_part = re.sub(r"\n{3,}", "\n\n", semi_stable_part).strip()
|
||||||
|
|
||||||
# 第四段:实际对话历史(不含 few-shot)
|
# 第三段:半稳定 system prompt(日期、农历、位置、天气等)
|
||||||
|
if semi_stable_part:
|
||||||
|
dialogue.append({"role": "system", "content": semi_stable_part})
|
||||||
|
|
||||||
|
# 第四段:实时变化内容(user 角色,不影响缓存前缀)
|
||||||
|
if realtime_parts:
|
||||||
|
dialogue.append({"role": "user", "content": "\n".join(realtime_parts)})
|
||||||
|
|
||||||
|
# 第五段:实际对话历史(不含 few-shot)
|
||||||
actual_messages = [m for m in non_system_messages if not m.is_temporary]
|
actual_messages = [m for m in non_system_messages if not m.is_temporary]
|
||||||
complete_actual = self._ensure_tool_calls_complete(actual_messages)
|
complete_actual = self._ensure_tool_calls_complete(actual_messages)
|
||||||
for m in complete_actual:
|
for m in complete_actual:
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,10 @@ services:
|
||||||
- ./data:/opt/xiaozhi-esp32-server/data
|
- ./data:/opt/xiaozhi-esp32-server/data
|
||||||
# 模型文件挂接,很重要
|
# 模型文件挂接,很重要
|
||||||
- ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt
|
- ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt
|
||||||
|
# aipet 记忆 provider
|
||||||
|
- ./core/providers/memory/aipet:/opt/xiaozhi-esp32-server/core/providers/memory/aipet
|
||||||
|
# xiaozhi-memory 记忆框架
|
||||||
|
- ./xiaozhi-memory:/opt/xiaozhi-esp32-server/xiaozhi-memory
|
||||||
|
|
||||||
# manager-api和manager-web模块
|
# manager-api和manager-web模块
|
||||||
xiaozhi-esp32-server-web:
|
xiaozhi-esp32-server-web:
|
||||||
|
|
@ -55,7 +59,7 @@ services:
|
||||||
- ./uploadfile:/uploadfile
|
- ./uploadfile:/uploadfile
|
||||||
# 数据库模块
|
# 数据库模块
|
||||||
xiaozhi-esp32-server-db:
|
xiaozhi-esp32-server-db:
|
||||||
image: mysql:latest
|
image: docker.1ms.run/mysql:latest
|
||||||
container_name: xiaozhi-esp32-server-db
|
container_name: xiaozhi-esp32-server-db
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
|
test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
|
||||||
|
|
@ -76,7 +80,7 @@ services:
|
||||||
- MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci"
|
- MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci"
|
||||||
# redis模块
|
# redis模块
|
||||||
xiaozhi-esp32-server-redis:
|
xiaozhi-esp32-server-redis:
|
||||||
image: redis:8.0
|
image: docker.1ms.run/redis:8.0
|
||||||
expose:
|
expose:
|
||||||
- 6379
|
- 6379
|
||||||
container_name: xiaozhi-esp32-server-redis
|
container_name: xiaozhi-esp32-server-redis
|
||||||
|
|
|
||||||
|
|
@ -15,12 +15,12 @@ vector_store:
|
||||||
path: ./data/chroma
|
path: ./data/chroma
|
||||||
collection_name: xiaozhi_memories
|
collection_name: xiaozhi_memories
|
||||||
|
|
||||||
# LLM配置
|
# LLM配置(使用ChatGLM免费模型)
|
||||||
llm:
|
llm:
|
||||||
provider: ollama # openai, ollama, zhipu
|
provider: openai
|
||||||
model: qwen2:7b
|
model: glm-4-flash
|
||||||
base_url: http://localhost:11434 # ollama默认地址
|
base_url: https://open.bigmodel.cn/api/paas/v4/
|
||||||
api_key: null # 可选
|
api_key: abf3f70c3b884da79be23b4a807e73f9.nVnNDc7EOaX6ckw7
|
||||||
|
|
||||||
# 嵌入模型配置(可选,embedding模式需要)
|
# 嵌入模型配置(可选,embedding模式需要)
|
||||||
embedding:
|
embedding:
|
||||||
|
|
|
||||||
|
|
@ -137,7 +137,8 @@ class MemoryManager:
|
||||||
facts = await self.llm_client.extract_facts(conversation, context)
|
facts = await self.llm_client.extract_facts(conversation, context)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# LLM 失败时回退到规则提取
|
# LLM 失败时回退到规则提取
|
||||||
print(f"LLM extraction failed, falling back to rule-based: {e}")
|
import logging
|
||||||
|
logging.error(f"[xiaozhi-memory] LLM extraction failed, falling back to rule-based: {e}")
|
||||||
return await self._add_memory_with_rules(messages, user_id)
|
return await self._add_memory_with_rules(messages, user_id)
|
||||||
|
|
||||||
# 4. 处理提取的事实
|
# 4. 处理提取的事实
|
||||||
|
|
|
||||||
|
|
@ -149,10 +149,10 @@ class SQLiteStore(BaseStore):
|
||||||
|
|
||||||
def add(self, memory: BaseMemory) -> str:
|
def add(self, memory: BaseMemory) -> str:
|
||||||
"""添加记忆"""
|
"""添加记忆"""
|
||||||
# 中文分词
|
# 中文分词(使用 tokenize_to_string 确保 FTS5 安全)
|
||||||
try:
|
try:
|
||||||
import jieba
|
from utils.tokenizer import tokenize_to_string
|
||||||
tokens = " ".join(jieba.lcut(memory.content))
|
tokens = tokenize_to_string(memory.content)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
tokens = memory.content
|
tokens = memory.content
|
||||||
|
|
||||||
|
|
@ -250,6 +250,12 @@ class SQLiteStore(BaseStore):
|
||||||
|
|
||||||
返回: [(memory, score), ...]
|
返回: [(memory, score), ...]
|
||||||
"""
|
"""
|
||||||
|
# 使用 tokenize_to_string 清理查询,避免 FTS5 语法错误
|
||||||
|
from utils.tokenizer import tokenize_to_string
|
||||||
|
safe_query = tokenize_to_string(query)
|
||||||
|
if not safe_query:
|
||||||
|
return []
|
||||||
|
|
||||||
cursor = self.conn.execute(f"""
|
cursor = self.conn.execute(f"""
|
||||||
SELECT
|
SELECT
|
||||||
m.*,
|
m.*,
|
||||||
|
|
@ -261,7 +267,7 @@ class SQLiteStore(BaseStore):
|
||||||
AND memories_fts MATCH ?
|
AND memories_fts MATCH ?
|
||||||
ORDER BY score
|
ORDER BY score
|
||||||
LIMIT ?
|
LIMIT ?
|
||||||
""", (user_id, query, top_k))
|
""", (user_id, safe_query, top_k))
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
for row in cursor.fetchall():
|
for row in cursor.fetchall():
|
||||||
|
|
|
||||||
|
|
@ -84,4 +84,13 @@ def tokenize(text: str) -> List[str]:
|
||||||
def tokenize_to_string(text: str) -> str:
|
def tokenize_to_string(text: str) -> str:
|
||||||
"""分词并返回字符串(用于FTS5)"""
|
"""分词并返回字符串(用于FTS5)"""
|
||||||
tokens = tokenize(text)
|
tokens = tokenize(text)
|
||||||
return " ".join(tokens)
|
safe_tokens = []
|
||||||
|
for t in tokens:
|
||||||
|
t = t.strip()
|
||||||
|
if not t:
|
||||||
|
continue
|
||||||
|
# 只保留字母、数字、中文字符、下划线,去掉所有FTS5特殊字符和标点
|
||||||
|
t = re.sub(r'[^\w一-鿿]', '', t)
|
||||||
|
if t:
|
||||||
|
safe_tokens.append(t)
|
||||||
|
return " ".join(safe_tokens)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue