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: 临时解决agent core不支持自定义模型 headers问题
ray_lece25a2a5cc00
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex f5aee76aab..12e40b52fc 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -177,6 +177,14 @@ class JiuWenClaw:model_client_config["api_base"] = config.pop("api_base", "")if "api_key" not in model_client_config:model_client_config["api_key"] = config.pop("api_key", "")+ try:+ default_headers = model_client_config.get("default_headers")+ model_client_config["default_headers"] = json.loads(default_headers) \+ if default_headers else None+ except json.decoder.JSONDecodeError as e:+ logger.error(f"Model default headers is not a valide json. {e}")+ model_client_config["default_headers"] = None+model_client_config["timeout"] = config.pop("timeout", 1800)config["model_client_config"] = model_client_configdiff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.pyindex d7dd0979a0..b99f8559a5 100644--- a/jiuwenclaw/app.py+++ b/jiuwenclaw/app.py@@ -37,6 +37,18 @@ from jiuwenclaw.channel import (for logger in LogManager.get_all_loggers().values():logger.set_level(logging.CRITICAL)++import openjiuwen.core.foundation.llm.schema.config as as_config_module+import openjiuwen.core.foundation.llm as as_llm_module+from openjiuwen.core.foundation.llm.model_clients.openai_model_client import OpenAIModelClient+from jiuwenclaw.jiuwen_core_patch import PatchModelClientConfig, PatchOpenAIModelClient++as_config_module.ModelClientConfig = PatchModelClientConfig+as_llm_module.ModelClientConfig = PatchModelClientConfig++OpenAIModelClient._create_async_openai_client = PatchOpenAIModelClient._create_async_openai_client+OpenAIModelClient._parse_stream_chunk = PatchOpenAIModelClient._parse_stream_chunk+from openjiuwen.core.foundation.llm import ProviderTypefrom jiuwenclaw.utils import (diff --git a/jiuwenclaw/channel/xiaoyi_channel.py b/jiuwenclaw/channel/xiaoyi_channel.pyindex 444bae68e3..4c2986ff93 100644--- a/jiuwenclaw/channel/xiaoyi_channel.py+++ b/jiuwenclaw/channel/xiaoyi_channel.py@@ -123,9 +123,10 @@ class XiaoyiChannel(BaseChannel):if not self.config.enabled:logger.warning("XiaoyiChannel 未启用(enabled=False)")return- if not self.config.ak or not self.config.sk or not self.config.agent_id:- logger.error("XiaoyiChannel 未配置 ak/sk/agent_id")- return+ if self.config.mode == "xiaoyi_channel":+ if not self.config.ak or not self.config.sk or not self.config.agent_id:+ logger.error("XiaoyiChannel 未配置 ak/sk/agent_id")+ returnself._running = True# Start dual channel connections@@ -817,7 +818,7 @@ class XiaoyiChannel(BaseChannel):async def _send_push_notification(self, text: str, push_text: str) -> bool:"""发送推送通知."""- if not (self.config.api_id and self.config.push_id and self.config.ak and self.config.sk):+ if not (self.config.api_id):logger.info("[PUSH] Push not configured, skipping")return Falsediff --git a/jiuwenclaw/channel/xiaoyi_utils/push.py b/jiuwenclaw/channel/xiaoyi_utils/push.pyindex 258c632dec..7dad9af7e3 100644--- a/jiuwenclaw/channel/xiaoyi_utils/push.py+++ b/jiuwenclaw/channel/xiaoyi_utils/push.py@@ -32,8 +32,6 @@ class PushConfig:return bool(self.api_id.strip()and self.push_id.strip()- and self.ak.strip()- and self.sk.strip())diff --git a/jiuwenclaw/jiuwen_core_patch.py b/jiuwenclaw/jiuwen_core_patch.pynew file mode 100644index 0000000000..144dd63f13--- /dev/null+++ b/jiuwenclaw/jiuwen_core_patch.py@@ -0,0 +1,109 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+from typing import Any, Optional++from pydantic import Field+import httpx+from openjiuwen.core.common.logging import llm_logger, LogEventType+from openjiuwen.core.common.security.ssl_utils import SslUtils+from openjiuwen.core.common.security.url_utils import UrlUtils+from openjiuwen.core.foundation.llm.schema.config import ModelClientConfig+from openjiuwen.core.foundation.llm.model_clients.openai_model_client import \+ AssistantMessageChunk, OpenAIModelClient, ToolCall, UsageMetadata+++class PatchModelClientConfig(ModelClientConfig):+ default_headers: Optional[dict] = Field(default=None, description="model client default headers")+++class PatchOpenAIModelClient(OpenAIModelClient):++ def _create_async_openai_client(self, timeout: Optional[float] = None) -> "openai.AsyncOpenAI":+ """+ Create an OpenAI Async client with configured SSL/proxy/http client settings.++ Args:+ timeout: Optional timeout override for this specific request+ """+ from openai import AsyncOpenAI++ ssl_verify, ssl_cert = self.model_client_config.verify_ssl, self.model_client_config.ssl_cert+ verify = SslUtils.create_strict_ssl_context(ssl_cert) if ssl_verify else ssl_verify++ http_client = httpx.AsyncClient(+ proxy=UrlUtils.get_global_proxy_url(self.model_client_config.api_base),+ verify=verify+ )++ # Use method-level timeout if provided, otherwise use config timeout+ final_timeout = timeout if timeout is not None else self.model_client_config.timeout+ llm_logger.info(+ "Before create openai client, model client config params ready.",+ event_type=LogEventType.LLM_CALL_START,+ timeout=final_timeout,+ max_retries=self.model_client_config.max_retries+ )++ return AsyncOpenAI(+ api_key=self.model_client_config.api_key,+ base_url=self.model_client_config.api_base,+ http_client=http_client,+ timeout=final_timeout,+ max_retries=self.model_client_config.max_retries,+ default_headers=self.model_client_config.default_headers+ )++ def _parse_stream_chunk(self, chunk: Any) -> Optional[AssistantMessageChunk]:+ """Parse OpenAI streaming response chunk++ Args:+ chunk: OpenAI streaming response chunk++ Returns:+ AssistantMessageChunk or None+ """+ if not chunk.choices:+ return None++ choice = chunk.choices[0]+ delta = choice.delta++ # Extract content+ content = getattr(delta, 'content', None) or ""+ reasoning_content = getattr(delta, 'reasoning_content', None)++ # Parse tool_calls delta+ tool_calls = []+ if hasattr(delta, 'tool_calls') and delta.tool_calls:+ for tc_delta in delta.tool_calls:+ if hasattr(tc_delta, 'function') and tc_delta.function:+ index = getattr(tc_delta, 'index', None)+ function_name = getattr(tc_delta.function, 'name', None) or ""+ function_arguments = getattr(tc_delta.function, 'arguments', None) or ""++ tool_call = ToolCall(+ id=getattr(tc_delta, 'id', '') or "",+ type="function",+ name=function_name,+ arguments=function_arguments,+ index=index+ )+ tool_calls.append(tool_call)++ # Build usage_metadata (usually only in the last chunk)+ usage_metadata = None+ if hasattr(chunk, 'usage') and chunk.usage:+ usage_metadata = UsageMetadata(+ model_name=self.model_config.model_name,+ input_tokens=getattr(chunk.usage, 'prompt_tokens', 0) or 0,+ output_tokens=getattr(chunk.usage, 'completion_tokens', 0) or 0,+ total_tokens=getattr(chunk.usage, 'total_tokens', 0) or 0+ )++ return AssistantMessageChunk(+ content=content,+ reasoning_content=reasoning_content,+ tool_calls=tool_calls if tool_calls else None,+ usage_metadata=usage_metadata,+ finish_reason=choice.finish_reason or "null"+ )+diff --git a/jiuwenclaw/resources/.env.template b/jiuwenclaw/resources/.env.templateindex 844f6ad7e6..ffcfc0c1ab 100644--- a/jiuwenclaw/resources/.env.template+++ b/jiuwenclaw/resources/.env.template@@ -2,6 +2,7 @@ API_BASE="https://example.com/compatible-mode/v1"API_KEY="sk-xxxxxxxxx"MODEL_NAME="your-model-name"MODEL_PROVIDER=OpenAI # or other provider like SiliconFlow, etc.+DEFAULT_HEADERS=EMBED_API_BASE=EMBED_API_KEY=diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yamlindex 29918ca647..fad51f5edd 100644--- a/jiuwenclaw/resources/config.yaml+++ b/jiuwenclaw/resources/config.yaml@@ -13,6 +13,7 @@ react:api_base: ${API_BASE:-https://api.modelarts-maas.com/openai/v1}api_key: ${API_KEY}verify_ssl: false+ default_headers: ${DEFAULT_HEADERS}model_config_obj:context_engine_config:enable_reload: true