Skip to main content

toolrepair

Your agent trims its history, and the next turn 400s.

messages.1: unexpected tool_use_id found in tool_result blocks

One function fixes it. Zero dependencies.


Anthropic and OpenAI both require a tool call and its result to stay adjacent: every tool_use must be answered in the immediately following message. Any history manipulation can cut between them — sliding-window trimming, summarization, compaction, resuming a session, dropping a failed tool.

Then the API rejects the request. And it does it late: the turn that trimmed succeeds, and the turn after that fails, so the traceback points nowhere near the code that caused it. From the LangChain issue thread:

"hard to catch because it only manifests on the second turn after a turn that used tools"

A GitHub search for that error string returns over 1,300 matching issues, spread thin across vercel/ai, litellm, github/copilot-cli, laravel/ai, and dozens of smaller agents — a handful each. It isn't one broken framework; it's everyone independently hitting the same wall, with repair logic living private inside each project. LangChain's issue has been open since Feb 2025 with 7 unmerged fix PRs from 6 contributors.

Install

pip install git+https://github.com/Umaraslam66/tool-call-repair.git

Or just copy toolrepair.py into your project. It's one file with no dependencies and works on plain dicts, so it doesn't care which SDK you use.

The import name is toolrepair either way.

Use

from toolrepair import validate, repair, safe_trim

validate(messages)   # -> [Violation(...)]  — what's broken, and exactly where
repair(messages)     # -> a corrected copy that the API will accept
safe_trim(messages, keep=20)   # -> a trim that cannot orphan anything

Format is detected automatically; pass format="anthropic" or "openai" to be explicit.

Stop the bug at the source

Replace the naive tail slice — the single most common cause:

- messages = messages[-20:]                    # cuts mid-pair, breaks next turn
+ messages = safe_trim(messages, keep=20)      # backs up to a legal boundary

keep is a floor, not a ceiling: the cut moves earlier to stay legal, so you may retain a couple more messages than you asked for. It never returns more than you gave it.

Repair what you already have

from toolrepair import repair

try:
    response = client.messages.create(model="claude-opus-5", messages=messages, ...)
except anthropic.BadRequestError:
    response = client.messages.create(model="claude-opus-5",
                                      messages=repair(messages), ...)

Two strategies:

Strategy What it does Use when
drop (default) Removes the unpaired call Cleaning up history you're about to discard anyway
synthesize Answers the call with an is_error placeholder Mid-conversation — keeps the assistant's reasoning in context, so following turns still read coherently

Orphaned results are always dropped under both. There's no call to attach them to, and inventing one would fabricate a request the model never made.

See what's wrong

for v in validate(messages):
    print(v)
# orphaned_tool_use at messages[4].content[1] (toolu_01A): tool_use has no
# tool_result in the immediately following user message.
Code Meaning
orphaned_tool_use A call with no result in the next message
orphaned_tool_result A result answering no call in the previous message
duplicate_tool_result Two results for the same call
tool_result_not_first Results must lead the content list (Anthropic)
malformed_tool_use A call with no id, so nothing can reference it

Correctness

The guarantee is a round trip: for any input, repair produces a history that validate accepts. That's asserted directly rather than by checking for a particular output shape, because the shape is an implementation choice and the invariant is not.

  • 86 unit tests covering both API formats, parallel calls, partial answers, misordered content, string-vs-list content, and the LangChain scenario above.

  • Property tests over randomly generated histories, including deliberately corrupted ones — naive head cuts, deleted middles, shuffled orders — asserting five invariants:

    1. repair(x) always validates clean
    2. repair is idempotent
    3. repair leaves an already-valid history byte-identical
    4. safe_trim(x, k) is legal at every k
    5. neither function mutates its input

2,886 tests pass. A separate 40,000-history fuzz run reports zero failures.

pytest tests/ -q

What this does not do

  • It won't re-run your tools. A synthesized result is explicitly an error placeholder, never a fabricated success.
  • It won't count tokens. safe_trim trims by message count; if you need a token budget, trim to your budget however you like and then call repair.
  • It won't fix a history that was never valid in a different way — malformed blocks, bad roles, missing fields outside the tool-pairing rules.

License

MIT

Metadata

Release files for tool-call-repair 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tool-call-repair 0.1.0
File Size Uploaded Provenance Actions
tool_call_repair-0.1.0.tar.gz 16.8 kB With provenance Details for tool_call_repair-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tool-call-repair 0.1.0
File Interpreter ABI Platform Actions
tool_call_repair-0.1.0-py3-none-any.whl Python 3 none any Details for tool_call_repair-0.1.0-py3-none-any.whl

Total release size: 27.3 kB

Release files / tool_call_repair-0.1.0.tar.gz

Download URL tool_call_repair-0.1.0.tar.gz
Size 16.8 kB
Tags Source
SHA-256 checksum
How to use checksums
2520a2ee6698d28e8b27201ca39866ad54cab457fe9e6c190765c59e33083d90
BLAKE2b-256 checksum
How to use checksums
b486a6f37916bee7498f63e22b57346947124383d6b09591ccd2edb53ac51d4b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 28, 2026.

Transparency log

Release files / tool_call_repair-0.1.0-py3-none-any.whl

Download URL tool_call_repair-0.1.0-py3-none-any.whl
Size 10.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5e58db2b2b408d5713c582dd543c98f09449f99abe4ed3eaeb3689d895989b8c
BLAKE2b-256 checksum
How to use checksums
03f0eb7d174b3612c23253607ea8b580db6ebed4e394d41e16e850decc2b5cf3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 28, 2026.

Transparency log

Security for tool-call-repair 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for tool_call_repair-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 28, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page