Compare commits

...

8 commits

Author SHA1 Message Date
Sakura-RanChen
7dcb216a14
Merge e09df59c13 into cda17f4d6a 2026-11-19 09:54:15 +08:00
wengzh
cda17f4d6a
Merge pull request #3548 from zhenglieAllen/zhenglieAllen/fix/check-model-key-none
Some checks failed
Tests / Java (manager-api) (push) Failing after 16s
Tests / Vue (manager-web) (push) Successful in 2m46s
Tests / Python (xiaozhi-server) (push) Successful in 3m24s
fix(util): check_model_key 遇到空 api_key 不再抛 TypeError
2026-11-19 09:52:20 +08:00
Allen
579538478b fix(util): check_model_key 遇到空 api_key 不再抛 TypeError
现象:provider 构造期报
    TypeError: argument of type 'NoneType' is not iterable
而且栈顶落在 core/utils/util.py 的 check_model_key,看不出是哪个模块的
key 没配。智控台下发的配置里未必带 api_key 字段(本地 LLM 场景也常把
它留空),HA 插件配置没填 api_key 时同样中招:hass_state 和
hass_play_music 都调 initialize_hass_handler,整个插件初始化被打断。

原因:check_model_key 直接写 ``"你" in modelKey``,modelKey 为 None 时
这行就炸了;modelKey 为空串时则静默返回 None,等于没检查。

改法:先把 None / 空串当成「未设置」处理,返回提示文案而不是抛异常。
    if not modelKey:
        return f"配置错误: {modelType} 的 API key 未设置"
出厂占位符的分支保持原样,提示文案里仍带当前值,方便用户对照改。

测试:
- 新增 tests/core/utils/test_check_model_key.py:缺 key / 占位符 / 真 key
  三种情况的契约
- tests/plugins_func/test_hass_init.py 补一条端到端:插件配置里没有
  api_key 时 initialize_hass_handler 不再崩
- 全量 pytest tests/ -q 无新增失败

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-11-07 22:33:44 +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
11 changed files with 143 additions and 13 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

@ -668,6 +668,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

@ -179,6 +179,14 @@ def remove_punctuation_and_length(text):
def check_model_key(modelType, modelKey):
"""检查 API key 是不是还停留在出厂占位符上。
modelKey 允许是 None / 空串:智控台下发的配置里未必带 api_key 字段
(本地 LLM 场景也常把它留空),而 ``"你" in None`` 会直接抛
TypeError,把「配置没填」这种业务错误变成了 provider 构造期的崩溃。
"""
if not modelKey:
return f"配置错误: {modelType} 的 API key 未设置"
if "你" in modelKey:
return f"配置错误: {modelType} 的 API key 未设置,当前值为: {modelKey}"
return None

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

@ -0,0 +1,38 @@
"""check_model_key 的行为约束。
背景:智控台下发的配置里未必带 api_key 字段,本地 LLM 场景也常把它留空。
原来的实现直接写 ``"你" in modelKey``,modelKey 为 None 时抛
``TypeError: argument of type 'NoneType' is not iterable``,
把「配置没填」这种业务错误变成了 provider 构造期的崩溃 ——
调用方想看到的那句「API key 未设置」根本来不及打印。
"""
import pytest
from core.utils.util import check_model_key
@pytest.mark.parametrize("model_key", [None, ""])
def test_missing_key_reports_error_instead_of_crashing(model_key):
"""key 没配(None / 空串)时返回提示文案,不能抛 TypeError。"""
msg = check_model_key("LLM", model_key)
assert msg is not None, "缺少 api_key 时应当返回提示文案"
assert "API key 未设置" in msg
def test_placeholder_key_reports_error_with_current_value():
"""出厂占位符仍按原样提示,并带上当前值,方便用户对照改。"""
msg = check_model_key("LLM", "你的api_key")
assert msg is not None
assert "API key 未设置" in msg
assert "你的api_key" in msg
def test_real_key_passes():
"""真 key 不该被拦。"""
assert check_model_key("LLM", "sk-abcdef123456") is None
def test_model_type_is_mentioned_in_the_message():
"""提示文案里要带上是哪个模块出的问题。"""
msg = check_model_key("VLLM", None)
assert "VLLM" in msg

View file

@ -6,7 +6,7 @@ can only concatenate str (not "list") to str,设备清单进不了提示词,
import pytest
import plugins_func.functions.hass_state # noqa: F401 注册 hass_state 模块,填充 module_func_map
from plugins_func.functions.hass_init import append_devices_to_prompt
from plugins_func.functions.hass_init import append_devices_to_prompt, initialize_hass_handler
HEADER = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
BASE_PROMPT = "你是小智。"
@ -82,3 +82,20 @@ def test_without_hass_functions_prompt_unchanged():
append_devices_to_prompt(conn)
assert conn.prompt == BASE_PROMPT
assert conn.dialogue.system_messages == []
def test_initialize_hass_handler_without_api_key_does_not_crash():
"""插件配置里没有 api_key 时,初始化不能以 TypeError 崩掉。
check_model_key 以前直接写 ``"你" in modelKey``,modelKey 为 None 时
抛 TypeError,HA 插件初始化(hass_state / hass_play_music 都调它)
会被整个打断。
"""
conn = FakeConn(_plugin())
conn.config["plugins"]["home_assistant"].pop("api_key")
conn.load_function_plugin = True
ha_config = initialize_hass_handler(conn)
assert ha_config["base_url"] == "http://homeassistant.local:8123"
assert ha_config["api_key"] is None

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 未配置")