diff --git a/.dockerignore b/.dockerignore index bc155a7c5..26196268f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -4,4 +4,8 @@ __pycache__ .env Dockerfile tmp/ -data/ \ No newline at end of file +data/ + +main/xiaozhi-server/mysql/data/* +main/xiaozhi-server/mysql/ +*.sock 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 ff0c98aac..737084e42 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 @@ -360,4 +360,11 @@ public class AgentController { return new Result().ok(null); } + @GetMapping("/{id}/chat-history/system") + @Operation(summary = "Obter histórico recente de áudios (chamada pelo serviço do sistema)") + public Result> getRecentlyFiftyByAgentIdSystem(@PathVariable("id") String id) { + List data = agentChatHistoryService.getRecentlyFiftyByAgentId(id); + return new Result>().ok(data); + } + } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java index 9b7555eb4..e5cb0c2de 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java @@ -84,4 +84,14 @@ public class AgentVoicePrintController { return new Result>().ok(list); } + @PostMapping("/system") + @Operation(summary = "Criar biometria de voz (Chamada interna do sistema)") + public Result saveSystem(@RequestBody @Valid AgentVoicePrintSaveDTO dto) { + boolean b = agentVoicePrintService.insert(dto); + if (b) { + return new Result<>(); + } + return new Result().error(ErrorCode.AGENT_VOICEPRINT_CREATE_FAILED); + } + } 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 b46364ca9..cc7230105 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 @@ -99,6 +99,9 @@ public class ShiroConfig { filterMap.put("/agent/play/**", "anon"); filterMap.put("/voiceClone/play/**", "anon"); filterMap.put("/agent/*/clear-memory", "server"); + filterMap.put("/agent/*/chat-history/system", "server"); + filterMap.put("/agent/voice-print/system", "server"); + filterMap.put("/**", "oauth2"); shiroFilter.setFilterChainDefinitionMap(filterMap); diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 10a0cee04..f66322c81 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -10,7 +10,6 @@ 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 64b881b99..1ad32b948 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -308,6 +308,31 @@ async def lookup_address_book(instance, caller_mac: str, nickname: str) -> Optio f"/device/address-book/lookup?callerMac={caller_mac}&nickname={nickname}", ) +@api_guard("Obter histórico de chat do sistema falhou") +async def get_agent_chat_history_system(instance, agent_id: str) -> Optional[list]: + """Obtém o histórico de áudios do agente via API de serviço""" + return await instance._execute_async_request( + "GET", + f"/agent/{agent_id}/chat-history/system", + ) + + +@api_guard("Registro de biometria de voz falhou") +async def register_voiceprint_system( + instance, agent_id: str, audio_id: str, speaker_id: str +) -> Optional[Dict]: + """Cadastra a voz do usuário via API de serviço""" + return await instance._execute_async_request( + "POST", + "/agent/voice-print/system", + json={ + "agentId": agent_id, + "audioId": audio_id, + "introduce": speaker_id, + "sourceName": speaker_id, + }, + ) + def init_service(config): ManageApiClient(config) diff --git a/main/xiaozhi-server/plugins_func/functions/register_voiceprint.py b/main/xiaozhi-server/plugins_func/functions/register_voiceprint.py index c51394287..2ac061271 100644 --- a/main/xiaozhi-server/plugins_func/functions/register_voiceprint.py +++ b/main/xiaozhi-server/plugins_func/functions/register_voiceprint.py @@ -1,10 +1,13 @@ from typing import TYPE_CHECKING, Optional -import requests import logging import traceback from plugins_func.register import register_function, ToolType, ActionResponse, Action from config.logger import setup_logging -from config.settings import XIAOZHI_BASE_URL, XIAOZHI_USER_TOKEN, DEFAULT_AGENT_ID +from config.manage_api_client import ( + get_agent_chat_history_system, + register_voiceprint_system, +) +from config.settings import DEFAULT_AGENT_ID if TYPE_CHECKING: from core.connection import ConnectionHandler @@ -34,50 +37,35 @@ register_voiceprint_function_desc = { @register_function( "register_voiceprint", register_voiceprint_function_desc, ToolType.SYSTEM_CTL ) -def register_voiceprint(conn: "ConnectionHandler", speaker_id: Optional[str] = None): +async def register_voiceprint(conn: "ConnectionHandler", speaker_id: Optional[str] = None): try: - # Configuração do Agent ID e Token de Autenticação ainda hardcoded - # TODO: Implementar a obtenção dinâmica do token de autenticação, aparentemente o agent_id não muda + agent_id = getattr(conn, "agent_id", None) or DEFAULT_AGENT_ID - agent_id = DEFAULT_AGENT_ID - user_token = XIAOZHI_USER_TOKEN - base_url = XIAOZHI_BASE_URL - - headers = {"Content-Type": "application/json"} - if user_token: - headers["Authorization"] = f"Bearer {user_token}" if not user_token.startswith("Bearer ") else user_token + # Buscar histórico recente de áudios via helper do ManageApiClient + logger.bind(tag=TAG).info(f"[Voiceprint] Buscando histórico para o agente {agent_id}") + audio_list = await get_agent_chat_history_system(agent_id) - # Consultar o histórico de áudios - history_url = f"{base_url}/agent/{agent_id}/chat-history/user" - logger.bind(tag=TAG).info(f"[Voiceprint] Buscando histórico em: {history_url}") - - history_res = requests.get(history_url, headers=headers, timeout=5) - logger.bind(tag=TAG).info(f"[Voiceprint] Resposta do histórico ({history_res.status_code}): {history_res.text}") - - if history_res.status_code != 200: + if audio_list is None: return ActionResponse( action=Action.NONE, - result=f"Erro na API de histórico: status {history_res.status_code}", + result="Erro na API ao buscar histórico", response="Não consegui obter o histórico recente para cadastrar sua voz." ) - history_data = history_res.json() - audio_list = history_data.get("data", []) - if not audio_list: - logger.bind(tag=TAG).warning("[Voiceprint] A API retornou uma lista de áudios vazia (data: []).") + logger.bind(tag=TAG).warning("[Voiceprint] Histórico de áudios retornado está vazio.") return ActionResponse( action=Action.NONE, result="Nenhum áudio encontrado no histórico do agente", response="Não encontrei nenhum registro de voz recente no histórico." ) - # evita registrar a voz se o usuário apenas perguntou "quem sou eu" ou algo similar + # Evita registrar se for apenas pergunta de identidade user_text = audio_list[0].get("content", "").lower() perguntas_identidade = ["quem sou", "me diga quem", "qual é o meu nome", "qual meu nome"] if any(p in user_text for p in perguntas_identidade): - logger.bind(tag=TAG).info(f"[Voiceprint] Interceptado: Usuário apenas perguntou a identidade ('{user_text}'). Cancelando registro.") + logger.bind(tag=TAG).info(f"[Voiceprint] Interceptado: Pergunta de identidade ('{user_text}'). Cancelando registro.") return ActionResponse( action=Action.NONE, result="Ignorado: O usuário apenas perguntou quem ele é.", @@ -98,42 +86,20 @@ def register_voiceprint(conn: "ConnectionHandler", speaker_id: Optional[str] = N logger.bind(tag=TAG).info(f"[Voiceprint] Áudio selecionado: audioId={audio_id}, texto='{latest_audio.get('content')}'") - # Enviar requisição de salvamento do Voiceprint - register_url = f"{base_url}/agent/voice-print" - payload = { - "agentId": agent_id, - "audioId": audio_id, - "introduce": speaker_id, - "sourceName": speaker_id - } + # Registrar biometria de voz no backend Java + logger.bind(tag=TAG).info(f"[Voiceprint] Registrando biometria para {speaker_id}") + res = await register_voiceprint_system(agent_id, audio_id, speaker_id) - logger.bind(tag=TAG).info(f"[Voiceprint] Enviando cadastro: {payload}") - register_res = requests.post(register_url, json=payload, headers=headers, timeout=5) - logger.bind(tag=TAG).info(f"[Voiceprint] Resposta do cadastro ({register_res.status_code}): {register_res.text}") - - res_json = register_res.json() if register_res.status_code == 200 else {} - code = res_json.get("code") - - # Sucesso - if register_res.status_code == 200 and code == 0: + if res is not None: return ActionResponse( action=Action.RESPONSE, result=f"Voiceprint de {speaker_id} registrado com sucesso", response=f"Pronto! Cadastrei a voz de {speaker_id} no sistema." ) - # Tratamento da voz já cadastrada - elif code == 10080: - logger.bind(tag=TAG).info(f"[Voiceprint] Voz já cadastrada anteriormente como {speaker_id}.") - return ActionResponse( - action=Action.RESPONSE, - result=f"Voz já cadastrada para {speaker_id}", - response=f"Sua voz já está cadastrada no sistema como {speaker_id}." - ) - # Outros erros else: return ActionResponse( action=Action.NONE, - result=f"Falha no salvamento: {register_res.text}", + result="Falha no salvamento do Voiceprint", response="Ocorreu um erro no servidor ao tentar salvar sua voz." )