Compare commits

...

8 commits

Author SHA1 Message Date
Sakura-RanChen
6abf90db5f
Merge e09df59c13 into 2dfaf44269 2026-11-14 11:13:15 +08:00
wengzh
2dfaf44269
Merge pull request #3559 from xinnan-tech/py-tts-session
Some checks failed
Tests / Java (manager-api) (push) Failing after 41s
Tests / Vue (manager-web) (push) Successful in 11m51s
Tests / Python (xiaozhi-server) (push) Successful in 13m37s
fix(tts): 流式 TTS 会话延迟到首个有效文本开启,修复慢 LLM 场景合成结果为空
2026-11-13 16:13:40 +08:00
Sakura-RanChen
e41bc98a25 fix(tts): 流式 TTS 会话延迟到首个有效文本开启,修复慢 LLM 场景合成结果为空 2026-11-13 10:10:20 +08:00
Sakura-RanChen
e09df59c13 调整相关逻辑 2026-11-03 11:53:21 +08:00
Sakura-RanChen
7f0d416e66
Merge branch 'main' into py-test-ollama 2026-11-02 11:12:49 +08:00
Sakura-RanChen
c282397cd2 fix: 修复review反馈——fields追加式更新与占位符判定 2026-11-02 11:09:40 +08:00
Sakura-RanChen
5f6e191d11 补充api_key示例 2026-10-29 16:04:20 +08:00
suharvest
27833f918c
fix(ollama): support custom api_key and normalize base_url (closes #3517) (#3518) 2026-10-29 14:44:39 +08:00
13 changed files with 260 additions and 120 deletions

View file

@ -64,6 +64,27 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
private static final String DEFAULT_TITLE_PROMPT = "请根据以下对话内容,生成一个简洁的会话标题(约15字以内),只返回标题,不要包含任何解释或标点符号:\n{conversation}";
/**
* Ollama的OpenAI兼容端点位于{base_url}/v1下,与xiaozhi-server侧ollama provider逻辑保持一致:
* 剥离用户误填的完整端点后缀后,仅对不含路径的纯主机地址补/v1
*/
private static String normalizeOllamaBaseUrl(String baseUrl) {
if (baseUrl == null) {
return null;
}
String url = baseUrl.trim();
if (url.endsWith("/chat/completions")) {
url = url.substring(0, url.length() - "/chat/completions".length());
}
while (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
if (url.replaceFirst("^https?://[^/]+", "").isEmpty()) {
url = url + "/v1";
}
return url;
}
@Override
public String generateSummary(String conversation) {
return generateSummary(conversation, null, null);
@ -101,6 +122,9 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url");
String model = configJson.getStr("model_name");
String apiKey = configJson.getStr("api_key");
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
baseUrl = normalizeOllamaBaseUrl(baseUrl);
}
Double temperature = configJson.getDouble("temperature");
Integer maxTokens = configJson.getInt("max_tokens");
@ -196,6 +220,9 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url");
String model = configJson.getStr("model_name");
String apiKey = configJson.getStr("api_key");
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
baseUrl = normalizeOllamaBaseUrl(baseUrl);
}
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
log.error("LLM配置不完整,baseUrl或apiKey为空");
@ -354,6 +381,9 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url");
String model = configJson.getStr("model_name");
String apiKey = configJson.getStr("api_key");
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
baseUrl = normalizeOllamaBaseUrl(baseUrl);
}
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
log.error("LLM配置不完整,baseUrl或apiKey为空");

View file

@ -0,0 +1,17 @@
-- Ollama LLM配置补充api_key占位值,走鉴权网关/Ollama Cloud时使用
UPDATE `ai_model_config`
SET `config_json` = JSON_SET(`config_json`, '$.api_key', 'ollama')
WHERE `id` = 'LLM_OllamaLLM' AND JSON_EXTRACT(`config_json`, '$.api_key') IS NULL;
-- Ollama供应商追加api_key字段定义,password类型
UPDATE `ai_model_provider`
SET `fields` = JSON_ARRAY_APPEND(COALESCE(`fields`, JSON_ARRAY()), '$',
JSON_OBJECT('key', 'api_key', 'label', 'API密钥', 'type', 'password'))
WHERE `id` = 'SYSTEM_LLM_ollama'
AND JSON_SEARCH(`fields`, 'one', 'api_key', NULL, '$[*].key') IS NULL;
-- 配置说明补充api_key条目
UPDATE `ai_model_config`
SET `remark` = CONCAT(`remark`, '\n4. 走鉴权网关或使用Ollama Cloud时,需填写api_key')
WHERE `id` = 'LLM_OllamaLLM'
AND `remark` IS NOT NULL AND `remark` NOT LIKE '%api_key%';

