mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-27 04:49:47 +01:00
feat(agent): implement backend memory clearing endpoint and update compose build context
This commit is contained in:
parent
8ab3e8c9a3
commit
0d9692d7fc
11 changed files with 101 additions and 87 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -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
|
||||
|
|
@ -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"]
|
||||
|
|
@ -350,4 +350,14 @@ public class AgentController {
|
|||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
|
|
|
|||
1
main/xiaozhi-server/.env.example
Normal file
1
main/xiaozhi-server/.env.example
Normal file
|
|
@ -0,0 +1 @@
|
|||
DEFAULT_AGENT_ID=
|
||||
|
|
@ -10,7 +10,7 @@ from config.manage_api_client import (
|
|||
DeviceNotFoundException,
|
||||
DeviceBindException,
|
||||
)
|
||||
|
||||
from config.settings import DEFAULT_AGENT_ID
|
||||
|
||||
def get_project_dir():
|
||||
"""获取项目根目录"""
|
||||
|
|
|
|||
|
|
@ -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]:
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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
|
||||
- ./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
|
||||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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="",
|
||||
)
|
||||
Loading…
Reference in a new issue