ByteCosts
programmatic-tool-calling-vs-tool-loops.mdx

AI Coding Agents

Programmatic tool calling vs. sequential tool loops

Programmatic tool calling lets a model write a script that calls several tools and returns only the data the model needs. Use it when intermediate results can be filtered by a known rule. Keep sequential calls when model judgment between results determines the next action, and compare both options using billed prompt replays, generated tokens, and any container charge.

Decide which results the model needs to see

Suppose a coding agent has to review recorded check results for a list of components. If the next step is to identify any failed checks, code can apply the same test to every result and return a short list. Asking the model to inspect each response individually sends the checks for every successful component through the model too. If the agent keeps the entire transcript, those responses remain in the input for later requests even after it has used them to make its initial comparison.

A sequential loop asks the model to call a tool, adds the result to the conversation, and asks the model to continue. Under full-history replay, each result is input when it first arrives and again on every later request. Prompt caching can lower the price of re-reading a matching prefix. Each reused result still takes up room in the prompt. If the loop continues after the lookups finish, keep counting those reads on the follow-up requests. Anthropic prompt caching

With Anthropic’s programmatic tool calling, Claude generates code that runs in a container. The client may still receive tool calls and supply responses over the API. The container uses these intermediate responses, and Claude sees the final code output. Plan for application round trips where the client has to fulfill a call. Each of those trips needn’t make the model inspect the tool output or decide which record to fetch next. Programmatic tool calling

WorkloadSequential callsProgrammatic calls
Fetch a known set of records and apply one filterEach result enters the conversationA script can apply the rule and return the retained records
Decide which diagnostic to run after inspecting the previous resultThe model can inspect the evidence before choosingUse a script for portions that can follow a known rule
Make a few calls with short resultsLittle persisted result history to avoidInclude script generation and container startup in the comparison
Investigate a surprising or incomplete resultIntermediate results are visible to the model and in its transcriptReturn evidence references and keep a separate client trace

Tool definitions are a separate source of input. A workflow can have expensive definitions and tiny tool responses, or a small tool list and expensive results. Identify which category is growing before changing both. A trace that attributes the two separately can tell you whether to filter tool results or narrow the tool definitions presented to the model. MCP tool definition token cost

Declare which tools the script can call

As of November 30, 2026, Anthropic documents code_execution_20260120 or later for programmatic tool calling. Add allowed_callers to the tool definition with code_execution_20260120 in the list. Claude Haiku 4.5 accepts that code execution version and later versions but lacks programmatic tool calling support. The feature is ineligible for Zero Data Retention, and Anthropic says that container data, including execution artifacts and outputs, is retained for up to 30 days. Check these conditions before routing internal records through the container. Programmatic tool calling

This illustrative Messages request uses an application-defined read-only tool named lookup_component. The property component_id and the returned failed_checks belong to that tool’s contract. Your application supplies the actual lookup, and the user message supplies the scope of IDs. The JSON is a request example for an integration, while the local cost model below runs independently.

{
  "model": "claude-sonnet-5-5",
  "max_tokens": 2048,
  "messages": [
    {
      "role": "user",
      "content": "In code, look up component-01 through component-20. Return only components with failed checks, including their IDs and failed check names."
    }
  ],
  "tools": [
    {"type": "code_execution_20260120", "name": "code_execution"},
    {
      "name": "lookup_component",
      "description": "Read recorded checks for one component. Returns JSON with component_id and an array of failed check names in failed_checks.",
      "input_schema": {
        "type": "object",
        "properties": {"component_id": {"type": "string"}},
        "required": ["component_id"]
      },
      "allowed_callers": ["code_execution_20260120"]
    }
  ]
}

If the script requests an application tool, the response marks the caller on the tool_use block. The documented continuation sends the full conversation history, the same tools array, and the paused response’s container ID in container. The new user message for that continuation contains only tool_result blocks. Keep client-side access and parameter checks in the handler. Anthropic describes allowed_callers as guidance to Claude and says the client should be prepared to handle direct calls to the tools it defines. Programmatic tool calling

Design the tool output so the script can tell the difference between a component with no failures and a component it couldn’t check. Include the evidence the model needs to report a real exception or request a retry. If all that comes back is a list of failures, a partial run and a successful run may appear identical to the model. Returning checked IDs or a coverage count and explicit lookup errors gives it a way to catch missing records. Preserve full details in the tool’s application trace so debugging doesn’t require replaying every raw result through the model.

Read the published savings in context

Anthropic reported that average token usage in its complex research tasks fell from 43,588 to 27,297, a 37% reduction, with programmatic tool calling. The comparison reflects the intermediate data in those workloads and what the scripts returned. Anthropic advanced tool use

In Anthropic’s internal evaluations, a project-management agent benchmark with 75 tools used roughly 38% fewer billed input tokens with programmatic calling. On τ²-bench, where turns make one or two sequential tool calls, it cost roughly 8% more. Anthropic reported unchanged accuracy or scores in both cases. Before enabling the feature broadly, compare billed input tokens with and without allowed_callers on a representative sample of traffic. Programmatic tool calling

Anthropic’s separate code-execution-with-MCP example went from 150,000 tokens to 2,000 by loading only the tool definitions it needed. That example measures discovery costs. Track those separately from the token cost of reading tool results. Anthropic code execution with MCP

Cloudflare’s Code Mode turns MCP tools into a TypeScript API and asks the model to write TypeScript that calls the tools. Cloudflare reports that agents can use a larger set of tools and use more complex tools through that API. When chaining calls, the script can return only the final results the model needs. Cloudflare Code Mode

Estimate twenty lookups and ten follow-ups

