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
feat: 新增图片音频识别分析
zhuxushen0d140b747699
diff --git "a/docs/\351\205\215\347\275\256\344\277\241\346\201\257.md" "b/docs/\351\205\215\347\275\256\344\277\241\346\201\257.md"index 7a7ddad86a..e14f9472ad 100644--- "a/docs/\351\205\215\347\275\256\344\277\241\346\201\257.md"+++ "b/docs/\351\205\215\347\275\256\344\277\241\346\201\257.md"@@ -23,6 +23,9 @@ JiuwenClaw 的配置来源包括:`config/config.yaml`、`.env` 环境变量、| `embed_api_base` | `EMBED_API_BASE` | Embed 服务 API 地址 || `embed_api_key` | `EMBED_API_KEY` | Embed 服务 API 密钥 || `embed_model` | `EMBED_MODEL` | Embed 模型名称 |+| `video_model` | `VIDEO_MODEL_NAME` | 视频处理调用模型 |+| `audio_model` | `AUDIO_MODEL_NAME` | 音频处理调用模型 |+| `vision_model` | `VISION_MODEL_NAME` | 图像处理调用模型 || `jina_api_key` | `JINA_API_KEY` | Jina 搜索 API 密钥 || `serper_api_key` | `SERPER_API_KEY` | Serper 搜索 API 密钥 || `perplexity_api_key` | `PERPLEXITY_API_KEY` | Perplexity API 密钥 |diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex f0ccb5e475..28275c0451 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -36,6 +36,11 @@ from jiuwenclaw.utils import (from jiuwenclaw.config import get_configfrom jiuwenclaw.agentserver.react_agent import JiuClawReActAgentfrom jiuwenclaw.agentserver.tools.browser_tools import register_browser_runtime_mcp_server+from jiuwenclaw.agentserver.tools.audio_tools import (+ audio_question_answering,+ audio_metadata,+)+from jiuwenclaw.agentserver.tools.image_tools import visual_question_answeringfrom jiuwenclaw.agentserver.tools.mcp_toolkits import get_mcp_toolsfrom jiuwenclaw.agentserver.tools.todo_toolkits import TaskStatus, TodoToolkitfrom jiuwenclaw.agentserver.tools.memory_tools import (@@ -46,7 +51,12 @@ from jiuwenclaw.agentserver.tools.memory_tools import (edit_memory,read_memory,)-from jiuwenclaw.agentserver.tools.video_understanding import video_understanding+from jiuwenclaw.agentserver.tools.video_tools import video_understanding+from jiuwenclaw.agentserver.tools.multimodal_config import (+ apply_audio_model_config_from_yaml,+ apply_vision_model_config_from_yaml,+ apply_video_model_config_from_yaml,+)from jiuwenclaw.agentserver.memory.compaction import ContextCompactionManagerfrom jiuwenclaw.agentserver.memory.config import clear_config_cachefrom jiuwenclaw.agentserver.memory import clear_memory_manager_cache@@ -130,6 +140,8 @@ class JiuWenClaw:self._agent_name: str = "main_agent"self._compaction_manager: ContextCompactionManager | None = Noneself._browser_mcp_registered: bool = False+ self._vision_mcp_registered: bool = False+ self._audio_mcp_registered: bool = Falseself._memory_tools_registered: bool = Falseself._mcp_tools_registered: bool = Falseself._video_tool_registered: bool = False@@ -161,7 +173,7 @@ class JiuWenClaw:self._agent_name = agent_name# 处理 model_client_config:确保包含必需字段- model_configs = config.get("models", []).copy()+ model_configs = config.get("models", []).copy()react_config = {**react_config, **model_configs.get("default", {}).copy(), "prompt_template": [{"role": "system", "content": build_system_prompt(mode="plan",@@ -223,6 +235,9 @@ class JiuWenClaw:await self.set_checkpoint()config_base = get_config()+ apply_video_model_config_from_yaml(config_base)+ apply_audio_model_config_from_yaml(config_base)+ apply_vision_model_config_from_yaml(config_base)agent_config = self._load_react_config(config_base)sysop_card_id: str | None = None@@ -261,7 +276,7 @@ class JiuWenClaw:# 检查是否有有效的模型配置(api_key 或 client_provider)has_valid_model_config = False- if isinstance(config_base.get("models", dict).get("default", dict).get("model_client_config"), dict):+ if isinstance(config_base.get("models", dict).get("default", dict).get("model_client_config"), dict):mcc = config_base.get("models", dict).get("default", dict)["model_client_config"]# 检查是否有 api_key(非空)或通过环境变量配置api_key = mcc.get("api_key", "")@@ -337,6 +352,26 @@ class JiuWenClaw:except Exception as exc:logger.warning("[JiuWenClaw] browser MCP registration skipped: %s", exc)+ # add vision tools (直接注册方式)+ try:+ for tool in [visual_question_answering]:+ Runner.resource_mgr.add_tool(tool)+ self._instance.ability_manager.add(tool.card)+ self._vision_mcp_registered = True+ logger.info("[JiuWenClaw] vision tools registered successfully")+ except Exception as exc:+ logger.warning("[JiuWenClaw] vision tools registration skipped: %s", exc)++ # add audio tools (直接注册方式)+ try:+ for tool in [audio_question_answering, audio_metadata]:+ Runner.resource_mgr.add_tool(tool)+ self._instance.ability_manager.add(tool.card)+ self._audio_mcp_registered = True+ logger.info("[JiuWenClaw] audio tools registered successfully")+ except Exception as exc:+ logger.warning("[JiuWenClaw] audio tools registration skipped: %s", exc)+# add cron toolstry:cron_controller = CronController.get_instance()@@ -362,6 +397,9 @@ class JiuWenClaw:clear_memory_manager_cache()config_base = get_config()+ apply_video_model_config_from_yaml(config_base)+ apply_audio_model_config_from_yaml(config_base)+ apply_vision_model_config_from_yaml(config_base)agent_config = self._load_react_config(config_base)if self._sysop_card_id:@@ -423,7 +461,7 @@ class JiuWenClaw:elif channel == "wecom":cron_controller.set_target_channel(CronTargetChannel.WECOM)elif channel == "xiaoyi":- cron_controller.set_target_channel(CronTargetChannel.XIAOYI)+ cron_controller.set_target_channel(CronTargetChannel.XIAOYI)elif channel in ("web", "sess"):cron_controller.set_target_channel(CronTargetChannel.WEB)@@ -451,7 +489,7 @@ class JiuWenClaw:for tool in session_toolkits.get_tools():Runner.resource_mgr.add_tool(tool)self._instance.ability_manager.add(tool.card)-+# Register send file toolkitif not self._send_file_tool_registered:send_file_toolkit = SendFileToolkit(@@ -488,6 +526,26 @@ class JiuWenClaw:except Exception as exc:logger.warning("[JiuWenClaw] ensure video_understanding tool failed: %s", exc)+ if not self._vision_mcp_registered:+ try:+ for tool in [visual_question_answering]:+ if not Runner.resource_mgr.get_tool(tool.card.id):+ Runner.resource_mgr.add_tool(tool)+ self._instance.ability_manager.add(tool.card)+ self._vision_mcp_registered = True+ except Exception as exc:+ logger.warning("[JiuWenClaw] ensure vision tools failed: %s", exc)++ if not self._audio_mcp_registered:+ try:+ for tool in [audio_question_answering, audio_metadata]:+ if not Runner.resource_mgr.get_tool(tool.card.id):+ Runner.resource_mgr.add_tool(tool)+ self._instance.ability_manager.add(tool.card)+ self._audio_mcp_registered = True+ except Exception as exc:+ logger.warning("[JiuWenClaw] ensure audio tools failed: %s", exc)+if not self._mcp_tools_registered:for mcp_tool in get_mcp_tools():Runner.resource_mgr.add_tool(mcp_tool)diff --git a/jiuwenclaw/agentserver/tools/audio_tools.py b/jiuwenclaw/agentserver/tools/audio_tools.pynew file mode 100644index 0000000000..2c80c577cb--- /dev/null+++ b/jiuwenclaw/agentserver/tools/audio_tools.py@@ -0,0 +1,321 @@+import asyncio+import base64+import contextlib+import hashlib+import hmac+import json+import logging+import mimetypes+import os+import sys+import tempfile+import time+import wave+from pathlib import Path+from urllib.parse import urlparse++from fastmcp import FastMCP+from mutagen import File as MutagenFile+from openai import OpenAI+from openjiuwen.core.foundation.tool import McpServerConfig, tool+from openjiuwen.core.runner import Runner+import requests++from jiuwenclaw.agentserver.tools.multimodal_config import apply_audio_model_config_from_yaml++ACR_ACCESS_KEY = os.environ.get("ACR_ACCESS_KEY", "")+ACR_ACCESS_SECRET = os.environ.get("ACR_ACCESS_SECRET", "")+ACR_BASE_URL = os.environ.get(+ "ACR_BASE_URL", "https://identify-ap-southeast-1.acrcloud.com/v1/identify"+)+HTTP_TIMEOUT = 20+MAX_AUDIO_BYTES = 25 * 1024 * 1024+DEFAULT_USER_AGENT = (+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"+)++mcp = FastMCP("audio-mcp-server")++_log = logging.getLogger(__name__)++_AUDIO_EXT_MAP = {+ ".mp3": "mp3", ".wav": "wav", ".m4a": "m4a",+ ".aac": "aac", ".ogg": "ogg", ".flac": "flac", ".wma": "wma",+}++_MIME_TO_FORMAT = {"mpeg": "mp3", "wav": "wav", "wave": "wav"}+++def _resolve_audio_extension(source_url: str, header_content_type: str = None) -> str:+ parsed = urlparse(source_url)+ path_lower = parsed.path.lower()+ for ext in _AUDIO_EXT_MAP:+ if path_lower.endswith(ext):+ return ext+ if header_content_type:+ ct_lower = header_content_type.lower()+ for mime_key, fmt in _MIME_TO_FORMAT.items():+ if mime_key in ct_lower:+ return f".{fmt}"+ for ext_key in _AUDIO_EXT_MAP:+ if ext_key[1:] in ct_lower:+ return ext_key+ return ".mp3"+++def _compute_audio_length_seconds(file_path: str) -> float:+ try:+ with contextlib.closing(wave.open(file_path, "rb")) as wf:+ frames = wf.getnframes()+ rate = wf.getframerate()+ secs = frames / float(rate)+ if secs > 0:+ return secs+ except (wave.Error, OSError):+ _log.debug("wave module failed to read %s, trying mutagen", file_path)+ try:+ audio_obj = MutagenFile(file_path)+ if audio_obj is not None and hasattr(audio_obj, "info"):+ if hasattr(audio_obj.info, "length"):+ secs = float(audio_obj.info.length)+ if secs > 0:+ return secs+ except Exception:+ _log.debug("mutagen failed to read %s", file_path, exc_info=True)+ raise ValueError("Unable to determine audio duration")+++def _load_audio_as_base64(file_path: str) -> tuple[str, str]:+ with open(file_path, "rb") as f:+ raw_bytes = f.read()+ b64_str = base64.b64encode(raw_bytes).decode("utf-8")+ guessed_mime, _ = mimetypes.guess_type(file_path)+ if guessed_mime and guessed_mime.startswith("audio/"):+ mime_suffix = guessed_mime.split("/")[-1]+ fmt = _MIME_TO_FORMAT.get(mime_suffix, "mp3")+ else:+ fmt = "mp3"+ return b64_str, fmt+++def _download_audio_to_tempfile(url: str) -> str:+ hdrs = {"User-Agent": DEFAULT_USER_AGENT}+ resp = requests.get(url, headers=hdrs, timeout=HTTP_TIMEOUT, stream=True)+ resp.raise_for_status()+ ct = resp.headers.get("content-type", "")+ ext = _resolve_audio_extension(url, ct)+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=ext)+ total = 0+ try:+ for chunk in resp.iter_content(chunk_size=64 * 1024):+ if chunk:+ total += len(chunk)+ if total > MAX_AUDIO_BYTES:+ tmp.close()+ os.remove(tmp.name)+ raise ValueError("Audio file exceeds size limit (25MB).")+ tmp.write(chunk)+ except Exception:+ tmp.close()+ if os.path.exists(tmp.name):+ os.remove(tmp.name)+ raise+ tmp.close()+ return tmp.name+++def _create_openai_client_for_audio():+ key = os.environ.get("AUDIO_API_KEY") or os.environ.get("API_KEY", "")+ base = os.environ.get("AUDIO_API_BASE") or os.environ.get("API_BASE", "")+ return key, base, OpenAI(api_key=key, base_url=base) if key else None+++def _build_sandbox_unavailable_msg(tool_name: str) -> str:+ return (+ f"The {tool_name} tool cannot access to sandbox file, "+ "please use the local path provided by original instruction"+ )+++def _build_missing_key_msg(tool_name: str) -> str:+ return (+ f"[ERROR]: AUDIO_API_KEY or API_KEY is not configured "+ f"for {tool_name}."+ )+++@tool(+ name="audio_question_answering",+ description=(+ "Answer questions based on audio content. Use this tool when the user provides "+ "an audio file and asks questions about the audio content, such as 'what is "+ "discussed in this audio', 'how many speakers', or any analysis requiring "+ "understanding of the audio."+ ),+)+async def audio_question_answering(audio_path_or_url: str, question: str) -> str:+ from jiuwenclaw.config import get_config+ try:+ apply_audio_model_config_from_yaml(get_config())+ except Exception:+ _log.debug("Failed to apply audio model config from yaml", exc_info=True)++ api_key, api_base, client = _create_openai_client_for_audio()+ if not api_key:+ return _build_missing_key_msg("audio question answering")++ try:+ prompt_text = f"Answer the following question based on the given audio information:\n\n{question}"+ cleanup_needed = False+ target_path = audio_path_or_url++ if os.path.exists(audio_path_or_url):+ pass+ elif "home/user" in audio_path_or_url:+ return _build_sandbox_unavailable_msg("audio_question_answering")+ else:+ target_path = _download_audio_to_tempfile(audio_path_or_url)+ cleanup_needed = True++ try:+ b64_data, fmt = _load_audio_as_base64(target_path)+ duration = _compute_audio_length_seconds(target_path)+ finally:+ if cleanup_needed and os.path.exists(target_path):+ os.remove(target_path)++ if not b64_data or not fmt:+ return (+ "[ERROR]: Audio question answering failed: Failed to encode audio file.\n"+ "Note: Files from sandbox are not available. "+ "You should use local path given in the instruction.\n"+ "URLs must include the proper scheme (e.g., 'https://') "+ "and be publicly accessible. The file should be in a common audio "+ "format such as MP3.\n"+ "Note: YouTube video URL is not supported."+ )++ resp = client.chat.completions.create(+ model="gpt-4o-audio-preview",+ messages=[+ {"role": "system", "content": "You are a helpful assistant specializing in audio analysis."},+ {+ "role": "user",+ "content": [+ {"type": "text", "text": prompt_text},+ {"type": "input_audio", "input_audio": {"data": b64_data, "format": fmt}},+ ],+ },+ ],+ )+ answer = resp.choices[0].message.content+ return f"{answer}\n\nAudio duration: {duration} seconds"+ except Exception as err:+ return (+ f"[ERROR]: Audio question answering failed when calling OpenAI API: {err}\n"+ "Note: Files from sandbox are not available. "+ "You should use local path given in the instruction. "+ "The file should be in a common audio format such as MP3, WAV, or M4A.\n"+ "Note: YouTube video URL is not supported."+ )+++@tool(+ name="audio_metadata",+ description="Identify the metadata (name, author, year) of the given audio file using the ACRCloud API.",+)+async def audio_metadata(audio_path_or_url: str) -> str:+ cleanup = False+ local_path = audio_path_or_url++ try:+ if os.path.exists(audio_path_or_url):+ pass+ elif "home/user" in audio_path_or_url:+ return (+ "The audio_question_answering tool cannot access to sandbox file, "+ "please use a local path instead. If the audio file has been preprocessed "+ "in the sandbox, please download the file to your local machine and use "+ "the local path instead."+ )+ else:+ local_path = _download_audio_to_tempfile(audio_path_or_url)+ cleanup = True++ duration = _compute_audio_length_seconds(local_path)++ if not ACR_ACCESS_KEY or not ACR_ACCESS_SECRET:+ return (+ f"Duration (seconds): {duration:.2f}\n"+ "Note: Title/artist identification is disabled because ACR credentials are not provided."+ )++ if duration > 15:+ return (+ "The audio_metadata tool is better used to process audio file with less than 15 seconds, "+ "please cut your audio file to a small one and try again."+ )++ ts = time.time()+ sig_base = (+ "POST\n/v1/identify\n" + ACR_ACCESS_KEY + "\naudio\n1\n" + str(ts)+ )+ sig = base64.b64encode(+ hmac.new(+ ACR_ACCESS_SECRET.encode("ascii"),+ sig_base.encode("ascii"),+ digestmod=hashlib.sha1,+ ).digest()+ ).decode("ascii")++ fname = os.path.basename(local_path)+ fsize = os.path.getsize(local_path)+ mime_guess, _ = mimetypes.guess_type(local_path)+ if mime_guess and mime_guess.startswith("audio/"):+ mime_suffix = mime_guess.split("/")[-1]+ upload_fmt = _MIME_TO_FORMAT.get(mime_suffix, "mp3")+ else:+ upload_fmt = "mp3"++ files_payload = [("sample", (fname, open(local_path, "rb"), upload_fmt))]+ form_data = {+ "access_key": ACR_ACCESS_KEY,+ "sample_bytes": fsize,+ "timestamp": str(ts),+ "signature": sig,+ "data_type": "audio",+ "signature_version": "1",+ }++ r = requests.post(ACR_BASE_URL, files=files_payload, data=form_data, timeout=HTTP_TIMEOUT)+ r.encoding = "utf-8"+ parsed = json.loads(r.text)++ meta = parsed.get("metadata", {})+ if "humming" in meta:+ items = meta["humming"]+ scored = []+ for itm in items:+ scored.append((+ itm.get("duration_ms"),+ itm.get("title"),+ itm.get("artists", [{}])[0].get("name"),+ itm.get("release_date"),+ itm.get("score"),+ ))+ scored.sort(key=lambda x: x[0] or 0, reverse=True)+ best = scored[0]+ return f"Name: {best[1]}, Artist: {best[2]}, Release Date: {best[3]}. Note: score={best[4]}"+ elif "music" in meta:+ itm = meta["music"][0]+ return f"Name: {itm['title']}, Artist: {itm['artists'][0]['name']}, Release Date: {itm['release_date']}."+ else:+ return f"Duration (seconds): {duration:.2f}\nACR: No metadata found for the given audio file."++ except Exception as err:+ return f"[ERROR]: Audio metadata identification failed: {err}\n"++ finally:+ if cleanup and os.path.exists(local_path):+ os.remove(local_path)diff --git a/jiuwenclaw/agentserver/tools/image_tools.py b/jiuwenclaw/agentserver/tools/image_tools.pynew file mode 100644index 0000000000..d56f2671e9--- /dev/null+++ b/jiuwenclaw/agentserver/tools/image_tools.py@@ -0,0 +1,293 @@+import argparse+import asyncio+import base64+import logging+import os+import sys+from pathlib import Path+from typing import Any++from dotenv import load_dotenv+from fastmcp import FastMCP+from google import genai+from google.genai import types+from openai import OpenAI+from openjiuwen.core.foundation.tool import McpServerConfig, tool+from openjiuwen.core.runner import Runner+import requests++from jiuwenclaw.agentserver.tools.multimodal_config import apply_vision_model_config_from_yaml++load_dotenv(verbose=True)++_SANDBOX_MARKER = "home/user"++mcp = FastMCP("vision-mcp-server")+_log = logging.getLogger(__name__)+++class _PathHelper:+ @staticmethod+ def is_sandbox(p: str) -> bool:+ return _SANDBOX_MARKER in p++ @staticmethod+ def to_https(u: str) -> str:+ if u.startswith("http://"):+ return u.replace("http://", "https://", 1)+ if not u.startswith("https://"):+ return "https://" + u+ return u+++class _MimeResolver:+ _EXT_MAP = {+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".png": "image/png",+ ".gif": "image/gif",+ ".webp": "image/webp",+ }++ @classmethod+ def from_path(cls, path: str) -> str:+ _, ext = os.path.splitext(path)+ return cls._EXT_MAP.get(ext.lower(), "image/jpeg")+++class _RetryExecutor:+ @staticmethod+ async def with_backoff(+ coro_factory,+ max_tries: int,+ base_delay: int = 4,+ on_failure=None,+ ) -> Any:+ last_err = None+ for i in range(1, max_tries + 1):+ try:+ return await coro_factory()+ except Exception as e:+ last_err = e+ if i == max_tries:+ if on_failure:+ return on_failure(max_tries, e)+ raise+ await asyncio.sleep(base_delay ** i)+ if on_failure and last_err:+ return on_failure(max_tries, last_err)+ raise RuntimeError("Retry exhausted")+++def _get_vision_api_credentials():+ k = os.environ.get("VISION_API_KEY") or os.environ.get("API_KEY", "")+ b = os.environ.get("VISION_API_BASE") or os.environ.get("API_BASE", "")+ m = os.environ.get("VISION_MODEL_NAME") or "gpt-4o"+ return k, b, m+++def _make_sandbox_error_msg() -> str:+ return (+ "The visual_question_answering tool cannot access to sandbox file, "+ "please use the local path provided by original instruction"+ )+++def _make_missing_key_error() -> str:+ return (+ "[ERROR]: VISION_API_KEY or API_KEY is not configured "+ "for vision question answering."+ )+++async def _invoke_openai_vision(src: str, q: str) -> str:+ api_key, api_base, model = _get_vision_api_credentials()+ if not api_key:+ return _make_missing_key_error()++ try:+ if os.path.exists(src):+ with open(src, "rb") as img_f:+ img_bytes = img_f.read()+ b64 = base64.b64encode(img_bytes).decode("utf-8")+ mime = _MimeResolver.from_path(src)+ img_block = {+ "type": "image_url",+ "image_url": {"url": f"data:{mime};base64,{b64}"},+ }+ elif _PathHelper.is_sandbox(src):+ return _make_sandbox_error_msg()+ else:+ img_block = {"type": "image_url", "image_url": {"url": src}}++ msgs = [{"role": "user", "content": [{"type": "text", "text": q}, img_block]}]++ async def _call():+ cli = OpenAI(api_key=api_key, base_url=api_base)+ r = cli.chat.completions.create(model=model, messages=msgs)+ txt = r.choices[0].message.content+ if not txt or not txt.strip():+ raise Exception("Response text is None or empty")+ return txt++ def _on_err(tries, exc):+ return f"Visual Question Answering (Client) failed after {tries} retries: {exc}\n"++ return await _RetryExecutor.with_backoff(_call, max_tries=3, on_failure=_on_err)++ except Exception as ex:+ return f"[ERROR]: OpenAI Error: {ex}"+++async def _invoke_gemini_vision(src: str, q: str) -> str:+ gemini_key = os.environ.get("GEMINI_API_KEY", "")+ if not gemini_key:+ return "[ERROR]: GEMINI_API_KEY is not configured for Gemini vision."++ try:+ mime = _MimeResolver.from_path(src)+ if os.path.exists(src):+ with open(src, "rb") as f:+ data = f.read()+ part = types.Part.from_bytes(data=data, mime_type=mime)+ elif _PathHelper.is_sandbox(src):+ return _make_sandbox_error_msg()+ else:+ ua = (+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "+ "(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"+ )+ data = None+ for attempt in range(4):+ try:+ r = requests.get(src, headers={"User-Agent": ua})+ r.raise_for_status()+ data = r.content+ break+ except Exception as err:+ if attempt == 3:+ raise err+ delays = [5, 15, 60]+ await asyncio.sleep(delays[attempt])+ part = types.Part.from_bytes(data=data, mime_type=mime)+ except Exception as e:+ return (+ f"[ERROR]: Failed to get image data {src}: {e}.\n"+ "Note: The visual_question_answering tool cannot access to sandbox file, "+ "please use the local path provided by original instruction or http url. "+ "If you are using http url, make sure it is an image file url."+ )++ retries = 0+ max_r = 3+ while retries <= max_r:+ try:+ cli = genai.Client(api_key=gemini_key)+ resp = cli.models.generate_content(+ model="gemini-2.5-pro",+ contents=[part, types.Part(text=q)],+ )+ if not resp.text or not resp.text.strip():+ raise Exception("Response text is None or empty")+ return resp.text+ except Exception as e:+ err_str = str(e)+ retry_codes = ["503", "429", "500", "Response text is None or empty"]+ if any(c in err_str for c in retry_codes):+ retries += 1+ if retries > max_r:+ return f"[ERROR]: Gemini Error after {retries} retries: {e}"+ if retries == 1:+ wt = random.randint(60, 300)+ elif retries == 2:+ wt = random.randint(60, 180)+ else:+ wt = 60+ await asyncio.sleep(wt)+ else:+ return f"[ERROR]: Gemini Error: {e}"+++_OCR_INSTRUCTIONS = (+ "You are an expert OCR engine. Examine the provided image thoroughly and "+ "transcribe every piece of visible text with high fidelity.\n\n"+ "GUIDELINES:\n"+ "- Perform a full sweep of the image — check every region including margins, "+ "corners, and overlapping areas.\n"+ "- Capture everything: titles, subtitles, annotations, footnotes, stamps, "+ "logos with text, watermarks, and any other textual elements.\n"+ "- Keep the original layout: respect paragraph breaks, indentation, and "+ "visual hierarchy.\n"+ "- Do not skip digits, punctuation marks, or special symbols.\n"+ "- After the first pass, re-examine the image to catch anything overlooked.\n"+ "- For illegible or partially hidden text, provide your best interpretation "+ "rather than omitting it. Note the uncertainty when applicable.\n\n"+ "The output will be consumed by a downstream system that has no visual "+ "access to this image. Therefore, err on the side of inclusion — report "+ "even tentative readings so that no information is silently dropped.\n\n"+ "Output the transcribed text only, preserving the original structure. "+ "Reply 'No text found' when the image contains no text whatsoever. "+ "For regions that might contain text but cannot be reliably read, "+ "include a brief description of what you observe."+)+++def _build_vqa_prompt(ocr_result: str, question: str) -> str:+ return (+ f"You are a detail-oriented visual analyst. Study the image carefully "+ f"and compose a well-reasoned answer to the user's question.\n\n"+ f"ANALYSIS GUIDELINES:\n"+ f"- Inspect the image repeatedly to notice subtle details — objects, "+ f"spatial layout, colors, text, and any faint or partially visible elements.\n"+ f"- Cross-validate your visual observations against the OCR transcript "+ f"provided below to ensure factual consistency.\n"+ f"- Reason through the question incrementally before giving a final answer; "+ f"this is especially important for questions involving multiple objects.\n"+ f"- Consider alternative interpretations of ambiguous regions before "+ f"committing to a single conclusion.\n"+ f"- Revisit specific areas of the image to confirm or revise your "+ f"initial impressions.\n"+ f"- Favor concrete, specific descriptions over vague generalizations.\n"+ f"- When you encounter blurry, occluded, or uncertain content, describe "+ f"what you observe in words instead of skipping it. It is better to "+ f"include a tentative observation than to omit potentially relevant information.\n\n"+ f"CONTEXT — OCR transcript (may be partial or contain errors):\n"+ f"{ocr_result}\n\n"+ f"QUESTION:\n"+ f"{question}\n\n"+ f"Deliver a thorough response grounded in careful observation. "+ f"Highlight any elements you are uncertain about.\n"+ f"If the subject is an animal, apply the following naming conventions:\n\n"+ f"ANIMAL NAMING RULES:\n"+ f"- Use only the simplest common name. Omit species or regional qualifiers "+ f"unless the user specifically asks for them. For example, say 'puffin' "+ f"instead of 'Atlantic puffin'.\n"+ f"- When multiple species are plausible, prefer the broader category.\n"+ f"- If you cannot determine the exact species, give the generic name and "+ f"only mention uncertainty when species-level identification is requested.\n"+ )+++@tool(+ name="visual_question_answering",+ description=(+ "Analyze and understand image content. Use this tool when the user provides "+ "an image file path (e.g., .jpg, .png, .gif) or image URL and asks questions "+ "about the image content, such as describing objects, scenes, text (OCR), "+ "or people in the image."+ ),+)+async def visual_question_answering(image_path_or_url: str, question: str) -> str:+ from jiuwenclaw.config import get_config+ try:+ apply_vision_model_config_from_yaml(get_config())+ except Exception:+ _log.debug("Failed to apply vision model config from yaml", exc_info=True)++ ocr_out = await _invoke_openai_vision(image_path_or_url, _OCR_INSTRUCTIONS)+ vqa_out = await _invoke_openai_vision(image_path_or_url, _build_vqa_prompt(ocr_out, question))+ _log.info("Visual Question Answering tool called via OpenRouter (Gemini model)")+ _log.info(f"OCR results: {ocr_out}")+ _log.info(f"VQA results: {vqa_out}")+ return f"OCR results:\n{ocr_out}\n\nVQA result:\n{vqa_out}"+diff --git a/jiuwenclaw/agentserver/tools/multimodal_config.py b/jiuwenclaw/agentserver/tools/multimodal_config.pynew file mode 100644index 0000000000..9afdbe42ab--- /dev/null+++ b/jiuwenclaw/agentserver/tools/multimodal_config.py@@ -0,0 +1,233 @@+# coding: utf-8+"""+多模态工具配置管理模块++配置优先级:+1. models.{audio/vision/video}.model_config+2. embed.{audio_model/video_model/vision_model} 和 embed.embed_api_key/embed_api_base+3. 环境变量 MODEL_NAME, API_KEY, API_BASE+"""+import os+from typing import Any+++def _parse_bool(val: Any, default: bool = False) -> bool:+ if val is None:+ return default+ if isinstance(val, bool):+ return val+ s = str(val).strip().lower()+ return s in ("1", "true", "yes", "on")+++def _get_embed_config(config_base: dict[str, Any]) -> dict[str, Any]:+ embed = config_base.get("embed", {})+ return embed if isinstance(embed, dict) else {}+++def _get_model_config(config_base: dict[str, Any], model_type: str) -> dict[str, Any]:+ """+ 从 config.yaml 中读取指定类型的模型配置++ Args:+ config_base: 配置字典+ model_type: 模型类型,如 'audio', 'vision', 'video'++ Returns:+ 模型配置字典+ """+ if not isinstance(config_base, dict):+ return {}++ raw_models = config_base.get("models")+ if isinstance(raw_models, dict):+ inner = raw_models.get(model_type)+ if isinstance(inner, dict):+ mc = inner.get("model_config") or inner.get("model_client_config")+ if isinstance(mc, dict):+ return mc+ return {}++ if not isinstance(raw_models, list):+ return {}++ for block in raw_models:+ if isinstance(block, dict) and model_type in block:+ inner = block.get(model_type)+ if isinstance(inner, dict):+ mc = inner.get("model_config") or inner.get("model_client_config")+ if isinstance(mc, dict):+ return mc+ return {}+++_EMBED_MODEL_KEY_MAP = {+ "audio": "audio_model",+ "vision": "vision_model",+ "video": "video_model",+}+++def _get_embed_model_name(embed_cfg: dict[str, Any], model_type: str) -> str:+ """+ 从 embed 配置中获取指定类型的模型名称++ Args:+ embed_cfg: embed 配置字典+ model_type: 模型类型,如 'audio', 'vision', 'video'++ Returns:+ 模型名称字符串+ """+ key = _EMBED_MODEL_KEY_MAP.get(model_type)+ if key and isinstance(embed_cfg, dict):+ return str(embed_cfg.get(key) or "").strip()+ return ""+++def apply_audio_model_config_from_yaml(config_base: dict[str, Any] | None) -> None:+ """+ 从 config.yaml 读取音频模型配置并设置环境变量++ 配置优先级:+ 1. models.audio.model_config+ 2. embed.audio_model + embed.embed_api_key/embed_api_base+ 3. 环境变量 MODEL_NAME, API_KEY, API_BASE+ """+ if not isinstance(config_base, dict):+ return++ mc = _get_model_config(config_base, "audio")+ embed_cfg = _get_embed_config(config_base)++ api_key = str(mc.get("api_key") or "").strip()+ api_base = str(mc.get("api_base") or "").strip()+ model_name = str(mc.get("model_name") or mc.get("model") or "").strip()+ provider = str(mc.get("model_provider") or "").strip()+ strict = _parse_bool(mc.get("strict"), default=False)++ if not strict:+ if not api_key:+ api_key = str(+ embed_cfg.get("embed_api_key") or os.getenv("API_KEY", "")+ ).strip()+ if not api_base:+ api_base = str(+ embed_cfg.get("embed_api_base") or os.getenv("API_BASE", "")+ ).strip()+ if not model_name:+ model_name = (+ _get_embed_model_name(embed_cfg, "audio")+ or os.getenv("MODEL_NAME", "").strip()+ )+ if not provider:+ provider = os.getenv("MODEL_PROVIDER", "").strip()++ if api_key:+ os.environ["AUDIO_API_KEY"] = api_key+ if api_base:+ os.environ["AUDIO_API_BASE"] = api_base+ if model_name:+ os.environ["AUDIO_MODEL_NAME"] = model_name+ if provider:+ os.environ["AUDIO_PROVIDER"] = provider+++def apply_vision_model_config_from_yaml(config_base: dict[str, Any] | None) -> None:+ """+ 从 config.yaml 读取图像模型配置并设置环境变量++ 配置优先级:+ 1. models.vision.model_config+ 2. embed.vision_model + embed.embed_api_key/embed_api_base+ 3. 环境变量 MODEL_NAME, API_KEY, API_BASE+ """+ if not isinstance(config_base, dict):+ return++ mc = _get_model_config(config_base, "vision")+ embed_cfg = _get_embed_config(config_base)++ api_key = str(mc.get("api_key") or "").strip()+ api_base = str(mc.get("api_base") or "").strip()+ model_name = str(mc.get("model_name") or mc.get("model") or "").strip()+ provider = str(mc.get("model_provider") or "").strip()+ strict = _parse_bool(mc.get("strict"), default=False)++ if not strict:+ if not api_key:+ api_key = str(+ embed_cfg.get("embed_api_key") or os.getenv("API_KEY", "")+ ).strip()+ if not api_base:+ api_base = str(+ embed_cfg.get("embed_api_base") or os.getenv("API_BASE", "")+ ).strip()+ if not model_name:+ model_name = (+ _get_embed_model_name(embed_cfg, "vision")+ or os.getenv("MODEL_NAME", "").strip()+ )+ if not provider:+ provider = os.getenv("MODEL_PROVIDER", "").strip()++ if api_key:+ os.environ["VISION_API_KEY"] = api_key+ if api_base:+ os.environ["VISION_API_BASE"] = api_base+ if model_name:+ os.environ["VISION_MODEL_NAME"] = model_name+ if provider:+ os.environ["VISION_PROVIDER"] = provider+++def apply_video_model_config_from_yaml(config_base: dict[str, Any] | None) -> None:+ """+ 从 config.yaml 读取视频模型配置并设置环境变量++ 配置优先级:+ 1. models.video.model_config+ 2. embed.video_model + embed.embed_api_key/embed_api_base+ 3. 环境变量 MODEL_NAME, API_KEY, API_BASE+ """+ if not isinstance(config_base, dict):+ os.environ.pop("VIDEO_UNDERSTANDING_STRICT", None)+ return++ mc = _get_model_config(config_base, "video")+ embed_cfg = _get_embed_config(config_base)++ api_key = str(mc.get("api_key") or "").strip()+ api_base = str(mc.get("api_base") or "").strip()+ model_name = str(mc.get("model_name") or mc.get("model") or "").strip()+ provider = str(mc.get("model_provider") or "").strip()+ strict = _parse_bool(mc.get("strict"), default=False)++ if strict:+ os.environ["VIDEO_UNDERSTANDING_STRICT"] = "1"+ else:+ os.environ.pop("VIDEO_UNDERSTANDING_STRICT", None)+ if not api_key:+ api_key = str(+ embed_cfg.get("embed_api_key") or os.getenv("API_KEY", "")+ ).strip()+ if not api_base:+ api_base = str(+ embed_cfg.get("embed_api_base") or os.getenv("API_BASE", "")+ ).strip()+ if not model_name:+ model_name = (+ _get_embed_model_name(embed_cfg, "video")+ or os.getenv("MODEL_NAME", "").strip()+ )+ if not provider:+ provider = os.getenv("MODEL_PROVIDER", "").strip()++ if api_key:+ os.environ["VIDEO_API_KEY"] = api_key+ if api_base:+ os.environ["VIDEO_API_BASE"] = api_base+ if model_name:+ os.environ["VIDEO_MODEL_NAME"] = model_name+ if provider:+ os.environ["VIDEO_PROVIDER"] = providerdiff --git a/jiuwenclaw/agentserver/tools/video_tools.py b/jiuwenclaw/agentserver/tools/video_tools.pynew file mode 100644index 0000000000..ad23bc8341--- /dev/null+++ b/jiuwenclaw/agentserver/tools/video_tools.py@@ -0,0 +1,225 @@+# coding: utf-8+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import asyncio+import base64+import mimetypes+import os+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import requests+from openjiuwen.core.foundation.tool import tool++from jiuwenclaw.config import get_config+from jiuwenclaw.utils import get_config_file, logger+from jiuwenclaw.agentserver.tools.multimodal_config import apply_video_model_config_from_yaml++_USER_AGENT = (+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "+ "AppleWebKit/537.36 (KHTML, like Gecko) "+ "Chrome/124.0.0.0 Safari/537.36"+)+_REQUEST_HEADERS = {+ "User-Agent": _USER_AGENT,+ "Content-Type": "application/json",+}++_SUPPORTED_VIDEO_MODEL_ALIASES = {+ "video_understanding",+ "video_tools.py",+ "jiuwenclaw/agentserver/tools/video_tools.py",+}+++def _normalize_video_model_selection(value: str) -> str:+ value = (value or "").strip()+ if value.startswith("@"):+ value = value[1:]+ value = value.replace("\\", "/")+ return value.lower()+++def _is_video_model_supported(selection: str) -> bool:+ normalized = _normalize_video_model_selection(selection)+ if not normalized:+ return True+ if normalized in _SUPPORTED_VIDEO_MODEL_ALIASES:+ return True+ return any(normalized.endswith(alias) for alias in _SUPPORTED_VIDEO_MODEL_ALIASES)+++@dataclass(frozen=True)+class VideoUnderstandingRequest:+ query: str+ video_path: str+ model: str = "glm-4.6v"+ timeout_seconds: int = 120+ max_tokens: int = 2048+ temperature: float = 0.2+ thinking_enabled: bool = False+++def _http_post(url: str, **kwargs) -> requests.Response:+ try:+ return requests.post(url, **kwargs)+ except requests.exceptions.ProxyError:+ with requests.Session() as session:+ session.trust_env = False+ return session.post(url, **kwargs)+++def _guess_video_mime(path: str) -> str:+ mime, _ = mimetypes.guess_type(path)+ if mime and mime.startswith("video/"):+ return mime+ ext = Path(path).suffix.lower()+ mapping = {+ ".mp4": "video/mp4", ".mov": "video/quicktime", ".avi": "video/x-msvideo",+ ".mkv": "video/x-matroska", ".webm": "video/webm", ".mpeg": "video/mpeg",+ ".mpg": "video/mpeg", ".m4v": "video/x-m4v",+ }+ return mapping.get(ext, "video/mp4")+++def _video_path_to_url(video_path: str) -> str:+ value = (video_path or "").strip()+ if not value:+ raise ValueError("video_path cannot be empty")+ if value.startswith(("http://", "https://")):+ return value+ path = Path(value).expanduser().resolve()+ if not path.exists():+ raise FileNotFoundError(f"video file does not exist: {path}")+ if not path.is_file():+ raise ValueError(f"video_path is not a file: {path}")+ mime = _guess_video_mime(str(path))+ with open(path, "rb") as f:+ encoded = base64.b64encode(f.read()).decode("utf-8")+ return f"data:{mime};base64,{encoded}"+++def _extract_answer(data: dict[str, Any]) -> str:+ choices = data.get("choices")+ if not isinstance(choices, list) or not choices:+ return ""+ first = choices[0]+ if not isinstance(first, dict):+ return ""+ message = first.get("message", {})+ if not isinstance(message, dict):+ return ""+ content = message.get("content", "")+ if isinstance(content, str):+ return content.strip()+ if isinstance(content, list):+ texts = [str(item.get("text")) for item in content if isinstance(item, dict) and item.get("text")]+ return "\n".join(texts).strip()+ return str(content).strip()+++def _normalize_request(inputs: dict[str, Any]) -> VideoUnderstandingRequest:+ query = str(inputs.get("query", "") or "").strip()+ video_path = str(inputs.get("video_path", "") or "").strip()+ default_model = (os.environ.get("VIDEO_MODEL_NAME") or "glm-4.6v").strip() or "glm-4.6v"+ model = str(inputs.get("model", default_model) or default_model).strip()+ timeout_seconds = max(10, min(int(inputs.get("timeout_seconds", 120)), 600))+ max_tokens = max(128, min(int(inputs.get("max_tokens", 2048)), 8192))+ temperature = max(0.0, min(float(inputs.get("temperature", 0.2)), 2.0))+ thinking_enabled = bool(inputs.get("thinking_enabled", False))++ if not query:+ raise ValueError("query cannot be empty.")+ if not video_path:+ raise ValueError("video_path cannot be empty.")++ return VideoUnderstandingRequest(+ query=query, video_path=video_path, model=model,+ timeout_seconds=timeout_seconds, max_tokens=max_tokens,+ temperature=temperature, thinking_enabled=thinking_enabled,+ )+++def _resolve_chat_completions_url(base: str) -> str:+ b = (base or "").strip().rstrip("/")+ if not b:+ return ""+ return b if b.endswith("/chat/completions") else f"{b}/chat/completions"+++def _glm_video_understanding_sync(req: VideoUnderstandingRequest) -> str:+ yaml_key = os.environ.get("VIDEO_API_KEY", "").strip()+ yaml_base = os.environ.get("VIDEO_API_BASE", "").strip()++ if yaml_key and yaml_base:+ api_key = yaml_key+ api_url = _resolve_chat_completions_url(yaml_base)+ elif yaml_key and not yaml_base:+ raise ValueError("VIDEO_API_BASE is required when VIDEO_API_KEY is set.")+ else:+ api_key = os.environ.get("ZHIPU_API_KEY", "").strip()+ if not api_key:+ raise ValueError(+ f"No video API credentials. Config file: {get_config_file()}\n"+ "Set models.video.model_config with api_key and api_base, or set ZHIPU_API_KEY."+ )+ api_url = os.environ.get("ZHIPU_API_URL", "https://open.bigmodel.cn/api/paas/v4/chat/completions").strip()++ video_url = _video_path_to_url(req.video_path)++ payload = {+ "model": req.model,+ "messages": [{+ "role": "user",+ "content": [+ {"type": "video_url", "video_url": {"url": video_url}},+ {"type": "text", "text": req.query},+ ],+ }],+ "stream": False,+ "max_tokens": req.max_tokens,+ "temperature": req.temperature,+ }++ if req.thinking_enabled:+ payload["thinking"] = {"type": "enabled"}++ headers = {**_REQUEST_HEADERS, "Authorization": f"Bearer {api_key}"}+ response = _http_post(api_url, headers=headers, json=payload, timeout=req.timeout_seconds)++ if not response.ok:+ try:+ error_data = response.json()+ error_msg = error_data.get("error", {}).get("message", response.text[:200])+ except Exception:+ error_msg = response.text[:200]+ raise ValueError(f"API error {response.status_code}: {error_msg}")++ answer = _extract_answer(response.json())+ return answer if answer else "[ERROR]: GLM returned empty answer."+++@tool(+ name="video_understanding",+ description=(+ "Analyze and understand video content. "+ "Use this tool when the user provides a video file path (e.g., .mp4, .mov, .avi) "+ "or video URL and asks questions about the video content, such as describing "+ "scenes, actions, people, or objects in the video. "+ "Input: query (question about the video) and video_path (local file path or HTTP/HTTPS URL)."+ ),+)+async def video_understanding(inputs: dict[str, Any], **kwargs) -> str:+ _ = kwargs+ try:+ try:+ apply_video_model_config_from_yaml(get_config())+ except Exception as e:+ logger.warning("[video_understanding] refresh config failed: %s", e)+ req = _normalize_request(inputs or {})+ return await asyncio.to_thread(_glm_video_understanding_sync, req)+ except Exception as exc:+ return f"[ERROR]: glm video understanding failed: {exc}"diff --git a/jiuwenclaw/agentserver/tools/video_understanding.py b/jiuwenclaw/agentserver/tools/video_understanding.pydeleted file mode 100644index 0cb2823506..0000000000--- a/jiuwenclaw/agentserver/tools/video_understanding.py+++ /dev/null@@ -1,226 +0,0 @@-# coding: utf-8-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.--from __future__ import annotations--import asyncio-import base64-import mimetypes-import os-from dataclasses import dataclass-from pathlib import Path-from typing import Any--import requests-from openjiuwen.core.foundation.tool import tool--_USER_AGENT = (- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "- "AppleWebKit/537.36 (KHTML, like Gecko) "- "Chrome/124.0.0.0 Safari/537.36"-)-_REQUEST_HEADERS = {- "User-Agent": _USER_AGENT,- "Content-Type": "application/json",-}---@dataclass(frozen=True)-class VideoUnderstandingRequest:- query: str- video_path: str- model: str = "glm-4.6v"- timeout_seconds: int = 120- max_tokens: int = 2048- temperature: float = 0.2- thinking_enabled: bool = False---def _http_post(url: str, **kwargs) -> requests.Response:- """Try normal request first; retry without env proxies on ProxyError."""- try:- return requests.post(url, **kwargs)- except requests.exceptions.ProxyError:- with requests.Session() as session:- session.trust_env = False- return session.post(url, **kwargs)---def _guess_video_mime(path: str) -> str:- mime, _ = mimetypes.guess_type(path)- if mime and mime.startswith("video/"):- return mime-- ext = Path(path).suffix.lower()- mapping = {- ".mp4": "video/mp4",- ".mov": "video/quicktime",- ".avi": "video/x-msvideo",- ".mkv": "video/x-matroska",- ".webm": "video/webm",- ".mpeg": "video/mpeg",- ".mpg": "video/mpeg",- ".m4v": "video/x-m4v",- }- return mapping.get(ext, "video/mp4")---def _video_path_to_url(video_path: str) -> str:- """Convert a local video path to data URI, or keep remote URL as-is."""- value = (video_path or "").strip()- if not value:- raise ValueError("video_path cannot be empty")-- if value.startswith(("http://", "https://")):- return value-- path = Path(value).expanduser().resolve()- if not path.exists():- raise FileNotFoundError(f"video file does not exist: {path}")- if not path.is_file():- raise ValueError(f"video_path is not a file: {path}")-- mime = _guess_video_mime(str(path))- with open(path, "rb") as f:- encoded = base64.b64encode(f.read()).decode("utf-8")-- # Best-effort local-path support. If the API side rejects data URI for video,- # upload the file to an accessible HTTP(S) URL and pass that URL instead.- return f"data:{mime};base64,{encoded}"---def _extract_answer(data: dict[str, Any]) -> str:- choices = data.get("choices")- if not isinstance(choices, list) or not choices:- return ""-- first = choices[0]- if not isinstance(first, dict):- return ""-- message = first.get("message", {})- if not isinstance(message, dict):- return ""-- content = message.get("content", "")- if isinstance(content, str):- return content.strip()-- # Compatible fallback for structured content arrays.- if isinstance(content, list):- texts: list[str] = []- for item in content:- if isinstance(item, dict):- text = item.get("text")- if text:- texts.append(str(text))- return "\n".join(texts).strip()-- return str(content).strip()---def _normalize_request(inputs: dict[str, Any]) -> VideoUnderstandingRequest:- query = str(inputs.get("query", "") or "").strip()- video_path = str(inputs.get("video_path", "") or "").strip()- model = str(inputs.get("model", "glm-4.6v") or "glm-4.6v").strip()-- timeout_seconds = int(inputs.get("timeout_seconds", 120))- max_tokens = int(inputs.get("max_tokens", 2048))- temperature = float(inputs.get("temperature", 0.2))- thinking_enabled = bool(inputs.get("thinking_enabled", False))-- if not query:- raise ValueError("query cannot be empty.")- if not video_path:- raise ValueError("video_path cannot be empty.")-- timeout_seconds = max(10, min(timeout_seconds, 600))- max_tokens = max(128, min(max_tokens, 8192))- temperature = max(0.0, min(temperature, 2.0))-- return VideoUnderstandingRequest(- query=query,- video_path=video_path,- model=model,- timeout_seconds=timeout_seconds,- max_tokens=max_tokens,- temperature=temperature,- thinking_enabled=thinking_enabled,- )---def _glm_video_understanding_sync(req: VideoUnderstandingRequest) -> str:- api_key = os.environ.get("ZHIPU_API_KEY", "").strip()- if not api_key:- raise ValueError("ZHIPU_API_KEY is not set")-- api_url = os.environ.get(- "ZHIPU_API_URL",- "https://open.bigmodel.cn/api/paas/v4/chat/completions",- ).strip()-- video_url = _video_path_to_url(req.video_path)-- payload: dict[str, Any] = {- "model": req.model,- "messages": [- {- "role": "user",- "content": [- {- "type": "video_url",- "video_url": {- "url": video_url,- },- },- {- "type": "text",- "text": req.query,- },- ],- }- ],- "stream": False,- "max_tokens": req.max_tokens,- "temperature": req.temperature,- }-- if req.thinking_enabled:- payload["thinking"] = {"type": "enabled"}-- headers = {- **_REQUEST_HEADERS,- "Authorization": f"Bearer {api_key}",- }-- response = _http_post(- api_url,- headers=headers,- json=payload,- timeout=req.timeout_seconds,- )- response.raise_for_status()- data = response.json()-- answer = _extract_answer(data)- if not answer:- return "[ERROR]: GLM returned empty answer."-- return answer---@tool(- name="video_understanding",- description=(- "Use GLM-4.6V to understand a video and answer a user query. "- "Input query and video_path. HTTP/HTTPS video URL is preferred; "- "local file path is supported on a best-effort basis."- ),-)-async def video_understanding(inputs: dict[str, Any], **kwargs) -> str:- _ = kwargs- try:- req = _normalize_request(inputs or {})- return await asyncio.to_thread(_glm_video_understanding_sync, req)- except Exception as exc:- return f"[ERROR]: glm video understanding failed: {exc}"\ No newline at end of filediff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.pyindex 688d217a9f..18d6cf541c 100644--- a/jiuwenclaw/config.py+++ b/jiuwenclaw/config.py@@ -42,8 +42,15 @@ def resolve_env_vars(value: Any) -> Any:def replace_env(match):var_name = match.group(1)- default = match.group(2) if match.group(2) is not None else ""- return os.getenv(var_name, default)+ default = match.group(2)+ current = os.getenv(var_name)+ # Bash: ${VAR:-default} uses default when VAR is unset OR empty.+ # ${VAR} (no :-) keeps getenv behavior; unset -> "".+ if default is not None:+ if current is None or current == "":+ return default+ return current+ return current if current is not None else ""return re.sub(pattern, replace_env, value)elif isinstance(value, dict):diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yamlindex 468c8f6a8f..008aad5681 100644--- a/jiuwenclaw/resources/config.yaml+++ b/jiuwenclaw/resources/config.yaml@@ -42,7 +42,7 @@ models:timeout: 1800model_config_obj:temperature: 0.95-+react:agent_name: main_agentmax_iterations: 100