From a05880c8991f3d3cc1b879e98b975aa332a8fa12 Mon Sep 17 00:00:00 2001 From: Anoshor Date: Sat, 21 Nov 2026 00:22:33 +0530 Subject: [PATCH 1/3] fix(py/plugins/ollama): send tool calls and tool names in chat messages build_chat_messages ignored tool_request parts, so the assistant turn that asked for a tool reached Ollama with no tool_calls, and folded every tool response into one message with no tool_name. The model then saw a tool result for a call it never made and called the tool again until max_turns. Send tool requests as tool_calls, and each tool response as its own tool message with tool_name, encoding non-string output as JSON, as the JS Ollama plugin does. Fixes genkit-ai/genkit#7277 Upstream-Commit: genkit-ai/genkit@a60c918f9416dc94983f0dcebb84f0df0e72d9df Upstream-PR: https://github.com/genkit-ai/genkit/pull/7279 --- .../src/genkit_ollama/_models.py | 34 ++++++++--- .../tests/models/ollama_models_test.py | 61 +++++++++++++++++++ 2 files changed, 88 insertions(+), 7 deletions(-) diff --git a/packages/genkit-ollama/src/genkit_ollama/_models.py b/packages/genkit-ollama/src/genkit_ollama/_models.py index 7bc082597..d2b099746 100644 --- a/packages/genkit-ollama/src/genkit_ollama/_models.py +++ b/packages/genkit-ollama/src/genkit_ollama/_models.py @@ -739,19 +739,39 @@ async def build_chat_messages(cls, request: ModelRequest) -> list[ollama_api.Mes """ messages: list[ollama_api.Message] = [] for message in request.messages: - item = ollama_api.Message( - role=cls._to_ollama_role(role=cast(Role, message.role)), - content='', - images=[], - ) + role = cls._to_ollama_role(role=cast(Role, message.role)) + tool_responses = [part.tool_response for part in message.content if part.tool_response is not None] + if tool_responses: + for tool_response in tool_responses: + output = tool_response.output + messages.append( + ollama_api.Message( + role=role, + content=output if isinstance(output, str) else json.dumps(output, default=str), + tool_name=tool_response.name, + ) + ) + continue + item = ollama_api.Message(role=role, content='', images=[]) + tool_calls: list[ollama_api.Message.ToolCall] = [] for text_part in message.content: if text_part.text is not None: item.content = (item.content or '') + text_part.text - elif text_part.tool_response is not None: - item.content = (item.content or '') + str(text_part.tool_response.output) + elif text_part.tool_request is not None: + tool_input = text_part.tool_request.input + tool_calls.append( + ollama_api.Message.ToolCall( + function=ollama_api.Message.ToolCall.Function( + name=text_part.tool_request.name, + arguments=tool_input if isinstance(tool_input, dict) else {}, + ) + ) + ) elif text_part.media is not None: image_value = await cls._resolve_image(text_part.media.url) item['images'].append(ollama_api.Image(value=image_value)) + if tool_calls: + item.tool_calls = tool_calls messages.append(item) return messages diff --git a/packages/genkit-ollama/tests/models/ollama_models_test.py b/packages/genkit-ollama/tests/models/ollama_models_test.py index 17149b5a8..cee84be07 100644 --- a/packages/genkit-ollama/tests/models/ollama_models_test.py +++ b/packages/genkit-ollama/tests/models/ollama_models_test.py @@ -1075,6 +1075,67 @@ async def test_media_only_message(self) -> None: assert len(messages[0]['images']) == 1 +class TestBuildChatMessagesWithTools(unittest.IsolatedAsyncioTestCase): + """Tests for build_chat_messages with tool request and tool response parts.""" + + async def test_tool_request_and_response_round_trip(self) -> None: + """The model's tool call and the matching tool result both reach Ollama.""" + request = ModelRequest( + messages=[ + Message(role=Role.USER, content=[Part.from_text('What time is it?')]), + Message( + role=Role.MODEL, + content=[Part.from_tool_request('getCurrentTime', input={'zone': 'CET'}, ref='0')], + ), + Message( + role=Role.TOOL, + content=[Part.from_tool_response('getCurrentTime', output={'time': '18:00'}, ref='0')], + ), + ] + ) + + messages = await OllamaModel.build_chat_messages(request) + + assert len(messages) == 3 + tool_calls = messages[1].tool_calls + assert tool_calls is not None + assert len(tool_calls) == 1 + assert tool_calls[0].function.name == 'getCurrentTime' + assert dict(tool_calls[0].function.arguments) == {'zone': 'CET'} + assert messages[2].role == 'tool' + assert messages[2].tool_name == 'getCurrentTime' + assert json.loads(messages[2].content or '') == {'time': '18:00'} + + async def test_parallel_tool_responses_become_separate_messages(self) -> None: + """Each tool response is its own message, and string output is sent as is.""" + request = ModelRequest( + messages=[ + Message( + role=Role.MODEL, + content=[ + Part.from_tool_request('getCurrentTime', input={}, ref='0'), + Part.from_tool_request('getWeather', input={'city': 'Paris'}, ref='1'), + ], + ), + Message( + role=Role.TOOL, + content=[ + Part.from_tool_response('getCurrentTime', output='18:00', ref='0'), + Part.from_tool_response('getWeather', output={'sky': 'clear'}, ref='1'), + ], + ), + ] + ) + + messages = await OllamaModel.build_chat_messages(request) + + assert [call.function.name for call in messages[0].tool_calls or []] == ['getCurrentTime', 'getWeather'] + assert [(m.tool_name, m.content) for m in messages[1:]] == [ + ('getCurrentTime', '18:00'), + ('getWeather', '{"sky": "clear"}'), + ] + + class TestToOllamaRole: """Tests for OllamaModel._to_ollama_role. From cbab670e62f96e329649a90f95c2b7d4ee158377 Mon Sep 17 00:00:00 2001 From: Hilary Date: Mon, 23 Nov 2026 11:39:41 +0100 Subject: [PATCH 2/3] fix(py/ollama): keep non-ASCII tool output unescaped and test the tool loop --- .../src/genkit_ollama/_models.py | 9 +++- .../genkit-ollama/tests/integration_test.py | 47 +++++++++++++++++++ .../tests/models/ollama_models_test.py | 33 +++++++++++++ 3 files changed, 88 insertions(+), 1 deletion(-) diff --git a/packages/genkit-ollama/src/genkit_ollama/_models.py b/packages/genkit-ollama/src/genkit_ollama/_models.py index d2b099746..ff194a1bc 100644 --- a/packages/genkit-ollama/src/genkit_ollama/_models.py +++ b/packages/genkit-ollama/src/genkit_ollama/_models.py @@ -727,6 +727,11 @@ def _thinking_requested( async def build_chat_messages(cls, request: ModelRequest) -> list[ollama_api.Message]: """Build the messages for the chat API. + ToolRequestParts become the message's ``tool_calls``; non-object + input is sent as ``{}``. Each ToolResponsePart becomes its own + ``tool`` message carrying ``tool_name``, with non-string output + encoded as JSON. + Each MediaPart becomes image bytes via ``_resolve_image``: data URIs and bare base64 are decoded, HTTP/HTTPS URLs are downloaded, and anything else raises ``INVALID_ARGUMENT``. @@ -747,7 +752,9 @@ async def build_chat_messages(cls, request: ModelRequest) -> list[ollama_api.Mes messages.append( ollama_api.Message( role=role, - content=output if isinstance(output, str) else json.dumps(output, default=str), + content=output + if isinstance(output, str) + else json.dumps(output, default=str, ensure_ascii=False), tool_name=tool_response.name, ) ) diff --git a/packages/genkit-ollama/tests/integration_test.py b/packages/genkit-ollama/tests/integration_test.py index 20d7c4730..7df24adfa 100644 --- a/packages/genkit-ollama/tests/integration_test.py +++ b/packages/genkit-ollama/tests/integration_test.py @@ -16,10 +16,12 @@ """Integration tests for Ollama plugin with Genkit.""" +from typing import Any from unittest.mock import Mock import ollama as ollama_api import pytest +from pydantic import BaseModel from genkit import Genkit, Message, ModelResponse, Part, Role @@ -71,4 +73,49 @@ async def _test_fun() -> ModelResponse: assert response.message.content[0].text == mock_response_message +class _NoInput(BaseModel): + pass + + +@pytest.mark.asyncio +async def test_tool_turn_is_sent_back_with_its_call( + mock_ollama_api_async_client: Mock, + genkit_veneer_chat_model: Genkit, +) -> None: + """The follow-up request carries the model's tool call and the named tool result.""" + ai = genkit_veneer_chat_model + sent: list[list[ollama_api.Message]] = [] + replies = [ + ollama_api.Message( + role='assistant', + content='', + tool_calls=[ + ollama_api.Message.ToolCall( + function=ollama_api.Message.ToolCall.Function(name='getCurrentTime', arguments={}) + ) + ], + ), + ollama_api.Message(role='assistant', content='It is 18:00.'), + ] + + async def fake_chat(*args: object, **kwargs: Any) -> ollama_api.ChatResponse: + sent.append(list(kwargs['messages'])) + return ollama_api.ChatResponse(message=replies[len(sent) - 1]) + + mock_ollama_api_async_client.return_value.chat.side_effect = fake_chat + + @ai.tool(name='getCurrentTime') + async def get_current_time(_: _NoInput) -> str: + """Returns the current time.""" + return '18:00' + + response = await ai.generate(prompt='What time is it?', tools=['getCurrentTime'], max_turns=2) + + assert response.text == 'It is 18:00.' + assert len(sent) == 2 + assistant, tool = sent[1][-2:] + assert [call.function.name for call in assistant.tool_calls or []] == ['getCurrentTime'] + assert (tool.role, tool.tool_name, tool.content) == ('tool', 'getCurrentTime', '18:00') + + # Integration tests are covered by the above test cases diff --git a/packages/genkit-ollama/tests/models/ollama_models_test.py b/packages/genkit-ollama/tests/models/ollama_models_test.py index cee84be07..b0cdec2a7 100644 --- a/packages/genkit-ollama/tests/models/ollama_models_test.py +++ b/packages/genkit-ollama/tests/models/ollama_models_test.py @@ -1135,6 +1135,39 @@ async def test_parallel_tool_responses_become_separate_messages(self) -> None: ('getWeather', '{"sky": "clear"}'), ] + async def test_non_object_tool_input_is_sent_as_empty_arguments(self) -> None: + """Ollama only takes object arguments, so other input is sent as {}.""" + request = ModelRequest( + messages=[ + Message( + role=Role.MODEL, + content=[ + Part.from_tool_request('noInput', ref='0'), + Part.from_tool_request('scalarInput', input='Paris', ref='1'), + ], + ), + ] + ) + + messages = await OllamaModel.build_chat_messages(request) + + assert [dict(call.function.arguments) for call in messages[0].tool_calls or []] == [{}, {}] + + async def test_non_ascii_tool_output_is_not_escaped(self) -> None: + """Non-ASCII tool output reaches the model as written.""" + request = ModelRequest( + messages=[ + Message( + role=Role.TOOL, + content=[Part.from_tool_response('getWeather', output={'city': 'Zürich'}, ref='0')], + ), + ] + ) + + messages = await OllamaModel.build_chat_messages(request) + + assert messages[0].content == '{"city": "Zürich"}' + class TestToOllamaRole: """Tests for OllamaModel._to_ollama_role. From fd5b089cd562d15a387c8ea3efa486d4546ff48d Mon Sep 17 00:00:00 2001 From: Hilary Date: Mon, 23 Nov 2026 14:17:42 +0100 Subject: [PATCH 3/3] test(py/ollama): reproduce the tool loop and pin dropped parts --- .../src/genkit_ollama/_models.py | 4 +- .../genkit-ollama/tests/integration_test.py | 39 ++++++++----------- .../tests/models/ollama_models_test.py | 21 ++++++++++ 3 files changed, 40 insertions(+), 24 deletions(-) diff --git a/packages/genkit-ollama/src/genkit_ollama/_models.py b/packages/genkit-ollama/src/genkit_ollama/_models.py index ff194a1bc..6824788c9 100644 --- a/packages/genkit-ollama/src/genkit_ollama/_models.py +++ b/packages/genkit-ollama/src/genkit_ollama/_models.py @@ -729,8 +729,8 @@ async def build_chat_messages(cls, request: ModelRequest) -> list[ollama_api.Mes ToolRequestParts become the message's ``tool_calls``; non-object input is sent as ``{}``. Each ToolResponsePart becomes its own - ``tool`` message carrying ``tool_name``, with non-string output - encoded as JSON. + message carrying ``tool_name``, with non-string output encoded as + JSON; other parts in that message are dropped. Each MediaPart becomes image bytes via ``_resolve_image``: data URIs and bare base64 are decoded, HTTP/HTTPS URLs are downloaded, diff --git a/packages/genkit-ollama/tests/integration_test.py b/packages/genkit-ollama/tests/integration_test.py index 7df24adfa..51f2b7c12 100644 --- a/packages/genkit-ollama/tests/integration_test.py +++ b/packages/genkit-ollama/tests/integration_test.py @@ -23,7 +23,7 @@ import pytest from pydantic import BaseModel -from genkit import Genkit, Message, ModelResponse, Part, Role +from genkit import FinishReason, Genkit, Message, ModelResponse, Part, Role @pytest.mark.asyncio @@ -82,25 +82,22 @@ async def test_tool_turn_is_sent_back_with_its_call( mock_ollama_api_async_client: Mock, genkit_veneer_chat_model: Genkit, ) -> None: - """The follow-up request carries the model's tool call and the named tool result.""" + """The model answers once its tool call and the named result are in the history.""" ai = genkit_veneer_chat_model - sent: list[list[ollama_api.Message]] = [] - replies = [ - ollama_api.Message( - role='assistant', - content='', - tool_calls=[ - ollama_api.Message.ToolCall( - function=ollama_api.Message.ToolCall.Function(name='getCurrentTime', arguments={}) - ) - ], - ), - ollama_api.Message(role='assistant', content='It is 18:00.'), - ] + calls = 0 async def fake_chat(*args: object, **kwargs: Any) -> ollama_api.ChatResponse: - sent.append(list(kwargs['messages'])) - return ollama_api.ChatResponse(message=replies[len(sent) - 1]) + nonlocal calls + calls += 1 + history = kwargs['messages'] + called = any(call.function.name == 'getCurrentTime' for m in history for call in m.tool_calls or []) + answered = any(m.role == 'tool' and m.tool_name == 'getCurrentTime' for m in history) + if called and answered: + return ollama_api.ChatResponse(message=ollama_api.Message(role='assistant', content='It is 18:00.')) + tool_call = ollama_api.Message.ToolCall( + function=ollama_api.Message.ToolCall.Function(name='getCurrentTime', arguments={}) + ) + return ollama_api.ChatResponse(message=ollama_api.Message(role='assistant', content='', tool_calls=[tool_call])) mock_ollama_api_async_client.return_value.chat.side_effect = fake_chat @@ -109,13 +106,11 @@ async def get_current_time(_: _NoInput) -> str: """Returns the current time.""" return '18:00' - response = await ai.generate(prompt='What time is it?', tools=['getCurrentTime'], max_turns=2) + response = await ai.generate(prompt='What time is it?', tools=['getCurrentTime'], max_turns=3) + assert response.finish_reason != FinishReason.ABORTED assert response.text == 'It is 18:00.' - assert len(sent) == 2 - assistant, tool = sent[1][-2:] - assert [call.function.name for call in assistant.tool_calls or []] == ['getCurrentTime'] - assert (tool.role, tool.tool_name, tool.content) == ('tool', 'getCurrentTime', '18:00') + assert calls == 2 # Integration tests are covered by the above test cases diff --git a/packages/genkit-ollama/tests/models/ollama_models_test.py b/packages/genkit-ollama/tests/models/ollama_models_test.py index b0cdec2a7..5e3816b79 100644 --- a/packages/genkit-ollama/tests/models/ollama_models_test.py +++ b/packages/genkit-ollama/tests/models/ollama_models_test.py @@ -1168,6 +1168,27 @@ async def test_non_ascii_tool_output_is_not_escaped(self) -> None: assert messages[0].content == '{"city": "Zürich"}' + async def test_other_parts_next_to_tool_responses_are_dropped(self) -> None: + """A message with tool responses sends only the responses.""" + request = ModelRequest( + messages=[ + Message( + role=Role.TOOL, + content=[ + Part.from_text('note'), + Part.from_tool_response('getCurrentTime', output='18:00', ref='0'), + Part.from_media('data:image/png;base64,AAAA', content_type='image/png'), + ], + ), + ] + ) + + messages = await OllamaModel.build_chat_messages(request) + + assert [(m.role, m.tool_name, m.content, m.images) for m in messages] == [ + ('tool', 'getCurrentTime', '18:00', None) + ] + class TestToOllamaRole: """Tests for OllamaModel._to_ollama_role.