Assume 20 lookups, each returning 2,000 tokens, followed by ten more model requests. Count one initial dispatch in each design. In the sequential case, one model request consumes each lookup result and the transcript retains all 40,000 result tokens. In the programmatic case, one request consumes a 500-token filtered result that stays in history, and the intermediate lookups stay in code. The 500 tokens are an assumption for the final output of the script.

Hold the cacheable base prompt at 2,000 tokens and the other uncached input at 400 tokens per model request. That second number represents all input beyond the base and result history as a fixed allowance. The model generates 100 output tokens per request, except for the programmatic dispatch, where it generates 600 to allow for the script. Output counts include any billed reasoning in this fixture. The calculation omits growth of non-result history and any additional inference outside the modeled requests.

Anthropic excludes intermediate programmatic tool results from token usage and counts the final code execution result and Claude’s response. The estimate assumes all 20 client tool-result round trips simply resume the running script, so it adds zero model tokens for those intermediate continuations even though the client sends the conversation history. The estimate prices the dispatch and the model request that reads the final result. If your trace shows additional inference during a retry or continuation, price that usage separately. Programmatic tool calling, Anthropic advanced tool use

For uncached sequential input, each lookup result contributes on arrival and on every later request. The first result appears on 30 requests, and the last appears on 11. Add those appearances and multiply by 2,000 to get 820,000 result-token occurrences. In the cached case, each result is written on arrival and the previous prefix is read on later requests, assuming stable breakpoints and requests within the five-minute lifetime. The programmatic result has one write and ten reads. This compares a warm growing prefix with full-history replay at the uncached rate.

Price Sonnet 5.5 at $2 per million uncached input, $0.10 per million cache reads, $2.50 per million five-minute writes, and $10 per million output. Multiply each token bucket by its rate and divide by one million, then add applicable container cost. As of November 30, 2026, Anthropic says there’s no additional code execution charge when the request includes web_search_20260209 or web_fetch_20260209 or later versions. Otherwise execution time is billed separately with a five-minute minimum, 1,550 free hours per organization per month, then $0.05 per container hour. Assume this lookup uses one minimum-duration billable container after the allowance, about $0.004167. The container column would be zero within the free allowance. ByteCosts pricing index, Anthropic pricing

Run the cost model before choosing a route

Save the Python reference as cost_model.py and run python3 -B cost_model.py to reproduce the table. The script models when new result tokens arrive in the model’s history, including the leading dispatch and ten later requests that continue reading the history. When you adapt the input sequence, write a local test that checks one known case by hand. For example, a cached run with one 500-token result and ten further requests should write 2,500 tokens, including the initial 2,000-token base prompt.

from decimal import Decimal as D

INPUT, READ, WRITE, OUTPUT = map(D, ("2", "0.10", "2.50", "10"))
CONTAINER_MINIMUM = D(5) / 60 * D("0.05")


def estimate(result_batches, followups, *, cached, script_output=100, container_usd=D(0)):
    history = 0
    uncached = 0
    reads = 0
    writes = 0
    arrivals = [0, *result_batches, *([0] * followups)]
    for index, new_result in enumerate(arrivals):
        uncached += 400
        if cached:
            reads += (2_000 if index else 0) + history
            writes += new_result + (0 if index else 2_000)
        else:
            uncached += 2_000 + history + new_result
        history += new_result

    output = script_output + 100 * (len(arrivals) - 1)
    token_usd = (uncached * INPUT + reads * READ + writes * WRITE + output * OUTPUT) / 1_000_000
    return uncached, reads, writes, output, token_usd, token_usd + container_usd


if __name__ == "__main__":
    print("workflow cache uncached reads writes output token_USD total_USD")
    for cached in (False, True):
        for name, batches, output, fee in (
            ("sequential", [2_000] * 20, 100, D(0)),
            ("programmatic", [500], 600, CONTAINER_MINIMUM),
        ):
            uncached, reads, writes, output, tokens, total = estimate(
                batches, 10, cached=cached, script_output=output, container_usd=fee
            )
            print(name, cached, uncached, reads, writes, output, f"{tokens:.6f}", f"{total:.6f}")

These are estimates from running the script on the assumed lookup and follow-up fixture. All dollar amounts are in USD. The total includes the assumed container charge where applicable.

WorkflowUncached input tokensCache readsCache writesOutput tokensToken estimateTotal estimate
Sequential, uncached894,400003,100$1.819800$1.819800
Programmatic, uncached34,300001,700$0.085600$0.089767
Sequential, cached12,400840,00042,0003,100$0.244800$0.244800
Programmatic, cached4,80027,0002,5001,700$0.035550$0.039717

Use the cached comparison when a stable prefix is already part of your design. In that case much of the sequential replay is cheap, and the model still reads a long history. When the sequential workload has a single small result and few follow-ups, the retained history contributes less. A script that mostly forwards all of its inputs will also put more data into later turns. Adjust the final result, request count, and actual runtime in the calculation before treating the estimate as a reason to migrate.

Pilot one filter and compare accepted results

Choose a read-only lookup with a clear filter. Run the same input through both designs and check that they agree on failed checks and explicitly report missing records. Record the model usage, container usage, and end-to-end duration. Keep sequential calls for steps that need the model to reason about a result before acting, for small results where script overhead dominates, and for a debugging path where intermediate evidence needs to remain visible.

For test logs, start with the contract in the test output triage filter. Store per-request usage and the outcome using coding agent cost telemetry. If tool definitions turn out to be the larger cost, start with the lazy MCP tool registry and keep the result-filtering experiment comparable.

Sources

Interactive report

  • The Tool Tax: Connecting a tool server can make the very next request bigger, even if the agent never calls it. Follow the cost of the catalog, the search, and the results that come back.

How this note was produced

Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.

Programmatic tool calling vs. sequential tool loops. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/programmatic-tool-calling-vs-tool-loops/

Sources