Skip to content

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: config配置问题修复

ray_le76a9c8a30322
diff --git "a/docs/\351\242\221\351\201\223.md" "b/docs/\351\242\221\351\201\223.md"
index bbabf91587..9f2df7e6f9 100644
--- "a/docs/\351\242\221\351\201\223.md"
+++ "b/docs/\351\242\221\351\201\223.md"
@@ -4,7 +4,7 @@ JiuwenClaw 的​**频道**​,是您与不同聊天平台对话的**渠道**
配置频道有两种方式:
-* **网页配置**​(推荐)— 在 JiuwenClaw前端页面,点击 **`智能体` **/ **`频道`**卡片,在频道管理模块,填写相关配置。
+* **网页配置**​(推荐)— 在 JiuwenClaw前端页面,点击 **`智能体` / `频道`**卡片,在频道管理模块,填写相关配置。
* **手动编辑 `config.yaml`** — 默认在 `~/.jiuwenclaw/config.yaml` (由首次 `jiuwenclaw-start` 启动时自动生成),将需要的频道设 `enabled: true` 并填好鉴权信息;保存后自动重载,无需重启。
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.py
index 1e3a61d88b..6065a830d1 100644
--- a/jiuwenclaw/agentserver/interface.py
+++ b/jiuwenclaw/agentserver/interface.py
@@ -8,27 +8,19 @@ import asyncio
import os
from typing import Any, AsyncIterator
+from dotenv import load_dotenv
from openjiuwen.core.context_engine import MessageOffloaderConfig, DialogueCompressorConfig
from openjiuwen.core.foundation.llm import ModelRequestConfig
-from dotenv import load_dotenv
from openjiuwen.core.runner import Runner
from openjiuwen.core.single_agent import AgentCard, ReActAgentConfig
from openjiuwen.core.sys_operation import SysOperationCard, OperationMode, LocalWorkConfig
-
-from jiuwenclaw.gateway.cron import CronController
-from jiuwenclaw.utils import _get_config_module, get_root_dir, logger, USER_WORKSPACE_DIR
-
-_config_module = _get_config_module()
-get_config = _config_module.get_config
-set_config = _config_module.set_config
-update_heartbeat_in_config = _config_module.update_heartbeat_in_config
-update_channel_in_config = _config_module.update_channel_in_config
-update_browser_in_config = _config_module.update_browser_in_config
-
from openjiuwen.core.session.checkpointer import CheckpointerFactory
from openjiuwen.core.session.checkpointer.checkpointer import CheckpointerConfig
from openjiuwen.core.session.checkpointer.persistence import PersistenceCheckpointerProvider
+from jiuwenclaw.gateway.cron import CronController
+from jiuwenclaw.utils import get_root_dir, logger, USER_WORKSPACE_DIR
+from jiuwenclaw.config import get_config
from jiuwenclaw.agentserver.react_agent import JiuClawReActAgent
from jiuwenclaw.agentserver.tools.browser_tools import register_browser_runtime_mcp_server
from jiuwenclaw.agentserver.tools.mcp_toolkits import get_mcp_tools
diff --git a/jiuwenclaw/agentserver/memory/summarizer.py b/jiuwenclaw/agentserver/memory/summarizer.py
index 84619c8939..93094e0290 100644
--- a/jiuwenclaw/agentserver/memory/summarizer.py
+++ b/jiuwenclaw/agentserver/memory/summarizer.py
@@ -12,11 +12,8 @@ from pathlib import Path
from openjiuwen.core.foundation.llm import Model
from openjiuwen.core.foundation.llm.schema.config import ModelRequestConfig, ModelClientConfig
-from jiuwenclaw.utils import _get_config_module, logger
-
-# Import config functions dynamically to avoid path issues
-_config_module = _get_config_module()
-get_config = _config_module.get_config
+from jiuwenclaw.utils import logger
+from jiuwenclaw.config import get_config
def format_messages_for_summary(
diff --git a/jiuwenclaw/agentserver/react_agent.py b/jiuwenclaw/agentserver/react_agent.py
index fcc8a21494..61388bfb36 100644
--- a/jiuwenclaw/agentserver/react_agent.py
+++ b/jiuwenclaw/agentserver/react_agent.py
@@ -34,10 +34,9 @@ from jiuwenclaw.agentserver.tools.todo_toolkits import TodoToolkit
from jiuwenclaw.agentserver.prompt_builder import build_system_prompt
from jiuwenclaw.evolution.skill_call_operator import SkillCallOperator
from jiuwenclaw.evolution.skill_optimizer import SkillOptimizer
-from jiuwenclaw.utils import _get_config_module, logger, USER_WORKSPACE_DIR
+from jiuwenclaw.utils import logger, USER_WORKSPACE_DIR
+from jiuwenclaw.config import get_config
-_config_module = _get_config_module()
-get_config = _config_module.get_config
# 加载流式输出配置
_react_config = get_config().get("react", {})
diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.py
index 909e50b8b8..22d7cc6344 100644
--- a/jiuwenclaw/app.py
+++ b/jiuwenclaw/app.py
@@ -22,7 +22,9 @@ from typing import Any
import psutil
# 项目根目录,用于查找 workspace、agentserver 等目录
-from jiuwenclaw.utils import get_root_dir, get_config_dir, is_package_installation, logger
+from openjiuwen.core.foundation.llm import ProviderType
+from jiuwenclaw.utils import get_root_dir, is_package_installation, logger
+from jiuwenclaw.config import get_config, update_heartbeat_in_config, update_channel_in_config, update_browser_in_config
_PROJECT_ROOT = get_root_dir()
_ENV_FILE = _PROJECT_ROOT / ".env"
@@ -41,34 +43,6 @@ def _get_package_dir() -> Path:
return Path(__file__).resolve().parent.parent / "jiuwenclaw"
-# 在导入 config 模块前,将其路径添加到 sys.path
-_config_dir = get_config_dir()
-os.environ["JIUWENCLAW_CONFIG_DIR"] = str(_config_dir)
-if str(_config_dir) not in sys.path:
- sys.path.insert(0, str(_config_dir))
-
-# 动态导入 config 模块
-def _load_config_module():
- """Dynamically load config module from correct location."""
- import importlib.util
- config_dir = get_config_dir()
- config_path = config_dir / "config.py"
- spec = importlib.util.spec_from_file_location("config_module", str(config_path))
- if spec and spec.loader:
- module = importlib.util.module_from_spec(spec)
- sys.modules["config_module"] = module
- spec.loader.exec_module(module)
- return module
- raise ImportError(f"Cannot load config module from {config_path}")
-
-_config_module = _load_config_module()
-get_config = _config_module.get_config
-set_config = _config_module.set_config
-update_heartbeat_in_config = _config_module.update_heartbeat_in_config
-update_channel_in_config = _config_module.update_channel_in_config
-update_browser_in_config = _config_module.update_browser_in_config
-
-
# 仅满足 Channel 构造所需,不入队、不路由;仅用 channel_manager + message_handler 做入站/出站
class _DummyBus:
async def publish_user_messages(self, msg): # noqa: ANN001, ARG002
@@ -263,10 +237,16 @@ def _register_web_handlers(
await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")
return
updates: dict[str, str] = {}
+ available_model_providers = [provider.value for provider in ProviderType]
for param_key, env_key in _CONFIG_SET_ENV_MAP.items():
if param_key not in params:
continue
val = params[param_key]
+ if param_key == "model_provider" and val not in available_model_providers:
+ await channel.send_response(
+ ws, req_id, ok=False, error=f"Model provider must in: {available_model_providers} ", code="BAD_REQUEST"
+ )
+ return
if val is None:
updates[env_key] = ""
else:
diff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.py
index ab4e418d36..d6c9180746 100644
--- a/jiuwenclaw/config.py
+++ b/jiuwenclaw/config.py
@@ -9,8 +9,11 @@ from typing import Any
import yaml
from ruamel.yaml import YAML
-# Get config directory - check for user workspace or use default
+from jiuwenclaw.utils import get_config_file
+
+
_CONFIG_MODULE_DIR = Path(__file__).parent
+_CONFIG_YAML_PATH = get_config_file()
# Check if user workspace exists and use it if configured via env
_user_config = os.getenv("JIUWENCLAW_CONFIG_DIR")
@@ -52,7 +55,7 @@ def resolve_env_vars(value: Any) -> Any:
def get_config():
- with open(_CONFIG_MODULE_DIR / "config.yaml", "r", encoding="utf-8") as f:
+ with open(get_config_file(), "r", encoding="utf-8") as f:
config_base = yaml.safe_load(f)
config_base = resolve_env_vars(config_base)
@@ -61,12 +64,12 @@ def get_config():
def get_config_raw():
"""读 config.yaml 原始内容(不解析环境变量),供局部更新后写回。"""
- with open(_CONFIG_MODULE_DIR / "config.yaml", "r", encoding="utf-8") as f:
+ with open(_CONFIG_YAML_PATH, "r", encoding="utf-8") as f:
return yaml.safe_load(f) or {}
def set_config(config):
- with open(_CONFIG_MODULE_DIR / "config.yaml", "w", encoding="utf-8") as f:
+ with open(_CONFIG_YAML_PATH, "w", encoding="utf-8") as f:
yaml.safe_dump(config, f, allow_unicode=True, sort_keys=False)
@@ -92,8 +95,7 @@ def _dump_yaml_round_trip(config_path: Path, data: Any) -> None:
def update_heartbeat_in_config(payload: dict[str, Any]) -> None:
"""只更新 heartbeat 段并写回。"""
- config_path = _CONFIG_MODULE_DIR / "config.yaml"
- data = _load_yaml_round_trip(config_path)
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
if "heartbeat" not in data:
data["heartbeat"] = {}
hb = data["heartbeat"]
@@ -103,13 +105,12 @@ def update_heartbeat_in_config(payload: dict[str, Any]) -> None:
hb["target"] = payload["target"]
if "active_hours" in payload:
hb["active_hours"] = payload["active_hours"]
- _dump_yaml_round_trip(config_path, data)
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
def update_channel_in_config(channel_id: str, conf: dict[str, Any]) -> None:
"""只更新 channels[channel_id] 并写回。"""
- config_path = _CONFIG_MODULE_DIR / "config.yaml"
- data = _load_yaml_round_trip(config_path)
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
if "channels" not in data:
data["channels"] = {}
channels = data["channels"]
@@ -118,16 +119,15 @@ def update_channel_in_config(channel_id: str, conf: dict[str, Any]) -> None:
section = channels[channel_id]
for k, v in conf.items():
section[k] = v
- _dump_yaml_round_trip(config_path, data)
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
def update_browser_in_config(updates: dict[str, Any]) -> None:
"""只更新 browser 段(如 chrome_path)并写回。"""
- config_path = _CONFIG_MODULE_DIR / "config.yaml"
- data = _load_yaml_round_trip(config_path)
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
if "browser" not in data:
data["browser"] = {}
section = data["browser"]
for k, v in updates.items():
section[k] = v
- _dump_yaml_round_trip(config_path, data)
\ No newline at end of file
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
\ No newline at end of file
diff --git a/jiuwenclaw/init_workspace.py b/jiuwenclaw/init_workspace.py
index 252b40326b..646c89ccab 100644
--- a/jiuwenclaw/init_workspace.py
+++ b/jiuwenclaw/init_workspace.py
@@ -1,7 +1,7 @@
"""CLI for initializing runtime data into ~/.jiuwenclaw.
无论是通过 pip/whl 安装,还是在源码目录里直接运行:
-- 都可以通过运行本脚本,把内置的 config.yaml / config.py / .env.template
+- 都可以通过运行本脚本,把内置的 config.yaml / .env.template
以及 workspace 模板复制到用户主目录 ~/.jiuwenclaw 下,
之后运行 app.py 时会从该目录读取和写入配置。
"""
diff --git a/jiuwenclaw/utils.py b/jiuwenclaw/utils.py
index ad234023df..e6a7e6dec8 100644
--- a/jiuwenclaw/utils.py
+++ b/jiuwenclaw/utils.py
@@ -87,13 +87,11 @@ def init_user_workspace(overwrite: bool = True) -> Path:
资源布局(新):
- 模板配置: <package_root>/resources/config.yaml
- - 模块实现: <package_root>/config.py
- .env 模板: <package_root>/resources/.env.template
- workspace: 优先 <package_root>/workspace,其次 <package_root>/../workspace
上述内容会被复制到:
- ~/.jiuwenclaw/config/config.yaml
- - ~/.jiuwenclaw/config/config.py
- ~/.jiuwenclaw/.env
- ~/.jiuwenclaw/workspace/...
@@ -105,40 +103,27 @@ def init_user_workspace(overwrite: bool = True) -> Path:
USER_WORKSPACE_DIR.mkdir(parents=True, exist_ok=True)
- # ----- config: copy config.yaml + config.py -----
+ # ----- config: copy config.yaml -----
resources_dir = package_root / "resources"
config_yaml_src_candidates = [
resources_dir / "config.yaml",
package_root / "config" / "config.yaml",
]
- config_py_src_candidates = [
- package_root / "config.py",
- package_root / "config" / "config.py",
- ]
config_yaml_src = next((p for p in config_yaml_src_candidates if p.exists()), None)
- config_py_src = next((p for p in config_py_src_candidates if p.exists()), None)
if not config_yaml_src:
raise RuntimeError(
"config.yaml template not found; tried: "
+ ", ".join(str(p) for p in config_yaml_src_candidates)
)
- if not config_py_src:
- raise RuntimeError(
- "config.py source not found; tried: "
- + ", ".join(str(p) for p in config_py_src_candidates)
- )
config_dest_dir = USER_WORKSPACE_DIR / "config"
config_dest_dir.mkdir(parents=True, exist_ok=True)
config_yaml_dest = config_dest_dir / "config.yaml"
- config_py_dest = config_dest_dir / "config.py"
if overwrite or not config_yaml_dest.exists():
shutil.copy2(config_yaml_src, config_yaml_dest)
- if overwrite or not config_py_dest.exists():
- shutil.copy2(config_py_src, config_py_dest)
# ----- workspace: copy tree -----
workspace_src_candidates = [
@@ -247,35 +232,6 @@ def is_package_installation() -> bool:
return _detect_installation_mode()
-def _get_config_module() -> Any:
- """Get config module from correct location.
-
- This function dynamically loads the config module from either:
- - User workspace: ~/.jiuwenclaw/config
- - Source mode: project root config directory
-
- Returns:
- The loaded config module with get_config function
-
- Raises:
- ImportError: If config module cannot be loaded
- """
- # Check for user workspace
- config_dir = Path.home() / ".jiuwenclaw" / "config"
- if not config_dir.exists():
- # Source mode: use relative path
- config_dir = get_config_dir()
-
- # Import config as a module
- spec = importlib.util.spec_from_file_location("config_module", str(config_dir / "config.py"))
- if spec and spec.loader:
- module = importlib.util.module_from_spec(spec)
- sys.modules["config_module"] = module
- spec.loader.exec_module(module)
- return module
- raise ImportError(f"Cannot load config module from {config_dir}")
-
-
def setup_logger(log_level: str = "INFO") -> logging.Logger:
"""Setup logger with console and file handlers."""
project_root = get_root_dir()