Skip to content

fix: handle multiple tool calls in tools examples#634

Open
Krishnachaitanyakc wants to merge 1 commit intoollama:mainfrom
Krishnachaitanyakc:fix/tools-example-multiple-tool-calls
Open

fix: handle multiple tool calls in tools examples#634
Krishnachaitanyakc wants to merge 1 commit intoollama:mainfrom
Krishnachaitanyakc:fix/tools-example-multiple-tool-calls

Conversation

@Krishnachaitanyakc
Copy link
Copy Markdown

Summary

  • Fixes the tools.py and async-tools.py examples so that all tool call results are sent back to the model, not just the last one
  • Previously, the examples iterated over tool calls but only appended a single tool message after the loop using the last value of output, which meant earlier tool call results were silently discarded
  • Each tool result is now appended as a separate message inside the loop, consistent with the pattern already used in multi-tool.py and gpt-oss-tools.py

Fixes #476

Changes

  • examples/tools.py: Move messages.append(response.message) before the loop; append each tool result inside the loop
  • examples/async-tools.py: Same fix applied to the async variant

Test plan

  • ruff check passes on both changed files
  • Python syntax validation passes
  • Manual verification: run tools.py with a prompt that triggers multiple tool calls (e.g., "What is three plus one, then subtract two?") and confirm all results are sent to the model

The tools.py and async-tools.py examples only sent the last tool call
result back to the model, discarding results from earlier tool calls.
This fix appends each tool result as a separate message inside the loop,
matching the pattern already used in multi-tool.py and gpt-oss-tools.py.

Fixes ollama#476
Copy link
Copy Markdown

@Pawansingh3889 Pawansingh3889 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — I ran into this exact issue when building a multi-tool agent with Ollama. The original code only appended the last tool result because the loop variable got overwritten on each iteration.

The fix correctly:

  1. Appends the assistant message (with tool_calls) before iterating
  2. Appends each tool result inside the loop as a separate message
  3. Adds an "Function not found" fallback for missing functions

One minor thought: the fallback string "Function not found" could be more descriptive — something like f"Error: function {tool.function.name} not available" would help the model self-correct in the next turn.

Tested the same pattern in my own project and it works correctly. LGTM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tool calling example may have a glitch - seems to only record the result of the last tool call

2 participants