From 0d9692d7fc60e0f7b481ba0a8f72e0b88f6575be Mon Sep 17 00:00:00 2001 From: Jordan Date: Wed, 14 Oct 2026 11:39:38 -0300 Subject: [PATCH] feat(agent): implement backend memory clearing endpoint and update compose build context --- .gitignore | 3 + Dockerfile-web | 3 +- .../agent/controller/AgentController.java | 10 +++ .../modules/security/config/ShiroConfig.java | 1 + main/xiaozhi-server/.env.example | 1 + main/xiaozhi-server/config/config_loader.py | 2 +- .../config/manage_api_client.py | 9 ++- main/xiaozhi-server/config/settings.py | 2 - main/xiaozhi-server/docker-compose.yml | 22 ++++-- main/xiaozhi-server/docker-compose_all.yml | 60 ++++++++------- .../functions/handle_exit_intent.py | 75 +++++++------------ 11 files changed, 101 insertions(+), 87 deletions(-) create mode 100644 main/xiaozhi-server/.env.example diff --git a/.gitignore b/.gitignore index bbab869d4..2ecac5dc7 100644 --- a/.gitignore +++ b/.gitignore @@ -197,3 +197,6 @@ uploadfile main/digital-human/wakeword_runtime/models main/digital-human/wakeword_runtime/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01 sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2 + +## Piper tts files, adjust if necessary +main/xiaozhi-server/piper-data \ No newline at end of file diff --git a/Dockerfile-web b/Dockerfile-web index fd0eb017b..4dde0e36d 100644 --- a/Dockerfile-web +++ b/Dockerfile-web @@ -46,5 +46,6 @@ EXPOSE 8002 # 启动脚本 COPY docs/docker/start.sh /start.sh -RUN chmod +x /start.sh +RUN sed -i 's/\r$//' /start.sh && chmod +x /start.sh + CMD ["/start.sh"] \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java index 0961fe7b7..ff0c98aac 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java @@ -350,4 +350,14 @@ public class AgentController { return new Result().ok(null); } + + @PutMapping("/{id}/clear-memory") + @Operation(summary = "Limpar a memória do agente inteligente (chamada pelo serviço do sistema)") + public Result clearAgentMemory(@PathVariable("id") String id) { + AgentUpdateDTO dto = new AgentUpdateDTO(); + dto.setSummaryMemory(""); + agentService.updateAgentById(id, dto); + return new Result().ok(null); + } + } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java index 9e7c6387f..b46364ca9 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java @@ -98,6 +98,7 @@ public class ShiroConfig { filterMap.put("/agent/chat-title/**", "server"); filterMap.put("/agent/play/**", "anon"); filterMap.put("/voiceClone/play/**", "anon"); + filterMap.put("/agent/*/clear-memory", "server"); filterMap.put("/**", "oauth2"); shiroFilter.setFilterChainDefinitionMap(filterMap); diff --git a/main/xiaozhi-server/.env.example b/main/xiaozhi-server/.env.example new file mode 100644 index 000000000..2c46575a9 --- /dev/null +++ b/main/xiaozhi-server/.env.example @@ -0,0 +1 @@ +DEFAULT_AGENT_ID= \ No newline at end of file diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 9e7e1c113..10a0cee04 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -10,7 +10,7 @@ from config.manage_api_client import ( DeviceNotFoundException, DeviceBindException, ) - +from config.settings import DEFAULT_AGENT_ID def get_project_dir(): """获取项目根目录""" diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index d0512d03a..64b881b99 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -291,7 +291,14 @@ async def report( ), }, ) - + +@api_guard("Limpar memória do agente falhou") +async def clear_agent_memory(instance, agent_id: str) -> Optional[Dict]: + """Limpa a memória resumida do agente no Java via rota de serviço""" + return await instance._execute_async_request( + "PUT", + f"/agent/{agent_id}/clear-memory", + ) @api_guard("通讯录查找失败") async def lookup_address_book(instance, caller_mac: str, nickname: str) -> Optional[Dict]: diff --git a/main/xiaozhi-server/config/settings.py b/main/xiaozhi-server/config/settings.py index 4495af670..f7985a0ff 100644 --- a/main/xiaozhi-server/config/settings.py +++ b/main/xiaozhi-server/config/settings.py @@ -5,8 +5,6 @@ from config.config_loader import read_config, get_project_dir, load_config # Carrega as variáveis do arquivo .env para o ambiente Python load_dotenv() -XIAOZHI_BASE_URL = os.getenv("XIAOZHI_BASE_URL", "http://host.docker.internal:8002/xiaozhi") -XIAOZHI_USER_TOKEN = os.getenv("XIAOZHI_USER_TOKEN", "") DEFAULT_AGENT_ID = os.getenv("DEFAULT_AGENT_ID", "a69fbf960e9840f09a2ba12dd3ff4c15") default_config_file = "config.yaml" diff --git a/main/xiaozhi-server/docker-compose.yml b/main/xiaozhi-server/docker-compose.yml index 2427a79f1..25e1d1dc6 100644 --- a/main/xiaozhi-server/docker-compose.yml +++ b/main/xiaozhi-server/docker-compose.yml @@ -3,20 +3,28 @@ version: '3' services: xiaozhi-esp32-server: - image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:server_latest + build: + context: ../../ + dockerfile: Dockerfile-server container_name: xiaozhi-esp32-server restart: always security_opt: - seccomp:unconfined + env_file: + - .env + extra_hosts: + - "host.docker.internal:host-gateway" + environment: - - TZ=UTC + - VOICE_PRINT_URL=http://192.168.1.178:8005/voiceprint/health?key=39fd8c01-c868-4197-8308-f91893864d6a + - TZ=America/Sao_Paulo ports: - # ws服务端 - "8000:8000" - # http服务的端口,用于简单OTA接口(单服务部署),以及视觉分析接口 - "8003:8003" volumes: - # 配置文件目录 + # Persistent data files and large model files only: - ./data:/opt/xiaozhi-esp32-server/data - # 模型文件挂接,很重要 - - ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt \ No newline at end of file + - ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt + + # (Optional) Allows real-time plugin editing without rebuilding the image after each change: + - ./plugins_func:/opt/xiaozhi-esp32-server/plugins_func \ No newline at end of file diff --git a/main/xiaozhi-server/docker-compose_all.yml b/main/xiaozhi-server/docker-compose_all.yml index 327676e18..607046440 100644 --- a/main/xiaozhi-server/docker-compose_all.yml +++ b/main/xiaozhi-server/docker-compose_all.yml @@ -1,35 +1,40 @@ -# Docker安装全模块 +# Docker installation with all modules version: '3' services: - # Server模块 + # Server module xiaozhi-esp32-server: - image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:server_latest + build: + context: ../../ + dockerfile: Dockerfile-server container_name: xiaozhi-esp32-server - depends_on: - - xiaozhi-esp32-server-db - - xiaozhi-esp32-server-redis restart: always - networks: - - default - ports: - # ws服务端 - - "8000:8000" - # http服务的端口,用于视觉分析接口 - - "8003:8003" security_opt: - seccomp:unconfined + env_file: + - .env + extra_hosts: + - "host.docker.internal:host-gateway" + environment: - - TZ=Asia/Shanghai + - VOICE_PRINT_URL=http://192.168.1.178:8005/voiceprint/health?key=39fd8c01-c868-4197-8308-f91893864d6a + - TZ=America/Sao_Paulo + ports: + - "8000:8000" + - "8003:8003" volumes: - # 配置文件目录 + # Persistent data files and large model files only: - ./data:/opt/xiaozhi-esp32-server/data - # 模型文件挂接,很重要 - ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt - # manager-api和manager-web模块 + # (Optional) Allows real-time plugin editing without rebuilding the image after each change: + - ./plugins_func:/opt/xiaozhi-esp32-server/plugins_func + + # Manager API and Manager Web xiaozhi-esp32-server-web: - image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest + build: + context: ../../ # Project root directory (containing the 'main' and 'docs' directories) + dockerfile: Dockerfile-web # Dockerfile name (if located in the root directory) or relative path, e.g., docs/docker/Dockerfile container_name: xiaozhi-esp32-server-web restart: always networks: @@ -40,20 +45,19 @@ services: xiaozhi-esp32-server-redis: condition: service_healthy ports: - # 智控台 - "8002:8002" environment: - - TZ=Asia/Shanghai - - SPRING_DATASOURCE_DRUID_URL=jdbc:mysql://xiaozhi-esp32-server-db:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&connectTimeout=30000&socketTimeout=30000&autoReconnect=true&failOverReadOnly=false&maxReconnects=10 + - TZ=America/Sao_Paulo + - SPRING_DATASOURCE_DRUID_URL=jdbc:mysql://xiaozhi-esp32-server-db:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=America/Sao_Paulo&nullCatalogMeansCurrent=true&connectTimeout=30000&socketTimeout=30000&autoReconnect=true&failOverReadOnly=false&maxReconnects=10 - SPRING_DATASOURCE_DRUID_USERNAME=root - SPRING_DATASOURCE_DRUID_PASSWORD=123456 - SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis - SPRING_DATA_REDIS_PASSWORD= - SPRING_DATA_REDIS_PORT=6379 volumes: - # 配置文件目录 - ./uploadfile:/uploadfile - # 数据库模块 + + # Database module xiaozhi-esp32-server-db: image: mysql:latest container_name: xiaozhi-esp32-server-db @@ -65,16 +69,17 @@ services: restart: always networks: - default - expose: - - 3306 + ports: + - "3306:3306" volumes: - ./mysql/data:/var/lib/mysql environment: - - TZ=Asia/Shanghai + - TZ=America/Sao_Paulo - MYSQL_ROOT_PASSWORD=123456 - MYSQL_DATABASE=xiaozhi_esp32_server - MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci" - # redis模块 + + # Redis module xiaozhi-esp32-server-redis: image: redis:8.0 expose: @@ -88,5 +93,6 @@ services: retries: 3 networks: - default + networks: default: diff --git a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py index d302ca630..7940a2190 100644 --- a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py +++ b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py @@ -1,15 +1,13 @@ -import requests -from config.settings import XIAOZHI_BASE_URL, XIAOZHI_USER_TOKEN, DEFAULT_AGENT_ID -from plugins_func.register import register_function, ToolType, ActionResponse, Action -from config.logger import setup_logging +import threading +import asyncio from typing import TYPE_CHECKING +from plugins_func.register import register_function, ToolType, ActionResponse, Action +from config.settings import DEFAULT_AGENT_ID +from config.manage_api_client import clear_agent_memory if TYPE_CHECKING: from core.connection import ConnectionHandler -TAG = __name__ -logger = setup_logging() - handle_exit_intent_function_desc = { "type": "function", "function": { @@ -33,56 +31,37 @@ handle_exit_intent_function_desc = { "handle_exit_intent", handle_exit_intent_function_desc, ToolType.SYSTEM_CTL ) def handle_exit_intent(conn: "ConnectionHandler", say_goodbye: str | None = None): - # Processar intenção de encerramento da conversa try: if say_goodbye is None: - say_goodbye = "Até logo! Tenha um ótimo dia!" - if not conn.close_after_chat: - conn.close_after_chat = True + say_goodbye = "Até logo!" - logger.bind(tag=TAG).info( - f"Intenção de encerramento processada: {say_goodbye}" - ) - - + conn.close_after_chat = True + agent_id = getattr(conn, "agent_id", DEFAULT_AGENT_ID) - # SUCCESS - # Vamos montar uma requisição para o servidor JAVA - # PUT para o /agent/:agent_id/ - # Body - # { - # "summaryMemory": "eai " - # } - # --- REQUISIÇÃO PUT PARA O SERVIDOR JAVA --- - agent_id = DEFAULT_AGENT_ID - user_token = XIAOZHI_USER_TOKEN - base_url = XIAOZHI_BASE_URL + # Limpa a memória no Java em background via ManageApiClient + def clear_task(): + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + loop.run_until_complete(clear_agent_memory(agent_id)) + finally: + loop.close() - headers = {"Content-Type": "application/json"} - if user_token: - headers["Authorization"] = f"Bearer {user_token}" if not user_token.startswith("Bearer ") else user_token + threading.Thread(target=clear_task, daemon=True).start() - update_agent_url = f"{base_url}/agent/{agent_id}" - payload = { - "summaryMemory": "" # Adicione/substitua pelo resumo real caso tenha essa variável - } + # Limpa o histórico em memória local para não regravar nada na desconexão + if hasattr(conn, "dialogue") and conn.dialogue: + conn.dialogue.dialogue.clear() - logger.bind(tag=TAG).info(f"[ExitIntent] Enviando PUT para {update_agent_url} com payload: {payload}") - - # Requisição PUT - res = requests.put(update_agent_url, json=payload, headers=headers, timeout=5) - logger.bind(tag=TAG).info(f"[ExitIntent] Resposta do Java ({res.status_code}): {res.text}") - return ActionResponse( - action=Action.RESPONSE, result="Intenção de encerramento processada", response=say_goodbye, + action=Action.RESPONSE, + result="Intenção de encerramento processada", + response=say_goodbye, ) except Exception as e: - logger.bind(tag=TAG).error( - f"Erro ao processar intenção de encerramento: {e}" - ) - return ActionResponse( - action=Action.NONE, result="Falha ao processar intenção de encerramento", response="", - ) - + action=Action.NONE, + result=f"Falha ao processar intenção de encerramento: {e}", + response="", + ) \ No newline at end of file