anthropic-sdk-python icon indicating copy to clipboard operation
anthropic-sdk-python copied to clipboard

[Bug] append_messages() inside tool runner loop causes infinite loop (advanced usage docs example)

Open Camiloez opened this issue 6 months ago • 4 comments

Link to Advanced Usage Docs Example

Root cause

Calling runner.append_messages(user_message) inside the loop sets _messages_modified = True, which causes __run__ to skip the auto-append of the assistant message + tool result (line 281 of _beta_runner.py). The next iteration sends a request with no tool result in history, so Claude sees the original question unanswered and makes the tool call again.

Minimal repro

Compacted and consolidated from the website

from anthropic import beta_tool, Anthropic

client = Anthropic()


@beta_tool
def get_weather(location: str, unit: str = 'fahrenheit') -> str:
    return json.dumps({
        'temperature': '20°c', 'condition': 'sunny'
    })


runner = client.beta.messages.tool_runner(
    model="claude-haiku-4-5",
    max_tokens=1024,
    tools=[get_weather],
    messages=[{
        "role": "user",
        "content": "what's the weather in San Francisco?"
    }]
)


for message in runner:
    tool_response = runner.generate_tool_call_response()
    if tool_response:
        print(f"Tool result: {tool_response}")

    # increase tokens for next request
    runner.set_messages_params(
        lambda params: {
            **params,
            "max_tokens": 2048,
        }
    )

    # add additional messages
    runner.append_messages(
        {"role": "user", "content": "be concise in your response"}
    )

Expected behavior

The "be concise" user message is appended, tool results are still auto-appended, loop terminates.

Actual behavior

Infinite loop — tool result never reaches history.

Note

The "Modifying tool results" example on the same page correctly calls runner.append_messages(message, tool_response) (both the assistant message and the tool result), which is the pattern that works correctly.

The "Advanced usage" example is inconsistent with this.

Camiloez avatar May 13 '26 04:05 Camiloez

Confirmed by reading the source.

At src/anthropic/lib/tools/_beta_runner.py:291-292:

if not self._messages_modified:
    self.append_messages(message, response)

The _messages_modified flag is flipped by any append_messages call on the runner, including the legitimate "add extra context" pattern that the Advanced usage example shows. So when the loop body calls runner.append_messages({"role": "user", "content": "be concise..."}), the auto-append of (assistant message, tool result) is skipped on that iteration, the next request goes out without a tool result, Claude makes the same tool call again, repeat forever.

The "Modifying tool results" example on the same docs page sidesteps this by manually passing both message and tool_response to its own append_messages call — the user is replacing the auto-append, not just skipping it.

Two fix shapes feel viable:

  1. Narrow the flag — only set _messages_modified = True when the appended payload contains a tool_result block (i.e. the user is taking over tool-result handling). Extra user/assistant messages alone shouldn't suppress the auto-append.
  2. Reorder the iteration body so auto-append happens before user append_messages calls take effect — more invasive, and harder to reason about with respect to the cached tool-response invalidation that append_messages also performs.

(1) is the smaller patch and matches what the docs example clearly assumes. Happy to put up a PR if a maintainer signals it's the preferred direction — there's already an open tool-runner footgun PR (#1535) on this same module, so I'd put this on a separate branch.

Zawwarsami16 avatar May 19 '26 19:05 Zawwarsami16

I have implemented a fix for this issue. PR: https://github.com/anthropics/anthropic-sdk-python/pull/1594. The fix changes the logic so that auto-append always happens, even when users call both append_messages() and generate_tool_call_response() in the same loop iteration. This prevents the infinite loop while still allowing users to access the tool response for logging. Could I be assigned to this issue?

AliSharjeell avatar May 23 '26 06:05 AliSharjeell

Hi, I'd like to work on this. I'll submit a PR shortly.

nightcityblade avatar May 27 '26 03:05 nightcityblade

I noticed there is already an open PR for this at #1594, so I’m stepping back to avoid duplicating work.

nightcityblade avatar May 27 '26 03:05 nightcityblade