diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 064f6afab..be11b7316 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -173,6 +173,13 @@ Memory: type: mem_local_short ASR: + AistudioASR: + type: aistudio + scope: audio_voice_assistant_get + dev_pid: 1536 + api_key: 你的星河社区账户令牌 + secret_key: 你的星河社区账户令牌 + output_dir: tmp/ FunASR: type: fun_local model_dir: models/SenseVoiceSmall @@ -321,10 +328,10 @@ LLM: base_url: http://localhost:9997 # Xinference服务地址 AiStudioLLM: # 定义LLM API类型 - type: openai - model_name: ernie-speed-8k - url: https://aistudio.baidu.com/llm/lmapi/v3 - api_key: 你的星河社区账户令牌 # 可在这里找到你的api key https://aistudio.baidu.com/account/accessToken + type: aistudio + app_id: 你的星河社区账户令牌 + base_url: https://aistudio.baidu.com/llm/lmapi/v3 + secret_key: 你的星河社区账户令牌 # 可在这里找到你的api key https://aistudio.baidu.com/account/accessToken TTS: # 当前支持的type为edge、doubao,可自行适配 EdgeTTS: @@ -577,6 +584,12 @@ TTS: # Authorization: Bearer xxxx format: wav # 接口返回的音频格式 output_dir: tmp/ + AistudioTTS: + # 自定义的音频文件路径 + type: aistudio + output_dir: tmp/ + api_key: 你的星河社区账户令牌 + secret_key: 你的星河社区账户令牌 # 模块测试配置 module_test: test_sentences: # 自定义测试语句 diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index dac215de0..e53b1b7cd 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -27,6 +27,7 @@ from config.private_config import PrivateConfig from core.auth import AuthMiddleware, AuthenticationError from core.utils.auth_code_gen import AuthCodeGenerator from core.mcp.manager import MCPManager +from core.utils.IoT_status import get_IoT_status TAG = __name__ @@ -394,6 +395,9 @@ class ConnectionHandler: future.result() return True + # 临时插入 IoT 信息, 在对话结束时清除 + self.dialogue.put_top(Message(role="system", content=get_IoT_status())) + if not tool_call: self.dialogue.put(Message(role="user", content=query)) @@ -422,6 +426,7 @@ class ConnectionHandler: functions=functions, ) except Exception as e: + self.dialogue.pop_top() self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") return None @@ -553,6 +558,9 @@ class ConnectionHandler: ) self.tts_queue.put(future) + # 清理 IoT 临时加入的系统信息 + self.dialogue.pop_top() + # 存储对话内容 if len(response_message) > 0: self.dialogue.put( diff --git a/main/xiaozhi-server/core/providers/asr/aistudio.py b/main/xiaozhi-server/core/providers/asr/aistudio.py new file mode 100644 index 000000000..7e6330faa --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/aistudio.py @@ -0,0 +1,134 @@ +import os +import time +import uuid +import wave +from core.providers.asr.base import ASRProviderBase +from config.logger import setup_logging +import opuslib_next +import requests + +TAG = __name__ +logger = setup_logging() + + +class ASRProvider(ASRProviderBase): + def __init__(self, config: dict, delete_audio_file: bool): + self.scope = config.get("scope") + self.dev_pid = config.get("dev_pid") + self.output_dir = config.get("output_dir") + self.cuid = "123456PYTHON" + + self.asr_url = "http://vop.baidu.com/server_api" + self.token = self.fetch_token(config.get("api_key"), config.get("secret_key")) + + # 确保输出目录存在 + os.makedirs(self.output_dir, exist_ok=True) + + def save_audio_to_file(self, opus_data: list[bytes], session_id: str) -> str: + """解码Opus数据并保存为WAV文件""" + file_name = f"asr_{session_id}_{uuid.uuid4()}.wav" + file_path = os.path.join(self.output_dir, file_name) + + decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 + pcm_data = [] + + for opus_packet in opus_data: + try: + pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms + pcm_data.append(pcm_frame) + except opuslib_next.OpusError as e: + logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) + + with wave.open(file_path, "wb") as wf: + wf.setnchannels(1) + wf.setsampwidth(2) # 2 bytes = 16-bit + wf.setframerate(16000) + wf.writeframes(b"".join(pcm_data)) + + return file_path + + def fetch_token(self, api_key: str, secret_key: str) -> str: + """Fetch access token from Baidu API using requests.""" + params = {"grant_type": "client_credentials", "client_id": api_key, "client_secret": secret_key} + + try: + response = requests.get("https://openapi.baidu.com/oauth/2.0/token", params=params) + response.raise_for_status() # 抛出HTTP错误 + result = response.json() + + access_token = result.get("access_token") + scope = result.get("scope") + + if not access_token or self.scope not in (scope or ""): + raise RuntimeError("Failed to fetch token or scope is incorrect.") + + return access_token + + except requests.RequestException as e: + raise RuntimeError(f"Token request failed: {e}") from e + + + @staticmethod + def decode_opus(opus_data: list[bytes]) -> bytes: + """将Opus音频数据解码为PCM数据""" + decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 + pcm_data = [] + + for opus_packet in opus_data: + try: + pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms + pcm_data.append(pcm_frame) + except opuslib_next.OpusError as e: + logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) + + return b"".join(pcm_data) + + def _build_request_body(self, file_format: str = "wav", rate: int = 16000) -> tuple[dict, dict]: + params = { + 'cuid': self.cuid, + 'token': self.token, + 'dev_pid': self.dev_pid, + } + + headers = { + 'Content-Type': f'audio/{file_format}; rate={rate}' + } + return params, headers + + def _send_request(self, pcm_data: bytes, params: dict, headers: dict) -> dict: + response = requests.post( + self.asr_url, + params=params, + data=pcm_data, + headers=headers, + timeout=10 # 设置超时时间 + ) + response.raise_for_status() # 检查HTTP错误 + if response.json().get("result", None) is None: + raise RuntimeError("语音识别失败,结果为空!") + return "".join(response.json().get("result", None)) + + async def speech_to_text(self, opus_data: list[bytes], session_id: str) -> list[str | None, str | None]: + """将语音数据转换为文本""" + if not opus_data: + logger.bind(tag=TAG).warn("音频数据为空!") + return None, None + + try: + # 将Opus音频数据解码为PCM + pcm_data = self.decode_opus(opus_data) + params, headers = self._build_request_body() + + # 发送请求 + start_time = time.time() + result = self._send_request(pcm_data, params, headers) + + if result: + logger.bind(tag=TAG).debug(f"aistudio 语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}") + + # TODO: 可能需要处理异常结果 + return result, None + + except Exception as e: + logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True) + return None, None diff --git a/main/xiaozhi-server/core/providers/llm/aistudio/aistudio.py b/main/xiaozhi-server/core/providers/llm/aistudio/aistudio.py new file mode 100644 index 000000000..f95b1bd57 --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/aistudio/aistudio.py @@ -0,0 +1,75 @@ +from config.logger import setup_logging +import requests +import json +from core.providers.llm.base import LLMProviderBase + +TAG = __name__ +logger = setup_logging() + +class LLMProvider(LLMProviderBase): + def __init__(self, config): + self.app_id = config.get("app_id") + self.secret_key = config.get("secret_key") + self.base_url = config.get("base_url") + + if not self.app_id or not self.secret_key: + # logger.bind(tag=TAG).error("Missing app_id or secret_key in config") + raise ValueError("app_id and secret_key are required for Wenxin LLM") + + def _construct_payload(self, session_id, dialogue): + last_message = dialogue[-1]["content"] if dialogue else "" + return { + "message": { + "content": { + "type": "text", + "value": {"showText": last_message} + } + }, + "source": self.app_id, + "from": "openapi", + "openId": session_id + } + + def response(self, session_id, dialogue): + try: + url = f"{self.base_url}?appId={self.app_id}&secretKey={self.secret_key}" + headers = {"Content-Type": "application/json"} + payload = self._construct_payload(session_id, dialogue) + + response = requests.post(url, headers=headers, json=payload, stream=True, timeout=60) + response.raise_for_status() + + buffer = "" + for chunk in response.iter_content(chunk_size=1024): + buffer += chunk.decode('utf-8') + while '\n\n' in buffer: + event_part, _, buffer = buffer.partition('\n\n') + for line in event_part.split('\n'): + if line.startswith('data:'): + data = json.loads(line[len('data:'):].strip()) + if data.get("status") != 0 or data.get("data") is None: + # logger.bind(tag=TAG).error(f"API error: {data.get('message')}") + continue + + message = data["data"].get("message", {}) + contents = message.get("content", []) + for content in contents: + if not content["isFinished"] and content.get("data"): + text = content["data"].get("text", "") + if text.strip(): + yield text + + except requests.exceptions.RequestException as e: + logger.bind(tag=TAG).error(f"Request failed: {str(e)}") + yield "【网络请求异常,请稍后重试】" + except json.JSONDecodeError as e: + logger.bind(tag=TAG).error(f"JSON decode error: {str(e)}") + yield "【服务响应解析错误】" + except Exception as e: + logger.bind(tag=TAG).error(f"Unexpected error: {str(e)}") + yield "【文心服务响应异常】" + + def response_with_functions(self, session_id, dialogue, functions=None): + logger.bind(tag=TAG).warning("Function calling not supported by Wenxin LLM") + for chunk in self.response(session_id, dialogue): + yield {"type": "content", "content": chunk} \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/aistudio.py b/main/xiaozhi-server/core/providers/tts/aistudio.py new file mode 100644 index 000000000..fab0044e9 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/aistudio.py @@ -0,0 +1,88 @@ +from functools import lru_cache +import os +import uuid +import json +import base64 +import requests +from datetime import datetime +from core.providers.tts.base import TTSProviderBase +from urllib.parse import quote +import wave + +@lru_cache +def gen_text_auto(text: str, tts_url: str, access_token: str, **kwargs) -> bytes: + default_params = { + "tex": text, + "tok": access_token, + "cuid": "yvON5IRqAdXhh6IFtZ5QF1nxbi4bv32Y", # 默认 CUID + "ctp": 1, # 客户端类型 + "lan": "zh", # 语言类型,中文 + "spd": 5, # 语速 + "pit": 5, # 音调 + "vol": 5, # 音量 + "per": 1, # 发音人 + "aue": 6 # 音频编码格式 wav + } + # 更新默认参数 + default_params.update(kwargs) + + # 特殊处理tex参数,需要进行两次URL编码 + # 先对tex参数进行一次URL编码(httpx会自动进行第二次编码) + default_params["tex"] = quote(default_params["tex"]) + + # 发送 POST 请求 + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Accept': '*/*' + } + response = requests.post(tts_url, headers=headers, data=default_params) + response.raise_for_status() # 检查HTTP错误 + return response.content # 返回音频内容 + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.tts_url = "https://tsn.baidu.com/text2audio" + self.token_url = "https://aip.baidubce.com/oauth/2.0/token" + self.access_token = self.get_access_token(config.get("api_key"), config.get("secret_key")) + + def get_access_token(self, api_key: str, secret_key: str) -> str | None: + """ + 使用 AK,SK 生成鉴权签名(Access Token) + :return: access_token,或是 None(如果错误) + """ + params = { + "grant_type": "client_credentials", + "client_id": api_key, + "client_secret": secret_key + } + try: + response = requests.post(self.token_url, params=params, timeout=10) + response.raise_for_status() # 检查HTTP错误 + token_response = response.json() # 直接解析为JSON字典 + return token_response.get("access_token") + except requests.RequestException as e: + print("Failed to get access token:", e) + return None + + def generate_filename(self, extension=".wav"): + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") + + async def text_to_speak(self, text, output_file): + if not text: + raise ValueError("Text cannot be empty") + if not self.access_token: + raise ValueError("Access token is not available") + + try: + resp = gen_text_auto(text, self.tts_url, self.access_token) + if resp is not None and len(resp) > 0: + with wave.open(output_file, 'wb') as wf: + wf.setnchannels(1) # Mono + wf.setsampwidth(2) # 16-bit PCM + wf.setframerate(16000) # rate + wf.writeframes(resp) + else: + raise Exception(f"{__name__} response is empty or invalid") + except Exception as e: + raise Exception(f"{__name__} error: {e}") diff --git a/main/xiaozhi-server/core/utils/IoT_status.py b/main/xiaozhi-server/core/utils/IoT_status.py new file mode 100644 index 000000000..89ae6ead4 --- /dev/null +++ b/main/xiaozhi-server/core/utils/IoT_status.py @@ -0,0 +1,8 @@ +import requests + +def get_IoT_status() -> str: + """从 IoT 获取, 并生成提示词""" + + # request + + return "湿度 100% 温度 25°C 亮度 1000lx 二氧化碳 1000ppm" diff --git a/main/xiaozhi-server/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py index d4e66bb65..098684f5d 100644 --- a/main/xiaozhi-server/core/utils/dialogue.py +++ b/main/xiaozhi-server/core/utils/dialogue.py @@ -18,6 +18,15 @@ class Dialogue: # 获取当前时间 self.current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + def pop_top(self): + """删除对话的顶部消息""" + if len(self.dialogue) > 0: + self.dialogue.pop(0) + + def put_top(self, message: Message): + """将消息放在对话的顶部""" + self.dialogue.insert(0, message) + def put(self, message: Message): self.dialogue.append(message)