feat(agent): implement backend memory clearing endpoint and update compose build context

This commit is contained in:
Jordan 2026-10-14 11:39:38 -03:00
parent 8ab3e8c9a3
commit 0d9692d7fc
11 changed files with 101 additions and 87 deletions

3
.gitignore vendored
View file

@ -197,3 +197,6 @@ uploadfile
main/digital-human/wakeword_runtime/models main/digital-human/wakeword_runtime/models
main/digital-human/wakeword_runtime/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01 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 sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2
## Piper tts files, adjust if necessary
main/xiaozhi-server/piper-data

View file

@ -46,5 +46,6 @@ EXPOSE 8002
# 启动脚本 # 启动脚本
COPY docs/docker/start.sh /start.sh 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"] CMD ["/start.sh"]

View file

@ -350,4 +350,14 @@ public class AgentController {
return new Result<Void>().ok(null); return new Result<Void>().ok(null);
} }
@PutMapping("/{id}/clear-memory")
@Operation(summary = "Limpar a memória do agente inteligente (chamada pelo serviço do sistema)")
public Result<Void> clearAgentMemory(@PathVariable("id") String id) {
AgentUpdateDTO dto = new AgentUpdateDTO();
dto.setSummaryMemory("");
agentService.updateAgentById(id, dto);
return new Result<Void>().ok(null);
}
} }

View file

@ -98,6 +98,7 @@ public class ShiroConfig {
filterMap.put("/agent/chat-title/**", "server"); filterMap.put("/agent/chat-title/**", "server");
filterMap.put("/agent/play/**", "anon"); filterMap.put("/agent/play/**", "anon");
filterMap.put("/voiceClone/play/**", "anon"); filterMap.put("/voiceClone/play/**", "anon");
filterMap.put("/agent/*/clear-memory", "server");
filterMap.put("/**", "oauth2"); filterMap.put("/**", "oauth2");
shiroFilter.setFilterChainDefinitionMap(filterMap); shiroFilter.setFilterChainDefinitionMap(filterMap);

View file

@ -0,0 +1 @@
DEFAULT_AGENT_ID=

View file

@ -10,7 +10,7 @@ from config.manage_api_client import (
DeviceNotFoundException, DeviceNotFoundException,
DeviceBindException, DeviceBindException,
) )
from config.settings import DEFAULT_AGENT_ID
def get_project_dir(): def get_project_dir():
"""获取项目根目录""" """获取项目根目录"""

View file

@ -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("通讯录查找失败") @api_guard("通讯录查找失败")
async def lookup_address_book(instance, caller_mac: str, nickname: str) -> Optional[Dict]: async def lookup_address_book(instance, caller_mac: str, nickname: str) -> Optional[Dict]:

View file

@ -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 # Carrega as variáveis do arquivo .env para o ambiente Python
load_dotenv() 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_AGENT_ID = os.getenv("DEFAULT_AGENT_ID", "a69fbf960e9840f09a2ba12dd3ff4c15")
default_config_file = "config.yaml" default_config_file = "config.yaml"

View file

@ -3,20 +3,28 @@
version: '3' version: '3'
services: services:
xiaozhi-esp32-server: 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 container_name: xiaozhi-esp32-server
restart: always restart: always
security_opt: security_opt:
- seccomp:unconfined - seccomp:unconfined
env_file:
- .env
extra_hosts:
- "host.docker.internal:host-gateway"
environment: 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: ports:
# ws服务端
- "8000:8000" - "8000:8000"
# http服务的端口,用于简单OTA接口(单服务部署),以及视觉分析接口
- "8003:8003" - "8003:8003"
volumes: volumes:
# 配置文件目录 # Persistent data files and large model files only:
- ./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
# (Optional) Allows real-time plugin editing without rebuilding the image after each change:
- ./plugins_func:/opt/xiaozhi-esp32-server/plugins_func

View file

