feat: support aistudio asr and support aistudio llm

This commit is contained in:
gouzi 2025-04-07 23:16:34 +08:00
parent a6507954a7
commit 0c74043d3d
6 changed files with 241 additions and 4 deletions

View file

@ -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:

View file

@ -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(

View file

@ -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

View file

@ -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}

View file

@ -0,0 +1,8 @@
import requests
def get_IoT_status() -> str:
"""从 IoT 获取, 并生成提示词"""
# request
return "湿度 100% 温度 25°C 亮度 1000lx 二氧化碳 1000ppm"

View file

@ -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)