Skip to content

⭐AI-driven public opinion & trend monitor with multi-platform aggregation, RSS, and smart alerts.🎯 告别信息过载,你的 AI 舆情监控助手与热点筛选工具!聚合多平台热点 + RSS 订阅,支持关键词精准筛选。AI 智能筛选新闻 + AI 翻译 + AI 分析简报直推手机,也支持接入 MCP 架构,赋能 AI 自然语言对话分析、情感洞察与趋势预测等。支持 Docker ,数据本地/云端自持。集成微信/飞书/钉钉/Telegram/邮件/ntfy/bark/slack 等渠道智能推送。

fix(ai): 接通配置中的通用额外请求参数 (#1237)

GaRY3ad65782dad1
diff --git a/config/config.en.yaml b/config/config.en.yaml
index b89a4d5126..82388840de 100644
--- a/config/config.en.yaml
+++ b/config/config.en.yaml
@@ -400,6 +400,7 @@ ai:
# Example: ["openai/gpt-4o-mini", "openai/deepseek-ai/DeepSeek-V3"]
# Extra params (usually no need to change; uncomment to enable)
+ # Passed through to LiteLLM as-is; useful for extra request params or headers
# extra_params:
# top_p: 1.0
# presence_penalty: 0.0
diff --git a/config/config.yaml b/config/config.yaml
index b743c7c76a..7225ef4fa1 100644
--- a/config/config.yaml
+++ b/config/config.yaml
@@ -401,6 +401,7 @@ ai:
# 示例: ["openai/gpt-4o-mini", "openai/deepseek-ai/DeepSeek-V3"]
# 额外参数(一般无需修改,删掉 # 号即可启用)
+ # 会原样透传给 LiteLLM,可用于补充请求参数或自定义请求头
# extra_params:
# top_p: 1.0
# presence_penalty: 0.0
diff --git a/tests/test_ai_extra_params.py b/tests/test_ai_extra_params.py
new file mode 100644
index 0000000000..965595d30c
--- /dev/null
+++ b/tests/test_ai_extra_params.py
@@ -0,0 +1,151 @@
+"""Regression coverage for configured LiteLLM parameters without API requests."""
+
+import io
+import os
+import unittest
+from contextlib import redirect_stdout
+from types import SimpleNamespace
+from unittest.mock import patch
+
+# LiteLLM may otherwise fetch its model cost map while being imported.
+with patch.dict(os.environ, {"LITELLM_LOCAL_MODEL_COST_MAP": "True"}):
+ from trendradar.ai.client import AIClient
+
+
+class AIExtraParamsTests(unittest.TestCase):
+ def setUp(self):
+ env_patch = patch.dict(os.environ, {"AI_API_KEY": ""})
+ env_patch.start()
+ self.addCleanup(env_patch.stop)
+
+ response = SimpleNamespace(
+ choices=[SimpleNamespace(message=SimpleNamespace(content="mocked reply"))]
+ )
+ completion_patch = patch(
+ "trendradar.ai.client.completion", return_value=response
+ )
+ self.completion = completion_patch.start()
+ self.addCleanup(completion_patch.stop)
+
+ self.messages = [{"role": "user", "content": "Summarize this test item."}]
+ self.config = {
+ "MODEL": "test/model",
+ "API_KEY": "test-api-key",
+ "API_BASE": "https://api.example.invalid/v1",
+ "TEMPERATURE": 0.6,
+ "MAX_TOKENS": 128,
+ "TIMEOUT": 30,
+ "NUM_RETRIES": 0,
+ "FALLBACK_MODELS": ["test/backup"],
+ }
+ self.expected = {
+ "model": "test/model",
+ "messages": self.messages,
+ "api_key": "test-api-key",
+ "api_base": "https://api.example.invalid/v1",
+ "temperature": 0.6,
+ "max_tokens": 128,
+ "timeout": 30,
+ "num_retries": 0,
+ "fallbacks": ["test/backup"],
+ }
+
+ def chat_params(self, overrides=None, **kwargs):
+ self.completion.reset_mock()
+ client = AIClient({**self.config, **(overrides or {})})
+ self.assertEqual(client.chat(self.messages, **kwargs), "mocked reply")
+ self.completion.assert_called_once()
+ return self.completion.call_args.kwargs
+
+ def test_missing_none_or_empty_extra_params_preserve_existing_request(self):
+ for overrides in ({}, {"EXTRA_PARAMS": None}, {"EXTRA_PARAMS": {}}):
+ with self.subTest(overrides=overrides):
+ self.assertEqual(self.chat_params(overrides), self.expected)
+
+ def test_extra_request_parameters_and_headers_are_forwarded(self):
+ extra = {
+ "top_p": 0.8,
+ "presence_penalty": 0.0,
+ "stop": ["END"],
+ "extra_headers": {"X-Example-Trace": "test-trace"},
+ }
+ self.assertEqual(
+ self.chat_params({"EXTRA_PARAMS": extra}), {**self.expected, **extra}
+ )
+
+ def test_non_dict_extra_params_are_ignored(self):
+ for invalid in ("invalid", 42, True, ["unexpected"]):
+ with self.subTest(value=invalid), redirect_stdout(io.StringIO()) as output:
+ self.assertEqual(
+ self.chat_params({"EXTRA_PARAMS": invalid}), self.expected
+ )
+ self.assertIn("extra_params", output.getvalue())
+
+ def test_call_kwargs_override_configured_supplemental_parameters(self):
+ extra = {
+ "top_p": 0.8,
+ "stop": ["CONFIG_END"],
+ "presence_penalty": 0.4,
+ }
+ self.assertEqual(
+ self.chat_params(
+ {"EXTRA_PARAMS": extra}, top_p=0.2, stop=["CALL_END"]
+ ),
+ {
+ **self.expected,
+ "top_p": 0.2,
+ "stop": ["CALL_END"],
+ "presence_penalty": 0.4,
+ },
+ )
+
+ def test_extra_params_cannot_replace_assembled_core_parameters(self):
+ extra = {
+ "model": "test/other",
+ "messages": [{"role": "user", "content": "Replace the request."}],
+ "api_key": "other-test-key",
+ "api_base": "https://other.example.invalid/v1",
+ "temperature": 0.1,
+ "max_tokens": 512,
+ "timeout": 1,
+ "num_retries": 3,
+ "fallbacks": ["test/other-backup"],
+ }
+ self.assertEqual(self.chat_params({"EXTRA_PARAMS": extra}), self.expected)
+
+ def test_existing_core_call_overrides_still_work_without_extra_params(self):
+ call_options = {
+ "temperature": 0.1,
+ "max_tokens": 64,
+ "timeout": 5,
+ "num_retries": 2,
+ }
+ self.assertEqual(
+ self.chat_params(**call_options), {**self.expected, **call_options}
+ )
+
+ def test_extra_params_can_supply_optional_parameters_not_yet_assembled(self):
+ # Empty optional settings do not occupy keys in the request. Keep the
+ # PR's supplemental behavior while preserving call-argument priority.
+ extra = {
+ "api_base": "https://extra.example.invalid/v1",
+ "max_tokens": 256,
+ "fallbacks": ["test/extra-backup"],
+ }
+ actual = self.chat_params(
+ {
+ "API_BASE": "",
+ "MAX_TOKENS": 0,
+ "FALLBACK_MODELS": [],
+ "EXTRA_PARAMS": extra,
+ },
+ api_base="https://call.example.invalid/v1",
+ )
+ self.assertEqual(
+ actual,
+ {**self.expected, **extra, "api_base": "https://call.example.invalid/v1"},
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/trendradar/ai/client.py b/trendradar/ai/client.py
index a2a974e01b..aa631d08ff 100644
--- a/trendradar/ai/client.py
+++ b/trendradar/ai/client.py
@@ -29,6 +29,8 @@ class AIClient:
- TIMEOUT: 请求超时时间(秒)
- NUM_RETRIES: 重试次数(可选)
- FALLBACK_MODELS: 备用模型列表(可选)
+ - EXTRA_PARAMS: 透传给 LiteLLM 的额外参数(可选),如
+ extra_headers、top_p、presence_penalty、stop 等
"""
self.model = config.get("MODEL", "deepseek/deepseek-chat")
self.api_key = config.get("API_KEY") or os.environ.get("AI_API_KEY", "")
@@ -38,6 +40,14 @@ class AIClient:
self.timeout = config.get("TIMEOUT", 120)
self.num_retries = config.get("NUM_RETRIES", 2)
self.fallback_models = config.get("FALLBACK_MODELS", [])
+ # config.yaml 中 ai.extra_params 的透传参数(如自定义请求头)
+ self.extra_params = config.get("EXTRA_PARAMS") or {}
+ if not isinstance(self.extra_params, dict):
+ print(
+ f"[AI] 配置错误: ai.extra_params 应为字典,"
+ f"当前为 {type(self.extra_params).__name__},已忽略"
+ )
+ self.extra_params = {}
def chat(
self,
@@ -83,8 +93,10 @@ class AIClient:
if self.fallback_models:
params["fallbacks"] = self.fallback_models
- # 合并其他额外参数
- for key, value in kwargs.items():
+ # 合并配置文件中的 extra_params(如自定义请求头 extra_headers),
+ # 再用调用方 kwargs 覆盖;两者均不覆盖上方已确定的核心参数,
+ # 因此未配置 extra_params 时行为与原先完全一致
+ for key, value in {**self.extra_params, **kwargs}.items():
if key not in params:
params[key] = value