View file

@ -753,6 +753,13 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202609172100.sql
- changeSet:
id: 202610291451
author: RanChen
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202610291451.sql
- changeSet:
id: 202610302051
author: shinjiyu

View file

@ -667,6 +667,7 @@ LLM:
type: ollama
model_name: qwen2.5 # 使用的模型名称,需要预先使用ollama pull下载
base_url: http://localhost:11434 # Ollama服务地址
api_key: ollama # 本地部署无需真实密钥,占位即可;走鉴权网关或Ollama Cloud时修改为真实key
DifyLLM:
# 定义LLM API类型
type: dify

View file

@ -1,5 +1,6 @@
from config.logger import setup_logging
from openai import OpenAI
from urllib.parse import urlsplit
import json
from core.providers.llm.base import LLMProviderBase
@ -10,15 +11,20 @@ logger = setup_logging()
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 = (
str(config.get("base_url") or "").strip() or "http://localhost:11434"
).rstrip("/")
# 兼容处理用户输入完整端点的情况
if self.base_url.endswith("/chat/completions"):
self.base_url = self.base_url[:-len("/chat/completions")].rstrip("/")
# Initialize OpenAI client with Ollama base URL
# 如果没有v1,增加v1
if not self.base_url.endswith("/v1"):
# 纯主机地址补/v1(Ollama默认约定);带路径的地址尊重用户输入,不再改写
if not urlsplit(self.base_url).path.strip("/"):
self.base_url = f"{self.base_url}/v1"
self.client = OpenAI(
base_url=self.base_url,
api_key="ollama", # Ollama doesn't need an API key but OpenAI client requires one
api_key=config.get("api_key") or "ollama",
)
# 检查是否是qwen3模型

View file

