_check_and_compact() — anthropic-sdk-python Function Reference
Architecture documentation for the _check_and_compact() function in _beta_runner.py from the anthropic-sdk-python codebase.
Entity Profile
Dependency Diagram
graph TD dc62d390_be42_9d71_fa80_f161d7ae3cc8["_check_and_compact()"] e1032e12_8173_7783_f9c6_c9b9260e5366["BaseAsyncToolRunner"] dc62d390_be42_9d71_fa80_f161d7ae3cc8 -->|defined in| e1032e12_8173_7783_f9c6_c9b9260e5366 fc3214ad_dd7a_b1a4_994d_95d55d1f3a68["_check_and_compact()"] fc3214ad_dd7a_b1a4_994d_95d55d1f3a68 -->|calls| dc62d390_be42_9d71_fa80_f161d7ae3cc8 e767db6b_72ea_d60e_0f49_54ac2dd6c0a7["__run__()"] e767db6b_72ea_d60e_0f49_54ac2dd6c0a7 -->|calls| dc62d390_be42_9d71_fa80_f161d7ae3cc8 1fdee5f9_923d_e71a_5610_d1556341274b["_get_last_message()"] dc62d390_be42_9d71_fa80_f161d7ae3cc8 -->|calls| 1fdee5f9_923d_e71a_5610_d1556341274b adc89f46_a31c_f374_60f3_d6ae19ce9e15["set_messages_params()"] dc62d390_be42_9d71_fa80_f161d7ae3cc8 -->|calls| adc89f46_a31c_f374_60f3_d6ae19ce9e15 fc3214ad_dd7a_b1a4_994d_95d55d1f3a68["_check_and_compact()"] dc62d390_be42_9d71_fa80_f161d7ae3cc8 -->|calls| fc3214ad_dd7a_b1a4_994d_95d55d1f3a68 b2a98d76_24b2_7388_d54b_d0f7084fdb5f["_get_last_message()"] dc62d390_be42_9d71_fa80_f161d7ae3cc8 -->|calls| b2a98d76_24b2_7388_d54b_d0f7084fdb5f style dc62d390_be42_9d71_fa80_f161d7ae3cc8 fill:#6366f1,stroke:#818cf8,color:#fff
Relationship Graph
Source Code
src/anthropic/lib/tools/_beta_runner.py lines 409–491
async def _check_and_compact(self) -> bool:
"""
Check token usage and compact messages if threshold exceeded.
Returns True if compaction was performed, False otherwise.
"""
if self._compaction_control is None or not self._compaction_control["enabled"]:
return False
message = await self._get_last_message()
tokens_used = 0
if message is not None:
total_input_tokens = (
message.usage.input_tokens
+ (message.usage.cache_creation_input_tokens or 0)
+ (message.usage.cache_read_input_tokens or 0)
)
tokens_used = total_input_tokens + message.usage.output_tokens
threshold = self._compaction_control.get("context_token_threshold", DEFAULT_THRESHOLD)
if tokens_used < threshold:
return False
# Perform compaction
log.info(f"Token usage {tokens_used} has exceeded the threshold of {threshold}. Performing compaction.")
model = self._compaction_control.get("model", self._params["model"])
messages = list(self._params["messages"])
if messages[-1]["role"] == "assistant":
# Remove tool_use blocks from the last message to avoid 400 error
# (tool_use requires tool_result, which we don't have yet)
non_tool_blocks = [
block
for block in messages[-1]["content"]
if isinstance(block, dict) and block.get("type") != "tool_use"
]
if non_tool_blocks:
messages[-1]["content"] = non_tool_blocks
else:
messages.pop()
messages = [
*self._params["messages"],
BetaMessageParam(
role="user",
content=self._compaction_control.get("summary_prompt", DEFAULT_SUMMARY_PROMPT),
),
]
response = await self._client.beta.messages.create(
model=model,
messages=messages,
max_tokens=self._params["max_tokens"],
extra_headers={"X-Stainless-Helper": "compaction"},
)
log.info(f"Compaction complete. New token usage: {response.usage.output_tokens}")
first_content = list(response.content)[0]
if first_content.type != "text":
raise ValueError("Compaction response content is not of type 'text'")
self.set_messages_params(
lambda params: {
**params,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": first_content.text,
}
],
}
],
}
Domain
Subdomains
Defined In
Called By
Source
Frequently Asked Questions
What does _check_and_compact() do?
_check_and_compact() is a function in the anthropic-sdk-python codebase, defined in src/anthropic/lib/tools/_beta_runner.py.
Where is _check_and_compact() defined?
_check_and_compact() is defined in src/anthropic/lib/tools/_beta_runner.py at line 409.
What does _check_and_compact() call?
_check_and_compact() calls 4 function(s): _check_and_compact, _get_last_message, _get_last_message, set_messages_params.
What calls _check_and_compact()?
_check_and_compact() is called by 2 function(s): __run__, _check_and_compact.
Analyze Your Own Codebase
Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.
Try Supermodel Free