@ -1,35 +1,40 @@
# Docker安装全模块 # Docker installation with all modules
version: '3' version: '3'
services: services:
# Server模块 # Server module
xiaozhi-esp32-server: 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 container_name: xiaozhi-esp32-server
depends_on:
- xiaozhi-esp32-server-db
- xiaozhi-esp32-server-redis
restart: always restart: always
networks:
- default
ports:
# ws服务端
- "8000:8000"
# http服务的端口,用于视觉分析接口
- "8003:8003"
security_opt: security_opt:
- seccomp:unconfined - seccomp:unconfined
env_file:
- .env
extra_hosts:
- "host.docker.internal:host-gateway"
environment: 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: volumes:
# 配置文件目录 # Persistent data files and large model files only:
- ./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
# 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: 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 container_name: xiaozhi-esp32-server-web
restart: always restart: always
networks: networks:
@ -40,20 +45,19 @@ services:
xiaozhi-esp32-server-redis: xiaozhi-esp32-server-redis:
condition: service_healthy condition: service_healthy
ports: ports:
# 智控台
- "8002:8002" - "8002:8002"
environment: environment:
- TZ=Asia/Shanghai - TZ=America/Sao_Paulo
- 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 - 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_USERNAME=root
- SPRING_DATASOURCE_DRUID_PASSWORD=123456 - SPRING_DATASOURCE_DRUID_PASSWORD=123456
- SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis - SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis
- SPRING_DATA_REDIS_PASSWORD= - SPRING_DATA_REDIS_PASSWORD=
- SPRING_DATA_REDIS_PORT=6379 - SPRING_DATA_REDIS_PORT=6379
volumes: volumes:
# 配置文件目录
- ./uploadfile:/uploadfile - ./uploadfile:/uploadfile
# 数据库模块
# Database module
xiaozhi-esp32-server-db: xiaozhi-esp32-server-db:
image: mysql:latest image: mysql:latest
container_name: xiaozhi-esp32-server-db container_name: xiaozhi-esp32-server-db
@ -65,16 +69,17 @@ services:
restart: always restart: always
networks: networks:
- default - default
expose: ports:
- 3306 - "3306:3306"
volumes: volumes:
- ./mysql/data:/var/lib/mysql - ./mysql/data:/var/lib/mysql
environment: environment:
- TZ=Asia/Shanghai - TZ=America/Sao_Paulo
- MYSQL_ROOT_PASSWORD=123456 - MYSQL_ROOT_PASSWORD=123456
- MYSQL_DATABASE=xiaozhi_esp32_server - MYSQL_DATABASE=xiaozhi_esp32_server
- 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 module
xiaozhi-esp32-server-redis: xiaozhi-esp32-server-redis:
image: redis:8.0 image: redis:8.0
expose: expose:
@ -88,5 +93,6 @@ services:
retries: 3 retries: 3
networks: networks:
- default - default
networks: networks:
default: default:

View file

@ -1,15 +1,13 @@
import requests import threading
from config.settings import XIAOZHI_BASE_URL, XIAOZHI_USER_TOKEN, DEFAULT_AGENT_ID import asyncio
from plugins_func.register import register_function, ToolType, ActionResponse, Action
from config.logger import setup_logging
from typing import TYPE_CHECKING 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: if TYPE_CHECKING:
from core.connection import ConnectionHandler from core.connection import ConnectionHandler
TAG = __name__
logger = setup_logging()
handle_exit_intent_function_desc = { handle_exit_intent_function_desc = {
"type": "function", "type": "function",
"function": { "function": {
@ -33,56 +31,37 @@ handle_exit_intent_function_desc = {
"handle_exit_intent", handle_exit_intent_function_desc, ToolType.SYSTEM_CTL "handle_exit_intent", handle_exit_intent_function_desc, ToolType.SYSTEM_CTL
) )
def handle_exit_intent(conn: "ConnectionHandler", say_goodbye: str | None = None): def handle_exit_intent(conn: "ConnectionHandler", say_goodbye: str | None = None):
# Processar intenção de encerramento da conversa
try: try:
if say_goodbye is None: if say_goodbye is None:
say_goodbye = "Até logo! Tenha um ótimo dia!" say_goodbye = "Até logo!"
if not conn.close_after_chat:
conn.close_after_chat = True
logger.bind(tag=TAG).info( conn.close_after_chat = True
f"Intenção de encerramento processada: {say_goodbye}" agent_id = getattr(conn, "agent_id", DEFAULT_AGENT_ID)
)
# SUCCESS # Limpa a memória no Java em background via ManageApiClient
# Vamos montar uma requisição para o servidor JAVA def clear_task():
# PUT para o /agent/:agent_id/ loop = asyncio.new_event_loop()
# Body asyncio.set_event_loop(loop)
# { try:
# "summaryMemory": "eai " loop.run_until_complete(clear_agent_memory(agent_id))
# } finally:
# --- REQUISIÇÃO PUT PARA O SERVIDOR JAVA --- loop.close()
agent_id = DEFAULT_AGENT_ID
user_token = XIAOZHI_USER_TOKEN
base_url = XIAOZHI_BASE_URL
headers = {"Content-Type": "application/json"} threading.Thread(target=clear_task, daemon=True).start()
if user_token:
headers["Authorization"] = f"Bearer {user_token}" if not user_token.startswith("Bearer ") else user_token
update_agent_url = f"{base_url}/agent/{agent_id}" # Limpa o histórico em memória local para não regravar nada na desconexão
payload = { if hasattr(conn, "dialogue") and conn.dialogue:
"summaryMemory": "" # Adicione/substitua pelo resumo real caso tenha essa variável 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( 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: except Exception as e:
logger.bind(tag=TAG).error(
f"Erro ao processar intenção de encerramento: {e}"
)
return ActionResponse( 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="",
)