tenseleyflow/loader / f063e57

Browse files

Format tool_calls with function wrapper for Ollama conversation history

Authored by espadonne
SHA
f063e57a0edc23c90c9ef4ebfa7c034be6288568
Parents
06f8c45
Tree
df95c9b

1 changed file

StatusFile+-
M src/loader/llm/ollama.py 27 2
src/loader/llm/ollama.pymodified
@@ -203,8 +203,33 @@ class OllamaBackend(LLMBackend):
203203
         return self._supports_native_tools
204204
 
205205
     def _format_messages(self, messages: list[Message]) -> list[dict[str, Any]]:
206
-        """Format messages for Ollama API."""
207
-        return [message.to_dict() for message in messages]
206
+        """Format messages for Ollama API.
207
+
208
+        Ollama expects tool_calls wrapped in ``{"function": {...}}`` and tool
209
+        results with ``role: "tool"``.  The generic ``Message.to_dict()``
210
+        uses a flat layout, so we re-wrap here.
211
+        """
212
+        formatted = []
213
+        for message in messages:
214
+            entry: dict[str, Any] = {
215
+                "role": message.role.value,
216
+                "content": message.content,
217
+            }
218
+            if message.tool_calls:
219
+                entry["tool_calls"] = [
220
+                    {
221
+                        "function": {
222
+                            "name": tc.name,
223
+                            "arguments": tc.arguments,
224
+                        }
225
+                    }
226
+                    for tc in message.tool_calls
227
+                ]
228
+            if message.tool_results:
229
+                # Ollama expects tool results as role=tool with the content
230
+                entry["role"] = "tool"
231
+            formatted.append(entry)
232
+        return formatted
208233
 
209234
     def _format_tools(self, tools: list[dict[str, Any]] | None) -> list[dict[str, Any]] | None:
210235
         """Format tools for Ollama API.