diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 064f6afab..296821e3d 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -173,6 +173,12 @@ Memory: type: mem_local_short ASR: + AistudioASR: + type: aistudio + scope: audio_voice_assistant_get + dev_pid: 1536 + api_key: 你的星河社区账户令牌 + secret_key: 你的星河社区账户令牌 FunASR: type: fun_local model_dir: models/SenseVoiceSmall @@ -321,10 +327,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: 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..869e4792c --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/aistudio.py @@ -0,0 +1,131 @@ +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.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") -> tuple[dict, dict]: + params = { + 'cuid': self.cuid, + 'token': self.token, + 'dev_pid': self.dev_pid, + } + + headers = { + 'Content-Type': f'audio/{file_format}; rate={self.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错误 + return response.json() + + 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/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)