mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge branch 'main' into main
This commit is contained in:
commit
014ec0522e
6 changed files with 115 additions and 11 deletions
|
|
@ -0,0 +1,19 @@
|
||||||
|
-- LLM意图识别配置说明
|
||||||
|
UPDATE `ai_model_config` SET
|
||||||
|
`doc_link` = NULL,
|
||||||
|
`remark` = 'LLM意图识别配置说明:
|
||||||
|
1. 使用独立的LLM进行意图识别
|
||||||
|
2. 默认使用selected_module.LLM的模型
|
||||||
|
3. 可以配置使用独立的LLM(如免费的ChatGLMLLM)
|
||||||
|
4. 通用性强,但会增加处理时间
|
||||||
|
配置说明:
|
||||||
|
1. 在llm字段中指定使用的LLM模型
|
||||||
|
2. 如果不指定,则使用selected_module.LLM的模型' WHERE `id` = 'Intent_intent_llm';
|
||||||
|
|
||||||
|
-- 函数调用意图识别配置说明
|
||||||
|
UPDATE `ai_model_config` SET
|
||||||
|
`doc_link` = NULL,
|
||||||
|
`remark` = '函数调用意图识别配置说明:
|
||||||
|
1. 使用LLM的function_call功能进行意图识别
|
||||||
|
2. 需要所选择的LLM支持function_call
|
||||||
|
3. 按需调用工具,处理速度快' WHERE `id` = 'Intent_function_call';
|
||||||
|
|
@ -212,6 +212,13 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202506161101.sql
|
path: classpath:db/changelog/202506161101.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202506191643
|
||||||
|
author: hrz
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202506191643.sql
|
||||||
- changeSet:
|
- changeSet:
|
||||||
id: 202506181501
|
id: 202506181501
|
||||||
author: chan
|
author: chan
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,27 @@ class MCPClient:
|
||||||
fut: concurrent.futures.Future = asyncio.run_coroutine_threadsafe(coro, loop)
|
fut: concurrent.futures.Future = asyncio.run_coroutine_threadsafe(coro, loop)
|
||||||
return await asyncio.wrap_future(fut)
|
return await asyncio.wrap_future(fut)
|
||||||
|
|
||||||
|
def is_connected(self) -> bool:
|
||||||
|
"""检查MCP客户端是否连接正常
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 如果客户端已连接并正常工作,返回True,否则返回False
|
||||||
|
"""
|
||||||
|
# 检查工作任务是否存在
|
||||||
|
if self._worker_task is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 检查工作任务是否已经完成或取消
|
||||||
|
if self._worker_task.done():
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 检查会话是否存在
|
||||||
|
if self.session is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 所有检查都通过,连接正常
|
||||||
|
return True
|
||||||
|
|
||||||
async def _worker(self):
|
async def _worker(self):
|
||||||
async with AsyncExitStack() as stack:
|
async with AsyncExitStack() as stack:
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -100,7 +100,7 @@ class MCPManager:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
|
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
|
||||||
"""执行工具调用
|
"""执行工具调用,失败时会尝试重新连接
|
||||||
Args:
|
Args:
|
||||||
tool_name: 工具名称
|
tool_name: 工具名称
|
||||||
arguments: 工具参数
|
arguments: 工具参数
|
||||||
|
|
@ -112,11 +112,64 @@ class MCPManager:
|
||||||
self.conn.logger.bind(tag=TAG).info(
|
self.conn.logger.bind(tag=TAG).info(
|
||||||
f"Executing tool {tool_name} with arguments: {arguments}"
|
f"Executing tool {tool_name} with arguments: {arguments}"
|
||||||
)
|
)
|
||||||
for client in self.client.values():
|
|
||||||
|
max_retries = 3 # 最大重试次数
|
||||||
|
retry_interval = 2 # 重试间隔(秒)
|
||||||
|
|
||||||
|
# 找到对应的客户端
|
||||||
|
client_name = None
|
||||||
|
target_client = None
|
||||||
|
for name, client in self.client.items():
|
||||||
if client.has_tool(tool_name):
|
if client.has_tool(tool_name):
|
||||||
return await client.call_tool(tool_name, arguments)
|
client_name = name
|
||||||
|
target_client = client
|
||||||
raise ValueError(f"Tool {tool_name} not found in any MCP server")
|
break
|
||||||
|
|
||||||
|
if not target_client:
|
||||||
|
raise ValueError(f"Tool {tool_name} not found in any MCP server")
|
||||||
|
|
||||||
|
# 带重试机制的工具调用
|
||||||
|
for attempt in range(max_retries):
|
||||||
|
try:
|
||||||
|
return await target_client.call_tool(tool_name, arguments)
|
||||||
|
except Exception as e:
|
||||||
|
# 最后一次尝试失败时直接抛出异常
|
||||||
|
if attempt == max_retries - 1:
|
||||||
|
raise
|
||||||
|
|
||||||
|
self.conn.logger.bind(tag=TAG).warning(
|
||||||
|
f"执行工具 {tool_name} 失败 (尝试 {attempt+1}/{max_retries}): {e}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 尝试重新连接
|
||||||
|
self.conn.logger.bind(tag=TAG).info(
|
||||||
|
f"重试前尝试重新连接 MCP 客户端 {client_name}"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
# 关闭旧的连接
|
||||||
|
await target_client.cleanup()
|
||||||
|
|
||||||
|
# 重新初始化客户端
|
||||||
|
config = self.load_config()
|
||||||
|
if client_name in config:
|
||||||
|
client = MCPClient(config[client_name])
|
||||||
|
await client.initialize()
|
||||||
|
self.client[client_name] = client
|
||||||
|
target_client = client
|
||||||
|
self.conn.logger.bind(tag=TAG).info(
|
||||||
|
f"成功重新连接 MCP 客户端: {client_name}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.conn.logger.bind(tag=TAG).error(
|
||||||
|
f"Cannot reconnect MCP client {client_name}: config not found"
|
||||||
|
)
|
||||||
|
except Exception as reconnect_error:
|
||||||
|
self.conn.logger.bind(tag=TAG).error(
|
||||||
|
f"Failed to reconnect MCP client {client_name}: {reconnect_error}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 等待一段时间再重试
|
||||||
|
await asyncio.sleep(retry_interval)
|
||||||
|
|
||||||
async def cleanup_all(self) -> None:
|
async def cleanup_all(self) -> None:
|
||||||
"""依次关闭所有 MCPClient,不让异常阻断整体流程。"""
|
"""依次关闭所有 MCPClient,不让异常阻断整体流程。"""
|
||||||
|
|
|
||||||
|
|
@ -93,9 +93,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
# 检查初始化响应
|
# 检查初始化响应
|
||||||
if "code" in result and result["code"] != 1000:
|
if "code" in result and result["code"] != 1000:
|
||||||
error_msg = f"ASR服务初始化失败: {result.get('payload_msg', {}).get('message', '未知错误')}"
|
error_msg = f"ASR服务初始化失败: {result.get('payload_msg', {}).get('error', '未知错误')}"
|
||||||
if "payload_msg" in result:
|
|
||||||
error_msg += f"\n详细错误信息: {json.dumps(result['payload_msg'], ensure_ascii=False)}"
|
|
||||||
logger.bind(tag=TAG).error(error_msg)
|
logger.bind(tag=TAG).error(error_msg)
|
||||||
raise Exception(error_msg)
|
raise Exception(error_msg)
|
||||||
|
|
||||||
|
|
@ -309,9 +307,10 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
# 如果是错误响应
|
# 如果是错误响应
|
||||||
if message_type == 0x0F: # SERVER_ERROR_RESPONSE
|
if message_type == 0x0F: # SERVER_ERROR_RESPONSE
|
||||||
code = int.from_bytes(header[4:8], "big", signed=False)
|
code = int.from_bytes(res[4:8], "big", signed=False)
|
||||||
error_msg = res[8:].decode("utf-8")
|
msg_length = int.from_bytes(res[8:12], "big", signed=False)
|
||||||
return {"code": code, "error": error_msg}
|
error_msg = json.loads(res[12:].decode("utf-8"))
|
||||||
|
return {"code": code, "msg_length": msg_length, "payload_msg": error_msg}
|
||||||
|
|
||||||
# 获取JSON数据(跳过12字节头部)
|
# 获取JSON数据(跳过12字节头部)
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import os
|
||||||
import yaml
|
import yaml
|
||||||
from config.config_loader import get_project_dir
|
from config.config_loader import get_project_dir
|
||||||
from config.manage_api_client import save_mem_local_short
|
from config.manage_api_client import save_mem_local_short
|
||||||
|
from core.utils.util import check_model_key
|
||||||
|
|
||||||
|
|
||||||
short_term_memory_prompt = """
|
short_term_memory_prompt = """
|
||||||
|
|
@ -145,6 +146,10 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
# 打印使用的模型信息
|
# 打印使用的模型信息
|
||||||
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
|
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
|
||||||
logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
|
logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
|
||||||
|
api_key = getattr(self.llm, "api_key", None)
|
||||||
|
memory_key_msg = check_model_key("记忆总结专用LLM", api_key)
|
||||||
|
if memory_key_msg:
|
||||||
|
logger.bind(tag=TAG).error(memory_key_msg)
|
||||||
if self.llm is None:
|
if self.llm is None:
|
||||||
logger.bind(tag=TAG).error("LLM is not set for memory provider")
|
logger.bind(tag=TAG).error("LLM is not set for memory provider")
|
||||||
return None
|
return None
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue