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

fix(tools): resume paused turns in the beta tool runner

Open slegarraga opened this issue 5 months ago • 0 comments

Summary

client.beta.messages.tool_runner(...) exits the loop too early when a response contains only server-side tool use blocks (e.g. web_search, web_fetch) with stop_reason: "pause_turn". until_done() then returns the intermediate server_tool_use message instead of the model's final answer, so accessing e.g. response.content[0].text raises AttributeError.

Fixes #1170.

Root cause

After each turn, __run__ calls generate_tool_call_response(), which returns None whenever there are no client-side tool_use blocks to satisfy. The loop treated None as "the model is done" and returned — regardless of stop_reason. But "pause_turn" means the turn is still in progress (the server is running a long-running tool); per the documented contract you continue it by sending the partial response back:

"pause_turn": we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.

— BetaMessage.stop_reason docstring

Fix

When there are no client-side tool calls and stop_reason == "pause_turn", the runner now appends the paused assistant message unchanged and continues the loop, only exiting on a genuinely terminal stop reason. Applied symmetrically to the sync (BaseSyncToolRunner) and async (BaseAsyncToolRunner) runners.

  • The existing _messages_modified guard is preserved, so callers that manage their own message history are unaffected.
  • pause_turn iterations increment _iteration_count, so any max_iterations ceiling bounds them exactly like regular tool-use iterations.

Tests

Added offline regression tests (sync + async, via respx) in tests/lib/tools/test_runners.py:

  • test_pause_turn_resumes_loop_sync / test_pause_turn_resumes_loop_async — a pause_turn response (server tool only) followed by an end_turn answer; assert the runner makes the second request, returns the final text, and re-sends the paused assistant turn.
  • test_pause_turn_chained_sync — two pause_turn responses before end_turn, covering a long server-tool wait.

These fail on main (the runner stops after the first response) and pass with the fix. ruff, pyright, and mypy are all clean.

slegarraga avatar Jun 04 '26 15:06 slegarraga