Bug: async _check_and_compact() ignores tool_use filtering, causes BadRequestError
Problem
Bug When using the async tool runner with compaction enabled, `_check_and_compact()` sends unfiltered `tool_use` blocks to the API, causing a `BadRequestError`. Error: [code block] Root Cause In `src/anthropic/lib/tools/_beta_runner.py`, the async `_check_and_compact()` method (line ~472) uses `self._params["messages"]` instead of the filtered local `messages` variable when building the summarization request. The filtering logic (lines ~457-469) correctly removes assistant messages containing only `tool_use` blocks, but the result is discarded because `self._params["messages"]` is used instead: [code block] Reproduction Gist with standalone reproduction (no API key needed): https://gist.github.com/fede-kamel/175f0e99abdb53a380ded3f41236e7dd Fix PR #1124 โ one-line change: replace `self._params["messages"]` with `messages` on line ~472. The PR also fixes a similar issue in `append_messages` (line ~120) where a lambda captures `self._params["messages"]` at definition time instead of using `params["messages"]` at call time.
Error Output
Error: messages.2: `tool_use` ids were found without
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Fix async _check_and_compact() to Use Filtered Messages
The async _check_and_compact() method incorrectly uses self._params['messages'] instead of the filtered local messages variable when constructing the summarization request. This leads to unfiltered tool_use blocks being sent to the API, resulting in a BadRequestError.
Awaiting Verification
Be the first to verify this fix
- 1
Locate the _check_and_compact() method
Open the file src/anthropic/lib/tools/_beta_runner.py and navigate to the _check_and_compact() method around line 472.
- 2
Replace self._params['messages'] with filtered messages
Change the line that currently reads self._params['messages'] to use the filtered messages variable instead. This ensures that only the relevant messages are sent to the API.
pythonself._params['messages'] = messages - 3
Fix append_messages method
Locate the append_messages method around line 120 and ensure it uses params['messages'] at call time instead of capturing self._params['messages'] at definition time.
pythonlambda: self.append_messages(params['messages']) - 4
Run tests to verify the fix
Execute the existing test suite to ensure that the changes do not introduce new errors and that the BadRequestError no longer occurs when tool_use filtering is applied.
bashpytest tests/ - 5
Deploy the changes
Once the tests pass, merge the changes into the main branch and deploy to the production environment.
Validation
Confirm that the BadRequestError no longer occurs when running the async tool runner with compaction enabled. Additionally, verify that the filtered messages are correctly sent to the API by checking the logs or API responses.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep