diff --git a/packages/genkit-ollama/src/genkit_ollama/_models.py b/packages/genkit-ollama/src/genkit_ollama/_models.py index 7bc082597..6824788c9 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 + 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, and anything else raises ``INVALID_ARGUMENT``. @@ -739,19 +744,41 @@ 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, ensure_ascii=False), + 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/integration_test.py b/packages/genkit-ollama/tests/integration_test.py index 20d7c4730..51f2b7c12 100644 --- a/packages/genkit-ollama/tests/integration_test.py +++ b/packages/genkit-ollama/tests/integration_test.py @@ -16,12 +16,14 @@ """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 +from genkit import FinishReason, Genkit, Message, ModelResponse, Part, Role @pytest.mark.asyncio @@ -71,4 +73,44 @@ 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 model answers once its tool call and the named result are in the history.""" + ai = genkit_veneer_chat_model + calls = 0 + + async def fake_chat(*args: object, **kwargs: Any) -> ollama_api.ChatResponse: + 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 + + @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=3) + + assert response.finish_reason != FinishReason.ABORTED + assert response.text == 'It is 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 17149b5a8..5e3816b79 100644 --- a/packages/genkit-ollama/tests/models/ollama_models_test.py +++ b/packages/genkit-ollama/tests/models/ollama_models_test.py @@ -1075,6 +1075,121 @@ 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"}'), + ] + + 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"}' + + 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.