JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(llm): add app attribution headers for OpenRouter provider
yangzeque268e103cf1d
diff --git a/jiuwenswarm/agents/harness/common/memory/embeddings.py b/jiuwenswarm/agents/harness/common/memory/embeddings.pyindex a9f32757d8..edc64e34bb 100644--- a/jiuwenswarm/agents/harness/common/memory/embeddings.py+++ b/jiuwenswarm/agents/harness/common/memory/embeddings.py@@ -62,6 +62,19 @@ class OpenAICompatibleEmbeddingProvider(EmbeddingProvider):self._client = httpx.AsyncClient(timeout=60.0)return self._client+ def _is_openrouter_endpoint(self) -> bool:+ return bool(self.base_url and "openrouter.ai" in self.base_url.lower())++ def _build_request_headers(self) -> dict[str, str]:+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ }+ if self._is_openrouter_endpoint():+ from jiuwenswarm.common.openrouter_attribution import OPENROUTER_ATTRIBUTION_HEADERS+ headers.update(OPENROUTER_ATTRIBUTION_HEADERS)+ return headers+async def embed_query(self, text: str) -> List[float]:"""Generate embedding for a query."""embeddings = await self.embed_documents([text])@@ -78,10 +91,7 @@ class OpenAICompatibleEmbeddingProvider(EmbeddingProvider):response = await client.post(f"{self.base_url}/embeddings",- headers={- "Authorization": f"Bearer {self.api_key}",- "Content-Type": "application/json"- },+ headers=self._build_request_headers(),json={"model": self.model,"input": texts,diff --git a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.pyindex e74949b5c5..cf7ef3ef9e 100644--- a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py+++ b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py@@ -468,6 +468,9 @@ def build_evolution_llm(model_client_config, model_config_obj, model_name = resolve_model_config(config)+ from jiuwenswarm.common.openrouter_attribution import inject_attribution_headers+ inject_attribution_headers(model_client_config)+request_config = ModelRequestConfig(model=model_name,temperature=model_config_obj.get("temperature", 0.95),diff --git a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsxindex 24dfb0d2f2..e9684f0dde 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx@@ -700,6 +700,7 @@ function GroupSection({<option value="SiliconFlow">SiliconFlow</option><option value="InferenceAffinity">InferenceAffinity</option><option value="DeepSeek">DeepSeek</option>+ <option value="OpenRouter">OpenRouter</option></>)}</select>@@ -761,7 +762,7 @@ function GroupSection({);}-const MODEL_PROVIDER_OPTIONS = ["OpenAI", "DashScope", "SiliconFlow", "InferenceAffinity", "DeepSeek"] as const;+const MODEL_PROVIDER_OPTIONS = ["OpenAI", "OpenRouter", "DashScope", "SiliconFlow", "InferenceAffinity", "DeepSeek"] as const;/** 多默认模型管理(受控组件,编辑状态由父组件持有) */function MultiModelSection({diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex ec2e41e8c6..fc4bbb0fc6 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -597,15 +597,19 @@ def _normalize_rule_severity_action(rule: dict[str, Any]) -> None:rule["action"] = act-def _parse_custom_headers(value: str | None) -> dict[str, Any] | None:- """解析 custom_headers 配置,支持 JSON 字符串格式。+def _parse_custom_headers(value: str | dict | None) -> dict[str, Any] | None:+ """解析 custom_headers 配置,支持 JSON 字符串格式或已解析的字典。Args:- value: 环境变量值,可以是 None、空字符串或 JSON 字符串+ value: 环境变量值,可以是 None、空字符串、JSON 字符串或已解析的字典Returns:解析后的字典,如果输入为空或解析失败则返回 None"""+ if value is None:+ return None+ if isinstance(value, dict):+ return valueif not value or value.strip() == "":return Nonetry:diff --git a/jiuwenswarm/common/openrouter_attribution.py b/jiuwenswarm/common/openrouter_attribution.pynew file mode 100644index 0000000000..8770a3b30c--- /dev/null+++ b/jiuwenswarm/common/openrouter_attribution.py@@ -0,0 +1,68 @@+# coding: utf-8+from __future__ import annotations++from typing import Any, Optional+++OPENROUTER_ATTRIBUTION_HEADERS: dict[str, str] = {+ "HTTP-Referer": "https://openjiuwen.com/",+ "X-OpenRouter-Title": "JiuwenSwarm",+ "X-OpenRouter-Categories": (+ "cli-agent,cloud-agent,programming-app,"+ "creative-writing,writing-assistant,general-chat,personal-agent"+ ),+}+++def is_openrouter_provider(provider: Optional[str]) -> bool:+ if not provider:+ return False+ return str(provider).strip().lower() == "openrouter"+++def inject_attribution_headers(mcc: dict[str, Any]) -> dict[str, Any]:+ """Inject OpenRouter attribution headers into model_client_config dict.++ Only injects when client_provider is OpenRouter.+ Returns the same dict (mutated in place) for chaining convenience.+ """+ if not is_openrouter_provider(mcc.get("client_provider")):+ return mcc++ custom_headers = mcc.get("custom_headers")+ if not isinstance(custom_headers, dict):+ custom_headers = {}+ else:+ custom_headers = dict(custom_headers)++ for key, value in OPENROUTER_ATTRIBUTION_HEADERS.items():+ custom_headers.setdefault(key, value)++ mcc["custom_headers"] = custom_headers+ return mcc+++def inject_attribution_to_config(config: dict[str, Any]) -> None:+ """Inject OpenRouter attribution headers into all model_client_config entries in-place.++ Covers models.defaults (list), models.default (single), and react sections.+ """+ models = config.get("models", {})+ if isinstance(models, dict):+ defaults = models.get("defaults")+ if isinstance(defaults, list):+ for entry in defaults:+ mcc = entry.get("model_client_config") if isinstance(entry, dict) else None+ if isinstance(mcc, dict):+ inject_attribution_headers(mcc)+ default_single = models.get("default")+ if isinstance(default_single, dict):+ mcc = default_single.get("model_client_config")+ if isinstance(mcc, dict):+ inject_attribution_headers(mcc)++ react = config.get("react")+ if isinstance(react, dict):+ mcc = react.get("model_client_config")+ if isinstance(mcc, dict):+ inject_attribution_headers(mcc)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 10b34043f7..6a36f1fcb3 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -1580,8 +1580,15 @@ class JiuWenClawDeepAdapter:model_name, exc,)+ @staticmethod+ def _inject_attribution_to_config(config: dict) -> None:+ """Inject OpenRouter attribution headers into all model_client_config entries in-place."""+ from jiuwenswarm.common.openrouter_attribution import inject_attribution_to_config+ inject_attribution_to_config(config)+def _create_model(self, config: dict) -> Model:self._model_cache.clear()+ self._inject_attribution_to_config(config)self._build_model_cache_from_defaults(config)if not self._model_cache:self._build_model_cache_legacy(config)diff --git a/pyproject.toml b/pyproject.tomlindex c4851d42a4..d59f9cb9ee 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -16,7 +16,7 @@ dependencies = ["ruamel.yaml>=0.18.0","lark-oapi>=1.5.3","loguru>=0.7.3",- "openjiuwen==0.1.14",+ "openjiuwen @ git+https://gitcode.com/openJiuwen/agent-core.git@develop","pgvector>=0.4.2","websockets>=12.0","psutil>=7.2.2",diff --git a/uv.lock b/uv.lockindex 35491010fd..30094f29bb 100644--- a/uv.lock+++ b/uv.lock@@ -1718,7 +1718,7 @@ requires-dist = [{ name = "lark-oapi", specifier = ">=1.5.3" },{ name = "loguru", specifier = ">=0.7.3" },{ name = "mutagen", specifier = ">=1.47.0" },- { name = "openjiuwen", specifier = "==0.1.14" },+ { name = "openjiuwen", git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop" },{ name = "openjiuwen", extras = ["postgres", "zmq"], marker = "extra == 'distribute'" },{ name = "opentelemetry-api", specifier = ">=1.25.0" },{ name = "opentelemetry-exporter-otlp-proto-grpc", specifier = ">=1.25.0" },@@ -2578,7 +2578,7 @@ wheels = [[[package]]name = "openjiuwen"version = "0.1.14"-source = { registry = "https://pypi.org/simple" }+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#ca551cf83f90e18fa024cb33f02bd1977dff9d37" }dependencies = [{ name = "aiofiles" },{ name = "aiohttp" },@@ -2614,10 +2614,6 @@ dependencies = [{ name = "tiktoken" },{ name = "transformers" },]-sdist = { url = "https://files.pythonhosted.org/packages/e0/b9/25492385ebe70cf4db5a27be8146c9b9b4aa85b3f52027eeeee56a2c2d68/openjiuwen-0.1.14.tar.gz", hash = "sha256:49cda205cad9e1b1b4251207cf26c6690c1ee21be80f11fa151d8388f9d0a7e2", size = 2731809, upload-time = "2026-06-02T13:01:30.543Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/0c/75/4fa7621d37b32f543b62e7841f0444f95e40f83af0927d04a6e08a1a4b72/openjiuwen-0.1.14-py3-none-any.whl", hash = "sha256:84396020ac37ba66ba5d70493260c7674dc6a8884c01a725dce2631fd24e4eed", size = 3618848, upload-time = "2026-06-02T13:01:28.255Z" },-][package.optional-dependencies]postgres = [