Skip to content

fix: Anthropic tool loops send tool_use_id, error text and thinking blocks (#124) - #142

Merged
stackbilt-admin merged 8 commits into
mainfrom
fix/124-anthropic-tool-loop
Nov 7, 2026
Merged

stackbilt-admin merged 8 commits into
mainfrom
fix/124-anthropic-tool-loop

Conversation

@stackbilt-admin

@stackbilt-admin stackbilt-admin commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Fixes #124. Additive, so it targets a minor release (1.25.0).

Multi-turn tool use through the Anthropic provider, including generateResponseWithTools(), was rejected by the Messages API on every Claude model. Anthropic docs checked 2026-11-06: Handle tool calls, Define tools and Thinking (Preserving thinking blocks, Redacted thinking, Preserved thinking).

Fixed

  • Anthropic tool_result blocks send tool_use_id; they sent id.
  • Anthropic tool errors: a failed tool's error message is sent as the result's content with is_error: true, after any partial output; it was sent as empty content.
  • Rebuilt Anthropic turns: an assistant tool-call turn rebuilt from content and toolCalls keeps its text before the tool_use blocks (whitespace-only text is left out); the text was dropped.
  • Groq, Cerebras and NVIDIA now send a failed tool's error as { "output", "error" } JSON in the tool message, the format OpenAI already used (shared helper src/utils/tool-results.ts). They sent only the output, so failures reached the model as empty successes.
  • generateResponseWithTools() no longer reports a failed tool as an empty success when it throws something other than an Error with a message: a thrown string, or any object with a non-blank message, is the error text; anything else gets Tool '<name>' failed without an error message.

Added: providerContent

Claude 5.x models think by default. Within a tool-use turn, Anthropic requires the thinking blocks (including redacted_thinking) to be sent back complete, unmodified and in order; on 5.1+ models a block is valid only if everything before it is unchanged. So the turn is replayed verbatim:

  • New field: optional LLMResponse.providerContent and LLMMessage.providerContent, type ProviderContent ({ provider, blocks }).
  • Capture: an Anthropic response that calls tools carries a copy of the turn's content blocks, in order. It's left unset when a tool_use block fails validation (the call is dropped from toolCalls), when a thinking block has no signature, and on JSON-prefill responses; those turns are rebuilt instead.
  • Replay: generateResponseWithTools() copies the field onto the assistant message, and the Anthropic provider sends it in place of content and toolCalls. An edit made only to content is therefore not sent; the provider logs a warning when content differs from the replayed text (blank or missing content included), and the README says so. Other providers ignore the field; a fallback partway through a loop rebuilds the turn, as before.
  • Validation (src/utils/provider-content.ts, shared by replay and the response cache):
    • non-empty blocks;
    • no user-turn block types (tool_result, image, document, search_result);
    • every tool_use block has an id, name and input;
    • every thinking block has string thinking text and a signature, every redacted_thinking block has data, and every text block has string text;
    • otherwise a ConfigurationError in validateRequest, before dispatch, so it isn't recorded in the provider's metrics or circuit breaker (the factory still logs it, fires onRequestError and reports the failed attempt); a cache entry that fails is treated as a miss;
    • if the tool_use ids differ from the message's toolCalls, the turn is rebuilt; the shape is checked first, so malformed content throws even then.
  • Cache key: response cache keys move from llmp:v2: to llmp:v3:, so entries written by 1.24.x or earlier, which lack providerContent, are not reused (the cache starts cold after upgrading). Tool-call responses without providerContent are still cached.
  • Elsewhere: the response schema recognizes redacted_thinking and the thinking signature. Canonical normalization deep-copies the field as JSON, and throws ConfigurationError for blocks with a BigInt or a circular reference.

Tests

src/__tests__/anthropic-tool-loop.test.ts, 57 tests asserting exact request bodies:

  • tool_use_id, and error text with and without partial output;
  • capture order and copy, including a dropped tool_use, unsigned thinking and JSON prefill;
  • verbatim replay, on the non-streaming and streaming paths;
  • rebuilds: content from another provider, whitespace-only text, and an id mismatch;
  • malformed-content rejection, with thirteen cases, before dispatch and without touching provider metrics;
  • the warning when content was edited, blank or null but providerContent wasn't;
  • provider-prefix cache hints leaving replayed blocks untouched;
  • two- and three-round generateResponseWithTools loops;
  • tool-failure shapes: string, empty, object, error-like object, whitespace, and a throwing message getter;
  • a fallback partway through a loop, in both directions (Anthropic to OpenAI, and OpenAI to Anthropic);
  • tool errors on Groq, Cerebras, NVIDIA and OpenAI;
  • a factory cache hit, a corrupt-entry miss, the v3 key, and writing and then serving tool-call responses with and without providerContent;
  • cache validation, canonical pass-through, deep copy, and a copy of blocks with a circular reference.

Each review round's new tests were also run against the code from before that round's fixes; the ones covering a fix failed there.

Local: typecheck, 894 tests, build, package smoke test, worker import smoke test.

Not in this PR

  • Claude 5.x routing: the catalog entries stay explicitOnly. Before making them routable, toolChoice: 'none' should keep tools in the request, so earlier thinking stays valid on 5.1+ (see the comment on Anthropic adapter sends tool_result blocks without tool_use_id, so multi-turn tool use fails #124). Forced toolChoice is already rejected before the call on Fable 5.1, Opus 5.5 and Sonnet 5.5.
  • Final-answer thinking: providerContent is set only on tool-use turns, so thinking from final answers isn't carried into later turns. That's allowed, and it doesn't cause an error.
  • No live API call: all tests mock fetch.
  • Streaming: streamed responses don't produce providerContent (the tool loop doesn't stream).

🤖 Generated with Claude Code

…locks (#124)

- tool_result blocks send tool_use_id instead of id.
- A failed tool's error message goes in content with is_error: true.
- Rebuilt assistant tool-call turns keep their text before tool_use.
- New LLMResponse/LLMMessage.providerContent ({ provider, blocks }): an
  Anthropic response that calls tools carries the turn's content blocks
  (thinking with signatures, redacted_thinking, text, tool_use) in order,
  and the Anthropic provider replays them unchanged, as Anthropic requires
  for tool-use turns. generateResponseWithTools copies it; other providers
  ignore it; malformed Anthropic content throws ConfigurationError.
- Response schema knows redacted_thinking and the thinking signature;
  canonical normalization and the response cache carry and validate the
  new field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kovermier and others added 7 commits November 6, 2026 16:32
- Rebuilt assistant turns skip whitespace-only text (not a valid text block).
- generateResponseWithTools reports non-Error throws and empty-message
  errors as tool errors instead of empty successes.
- Shared isValidProviderContent: the Anthropic replay and the response
  cache now accept the same values (non-empty, typed blocks, no user-turn
  block types such as tool_result or image for Anthropic).
- Canonical normalization deep-copies providerContent.
- Tests: whitespace text, streaming replay, user-turn/image blocks,
  silent tool failures, mid-loop fallback in both directions, cache
  empty-array rejection, canonical deep copy.
- README/CHANGELOG: tool-use-turn scope and error wording; checkpoint
  notes #142 and the remaining Claude 5.x gaps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Groq, Cerebras and NVIDIA send a failed tool's error as { output, error }
  JSON, like OpenAI (shared openAIToolResultContent helper).
- Tool loop takes error text from any thrown object with a non-blank
  message; whitespace-only messages get the generic text.
- providerContent is captured only when every tool_use survives
  validation, and not on JSON-prefill responses; replay requires complete
  tool_use blocks and rebuilds the turn when tool_use ids differ from
  toolCalls.
- copyProviderContent throws ConfigurationError for non-JSON blocks.
- Tests for each, plus a three-round loop and factory cache hit/miss.
- README/CHANGELOG/checkpoint wording matches the code; the checkpoint no
  longer lists done #124 work or forced toolChoice as open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Anthropic content needs signed thinking and redacted_thinking data:
  unsigned turns aren't captured and are rejected on replay.
- Replay shape check moved to validateRequest, so a caller mistake isn't
  recorded as a provider failure.
- Warn when an assistant message's content differs from the providerContent
  being sent; README documents that edits to content are not sent.
- The response cache treats an Anthropic tool-call entry without
  providerContent (written by 1.24.x) as a miss.
- Tool loop guards a throwing message getter.
- Tests for each, plus provider-prefix cache hints leaving replayed blocks
  untouched; reset the fetch mock between tests so failures can't cascade.
- README/CHANGELOG/checkpoint updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Response cache keys move to llmp:v3:, so pre-1.25 entries without
  providerContent aren't reused; drop the cache rule that also blocked
  writes of tool-call responses without providerContent.
- Warn whenever replayed content differs from the message's content,
  including blank content; a null content no longer throws.
- Document that the shape check runs before the tool_use id check, and
  narrow "not a provider failure" to provider metrics and the breaker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Replayed Anthropic thinking blocks need string thinking text (empty is
  fine) and text blocks need string text, so a hand-built or corrupted
  block is rejected before dispatch instead of failing at the provider.
- Test that a tool-call response with providerContent is written to the
  response cache and then served from it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The rebuild path's comment no longer calls whitespace-only text an
  invalid block; it says the rebuilt turn leaves it out and replay keeps
  every block as returned.
- copyProviderContent throws only for BigInt and circular references;
  say so, and describe how other non-JSON values are converted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@stackbilt-admin
stackbilt-admin merged commit a926dd1 into main Nov 7, 2026
2 checks passed
@stackbilt-admin
stackbilt-admin deleted the fix/124-anthropic-tool-loop branch November 7, 2026 02:34
stackbilt-admin pushed a commit that referenced this pull request Nov 7, 2026
- README: the Claude 5.x models stay explicitOnly until the remaining
  routing steps tracked on #112 are done (not "until #124").
- CHANGELOG: the llmp:v3: cache-key change moves to Changed; the
  providerContent entry cites #142.
- Checkpoint: the publish workflow re-run is future tense; clearer
  wording for the #112 routing steps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
stackbilt-admin added a commit that referenced this pull request Nov 7, 2026
Anthropic tool loops (#124, #142): tool_use_id, tool error text and
verbatim replay of tool-use turns via the new providerContent field;
tool error text on Groq, Cerebras and NVIDIA. Bumps package.json,
package-lock.json and src/version.ts to 1.25.0, adds the CHANGELOG
section (the llmp:v3: cache-key change under Changed, with an upgrade
note), points the README Claude 5.x explicitOnly note at the routing
steps now tracked on #112, and refreshes the issue-sweep checkpoint.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

Anthropic adapter sends tool_result blocks without tool_use_id, so multi-turn tool use fails

2 participants