mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
新增openai_edge_tts的支持,修复ollama对话错误的问题
This commit is contained in:
parent
b94842c312
commit
5401f3fe04
4 changed files with 85 additions and 31 deletions
11
config.yaml
11
config.yaml
|
|
@ -126,7 +126,7 @@ LLM:
|
|||
# 定义LLM API类型
|
||||
type: ollama
|
||||
model_name: qwen2.5 # 使用的模型名称,需要预先使用ollama pull下载
|
||||
base_url: http://localhost:11434 # Ollama服务地址
|
||||
base_url: http://localhost:11434/v1 # Ollama服务地址
|
||||
DifyLLM:
|
||||
# 定义LLM API类型
|
||||
type: dify
|
||||
|
|
@ -306,6 +306,15 @@ TTS:
|
|||
# speech_rate: 0
|
||||
# pitch_rate: 0
|
||||
|
||||
OpenAIEdgeTTS:
|
||||
# edge-tts的OpenAI格式版本可自行搭建在本地或远程服务器上
|
||||
# https://github.com/travisvn/openai-edge-tts
|
||||
type: openai_edge_tts
|
||||
output_file: tmp/
|
||||
voice: zh-CN-XiaoxiaoNeural
|
||||
host: 127.0.0.1:5050
|
||||
apikey: apikey
|
||||
|
||||
# 模块测试配置
|
||||
module_test:
|
||||
test_sentences: # 自定义测试语句
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
from config.logger import setup_logging
|
||||
import requests, json
|
||||
import openai
|
||||
from core.providers.llm.base import LLMProviderBase
|
||||
|
||||
TAG = __name__
|
||||
|
|
@ -10,37 +10,36 @@ class LLMProvider(LLMProviderBase):
|
|||
def __init__(self, config):
|
||||
|
||||
self.model_name = config.get("model_name")
|
||||
self.base_url = config.get("base_url", "http://localhost:11434")
|
||||
self.base_url = config.get("base_url", "http://127.0.0.1:11434/v1")
|
||||
|
||||
self.client = openai.OpenAI(api_key="ollama", base_url=self.base_url)
|
||||
|
||||
def response(self, session_id, dialogue):
|
||||
try:
|
||||
# Convert dialogue format to Ollama format
|
||||
prompt = ""
|
||||
for msg in dialogue:
|
||||
if msg["role"] == "system":
|
||||
prompt += f"System: {msg['content']}\n"
|
||||
elif msg["role"] == "user":
|
||||
prompt += f"User: {msg['content']}\n"
|
||||
elif msg["role"] == "assistant":
|
||||
prompt += f"Assistant: {msg['content']}\n"
|
||||
|
||||
# Make request to Ollama API
|
||||
response = requests.post(
|
||||
f"{self.base_url}/api/generate",
|
||||
json={
|
||||
"model": self.model_name,
|
||||
"prompt": prompt,
|
||||
"stream": True
|
||||
},
|
||||
responses = self.client.chat.completions.create(
|
||||
model=self.model_name,
|
||||
messages=dialogue,
|
||||
stream=True
|
||||
)
|
||||
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
json_response = json.loads(line)
|
||||
if "response" in json_response:
|
||||
yield json_response["response"]
|
||||
is_active = True
|
||||
for chunk in responses:
|
||||
try:
|
||||
# 检查是否存在有效的choice且content不为空
|
||||
delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None
|
||||
content = delta.content if hasattr(delta, 'content') else ''
|
||||
except IndexError:
|
||||
content = ''
|
||||
if content:
|
||||
# 处理标签跨多个chunk的情况
|
||||
if '<think>' in content:
|
||||
is_active = False
|
||||
content = content.split('<think>')[0]
|
||||
if '</think>' in content:
|
||||
is_active = True
|
||||
content = content.split('</think>')[-1]
|
||||
if is_active:
|
||||
yield content
|
||||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
|
||||
yield "【Ollama服务响应异常】"
|
||||
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
|
||||
45
core/providers/tts/openai_edge_tts.py
Normal file
45
core/providers/tts/openai_edge_tts.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import os
|
||||
import uuid
|
||||
import json
|
||||
import emoji
|
||||
import requests
|
||||
from datetime import datetime
|
||||
from core.providers.tts.base import TTSProviderBase
|
||||
|
||||
class TTSProvider(TTSProviderBase):
|
||||
def __init__(self, config, delete_audio_file):
|
||||
super().__init__(config, delete_audio_file)
|
||||
|
||||
self.host = config.get("host")
|
||||
self.apikey = config.get("apikey")
|
||||
self.voice = config.get("voice", "zh-CN-XiaoxiaoNeural")
|
||||
self.api_url = f"http://{self.host}/v1/audio/speech"
|
||||
self.header = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.apikey}"
|
||||
}
|
||||
|
||||
def clean_emojis(self, text):
|
||||
return emoji.replace_emoji(text, '')
|
||||
|
||||
def generate_filename(self, extension=".mp3"):
|
||||
return os.path.join(self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||
|
||||
async def text_to_speak(self, text, output_file):
|
||||
request_json = {
|
||||
"input": self.clean_emojis(text),
|
||||
"voice": self.voice
|
||||
}
|
||||
|
||||
print(self.api_url, json.dumps(request_json, ensure_ascii=False))
|
||||
try:
|
||||
resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header)
|
||||
# 检查返回请求数据的mime类型是否是audio/***,是则保存到指定路径下;返回的是binary格式的
|
||||
if resp.headers['Content-Type'].startswith('audio/'):
|
||||
with open(output_file, 'wb') as f:
|
||||
f.write(resp.content)
|
||||
return output_file
|
||||
else:
|
||||
raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}")
|
||||
except Exception as e:
|
||||
raise Exception(f"{__name__} error: {e}")
|
||||
|
|
@ -17,3 +17,4 @@ ormsgpack==1.7.0
|
|||
ruamel.yaml==0.18.10
|
||||
loguru==0.7.3
|
||||
requests==2.32.3
|
||||
emoji==2.14.1
|
||||
Loading…
Reference in a new issue