From 27833f918c8826cc220692b231a263d315fad691 Mon Sep 17 00:00:00 2001 From: suharvest <66322898+suharvest@users.noreply.github.com> Date: Thu, 29 Oct 2026 14:44:39 +0800 Subject: [PATCH 1/6] fix(ollama): support custom api_key and normalize base_url (closes #3517) (#3518) --- main/xiaozhi-server/core/providers/llm/ollama/ollama.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py index ba7ceef81..a6ec2608f 100644 --- a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py +++ b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py @@ -10,7 +10,10 @@ 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 = (config.get("base_url") or "http://localhost:11434").strip().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"): @@ -18,7 +21,7 @@ class LLMProvider(LLMProviderBase): 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模型 From 5f6e191d11743a9f5df2a89ee4b0f63bc82f1716 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Thu, 29 Oct 2026 16:04:20 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E8=A1=A5=E5=85=85api=5Fkey=E7=A4=BA?= =?UTF-8?q?=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/resources/db/changelog/202610291451.sql | 13 +++++++++++++ .../resources/db/changelog/db.changelog-master.yaml | 7 +++++++ main/xiaozhi-server/config.yaml | 1 + 3 files changed, 21 insertions(+) create mode 100644 main/manager-api/src/main/resources/db/changelog/202610291451.sql diff --git a/main/manager-api/src/main/resources/db/changelog/202610291451.sql b/main/manager-api/src/main/resources/db/changelog/202610291451.sql new file mode 100644 index 000000000..3f7df1644 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202610291451.sql @@ -0,0 +1,13 @@ +-- 为Ollama LLM配置补充api_key键,用于鉴权网关/Ollama Cloud场景 +-- 仅在未设置时添加占位值,不覆盖用户已有配置;本地Ollama无需鉴权,保持默认即可 +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字段定义,使管理后台新增/编辑Ollama模型时可直接填写API密钥 +-- 仅在fields中尚无api_key时更新,不覆盖其他自定义字段 +UPDATE `ai_model_provider` +SET `fields` = '[{"key":"model_name","label":"模型名称","type":"string"},{"key":"base_url","label":"服务地址","type":"string"},{"key":"api_key","label":"API密钥","type":"string"}]' +WHERE `id` = 'SYSTEM_LLM_ollama' + AND JSON_SEARCH(`fields`, 'one', 'api_key', NULL, '$[*].key') IS NULL; + diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 282fbaf48..5cb7b7257 100644 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -753,3 +753,10 @@ 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 diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 17329459a..fea254056 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -666,6 +666,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 From c282397cd23629eb8fa49420629570a73ae4140a Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Mon, 2 Nov 2026 11:09:40 +0800 Subject: [PATCH 3/6] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Dreview=E5=8F=8D?= =?UTF-8?q?=E9=A6=88=E2=80=94=E2=80=94fields=E8=BF=BD=E5=8A=A0=E5=BC=8F?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=B8=8E=E5=8D=A0=E4=BD=8D=E7=AC=A6=E5=88=A4?= =?UTF-8?q?=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/resources/db/changelog/202610291451.sql | 14 +++++++++----- main/xiaozhi-server/tests/conftest.py | 5 +++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/main/manager-api/src/main/resources/db/changelog/202610291451.sql b/main/manager-api/src/main/resources/db/changelog/202610291451.sql index 3f7df1644..fd958f605 100644 --- a/main/manager-api/src/main/resources/db/changelog/202610291451.sql +++ b/main/manager-api/src/main/resources/db/changelog/202610291451.sql @@ -1,13 +1,17 @@ --- 为Ollama LLM配置补充api_key键,用于鉴权网关/Ollama Cloud场景 --- 仅在未设置时添加占位值,不覆盖用户已有配置;本地Ollama无需鉴权,保持默认即可 +-- 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字段定义,使管理后台新增/编辑Ollama模型时可直接填写API密钥 --- 仅在fields中尚无api_key时更新,不覆盖其他自定义字段 +-- Ollama供应商追加api_key字段定义,password类型 UPDATE `ai_model_provider` -SET `fields` = '[{"key":"model_name","label":"模型名称","type":"string"},{"key":"base_url","label":"服务地址","type":"string"},{"key":"api_key","label":"API密钥","type":"string"}]' +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%'; diff --git a/main/xiaozhi-server/tests/conftest.py b/main/xiaozhi-server/tests/conftest.py index a269bb77f..f96f29ad1 100644 --- a/main/xiaozhi-server/tests/conftest.py +++ b/main/xiaozhi-server/tests/conftest.py @@ -184,7 +184,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 @@ -193,7 +194,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 From e09df59c13e7e73e14f3ac09fd15d65a6d25a29d Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Tue, 3 Nov 2026 11:53:21 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E8=B0=83=E6=95=B4=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../impl/OpenAIStyleLLMServiceImpl.java | 30 +++++++++++++++++++ .../core/providers/llm/ollama/ollama.py | 9 ++++-- .../performance_tester_llm.py | 11 +++++-- main/xiaozhi-server/tests/conftest.py | 3 ++ main/xiaozhi-server/tests/test_llm.py | 3 -- 5 files changed, 47 insertions(+), 9 deletions(-) diff --git a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java index b89ae982f..65ecbf65a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java @@ -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为空"); diff --git a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py index a6ec2608f..e6e009dea 100644 --- a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py +++ b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py @@ -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,13 +11,15 @@ logger = setup_logging() class LLMProvider(LLMProviderBase): def __init__(self, config): self.model_name = config.get("model_name") - self.base_url = (config.get("base_url") or "http://localhost:11434").strip().rstrip("/") + 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( diff --git a/main/xiaozhi-server/performance_tester/performance_tester_llm.py b/main/xiaozhi-server/performance_tester/performance_tester_llm.py index 7cb3e71f9..0b4e043ab 100644 --- a/main/xiaozhi-server/performance_tester/performance_tester_llm.py +++ b/main/xiaozhi-server/performance_tester/performance_tester_llm.py @@ -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: diff --git a/main/xiaozhi-server/tests/conftest.py b/main/xiaozhi-server/tests/conftest.py index f96f29ad1..5bf3a7f8b 100644 --- a/main/xiaozhi-server/tests/conftest.py +++ b/main/xiaozhi-server/tests/conftest.py @@ -391,6 +391,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 diff --git a/main/xiaozhi-server/tests/test_llm.py b/main/xiaozhi-server/tests/test_llm.py index 931a16f9f..88da49eff 100644 --- a/main/xiaozhi-server/tests/test_llm.py +++ b/main/xiaozhi-server/tests/test_llm.py @@ -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 未配置") From 7c5fe744105aa35d8f6b0c1ab9c70a9ed739fd7a Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Thu, 19 Nov 2026 10:32:21 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E8=B0=83=E6=95=B4=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E9=80=BB=E8=BE=91=E5=92=8C=E7=9B=B8=E5=85=B3=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../impl/OpenAIStyleLLMServiceImpl.java | 36 ++++++++++++++++--- main/xiaozhi-server/tests/test_llm.py | 18 +++++++--- 2 files changed, 44 insertions(+), 10 deletions(-) diff --git a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java index 65ecbf65a..45d79d0c0 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/llm/service/impl/OpenAIStyleLLMServiceImpl.java @@ -66,19 +66,29 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { /** * Ollama的OpenAI兼容端点位于{base_url}/v1下,与xiaozhi-server侧ollama provider逻辑保持一致: - * 剥离用户误填的完整端点后缀后,仅对不含路径的纯主机地址补/v1 + * 先去尾斜杠、再剥离用户误填的完整端点后缀,仅对不含路径的纯主机地址补/v1。 + * 空串返回null,交由上层"配置不完整"必填校验拦截 */ 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()); + if (url.isEmpty()) { + return null; } while (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } + 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.isEmpty()) { + return null; + } if (url.replaceFirst("^https?://[^/]+", "").isEmpty()) { url = url + "/v1"; } @@ -124,6 +134,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { String apiKey = configJson.getStr("api_key"); if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) { baseUrl = normalizeOllamaBaseUrl(baseUrl); + // Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致 + if (StringUtils.isBlank(apiKey)) { + apiKey = "ollama"; + } } Double temperature = configJson.getDouble("temperature"); Integer maxTokens = configJson.getInt("max_tokens"); @@ -222,6 +236,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { String apiKey = configJson.getStr("api_key"); if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) { baseUrl = normalizeOllamaBaseUrl(baseUrl); + // Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致 + if (StringUtils.isBlank(apiKey)) { + apiKey = "ollama"; + } } if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) { @@ -298,8 +316,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { String baseUrl = configJson.getStr("base_url"); String apiKey = configJson.getStr("api_key"); + // Ollama免鉴权:不要求api_key + boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type")); return baseUrl != null && !baseUrl.trim().isEmpty() && - apiKey != null && !apiKey.trim().isEmpty(); + (ollama || (apiKey != null && !apiKey.trim().isEmpty())); } catch (Exception e) { log.error("检查LLM服务可用性时发生异常:", e); return false; @@ -324,8 +344,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { String baseUrl = configJson.getStr("base_url"); String apiKey = configJson.getStr("api_key"); + // Ollama免鉴权:不要求api_key + boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type")); return baseUrl != null && !baseUrl.trim().isEmpty() && - apiKey != null && !apiKey.trim().isEmpty(); + (ollama || (apiKey != null && !apiKey.trim().isEmpty())); } catch (Exception e) { log.error("检查LLM服务可用性时发生异常,modelId: {}", modelId, e); return false; @@ -383,6 +405,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { String apiKey = configJson.getStr("api_key"); if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) { baseUrl = normalizeOllamaBaseUrl(baseUrl); + // Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致 + if (StringUtils.isBlank(apiKey)) { + apiKey = "ollama"; + } } if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) { diff --git a/main/xiaozhi-server/tests/test_llm.py b/main/xiaozhi-server/tests/test_llm.py index 88da49eff..f889198e9 100644 --- a/main/xiaozhi-server/tests/test_llm.py +++ b/main/xiaozhi-server/tests/test_llm.py @@ -11,7 +11,8 @@ Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考 特殊处理: - CozeLLM 看 bot_id / user_id 而非 api_key -- Ollama 要 model_name + 本地服务可用 +- Ollama(type=ollama)免鉴权:api_key 占位值 "ollama" 不算缺失, + 只要求 model_name 已配置;live 模式下直连本地 Ollama 服务 - placeholder 检测("你的" / "placeholder" / "xxx" / "sk-xxx") - 因为 LLM 是同步 generator,不能直接 asyncio.wait_for → 线程池 """ @@ -43,9 +44,19 @@ def _build_provider(): if not cfg: pytest.skip(f"LLM provider '{name}' 配置缺失") + ptype = get_provider_type("LLM", name) + if not ptype: + pytest.skip(f"LLM '{name}' 的 type 字段缺失") + # 任何模式下:key 是占位符 → skip。真请求需要真 key;mock 模式下 # 没有真 key 跑下去也会撞真 SDK 的网络栈(openai/edge_tts)报错。 - if name == "CozeLLM": + # Ollama 免鉴权供应器(比照 conftest._check_modules_ready 按 type 判断, + # provider 名是 OllamaLLM 而非 Ollama):api_key 占位 "ollama" 不算缺失, + # 只校验 model_name 后继续构造 provider。 + if str(cfg.get("type", "")).lower() == "ollama": + if not cfg.get("model_name"): + pytest.skip(f"LLM '{name}' 的 model_name 未配置") + elif name == "CozeLLM": if any(x in cfg.get("bot_id", "") for x in ["你的"]) or any( x in cfg.get("user_id", "") for x in ["你的"] ): @@ -59,9 +70,6 @@ def _build_provider(): "真请求模式:export RUN_LIVE_API_TESTS=1 并填真 key 后再跑。" ) - ptype = get_provider_type("LLM", name) - if not ptype: - pytest.skip(f"LLM '{name}' 的 type 字段缺失") from core.utils.llm import create_instance return create_instance(ptype, cfg) From 462b288bdae00e8eee796fc512ce8ef78abaaf12 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Thu, 19 Nov 2026 11:03:51 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E8=B0=83=E6=95=B4=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main/xiaozhi-server/tests/test_llm.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/main/xiaozhi-server/tests/test_llm.py b/main/xiaozhi-server/tests/test_llm.py index f889198e9..c049f9afa 100644 --- a/main/xiaozhi-server/tests/test_llm.py +++ b/main/xiaozhi-server/tests/test_llm.py @@ -12,7 +12,8 @@ Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考 特殊处理: - CozeLLM 看 bot_id / user_id 而非 api_key - Ollama(type=ollama)免鉴权:api_key 占位值 "ollama" 不算缺失, - 只要求 model_name 已配置;live 模式下直连本地 Ollama 服务 + 只要求 model_name 已配置;mock 模式无本地服务桩直接 skip, + live 模式下直连本地 Ollama 服务 - placeholder 检测("你的" / "placeholder" / "xxx" / "sk-xxx") - 因为 LLM 是同步 generator,不能直接 asyncio.wait_for → 线程池 """ @@ -52,10 +53,17 @@ def _build_provider(): # 没有真 key 跑下去也会撞真 SDK 的网络栈(openai/edge_tts)报错。 # Ollama 免鉴权供应器(比照 conftest._check_modules_ready 按 type 判断, # provider 名是 OllamaLLM 而非 Ollama):api_key 占位 "ollama" 不算缺失, - # 只校验 model_name 后继续构造 provider。 + # 只校验 model_name。 if str(cfg.get("type", "")).lower() == "ollama": if not cfg.get("model_name"): pytest.skip(f"LLM '{name}' 的 model_name 未配置") + if not LIVE_API_TESTS: + # mock 层没有本地 Ollama / openai 响应桩(httpx 网络桩只会抛 + # ConnectError),链路测试放行只会 fail —— 仅 live 模式运行。 + pytest.skip( + "ollama 链路测试仅 live 模式运行(mock 层无本地 Ollama 响应桩)。" + "真请求模式:export RUN_LIVE_API_TESTS=1 并确保本地 Ollama 可用。" + ) elif name == "CozeLLM": if any(x in cfg.get("bot_id", "") for x in ["你的"]) or any( x in cfg.get("user_id", "") for x in ["你的"]