Home / Function/ _check_and_compact() — anthropic-sdk-python Function Reference

_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
  fc3214ad_dd7a_b1a4_994d_95d55d1f3a68["_check_and_compact()"]
  9149fa46_e498_7ba3_1b94_e0095e473ff9["BaseSyncToolRunner"]
  fc3214ad_dd7a_b1a4_994d_95d55d1f3a68 -->|defined in| 9149fa46_e498_7ba3_1b94_e0095e473ff9
  98b55090_3b6f_2dd4_ca2d_6c52114d5a9e["__run__()"]
  98b55090_3b6f_2dd4_ca2d_6c52114d5a9e -->|calls| fc3214ad_dd7a_b1a4_994d_95d55d1f3a68
  dc62d390_be42_9d71_fa80_f161d7ae3cc8["_check_and_compact()"]
  dc62d390_be42_9d71_fa80_f161d7ae3cc8 -->|calls| fc3214ad_dd7a_b1a4_994d_95d55d1f3a68
  e767db6b_72ea_d60e_0f49_54ac2dd6c0a7["__run__()"]
  e767db6b_72ea_d60e_0f49_54ac2dd6c0a7 -->|calls| fc3214ad_dd7a_b1a4_994d_95d55d1f3a68
  b2a98d76_24b2_7388_d54b_d0f7084fdb5f["_get_last_message()"]
  fc3214ad_dd7a_b1a4_994d_95d55d1f3a68 -->|calls| b2a98d76_24b2_7388_d54b_d0f7084fdb5f
  adc89f46_a31c_f374_60f3_d6ae19ce9e15["set_messages_params()"]
  fc3214ad_dd7a_b1a4_994d_95d55d1f3a68 -->|calls| adc89f46_a31c_f374_60f3_d6ae19ce9e15
  dc62d390_be42_9d71_fa80_f161d7ae3cc8["_check_and_compact()"]
  fc3214ad_dd7a_b1a4_994d_95d55d1f3a68 -->|calls| dc62d390_be42_9d71_fa80_f161d7ae3cc8
  style fc3214ad_dd7a_b1a4_994d_95d55d1f3a68 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

src/anthropic/lib/tools/_beta_runner.py lines 158–240

    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 = 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 = [
            *messages,
            BetaMessageParam(
                role="user",
                content=self._compaction_control.get("summary_prompt", DEFAULT_SUMMARY_PROMPT),
            ),
        ]

        response = 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,
                            }
                        ],
                    }
                ],
            }

Subdomains

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 158.
What does _check_and_compact() call?
_check_and_compact() calls 3 function(s): _check_and_compact, _get_last_message, set_messages_params.
What calls _check_and_compact()?
_check_and_compact() is called by 3 function(s): __run__, __run__, _check_and_compact.

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free