Agent DailyAgent Daily
tutorialintermediate

Programmatic tool calling (PTC) Reduce latency and token consumption by letting Claude write code that calls tools programmatically in the code execution environment.

cookbook
View original on cookbook

Programmatic Tool Calling (PTC) enables Claude to write and execute code that calls tools directly within the code execution environment, eliminating round-trips through the model for each tool invocation. This approach significantly reduces latency and token consumption, especially when dealing with large datasets or sequential tool dependencies. The cookbook demonstrates PTC using a team expense management API scenario where Claude analyzes employee expenses across multiple tool calls, filters irrelevant data programmatically, and identifies budget overages without excessive context window usage.

Key Points

  • PTC allows Claude to write code that calls tools programmatically in the execution environment rather than requiring model round-trips for each tool invocation
  • Dramatically reduces end-to-end latency for multiple tool calls and token consumption by enabling the model to filter irrelevant context before it reaches the context window
  • Ideal for scenarios with sequential dependencies (e.g., fetching expenses first, then checking custom budgets) and large result sets (100+ expense line items per employee)
  • Requires Python 3.11+, Anthropic SDK >= 0.72, and understanding of async/await patterns and agentic tool-calling concepts
  • Tool definitions must clearly specify return formats (JSON arrays vs. objects) and parsing instructions for Claude to handle programmatically
  • Only approved expenses should be counted toward budget limits; the model must filter by status='approved' when aggregating data
  • PTC enables context optimization by allowing Claude to grep/filter large noisy files and remove irrelevant data before model processing
  • The cookbook uses three API functions: get_team_members (retrieve employees by department), get_expenses (fetch line items with metadata), and get_custom_budget (check budget exceptions)
  • Traditional tool calling serves as a baseline comparison to demonstrate PTC's efficiency gains in latency and token usage
  • Claude can write code to aggregate expenses by category, compare against budget limits, and compile reports without manual intervention

Found this useful? Add it to a playbook for a step-by-step implementation guide.

Workflow Diagram

Start Process
Step A
Step B
Step C
Complete
Quality

Concepts

Artifacts (3)

PTC Tool Definitionspythonconfig
tools = [
  {
    "name": "get_team_members",
    "description": "Returns a list of team members for a given department. Each team member includes their ID, name, role, level (junior, mid, senior, staff, principal), and contact information.",
    "input_schema": {
      "type": "object",
      "properties": {
        "department": {
          "type": "string",
          "description": "The department name. Case-insensitive. Available: engineering, sales, marketing."
        }
      },
      "required": ["department"]
    }
  },
  {
    "name": "get_expenses",
    "description": "Returns all expense line items for a given employee in a specific quarter. Only expenses with status='approved' should be counted toward budget limits.",
    "input_schema": {
      "type": "object",
      "properties": {
        "employee_id": {
          "type": "string",
          "description": "The unique employee identifier"
        },
        "quarter": {
          "type": "string",
          "description": "Quarter identifier: 'Q1', 'Q2', 'Q3', or 'Q4'"
        }
      },
      "required": ["employee_id", "quarter"]
    }
  },
  {
    "name": "get_custom_budget",
    "description": "Get the custom quarterly travel budget for a specific employee. Standard budget is $5,000; some employees have custom exceptions.",
    "input_schema": {
      "type": "object",
      "properties": {
        "user_id": {
          "type": "string",
          "description": "The unique employee identifier"
        }
      },
      "required": ["user_id"]
    }
  }
]
PTC Setup and Client Configurationpythonscript
from dotenv import load_dotenv
from utils.visualize import visualize
import anthropic
import json
from utils.team_expense_api import get_custom_budget, get_expenses, get_team_members

load_dotenv()

MODEL = "claude-sonnet-4-6"
viz = visualize(auto_show=True)

client = anthropic.Anthropic()

tool_functions = {
    "get_team_members": get_team_members,
    "get_expenses": get_expenses,
    "get_custom_budget": get_custom_budget,
}
PTC Implementation Patternpythontemplate
# Programmatic Tool Calling Pattern
# Claude writes code that calls tools directly in the execution environment

# 1. Define tools with clear return format specifications
# 2. Pass tools to Claude via messages API
# 3. Claude writes code that:
#    - Calls tools programmatically
#    - Filters irrelevant data (e.g., non-approved expenses)
#    - Aggregates results (e.g., sum by category)
#    - Handles sequential dependencies (e.g., check budget after fetching expenses)
# 4. Code executes in the code execution environment
# 5. Results returned without additional model round-trips

# Key Benefits:
# - Reduced latency: No round-trips for each tool call
# - Reduced tokens: Model can filter context before processing
# - Handles large datasets: 100+ expense items per employee
# - Sequential logic: Dependencies handled in code, not conversation