@ -74,7 +74,11 @@ class TTSProvider(TTSProviderBase):
"""确保WebSocket连接可用,支持60秒内连接复用"""
try:
current_time = time.time()
if self.ws and current_time - self.last_active_time < 60:
if (
self.ws
and self.ws.close_code is None
and current_time - self.last_active_time < 60
):
# 一分钟内才可以复用链接进行连续对话
logger.bind(tag=TAG).debug(f"使用已有链接...")
return self.ws
@ -110,10 +114,11 @@ class TTSProvider(TTSProviderBase):
if self.conn.client_abort:
try:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
if self.activate_session:
asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
continue
except Exception as e:
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
@ -132,21 +137,27 @@ class TTSProvider(TTSProviderBase):
self.reset_stream_state()
# 初始化会话
try:
if not getattr(self.conn, "sentence_id", None):
if not getattr(self.conn, "sentence_id", None):
self.conn.sentence_id = uuid.uuid4().hex
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
logger.bind(tag=TAG).debug("开始启动TTS会话...")
# 只建连,会话等文本到达再开启
logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...")
if self.activate_session:
future = asyncio.run_coroutine_threadsafe(
self.close(),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
future = asyncio.run_coroutine_threadsafe(
self.start_session(self.conn.sentence_id),
self._ensure_connection(),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
self.before_stop_play_files.clear()
logger.bind(tag=TAG).debug("TTS会话启动成功")
logger.bind(tag=TAG).debug("TTS连接准备完成")
except Exception as e:
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
continue
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
elif ContentType.TEXT == message.content_type:
if message.content_detail:
@ -174,6 +185,17 @@ class TTSProvider(TTSProviderBase):
if message.sentence_type == SentenceType.LAST:
try:
logger.bind(tag=TAG).debug("开始结束TTS会话...")
# 句尾替换词滑窗残留补发
if self._pending_prefix:
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(self._pending_prefix, None),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
if not self.activate_session:
# 本轮无文本,未开启会话,直接收尾
self._process_before_stop_play_files()
continue
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
@ -194,20 +216,23 @@ class TTSProvider(TTSProviderBase):
async def text_to_speak(self, text, _):
"""发送文本到TTS服务进行合成"""
try:
if self.ws is None:
logger.bind(tag=TAG).warning("WebSocket连接不存在,终止发送文本")
return
# 过滤Markdown
filtered_text = MarkdownCleaner.clean_markdown(text)
if filtered_text:
# 使用滑动窗口匹配处理跨分片的替换词
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
confirmed_texts = [txt for txt in confirmed_texts if txt]
if not confirmed_texts:
return
# 有文本时才开启会话
if not self.activate_session:
await self.start_session(self.conn.sentence_id)
# 发送每个确定的文本片段
for txt in confirmed_texts:
if txt and self.ws:
if self.ws:
continue_task_message = {
"header": {
"action": "continue-task",
@ -237,9 +262,6 @@ class TTSProvider(TTSProviderBase):
if self.activate_session:
await self.close()
# 设置会话激活标志
self.activate_session = True
# 确保连接可用
await self._ensure_connection()
@ -248,6 +270,9 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).debug("启动监听任务...")
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
self.activate_session = True
# 发送run-task消息启动会话
run_task_message = {
"header": {
@ -350,9 +375,6 @@ class TTSProvider(TTSProviderBase):
# 只处理当前活跃会话的响应
if task_id and self.conn.sentence_id != task_id:
if event in ["task-finished", "task-failed"]:
logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~")
self.activate_session = False
continue
if event == "task-started":
@ -376,6 +398,7 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).error(
f"TTS任务失败: {error_code} - {error_message}"
)
self.activate_session = False
break
except json.JSONDecodeError:
logger.bind(tag=TAG).warning("收到无效的JSON消息")
@ -392,16 +415,14 @@ class TTSProvider(TTSProviderBase):
)
break
# 连接异常时关闭WebSocket
# 监听任务退出时关闭连接并清理引用
finally:
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
# 监听任务退出时清理引用
finally:
self.activate_session = False
self._monitor_task = None
def audio_to_opus_data_stream(

View file

@ -186,7 +186,11 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...")
self._refresh_token()
current_time = time.time()
if self.ws and current_time - self.last_active_time < 10:
if (
self.ws
and self.ws.close_code is None
and current_time - self.last_active_time < 10
):
# 10秒内才可以复用链接进行连续对话
self.task_id = uuid.uuid4().hex
logger.bind(tag=TAG).debug(f"使用已有链接..., task_id: {self.task_id}")
@ -220,12 +224,17 @@ class TTSProvider(TTSProviderBase):
message = self.tts_text_queue.get(timeout=1)
if self.conn.client_abort:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
continue
try:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
if self.activate_session:
asyncio.run_coroutine_threadsafe(
self.finish_session(self.task_id),
loop=self.conn.loop,
)
continue
except Exception as e:
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
continue
# 过滤旧消息:检查sentence_id是否匹配
if message.sentence_id != self.conn.sentence_id:
@ -240,18 +249,24 @@ class TTSProvider(TTSProviderBase):
self.reset_stream_state()
# 初始化参数
try:
logger.bind(tag=TAG).debug("开始启动TTS会话...")
# 只建连,会话等文本到达再开启
logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...")
if self.activate_session:
future = asyncio.run_coroutine_threadsafe(
self.close(),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
future = asyncio.run_coroutine_threadsafe(
self.start_session(self.task_id),
self._ensure_connection(),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
self.before_stop_play_files.clear()
logger.bind(tag=TAG).debug("TTS会话启动成功")
logger.bind(tag=TAG).debug("TTS连接准备完成")
except Exception as e:
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
continue
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
elif ContentType.TEXT == message.content_type:
if message.content_detail:
@ -278,6 +293,17 @@ class TTSProvider(TTSProviderBase):
if message.sentence_type == SentenceType.LAST:
try:
logger.bind(tag=TAG).debug("开始结束TTS会话...")
# 句尾替换词滑窗残留补发
if self._pending_prefix:
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(self._pending_prefix, None),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
if not self.activate_session:
# 本轮无文本,未开启会话,直接收尾
self._process_before_stop_play_files()
continue
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.task_id),
loop=self.conn.loop,
@ -296,18 +322,22 @@ class TTSProvider(TTSProviderBase):
async def text_to_speak(self, text, _):
try:
if self.ws is None:
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
return
filtered_text = MarkdownCleaner.clean_markdown(text)
if filtered_text:
# 使用滑动窗口匹配处理跨分片的替换词
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
confirmed_texts = [txt for txt in confirmed_texts if txt]
if not confirmed_texts:
return
# 有文本时才开启会话
if not self.activate_session:
await self.start_session(self.task_id)
# 发送每个确定的文本片段
for txt in confirmed_texts:
if txt and self.ws:
if self.ws:
run_request = {
"header": {
"message_id": uuid.uuid4().hex,
@ -339,9 +369,6 @@ class TTSProvider(TTSProviderBase):
if self.activate_session:
await self.close()
# 设置会话激活标志
self.activate_session = True
# 建立新连接
await self._ensure_connection()
@ -350,6 +377,9 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).debug("启动监听任务...")
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
self.activate_session = True
start_request = {
"header": {
"message_id": uuid.uuid4().hex,
@ -431,9 +461,6 @@ class TTSProvider(TTSProviderBase):
# 只处理当前活跃会话的响应
if task_id and self.task_id != task_id:
if event_name in ["SynthesisCompleted", "TaskFailed"]:
logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~")
self.activate_session = False
continue
if event_name == "SynthesisStarted":
@ -469,16 +496,15 @@ class TTSProvider(TTSProviderBase):
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
)
break
# 连接异常时关闭WebSocket
# 监听任务退出时关闭连接并清理引用
finally:
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
# 监听任务退出时清理引用
finally:
self.activate_session = False
self._monitor_task = None
def audio_to_opus_data_stream(

View file

@ -704,3 +704,6 @@ class TTSProviderBase(ABC):
def reset_stream_state(self):
"""重置流式处理状态,用于会话开始时清理残留状态"""
self._pending_prefix = ""
# 清理编码器中未满一帧的PCM残留
if getattr(self, "opus_encoder", None):
self.opus_encoder.reset_state()

View file

@ -220,7 +220,7 @@ class TTSProvider(TTSProviderBase):
async def _ensure_connection(self):
"""建立新的WebSocket连接,并启动监听任务(仅第一次)"""
try:
if self.ws:
if self.ws and self.ws.close_code is None:
if self.enable_ws_reuse:
logger.bind(tag=TAG).debug(f"使用已有链接...")
return self.ws
@ -281,12 +281,12 @@ class TTSProvider(TTSProviderBase):
if self.conn.client_abort:
try:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
if self.enable_ws_reuse:
if self.activate_session:
asyncio.run_coroutine_threadsafe(
self.cancel_session(self.conn.sentence_id),
loop=self.conn.loop,
)
else:
if not self.enable_ws_reuse:
asyncio.run_coroutine_threadsafe(
self.finish_connection(),
loop=self.conn.loop,
@ -307,26 +307,29 @@ class TTSProvider(TTSProviderBase):
if message.sentence_type == SentenceType.FIRST:
# 重置流式处理状态
self.reset_stream_state()
# 重置 opus 流式编码器跨轮残留
if hasattr(self, "opus_encoder") and self.opus_encoder:
self.opus_encoder.reset_state()
# 初始化参数
try:
if not getattr(self.conn, "sentence_id", None):
if not getattr(self.conn, "sentence_id", None):
self.conn.sentence_id = uuid.uuid4().hex
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
logger.bind(tag=TAG).debug("开始启动TTS会话...")
# 只建连,会话等文本到达再开启
logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...")
if self.activate_session:
future = asyncio.run_coroutine_threadsafe(
self.close(),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
future = asyncio.run_coroutine_threadsafe(
self.start_session(self.conn.sentence_id),
self._ensure_connection(),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
self.before_stop_play_files.clear()
logger.bind(tag=TAG).debug("TTS会话启动成功")
logger.bind(tag=TAG).debug("TTS连接准备完成")
except Exception as e:
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
continue
logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}")
elif ContentType.TEXT == message.content_type:
if message.content_detail:
@ -353,11 +356,29 @@ class TTSProvider(TTSProviderBase):
if message.sentence_type == SentenceType.LAST:
try:
logger.bind(tag=TAG).debug("开始结束TTS会话...")
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
# 句尾替换词滑窗残留补发
if self._pending_prefix:
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(self._pending_prefix, None),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
if self.activate_session:
# 结束会话;LAST 与连接释放由监听任务在 SessionFinished 后处理
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
else:
# 未开启会话,没有 SessionFinished 事件,需自行收尾
self._process_before_stop_play_files()
if not self.enable_ws_reuse:
future = asyncio.run_coroutine_threadsafe(
self.finish_connection(),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
except Exception as e:
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
continue
@ -373,21 +394,23 @@ class TTSProvider(TTSProviderBase):
async def text_to_speak(self, text, _):
"""发送文本到TTS服务"""
try:
# 建立新连接
if self.ws is None:
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
return
# 过滤Markdown
filtered_text = MarkdownCleaner.clean_markdown(text)
if filtered_text:
# 使用滑动窗口匹配处理跨分片的替换词
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
confirmed_texts = [txt for txt in confirmed_texts if txt]
if not confirmed_texts:
return
# 有文本时才开启会话
if not self.activate_session:
await self.start_session(self.conn.sentence_id)
# 发送每个确定的文本片段
for txt in confirmed_texts:
if txt and self.ws:
if self.ws:
await self.send_text(self.voice, txt, self.conn.sentence_id)
return
@ -407,12 +430,11 @@ class TTSProvider(TTSProviderBase):
# 上个会话处于激活状态时关闭上个连接新建链接
if self.activate_session:
await self.close()
# 设置会话激活标志
self.activate_session = True
# 确保连接建立
await self._ensure_connection()
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
self.activate_session = True
header = Header(
message_type=FULL_CLIENT_REQUEST,
@ -437,9 +459,6 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}")
try:
if self.ws:
# 句尾替换词滑动窗口残留先发出去
if self._pending_prefix:
await self.text_to_speak(self._pending_prefix, None)
header = Header(
message_type=FULL_CLIENT_REQUEST,
message_type_specific_flags=MsgTypeFlagWithEvent,

View file

@ -127,7 +127,7 @@ class TTSProvider(TTSProviderBase):
raise ValueError("讯飞TTS需要配置app_id、api_key和api_secret")
async def _ensure_connection(self):
"""确保WebSocket连接可用"""
"""建立新的WebSocket连接"""
try:
logger.bind(tag=TAG).debug("开始建立新连接...")
@ -176,24 +176,14 @@ class TTSProvider(TTSProviderBase):
self.text_seq += 1
if message.sentence_type == SentenceType.FIRST:
# 初始化参数
# 初始化参数,连接在文本到达时建立
try:
if not getattr(self.conn, "sentence_id", None):
self.conn.sentence_id = uuid.uuid4().hex
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
logger.bind(tag=TAG).debug("开始启动TTS会话...")
future = asyncio.run_coroutine_threadsafe(
self.start_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
self.before_stop_play_files.clear()
logger.bind(tag=TAG).debug("TTS会话启动成功")
except Exception as e:
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
continue
logger.bind(tag=TAG).error(f"准备TTS状态失败: {str(e)}")
# 处理文本内容
if ContentType.TEXT == message.content_type:
@ -224,6 +214,17 @@ class TTSProvider(TTSProviderBase):
if message.sentence_type == SentenceType.LAST:
try:
logger.bind(tag=TAG).debug("开始结束TTS会话...")
# 句尾替换词滑窗残留补发
if self._pending_prefix:
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(self._pending_prefix, None),
loop=self.conn.loop,
)
future.result(timeout=self.tts_timeout)
if not self.activate_session:
# 本轮无文本,未开启会话,直接收尾
self._process_before_stop_play_files()
continue
asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
@ -242,19 +243,22 @@ class TTSProvider(TTSProviderBase):
async def text_to_speak(self, text, _):
"""发送文本到TTS服务进行合成"""
try:
if self.ws is None:
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
return
filtered_text = MarkdownCleaner.clean_markdown(text)
if filtered_text:
# 使用滑动窗口匹配处理跨分片的替换词
confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text)
confirmed_texts = [txt for txt in confirmed_texts if txt]
if not confirmed_texts:
return
# 有文本时才开启会话
if not self.activate_session:
await self.start_session(self.conn.sentence_id)
# 发送每个确定的文本片段
for txt in confirmed_texts:
if txt and self.ws:
if self.ws:
# 发送文本合成请求
run_request = self._build_base_request(status=1, text=txt)
await self.ws.send(json.dumps(run_request))
@ -277,9 +281,6 @@ class TTSProvider(TTSProviderBase):
if self.activate_session:
await self.close()
# 设置会话激活标志
self.activate_session = True
# 建立新连接
await self._ensure_connection()
@ -288,10 +289,15 @@ class TTSProvider(TTSProviderBase):
logger.bind(tag=TAG).debug("启动监听任务...")
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
# 发送会话启动请求
# 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志
self.activate_session = True
# 启动帧序号从1开始,避免与后续文本帧重复
self.text_seq = 1
start_request = self._build_base_request(status=0)
await self.ws.send(json.dumps(start_request))
self.text_seq += 1
logger.bind(tag=TAG).debug("会话启动请求已发送")
except Exception as e:
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
@ -412,16 +418,14 @@ class TTSProvider(TTSProviderBase):
)
break
# 链接不可复用
# 监听任务退出时关闭连接并清理引用
finally:
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
# 监听任务退出时清理引用
finally:
self.activate_session = False
self._monitor_task = None
def to_tts(self, text: str) -> list:

View file

@ -119,7 +119,12 @@ class LLMPerformanceTester:
return chunks, first_token_time
async def _check_ollama_service(self, base_url: str, model_name: str) -> bool:
"""异步检查 Ollama 服务状态"""
"""异步检查 Ollama 服务状态(兼容带/v1或完整端点的base_url写法)"""
base_url = base_url.strip().rstrip("/")
if base_url.endswith("/chat/completions"):
base_url = base_url[: -len("/chat/completions")].rstrip("/")
if base_url.endswith("/v1"):
base_url = base_url[: -len("/v1")].rstrip("/")
async with aiohttp.ClientSession() as session:
try:
async with session.get(f"{base_url}/api/version") as response:
@ -230,7 +235,7 @@ class LLMPerformanceTester:
"""异步测试单个 LLM 性能"""
try:
# 对于 Ollama,跳过 api_key 检查并进行特殊处理
if llm_name == "Ollama":
if llm_name == "OllamaLLM" or str(config.get("type", "")).lower() == "ollama":
base_url = config.get("base_url", "http://localhost:11434")
model_name = config.get("model_name")
if not model_name:
@ -474,7 +479,7 @@ class LLMPerformanceTester:
continue
# 对于 Ollama,先检查服务状态
if llm_name == "Ollama":
if llm_name == "OllamaLLM" or str(config.get("type", "")).lower() == "ollama":
base_url = config.get("base_url", "http://localhost:11434")
model_name = config.get("model_name")
if not model_name:

View file

@ -203,7 +203,8 @@ def get_provider_type(module: str, provider_name: str | None = None) -> str | No
def has_real_key(config: dict, *keys: str) -> bool:
"""任一候选 key 名下值不是占位符就算有真密钥。
占位符判定:空 / "你的..." / 包含 "placeholder" / 字面 "none"。
占位符判定:空 / "你的..." / 包含 "placeholder" / 字面 "none" / "ollama"
(Ollama本地服务无需鉴权,config.yaml默认占位值即为"ollama")。
"""
if not config:
return False
@ -212,7 +213,7 @@ def has_real_key(config: dict, *keys: str) -> bool:
if val is None:
continue
s = str(val).strip().lower()
if not s or s == "none":
if not s or s == "none" or s == "ollama":
continue
if s.startswith("你的") or "placeholder" in s:
continue
@ -399,6 +400,9 @@ def _check_modules_ready() -> None:
f"{module}.{provider_name} 配置缺失(CFG 字典里没这个 provider)"
)
continue
# Ollama免鉴权供应器无需真实key,跳过占位符检查
if str(cfg.get("type", "")).lower() == "ollama":
continue
secret_keys_present = [k for k in _SECRET_FIELDS if k in cfg]
if secret_keys_present and not any(
has_real_key(cfg, k) for k in secret_keys_present

View file

@ -50,9 +50,6 @@ def _build_provider():
x in cfg.get("user_id", "") for x in ["你的"]
):
pytest.skip("LLM 'CozeLLM' 的 bot_id/user_id 未配置")
elif name == "Ollama":
if not cfg.get("model_name"):
pytest.skip("LLM 'Ollama' 的 model_name 未配置")
elif not has_real_key(cfg, "api_key"):
if LIVE_API_TESTS:
pytest.skip(f"LLM '{name}' 的 api_key 未配置")