Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(formatter): decode ollama file URLs (#3141)
Qingsong Li36a057185672
diff --git a/src/agentscope/formatter/_ollama_formatter.py b/src/agentscope/formatter/_ollama_formatter.pyindex 56ed65ad8..3d7eb9a59 100644--- a/src/agentscope/formatter/_ollama_formatter.py+++ b/src/agentscope/formatter/_ollama_formatter.py@@ -4,6 +4,7 @@ import base64import fnmatchfrom abc import ABCfrom typing import Any+from urllib.request import url2pathnameimport requestsfrom pydantic import Field@@ -85,7 +86,7 @@ class _OllamaFormatterBase(FormatterBase, ABC):url = str(source.url)if url.startswith("file://"):# Local file - read and convert to base64- file_path = url.removeprefix("file://")+ file_path = url2pathname(url.removeprefix("file://"))with open(file_path, "rb") as f:data = base64.b64encode(f.read()).decode("utf-8")return datadiff --git a/tests/formatter_ollama_test.py b/tests/formatter_ollama_test.pyindex f7b6a90f6..9c1587bfb 100644--- a/tests/formatter_ollama_test.py+++ b/tests/formatter_ollama_test.py@@ -2,6 +2,9 @@"""Comprehensive formatter unit tests for OllamaChatFormatter andOllamaMultiAgentFormatter, with exact ground-truth comparisons."""+import base64+from pathlib import Path+from tempfile import TemporaryDirectoryfrom unittest import IsolatedAsyncioTestCasefrom agentscope.formatter import OllamaChatFormatter, OllamaMultiAgentFormatter@@ -15,6 +18,7 @@ from agentscope.message import (ToolResultBlock,ToolResultState,Base64Source,+ URLSource,ThinkingBlock,HintBlock,)@@ -296,6 +300,55 @@ class TestOllamaFormatter(IsolatedAsyncioTestCase):res,)+ async def test_formatters_read_percent_encoded_file_urls(self) -> None:+ """Local file URLs are decoded before their paths are opened."""+ with TemporaryDirectory() as directory:+ image_path = Path(directory) / "image #1.png"+ image_path.write_bytes(base64.b64decode(self.image_b64))+ msgs = [+ UserMsg(+ name="user",+ content=[+ TextBlock(text="What is this?"),+ DataBlock(+ source=URLSource(+ url=image_path.as_uri(),+ media_type="image/png",+ ),+ ),+ ],+ ),+ ]++ chat_result = await OllamaChatFormatter().format(msgs)+ multiagent_result = await OllamaMultiAgentFormatter().format(msgs)++ self.assertListEqual(+ [+ {+ "role": "user",+ "content": "What is this?",+ "images": [self.image_b64],+ },+ ],+ chat_result,+ )+ self.assertListEqual(+ [+ {+ "role": "user",+ "content": (+ "# Conversation History\n"+ "The content between <history></history> tags "+ "contains your conversation history\n"+ "<history>\nuser:\nWhat is this?\n</history>"+ ),+ "images": [self.image_b64],+ },+ ],+ multiagent_result,+ )+async def test_chat_formatter_base64_image_in_tool_result(self,) -> None: