mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-07-28 01:53:53 +08:00
fix:使用java端做聊天记录总结
This commit is contained in:
@@ -53,6 +53,7 @@ class ManageApiClient:
|
||||
async def _ensure_async_client(cls):
|
||||
"""确保异步客户端已创建(为每个事件循环创建独立的客户端)"""
|
||||
import asyncio
|
||||
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
loop_id = id(loop)
|
||||
@@ -115,6 +116,7 @@ class ManageApiClient:
|
||||
async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
|
||||
"""带重试机制的异步请求执行器"""
|
||||
import asyncio
|
||||
|
||||
retry_count = 0
|
||||
|
||||
while retry_count <= cls.max_retries:
|
||||
@@ -138,6 +140,7 @@ class ManageApiClient:
|
||||
def safe_close(cls):
|
||||
"""安全关闭所有异步连接池"""
|
||||
import asyncio
|
||||
|
||||
for client in list(cls._async_clients.values()):
|
||||
try:
|
||||
asyncio.run(client.aclose())
|
||||
@@ -149,7 +152,9 @@ class ManageApiClient:
|
||||
|
||||
async def get_server_config() -> Optional[Dict]:
|
||||
"""获取服务器基础配置"""
|
||||
return await ManageApiClient._instance._execute_async_request("POST", "/config/server-base")
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"POST", "/config/server-base"
|
||||
)
|
||||
|
||||
|
||||
async def get_agent_models(
|
||||
@@ -181,6 +186,30 @@ async def save_mem_local_short(mac_address: str, short_momery: str) -> Optional[
|
||||
return None
|
||||
|
||||
|
||||
async def generate_chat_summary(session_id: str) -> Optional[Dict]:
|
||||
"""生成聊天记录总结"""
|
||||
try:
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"POST",
|
||||
f"/agent/chat-summary/{session_id}",
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"生成聊天记录总结失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
async def generate_and_save_chat_summary(session_id: str) -> Optional[Dict]:
|
||||
"""生成并保存聊天记录总结"""
|
||||
try:
|
||||
return await ManageApiClient._instance._execute_async_request(
|
||||
"POST",
|
||||
f"/agent/chat-summary/{session_id}/save",
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"生成并保存聊天记录总结失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
async def report(
|
||||
mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
|
||||
) -> Optional[Dict]:
|
||||
|
||||
@@ -243,7 +243,9 @@ class ConnectionHandler:
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
loop.run_until_complete(
|
||||
self.memory.save_memory(self.dialogue.dialogue)
|
||||
self.memory.save_memory(
|
||||
self.dialogue.dialogue, self.session_id
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
|
||||
|
||||
@@ -14,7 +14,7 @@ class MemoryProviderBase(ABC):
|
||||
self.llm = llm
|
||||
|
||||
@abstractmethod
|
||||
async def save_memory(self, msgs):
|
||||
async def save_memory(self, msgs, session_id=None):
|
||||
"""Save a new memory for specific role and return memory ID"""
|
||||
print("this is base func", msgs)
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
|
||||
self.use_mem0 = False
|
||||
|
||||
async def save_memory(self, msgs):
|
||||
async def save_memory(self, msgs, session_id=None):
|
||||
if not self.use_mem0:
|
||||
return None
|
||||
if len(msgs) < 2:
|
||||
@@ -41,9 +41,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||
for message in msgs
|
||||
if message.role != "system"
|
||||
]
|
||||
result = self.client.add(
|
||||
messages, user_id=self.role_id
|
||||
)
|
||||
result = self.client.add(messages, user_id=self.role_id)
|
||||
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
|
||||
|
||||
@@ -4,7 +4,10 @@ import json
|
||||
import os
|
||||
import yaml
|
||||
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,
|
||||
generate_and_save_chat_summary,
|
||||
)
|
||||
import asyncio
|
||||
from core.utils.util import check_model_key
|
||||
|
||||
@@ -144,7 +147,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||
with open(self.memory_path, "w", encoding="utf-8") as f:
|
||||
yaml.dump(all_memory, f, allow_unicode=True)
|
||||
|
||||
async def save_memory(self, msgs):
|
||||
async def save_memory(self, msgs, session_id=None):
|
||||
# 打印使用的模型信息
|
||||
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
|
||||
logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
|
||||
@@ -188,20 +191,18 @@ class MemoryProvider(MemoryProviderBase):
|
||||
except Exception as e:
|
||||
print("Error:", e)
|
||||
else:
|
||||
result = self.llm.response_no_stream(
|
||||
short_term_memory_prompt_only_content,
|
||||
msgStr,
|
||||
max_tokens=2000,
|
||||
temperature=0.2,
|
||||
)
|
||||
# 当save_to_file为False时,调用Java端的聊天记录总结接口
|
||||
summary_id = session_id if session_id else self.role_id
|
||||
# 使用异步版本,需要在事件循环中运行
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
loop.create_task(save_mem_local_short(self.role_id, result))
|
||||
loop.create_task(generate_and_save_chat_summary(summary_id))
|
||||
except RuntimeError:
|
||||
# 如果没有运行中的事件循环,创建一个新的
|
||||
asyncio.run(save_mem_local_short(self.role_id, result))
|
||||
logger.bind(tag=TAG).info(f"Save memory successful - Role: {self.role_id}")
|
||||
asyncio.run(generate_and_save_chat_summary(summary_id))
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Save memory successful - Role: {self.role_id}, Session: {session_id}"
|
||||
)
|
||||
|
||||
return self.short_memory
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||
def __init__(self, config, summary_memory=None):
|
||||
super().__init__(config)
|
||||
|
||||
async def save_memory(self, msgs):
|
||||
async def save_memory(self, msgs, session_id=None):
|
||||
logger.bind(tag=TAG).debug("nomem mode: No memory saving is performed.")
|
||||
return None
|
||||
|
||||
|
||||
Reference in New Issue
Block a user