Using Code-Driven Tool Calls to Mitigate Context Corruption in AI Agents

    This article explains how context corruption occurs when AI agents append raw tool outputs to conversation history, and introduces a code-based approach where agents generate programs that process data in memory and only output summarized results. It compares direct and programmatic tool calling, highlights benefits such as variable scoping, control flow, and exception isolation, provides a practical example of order statistics, and discusses security, deployment, and limitations.

    Where Context Corruption Comes From

    In enterprise scenarios, AI agents often need to query databases, read files, or call business APIs. The traditional approach is to append the full tool result to the conversation history after each execution. For single-step queries, the data volume is small and the impact is limited. But in tasks involving multi-table joins or batch processing, the history grows quickly. The model must scan through large amounts of raw data to find the truly relevant fields, which reduces inference efficiency. Earlier key information may also be ignored, leading to repeated calls, parameter errors, or contradictory conclusions.

    This phenomenon can be called context corruption. The root cause is that raw data and reasoning processes share the same context space.

    The Idea Behind Programmatic Tool Calling

    The research direction referenced by ProgAgent centers on having the model generate a program instead of reporting each tool result step by step. The program calls tools sequentially, processes the data, and finally hands the conclusion to the model.

    In this mode, tool return values are assigned to variables within the program. These variables exist only in the program’s runtime environment and do not automatically enter the conversation history. The model only sees what the program outputs via print or an agreed return mechanism. Therefore, the model receives a filtered summary rather than the entire raw dataset.

    Comparison of Two Modes

    Dimension Direct Calling Programmatic Calling
    Tool return values Added as-is to conversation context Stored in program variables; only needed parts are output
    Model interaction rounds One interaction per step Generate a program once, then aggregate results after execution
    Context growth Increases with number of steps Depends mainly on output size
    Number of tool calls Decided step by step by the model Decided by the program; the number may not decrease
    Error handling Depends on model judgment for retries Can use try/except for fixed processing flows
    Best suited for Single-step or few calls, requiring manual confirmation Batch processing, multi-step calculations, predefined flows

    Note that programmatic calling reduces the amount of data entering context, but it does not necessarily reduce the number of tool calls. If the program calls the API for each record individually, the request volume remains high. If the underlying system provides batch endpoints, those should be preferred, as they reduce both request count and context usage.

    Three Underlying Advantages

    First, scope isolation. Intermediate variables exist only during program execution. The model focuses on the program logic and final output, without needing to process each raw record.

    Second, control flow expression. for loops, if conditions, sorting, and aggregation can be expressed in code. Filtering and statistics that would otherwise require multiple model decisions can be completed in a single execution.

    Third, exception isolation. try/except can set failure handling for individual records. If one order errors, other orders can still be processed, and the failure count is recorded. The model does not have to decide the next step after each error.

    These advantages do not guarantee success automatically. The quality of the program depends on whether the code is correct and whether the tool interfaces are stable.

    Example: Counting Unshipped Orders

    Assume the business requirement is: among 800 unshipped orders, calculate the total value of orders exceeding $100, and find the top three regions with the highest number of such orders. The code below is illustrative and cannot be run directly. It assumes the host system provides three tool functions and that the code executes in a restricted sandbox.

    Tool interface contract:

    • tool_query_unshipped_orders(limit: int) -> list: returns a list of unshipped orders, each containing id.
    • tool_get_order_detail(order_id: str): returns order details, including amount (USD, float) and customer_id.
    • tool_get_customer(customer_id: str): returns customer information, including region.
    1. # Illustrative code, not directly runnable.
    2. # Before running, the host system must register the above tool_* functions
    3. # and restrict their accessible scope in the sandbox.
    4. from collections import Counter
    5. MAX_ORDERS = 800 # Maximum number of orders processed in one task
    6. THRESHOLD = 100 # Amount threshold (USD)
    7. total_value = 0.0
    8. region_counter = Counter()
    9. failed_orders = []
    10. try:
    11. orders = tool_query_unshipped_orders(limit=MAX_ORDERS)
    12. for order in orders:
    13. try:
    14. detail = tool_get_order_detail(order.id)
    15. if detail.amount <= THRESHOLD:
    16. continue
    17. total_value += detail.amount
    18. customer = tool_get_customer(detail.customer_id)
    19. region_counter[customer.region] += 1
    20. except Exception as e:
    21. failed_orders.append(order.id)
    22. top_3 = region_counter.most_common(3)
    23. print(f"Total value of orders above {THRESHOLD} USD: {total_value:.2f}")
    24. print(f"Top 3 regions by order count: {top_3}")
    25. print(f"Number of failed orders: {len(failed_orders)}")
    26. except Exception as e:
    27. # Only output the exception type to avoid leaking interface details
    28. print(f"Task failed: {type(e).__name__}")

    The code makes two assumptions. First, regional ranking is based on the count of orders exceeding the threshold. Second, the amount field is represented as a numeric USD value.

    After running this code, the model’s context only contains a few lines of output. Order details and customer information stay in program variables and no longer enter the conversation history one by one. However, this code still calls two interfaces for each order. If the system provides a batch query endpoint for order details, that should be used instead.

    About Experimental Data

    Some studies show that as task data scale increases, the pass rate of direct calling mode drops noticeably, while programmatic calling maintains better stability. However, the original material does not specify model versions, task types, measurement methods, or sample sizes for the pass rates. This article does not cite specific numbers.

    To evaluate actual effectiveness, consult the original paper or run controlled experiments on your business. Experiments can compare both modes in terms of success rate, token consumption, and latency across different data scales.

    Security and Operational Considerations for Deployment

    Allowing the model to generate and execute code introduces new risks. The following points are recommended for deployment:

    • Least privilege: Only expose tools that are necessary for the task. Read-only tasks should not have write access.
    • Sensitive data: Redact sensitive information before it reaches the output, such as phone numbers, emails, and ID numbers.
    • Resource limits: Set CPU, memory, runtime, and network access limits for each execution to prevent infinite loops from exhausting resources.
    • Network isolation: The sandbox should only access whitelisted service addresses.
    • Audit logs: Record generated code, called tools, parameter summaries, execution results, and elapsed time for traceability.
    • Write operation protection: For operations involving writes, sends, or charges, perform pre-checks and idempotency validation. Critical actions should require manual confirmation, and compensation steps for failures should be designed.
    • Input validation: Before calling a tool, check the type and value range of parameters generated by the model.

    Applicability Boundaries

    Programmatic calling is not suitable for all scenarios:

    • If the model’s code generation capability is weak, the generated program