Skip to content

Build and run agents you can see, understand and trust.

fix(formatter): download remote image URLs to base64 for Moonshot API (#1653)

qbcc9b36a150d8b
diff --git a/scripts/model_examples/anthropic_call.py b/scripts/model_examples/anthropic_call.py
index f398f07a5..df8ab77f8 100644
--- a/scripts/model_examples/anthropic_call.py
+++ b/scripts/model_examples/anthropic_call.py
@@ -35,7 +35,7 @@ async def example_simple_call() -> None:
context_size=1_000_000,
parameters=AnthropicChatModel.Parameters(
thinking_enable=True,
- thinking_budget=4096,
+ thinking_budget=1024,
),
)
@@ -82,7 +82,7 @@ async def example_tool_call() -> None:
context_size=1_000_000,
parameters=AnthropicChatModel.Parameters(
thinking_enable=True,
- thinking_budget=4096,
+ thinking_budget=1024,
),
)
@@ -158,7 +158,7 @@ async def example_structured_output() -> None:
context_size=1_000_000,
parameters=AnthropicChatModel.Parameters(
thinking_enable=True,
- thinking_budget=4096,
+ thinking_budget=1024,
),
)
diff --git a/scripts/model_examples/anthropic_multiagent.py b/scripts/model_examples/anthropic_multiagent.py
index b28009cb7..7d529e0fe 100644
--- a/scripts/model_examples/anthropic_multiagent.py
+++ b/scripts/model_examples/anthropic_multiagent.py
@@ -31,6 +31,10 @@ async def example_multiagent() -> None:
model="claude-opus-4-5",
stream=True,
context_size=1_000_000,
+ parameters=AnthropicChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=1024,
+ ),
formatter=formatter,
)
diff --git a/scripts/model_examples/anthropic_multiagent_multimodal.py b/scripts/model_examples/anthropic_multiagent_multimodal.py
index add7040d3..873ef0699 100644
--- a/scripts/model_examples/anthropic_multiagent_multimodal.py
+++ b/scripts/model_examples/anthropic_multiagent_multimodal.py
@@ -32,6 +32,10 @@ async def example_multiagent_image_url() -> None:
model="claude-opus-4-5",
stream=True,
context_size=1_000_000,
+ parameters=AnthropicChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=1024,
+ ),
formatter=formatter,
)
diff --git a/scripts/model_examples/anthropic_multimodal.py b/scripts/model_examples/anthropic_multimodal.py
index 9b5bd0db5..78830c50b 100644
--- a/scripts/model_examples/anthropic_multimodal.py
+++ b/scripts/model_examples/anthropic_multimodal.py
@@ -33,6 +33,10 @@ async def example_image_url() -> None:
model="claude-opus-4-5",
stream=True,
context_size=1_000_000,
+ parameters=AnthropicChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=1024,
+ ),
)
image_block = DataBlock(
@@ -68,6 +72,10 @@ def _build_model() -> AnthropicChatModel:
model="claude-opus-4-5",
stream=True,
context_size=1_000_000,
+ parameters=AnthropicChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=1024,
+ ),
)
diff --git a/scripts/model_examples/dashscope_multiagent.py b/scripts/model_examples/dashscope_multiagent.py
index 8a08a33d8..132fd9ed7 100644
--- a/scripts/model_examples/dashscope_multiagent.py
+++ b/scripts/model_examples/dashscope_multiagent.py
@@ -30,6 +30,7 @@ async def example_multiagent() -> None:
model="qwen3.5-plus",
stream=True,
context_size=1_000_000,
+ parameters=DashScopeChatModel.Parameters(thinking_enable=True),
formatter=formatter,
)
diff --git a/scripts/model_examples/dashscope_multiagent_multimodal.py b/scripts/model_examples/dashscope_multiagent_multimodal.py
index 76f1b4976..441a9db07 100644
--- a/scripts/model_examples/dashscope_multiagent_multimodal.py
+++ b/scripts/model_examples/dashscope_multiagent_multimodal.py
@@ -31,6 +31,7 @@ async def example_multiagent_image_url() -> None:
model="qwen3.5-plus",
stream=True,
context_size=1_000_000,
+ parameters=DashScopeChatModel.Parameters(thinking_enable=True),
formatter=formatter,
)
diff --git a/scripts/model_examples/dashscope_multimodal.py b/scripts/model_examples/dashscope_multimodal.py
index 973a0de2b..4cae6c3ee 100644
--- a/scripts/model_examples/dashscope_multimodal.py
+++ b/scripts/model_examples/dashscope_multimodal.py
@@ -44,6 +44,7 @@ async def example_image_url() -> None:
model="qwen3.5-plus",
stream=True,
context_size=1_000_000,
+ parameters=DashScopeChatModel.Parameters(thinking_enable=True),
)
image_block = DataBlock(
@@ -79,6 +80,7 @@ def _build_model() -> DashScopeChatModel:
model="qwen3.5-plus",
stream=True,
context_size=1_000_000,
+ parameters=DashScopeChatModel.Parameters(thinking_enable=True),
)
diff --git a/scripts/model_examples/deepseek_call.py b/scripts/model_examples/deepseek_call.py
index 4854e515d..d49459282 100644
--- a/scripts/model_examples/deepseek_call.py
+++ b/scripts/model_examples/deepseek_call.py
@@ -1,9 +1,11 @@
# -*- coding: utf-8 -*-
"""Examples of DeepSeek model calls.
-For DeepSeek, thinking (chain-of-thought) is controlled by model selection:
- - deepseek-reasoner: always reasoning (uses reasoning_content field)
- - deepseek-v4-flash: non-thinking mode
+For DeepSeek, thinking (chain-of-thought) is controlled by the
+``thinking_enable`` parameter on ``deepseek-v4-flash``. The legacy
+``deepseek-chat`` / ``deepseek-reasoner`` model names will be deprecated;
+they correspond to the non-thinking / thinking modes of
+``deepseek-v4-flash`` respectively.
"""
import asyncio
import json
@@ -30,14 +32,15 @@ from agentscope.tool import Toolkit, ToolChoice, FunctionTool
async def example_simple_call() -> None:
- """Call the DeepSeek reasoning model with a simple text message."""
+ """Call DeepSeek with thinking enabled on a simple text message."""
model = DeepSeekChatModel(
credential=DeepSeekCredential(
api_key=os.environ["DEEPSEEK_API_KEY"],
),
- model="deepseek-reasoner",
+ model="deepseek-v4-flash",
stream=True,
- context_size=65_536,
+ context_size=1_000_000,
+ parameters=DeepSeekChatModel.Parameters(thinking_enable=True),
)
msgs = [
@@ -70,11 +73,7 @@ def get_weather(city: str) -> str:
async def example_tool_call() -> None:
- """Call the DeepSeek model with tool calling enabled.
-
- Uses deepseek-v4-flash (non-reasoning) for tool calling, since
- deepseek-reasoner has limited tool call support.
- """
+ """Call DeepSeek with thinking + tool calling enabled."""
toolkit = Toolkit(tools=[FunctionTool(get_weather)])
tools = await toolkit.get_tool_schemas()
@@ -84,7 +83,8 @@ async def example_tool_call() -> None:
),
model="deepseek-v4-flash",
stream=True,
- context_size=65_536,
+ context_size=1_000_000,
+ parameters=DeepSeekChatModel.Parameters(thinking_enable=True),
)
msgs = [
@@ -149,17 +149,15 @@ class MathSolution(BaseModel):
async def example_structured_output() -> None:
- """Call the DeepSeek reasoning model and force a structured output.
-
- Uses deepseek-reasoner — the reasoning model with chain-of-thought.
- """
+ """Call DeepSeek with thinking enabled and force a structured output."""
model = DeepSeekChatModel(
credential=DeepSeekCredential(
api_key=os.environ["DEEPSEEK_API_KEY"],
),
- model="deepseek-reasoner",
+ model="deepseek-v4-flash",
stream=True,
- context_size=65_536,
+ context_size=1_000_000,
+ parameters=DeepSeekChatModel.Parameters(thinking_enable=True),
)
msgs = [
diff --git a/scripts/model_examples/deepseek_multiagent.py b/scripts/model_examples/deepseek_multiagent.py
index e4f992d5e..c3cc5ef46 100644
--- a/scripts/model_examples/deepseek_multiagent.py
+++ b/scripts/model_examples/deepseek_multiagent.py
@@ -31,6 +31,7 @@ async def example_multiagent() -> None:
model="deepseek-v4-flash",
stream=True,
context_size=1_000_000,
+ parameters=DeepSeekChatModel.Parameters(thinking_enable=True),
formatter=formatter,
)
diff --git a/scripts/model_examples/gemini_call.py b/scripts/model_examples/gemini_call.py
index c99f5388f..c557e90fa 100644
--- a/scripts/model_examples/gemini_call.py
+++ b/scripts/model_examples/gemini_call.py
@@ -35,7 +35,7 @@ async def example_simple_call() -> None:
context_size=1_048_576,
parameters=GeminiChatModel.Parameters(
thinking_enable=True,
- thinking_budget=8192,
+ thinking_budget=1024,
),
)
@@ -82,7 +82,7 @@ async def example_tool_call() -> None:
context_size=1_048_576,
parameters=GeminiChatModel.Parameters(
thinking_enable=True,
- thinking_budget=8192,
+ thinking_budget=1024,
),
)
@@ -158,7 +158,7 @@ async def example_structured_output() -> None:
context_size=1_048_576,
parameters=GeminiChatModel.Parameters(
thinking_enable=True,
- thinking_budget=8192,
+ thinking_budget=1024,
),
)
diff --git a/scripts/model_examples/gemini_multiagent.py b/scripts/model_examples/gemini_multiagent.py
index 74d5e4ab2..8a28b7ab1 100644
--- a/scripts/model_examples/gemini_multiagent.py
+++ b/scripts/model_examples/gemini_multiagent.py
@@ -31,6 +31,10 @@ async def example_multiagent() -> None:
model="gemini-2.5-flash",
stream=True,
context_size=1_048_576,
+ parameters=GeminiChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=1024,
+ ),
formatter=formatter,
)
diff --git a/scripts/model_examples/gemini_multiagent_multimodal.py b/scripts/model_examples/gemini_multiagent_multimodal.py
index a9867a8ec..1ac6d9154 100644
--- a/scripts/model_examples/gemini_multiagent_multimodal.py
+++ b/scripts/model_examples/gemini_multiagent_multimodal.py
@@ -26,6 +26,10 @@ async def example_multiagent_image_url() -> None:
model="gemini-2.5-flash",
stream=True,
context_size=1_048_576,
+ parameters=GeminiChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=1024,
+ ),
formatter=formatter,
)
diff --git a/scripts/model_examples/gemini_multimodal.py b/scripts/model_examples/gemini_multimodal.py
index ed78c4fe0..665597d9a 100644
--- a/scripts/model_examples/gemini_multimodal.py
+++ b/scripts/model_examples/gemini_multimodal.py
@@ -32,6 +32,10 @@ async def example_image_url() -> None:
model="gemini-2.5-flash",
stream=True,
context_size=1_048_576,
+ parameters=GeminiChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=1024,
+ ),
)
image_block = DataBlock(
@@ -64,6 +68,10 @@ def _build_model() -> GeminiChatModel:
model="gemini-2.5-flash",
stream=True,
context_size=1_048_576,
+ parameters=GeminiChatModel.Parameters(
+ thinking_enable=True,
+ thinking_budget=1024,
+ ),
)
diff --git a/scripts/model_examples/moonshot_multiagent.py b/scripts/model_examples/moonshot_multiagent.py
index e3929ea1e..65bd99ed3 100644
--- a/scripts/model_examples/moonshot_multiagent.py
+++ b/scripts/model_examples/moonshot_multiagent.py
@@ -30,6 +30,7 @@ async def example_multiagent() -> None:
model="kimi-k2.6",
stream=True,
context_size=262_144,
+ parameters=MoonshotChatModel.Parameters(thinking_enable=True),
formatter=formatter,
)
diff --git a/scripts/model_examples/moonshot_multiagent_multimodal.py b/scripts/model_examples/moonshot_multiagent_multimodal.py
index 86c1f5655..0f15cabb4 100644
--- a/scripts/model_examples/moonshot_multiagent_multimodal.py
+++ b/scripts/model_examples/moonshot_multiagent_multimodal.py
@@ -27,6 +27,7 @@ async def example_multiagent_image_url() -> None:
model="kimi-k2.6",
stream=True,
context_size=262_144,
+ parameters=MoonshotChatModel.Parameters(thinking_enable=True),
formatter=formatter,
)
diff --git a/scripts/model_examples/moonshot_multimodal.py b/scripts/model_examples/moonshot_multimodal.py
index 4300975c8..498e3c583 100644
--- a/scripts/model_examples/moonshot_multimodal.py
+++ b/scripts/model_examples/moonshot_multimodal.py
@@ -16,7 +16,6 @@ from agentscope.message import (
from agentscope.model import MoonshotChatModel
from agentscope.credential import MoonshotCredential
-# A publicly accessible test image (a simple cat photo)
TEST_IMAGE_URL = (
"https://help-static-aliyun-doc.aliyuncs.com/file-manage"
"-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
@@ -32,6 +31,7 @@ async def example_image_url() -> None:
model="kimi-k2.6",
stream=True,
context_size=262_144,
+ parameters=MoonshotChatModel.Parameters(thinking_enable=True),
)
image_block = DataBlock(
@@ -64,6 +64,7 @@ def _build_model() -> MoonshotChatModel:
model="kimi-k2.6",
stream=True,
context_size=262_144,
+ parameters=MoonshotChatModel.Parameters(thinking_enable=True),
)
diff --git a/scripts/model_examples/ollama_multiagent.py b/scripts/model_examples/ollama_multiagent.py
index 2af53a5d1..34ed419c3 100644
--- a/scripts/model_examples/ollama_multiagent.py
+++ b/scripts/model_examples/ollama_multiagent.py
@@ -25,6 +25,7 @@ async def example_multiagent() -> None:
model="qwen3:14b",
stream=True,
context_size=40_960,
+ parameters=OllamaChatModel.Parameters(thinking_enable=True),
formatter=formatter,
)
diff --git a/src/agentscope/formatter/_moonshot_formatter.py b/src/agentscope/formatter/_moonshot_formatter.py
index b320c82e2..7fdf59ba6 100644
--- a/src/agentscope/formatter/_moonshot_formatter.py
+++ b/src/agentscope/formatter/_moonshot_formatter.py
@@ -1,13 +1,17 @@
# -*- coding: utf-8 -*-
"""The Moonshot AI formatter for agentscope."""
+import base64
from typing import Any
+import requests
from pydantic import Field
from ._openai_formatter import _OpenAIFormatterBase
from .._logging import logger
from ..message import (
Msg,
+ URLSource,
+ Base64Source,
TextBlock,
DataBlock,
ThinkingBlock,
@@ -17,6 +21,41 @@ from ..message import (
)
+def _moonshot_format_image_source(
+ source: URLSource | Base64Source,
+) -> dict[str, Any]:
+ """Convert an image source to Moonshot ``image_url`` format.
+
+ Moonshot's vision API only accepts base64 data URIs or file IDs — raw
+ remote URLs are rejected. This helper downloads remote ``http(s)://``
+ URLs and converts them to base64 data URIs, while ``file://`` URLs and
+ ``Base64Source`` go through the same conversion as the OpenAI base.
+ """
+ if isinstance(source, Base64Source):
+ url = f"data:{source.media_type};base64,{source.data}"
+
+ elif isinstance(source, URLSource):
+ url_str = str(source.url)
+ if url_str.startswith("file://"):
+ local_path = url_str.removeprefix("file://")
+ with open(local_path, "rb") as f:
+ encoded = base64.b64encode(f.read()).decode("utf-8")
+ url = f"data:{source.media_type};base64,{encoded}"
+ else:
+ response = requests.get(url_str, timeout=30)
+ response.raise_for_status()
+ encoded = base64.b64encode(response.content).decode("utf-8")
+ url = f"data:{source.media_type};base64,{encoded}"
+
+ else:
+ raise ValueError(f"Unsupported image source type: {type(source)}")
+
+ return {
+ "type": "image_url",
+ "image_url": {"url": url},
+ }
+
+
class MoonshotChatFormatter(_OpenAIFormatterBase):
"""The Moonshot AI formatter for chatbot scenario.
@@ -35,6 +74,12 @@ class MoonshotChatFormatter(_OpenAIFormatterBase):
),
)
+ def _format_image_source(
+ self,
+ source: URLSource | Base64Source,
+ ) -> dict[str, Any]:
+ return _moonshot_format_image_source(source)
+
async def format(
self,
msgs: list[Msg],
@@ -245,6 +290,12 @@ class MoonshotMultiAgentFormatter(_OpenAIFormatterBase):
),
)
+ def _format_image_source(
+ self,
+ source: URLSource | Base64Source,
+ ) -> dict[str, Any]:
+ return _moonshot_format_image_source(source)
+
async def format(self, msgs: list[Msg]) -> list[dict[str, Any]]:
"""Format input messages into the Moonshot AI API format for
multi-agent conversations.
diff --git a/src/agentscope/formatter/_openai_formatter.py b/src/agentscope/formatter/_openai_formatter.py
index d1a9212b4..ec4354b73 100644
--- a/src/agentscope/formatter/_openai_formatter.py
+++ b/src/agentscope/formatter/_openai_formatter.py
@@ -83,14 +83,17 @@ class _OpenAIFormatterBase(FormatterBase, ABC):
)
return None
- @staticmethod
def _format_image_source(
+ self,
source: URLSource | Base64Source,
) -> dict[str, Any]:
"""Convert an image source to OpenAI image_url format.
Local ``file://`` URLs are read from disk and converted to base64
- data URIs. Remote URLs are passed through unchanged.
+ data URIs. Remote URLs are passed through unchanged. Subclasses may
+ override this to apply provider-specific handling (e.g. forcing
+ remote URLs to be downloaded and base64-encoded for APIs that don't
+ accept raw HTTPS URLs).
Args:
source (`URLSource | Base64Source`):
@@ -177,7 +180,7 @@ class _OpenAIFormatterBase(FormatterBase, ABC):
f"Unsupported audio file extension: {extension}, "
"wav and mp3 are supported.",
)
- response = requests.get(url_str)
+ response = requests.get(url_str, timeout=30)
response.raise_for_status()
data = base64.b64encode(response.content).decode("utf-8")
diff --git a/src/agentscope/model/_deepseek/_model.py b/src/agentscope/model/_deepseek/_model.py
index 5f6974d1d..d05a84bb2 100644
--- a/src/agentscope/model/_deepseek/_model.py
+++ b/src/agentscope/model/_deepseek/_model.py
@@ -2,12 +2,12 @@
"""The DeepSeek chat model implementation."""
from collections import OrderedDict
from datetime import datetime
-from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List
+from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List, Type
from pydantic import BaseModel, Field
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
-from .._model_response import ChatResponse
+from .._model_response import ChatResponse, StructuredResponse
from .._model_usage import ChatUsage
from ...credential import DeepSeekCredential
from ...formatter import FormatterBase, DeepSeekChatFormatter
@@ -427,3 +427,50 @@ class DeepSeekChatModel(ChatModelBase):
return tools, {"type": "function", "function": {"name": mode}}
return tools, mode
+
+ async def _call_api_with_structured_output(
+ self,
+ model_name: str,
+ messages: list[Msg],
+ structured_model: Type[BaseModel] | dict,
+ tool_choice: ToolChoice | None = None,
+ **kwargs: Any,
+ ) -> StructuredResponse:
+ """DeepSeek-specific override for structured output.
+
+ DeepSeek rejects ``tool_choice="required"`` or an object-form
+ ``tool_choice`` when thinking mode is enabled. In that case we
+ default ``tool_choice`` to ``"auto"`` and rely on the base class's
+ injected system-reminder prompt to guide the model. When thinking
+ is disabled, this falls through to the base implementation.
+
+ Args:
+ model_name (`str`):
+ The model name to use for this call.
+ messages (`list[Msg]`):
+ The context for the LLM to generate the structured output.
+ structured_model (`Type[BaseModel] | dict`):
+ A Pydantic model class or a JSON schema dict describing the
+ required output structure.
+ tool_choice (`ToolChoice | None`, defaults to `None`):
+ The tool_choice forwarded to ``_call_api``. When ``None``
+ and thinking mode is enabled, it is downgraded to
+ ``ToolChoice(mode="auto")``; otherwise the base default
+ (force the structured-output tool) is used.
+ **kwargs (`Any`):
+ Additional keyword arguments forwarded to ``_call_api``.
+
+ Returns:
+ `StructuredResponse`:
+ The structured response whose ``content`` is the validated
+ output dict matching ``structured_model``.
+ """
+ if tool_choice is None and self.parameters.thinking_enable:
+ tool_choice = ToolChoice(mode="auto")
+ return await super()._call_api_with_structured_output(
+ model_name=model_name,
+ messages=messages,
+ structured_model=structured_model,
+ tool_choice=tool_choice,
+ **kwargs,
+ )
diff --git a/src/agentscope/model/_moonshot/_model.py b/src/agentscope/model/_moonshot/_model.py
index c08df5daa..fc23f996e 100644
--- a/src/agentscope/model/_moonshot/_model.py
+++ b/src/agentscope/model/_moonshot/_model.py
@@ -2,12 +2,12 @@
"""The Moonshot AI chat model implementation."""
from collections import OrderedDict
from datetime import datetime
-from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List
+from typing import Literal, Any, AsyncGenerator, TYPE_CHECKING, List, Type
from pydantic import BaseModel, Field
from .._base import ChatModelBase, _TOOL_CHOICE_LITERAL_MODES
-from .._model_response import ChatResponse
+from .._model_response import ChatResponse, StructuredResponse
from .._model_usage import ChatUsage
from ...credential import MoonshotCredential
from ...formatter import FormatterBase, MoonshotChatFormatter
@@ -413,3 +413,50 @@ class MoonshotChatModel(ChatModelBase):
return tools, {"type": "function", "function": {"name": mode}}
return tools, mode
+
+ async def _call_api_with_structured_output(
+ self,
+ model_name: str,
+ messages: list[Msg],
+ structured_model: Type[BaseModel] | dict,
+ tool_choice: ToolChoice | None = None,
+ **kwargs: Any,
+ ) -> StructuredResponse:
+ """Moonshot-specific override for structured output.
+
+ Moonshot rejects ``tool_choice="required"`` or an object-form
+ ``tool_choice`` when thinking mode is enabled. In that case we
+ default ``tool_choice`` to ``"auto"`` and rely on the base class's
+ injected system-reminder prompt to guide the model. When thinking
+ is disabled, this falls through to the base implementation.
+
+ Args:
+ model_name (`str`):
+ The model name to use for this call.
+ messages (`list[Msg]`):
+ The context for the LLM to generate the structured output.
+ structured_model (`Type[BaseModel] | dict`):
+ A Pydantic model class or a JSON schema dict describing the
+ required output structure.
+ tool_choice (`ToolChoice | None`, defaults to `None`):
+ The tool_choice forwarded to ``_call_api``. When ``None``
+ and thinking mode is enabled, it is downgraded to
+ ``ToolChoice(mode="auto")``; otherwise the base default
+ (force the structured-output tool) is used.
+ **kwargs (`Any`):
+ Additional keyword arguments forwarded to ``_call_api``.
+
+ Returns:
+ `StructuredResponse`:
+ The structured response whose ``content`` is the validated
+ output dict matching ``structured_model``.
+ """
+ if tool_choice is None and self.parameters.thinking_enable:
+ tool_choice = ToolChoice(mode="auto")
+ return await super()._call_api_with_structured_output(
+ model_name=model_name,
+ messages=messages,
+ structured_model=structured_model,
+ tool_choice=tool_choice,
+ **kwargs,
+ )
diff --git a/tests/formatter_moonshot_test.py b/tests/formatter_moonshot_test.py
index d2237bf01..b33682738 100644
--- a/tests/formatter_moonshot_test.py
+++ b/tests/formatter_moonshot_test.py
@@ -3,8 +3,9 @@
MoonshotMultiAgentFormatter, following the reference test style with exact
ground-truth comparisons.
"""
+import base64
from unittest import IsolatedAsyncioTestCase
-from unittest.mock import patch
+from unittest.mock import patch, MagicMock
from agentscope.formatter import (
MoonshotChatFormatter,
@@ -40,9 +41,24 @@ class TestMoonshotFormatter(IsolatedAsyncioTestCase):
)
self.image_url = str(_img_src.url)
+ # The Moonshot formatter downloads remote image URLs and inlines
+ # them as base64 data URIs (the Moonshot vision API rejects raw
+ # HTTPS URLs). Patch `requests.get` so tests don't hit the network
+ # and produce a deterministic payload that matches `image_b64`.
self.image_b64 = "ZmFrZSBpbWFnZSBkYXRh"
+ self.image_bytes = base64.b64decode(self.image_b64)
self.image_data_uri = f"data:image/png;base64,{self.image_b64}"
+ mock_response = MagicMock()
+ mock_response.content = self.image_bytes
+ mock_response.raise_for_status = MagicMock()
+ self._requests_get_patcher = patch(
+ "agentscope.formatter._moonshot_formatter.requests.get",
+ return_value=mock_response,
+ )
+ self._requests_get_patcher.start()
+ self.addCleanup(self._requests_get_patcher.stop)
+
# ---------------------------------------------------------------
# Message fixtures (no audio to avoid downloads)
# ---------------------------------------------------------------
@@ -126,7 +142,7 @@ class TestMoonshotFormatter(IsolatedAsyncioTestCase):
{"type": "text", "text": "What is the capital of France?"},
{
"type": "image_url",
- "image_url": {"url": self.image_url},
+ "image_url": {"url": self.image_data_uri},
},
],
},
@@ -272,7 +288,7 @@ class TestMoonshotFormatter(IsolatedAsyncioTestCase):
},
{
"type": "image_url",
- "image_url": {"url": self.image_url},
+ "image_url": {"url": self.image_data_uri},
},
],
},
@@ -491,7 +507,7 @@ class TestMoonshotFormatter(IsolatedAsyncioTestCase):
},
{
"type": "image_url",
- "image_url": {"url": self.image_url},
+ "image_url": {"url": self.image_data_uri},
},
{
"type": "text",