Programmatic Tool Calling: A Way to Reduce Context Corruption in Agents

    When agents handle multi-step tasks with large intermediate results, stuffing every tool response into the conversation often causes forgotten facts, repeated calls, and actions taken before conditions are met. This article explains that failure mode and describes programmatic tool calling: the model writes a program that calls tools, keeps intermediate data in variables, and returns only printed summaries to the conversation. It covers how the approach works, how it compares with step-by-step calling, where it helps, how to run it safely, and how to measure it on your own tasks.

    Agents are often unstable on complex tasks. A user asks for something that involves several steps, multiple data sources, and multiple conditions. The agent starts out fine. As tool calls accumulate, the conversation fills with query results. The model then forgets key data it already retrieved, calls the same interface again, or continues even when a precondition is not met.

    These failures look less like weak reasoning and more like a problem with how information is passed along. This article first explains why that happens, then describes a practice closer to how programmers work: programmatic tool calling.

    1. Where the problem comes from

    A conventional agent works by reporting each step. Every tool call—querying a database, reading a file, or calling an external API—writes the raw result into the conversation history, and later reasoning depends on that history. For short tasks this is fine. For bulk data it breaks quickly. Counting hundreds of orders, joining several tables, or filtering and then aggregating produces a large intermediate result at every step.

    1. Context corruption

    Tool results often include redundant fields, repeated structures, and details that do not matter for the task. Each additional call piles more of this into the context and competes for the model’s attention. When irrelevant content dominates, the model gets worse at extracting what actually matters. It has not become less capable; it is buried in noise and cannot focus on the variables that should drive the decision.

    2. Orchestration breaks down

    As the context nears the model’s length limit, two failures show up. The first is forgetting: a key result from an earlier step is never used later. The second is disordered sequencing: the agent queries data it already has, or it performs a write before a precondition is satisfied. Together, these failures make the task hard to control.

    2. What programmatic tool calling is

    The core idea is that the model no longer calls tools one at a time. It first generates a program. Inside that program it can call whatever tools it needs. Results stay in program variables. Only what the program prints with print() enters the conversation history, and later steps can see only that output.

    The intermediate work stays inside the program logic and is not exposed to the model. The model attends to the program’s structure—loops, conditions, and error handling—and to the few summary lines printed at the end.

    A concrete example

    Suppose the task is to total the value of 800 unshipped orders over 100 dollars and find the three regions with the most such orders.

    Step by step, the agent would query the order list, then fetch each order’s details, then look up the customer region for orders that qualify. Every response is written into history. The model has to remember and aggregate a large amount of data, and it often gets that wrong.

    A programmatic version can look like this:

    1. orders = tool.query_orders(status="unshipped")
    2. total = 0.0
    3. region_count = {}
    4. errors = []
    5. for o in orders:
    6. try:
    7. detail = tool.get_order_detail(o["id"])
    8. if detail["amount"] > 100:
    9. total += detail["amount"]
    10. region = tool.get_customer_region(detail["customer_id"])
    11. region_count[region] = region_count.get(region, 0) + 1
    12. except Exception as e:
    13. errors.append((o["id"], str(e)))
    14. top3 = sorted(region_count.items(), key=lambda x: x[1], reverse=True)[:3]
    15. print(f"Total value: {total:.2f}, top 3 regions: {top3}, error count: {len(errors)}")

    This snippet is only an illustration and will not run as written. tool is an adapter you implement, matching your real interfaces, field names, and pagination rules. The model only needs the final printed line, so the context cost stays small.

    3. Comparing the two approaches

    Dimension Step-by-step calls Programmatic calls
    Where intermediate data goes Written entirely into the conversation Kept in program variables
    Context growth Grows quickly with each call Depends on the length of printed output
    Error handling A single failure can derail later steps try/except can record the error and continue
    Explainability The process has to be reconstructed from the transcript The source is the record of the decision
    Main risk Forgotten information and repeated calls Generated code may exceed its authority or act incorrectly

    4. Benefits and limits

    1. Context use stays more predictable

    On aggregation tasks, if the output is a fixed-format summary, conversation length barely grows with the amount of data. If the output includes an error list or one line per record, length still grows with the data. Controlling the format and length of output is a prerequisite for this method.

    2. Logic is explicit

    Loops, branches, and exception handling turn business rules into code. The model does not have to recall the basis of each earlier judgment, because variables and control flow are fixed in the program. Attention can stay on the overall plan.

    3. Error handling is more robust

    If one data source is temporarily unavailable, the program can catch the exception, record it, and keep processing the rest, then report the failure count in the summary. With step-by-step calls, the model has to decide how to recover on its own, and the result is inconsistent.

    4. Easier to explain and maintain

    The code is a complete record of what the agent did. A developer can read the program and see why a tool was called, or change the logic to correct behavior, without retraining the model. Generated code still needs review. Readability is not a reason to skip an audit.

    5. Putting it into practice

    1. Design a tool adapter layer

    Write an adapter for each external system and return a consistent structure. Adapters should return only the fields the task needs, not the entire raw response. High-volume interfaces should support pagination and filter parameters. Prefer to design write operations separately from reads.

    2. Run the code in a sandbox

    In production, code generated by the model must run in an isolated sandbox. Common controls include:

    • Least privilege: the sandbox can reach only the interfaces and data the task requires, with read-only accounts preferred.
    • Network allowlists: connections are limited to specified domains or service addresses.
    • Resource limits: set an execution timeout, a memory cap, and a maximum output length.
    • Audit logs: record the code that ran, the interfaces it called, and a summary of what came back.
    • Human approval: for deletes, outbound sends, or permission changes, a person confirms the action before it runs.

    3. Agree on an output format

    Program output should use a fixed format, such as JSON or text with fixed fields. A stable format lets later steps parse the result reliably. Cap the output length as well. When it would exceed the cap, keep the statistics and only the first few sample rows.

    4. What to do during training

    If you train your own model, a common path is supervised fine-tuning so the model learns to turn a task description into a code skeleton. The code is then executed in a sandbox, and the execution result plus the final answer are used to judge whether the generation was correct. On top of that, reinforcement learning can optimize code structure according to task pass rate. How well these methods work depends on the task and the data, and it has to be measured in your own setting.

    5. Use both styles together

    Simple work—a single query, or an operation with only one or two steps—still fits step-by-step calling. Complex bulk work can switch to programmatic calling. Letting the system choose based on task size, number of steps, and risk is usually safer than using one style for everything.

    6. Where it fits and where it does not

    It fits well when:

    • You need to filter, aggregate, and sort a large number of records.
    • A business flow spans several systems, but each step is simple.
    • The decision has many branches, such as risk rules or inventory allocation.
    • The task needs retries or backtracking that loops and exception handling can express.

    Be careful when:

    • Every step needs the user to confirm. Writing the whole flow as one program removes that flexibility.
    • The data is a live stream, such as a continuous market feed. An event-driven design is a better fit.
    • You cannot isolate execution. Arbitrary code can delete data, access resources it should not, or leak credentials. Without isolation, do not use this approach.

    7. Risks

    Generated code runs according to its own logic, and wrong code can cause real damage. Typical risks include deleting data by mistake, sending incorrect messages in bulk, reading data beyond the granted permissions, and writing credentials into logs. Before going live: require human approval for writes, back up critical data and verify that restore works, give the sandbox its own credentials, and review audit logs on a regular schedule.

    8. How to check whether it helps on your tasks

    Whether this method works depends on the task. Do not rely only on someone else’s results. Measure it as follows:

    1. Pick a representative set of tasks and split them into small, medium, and large by data size.
    2. Run the same set with step-by-step calling and with programmatic calling.
    3. Record pass rate, average context length, number of calls, and error types for each group.
    4. Compare the two approaches at each data size and find the point where switching becomes worthwhile.

    Adopt it at scale only after your own data and tools show a clear result.

    9. Common questions

    What is programmatic tool calling?
    The model first generates a program. The program calls tools and handles intermediate data, and only what it prints is returned to the model.

    How do you tell whether a task should use it?
    It usually fits when the task involves a lot of data, several conditions, or consistent error handling. It is a poor fit when every step needs a person to confirm, or when the data arrives as a live stream.

    What goes wrong most often?
    First, output length is not capped, so the context still grows. Second, the sandbox is too privileged and the program can reach systems it should not. Third, tool adapters return too many fields, and the program itself becomes hard to maintain.

    What should you watch for in use?
    Validate in a read-only environment first, then open write operations gradually. Log every execution, and keep a way for a person to step in.

    Programmatic tool calling does not make an agent capable of everything. Its value is moving intermediate work out of the conversation and into a program. For bulk tasks with many conditions, that split usually makes the agent more stable. Measure it on your own tasks before you decide how widely to use it.