Programmatic Tool Calling with Amazon Nova Pro: Reduce Round Trips by 70%
Complete Python demo comparing traditional vs programmatic tool calling on Amazon Bedrock. AgentCore Code Interpreter executes AI code in secure sandboxes, reducing round trips 60-70% and tokens 30-50%. Includes copy-paste code, state/local government use cases (permits, tax, citizen services), security considerations, and full setup guide. Perfect for building responsive AI agents for government applications requiring multiple data sources
Programmatic Tool Calling with Amazon Nova Pro: A Game Changer for Agentic AI
Author: Mohan Alapati
Date: February 21, 2026
TL;DR
Amazon Bedrock now supports programmatic tool calling via the AgentCore Code Interpreter. Instead of making multiple round-trip API calls for each tool invocation, the model writes Python code that calls multiple tools in a single execution within a secure sandbox. This dramatically reduces latency and token usage.
Key Benefits:
- 60-75% reduction in round trips
- 30-50% token savings from in-sandbox data filtering
- Lower latency for multi-tool workflows
- Better for complex data processing tasks
The Problem with Traditional Tool Calling
When building AI agents that need to call multiple tools (APIs, databases, calculations), the traditional approach requires:
- Model decides to call Tool A → API round trip
- Tool A returns data → Send back to model
- Model decides to call Tool B → API round trip
- Tool B returns data → Send back to model
- Model processes and responds → Final round trip
Each round trip adds latency and tokens. For state/local government use cases involving multiple data sources (permits, tax records, citizen services), this becomes a bottleneck.
The Solution: Programmatic Tool Calling
With programmatic tool calling, the model writes Python code that:
- Calls multiple tools in sequence
- Processes and filters data in the sandbox
- Returns only the final result to the model
Flow:
- Model generates Python code → Single API call
- Code executes in AgentCore Code Interpreter secure sandbox → Calls all tools in isolated environment
- Data is processed and filtered inside the sandbox (never leaves AWS)
- Only filtered result returns to model → Final response
Key Security Feature: Code runs in completely isolated sandbox with no access to your infrastructure unless explicitly configured.
Real-World Example: Stock Comparison
I built a minimal demo comparing both approaches. Task: Compare two stocks (get prices, company info, calculate PE ratios).
Results:
Metric | Traditional | Programmatic | Improvement |
|---|---|---|---|
Round trips | 5-7 | 2 | 60-70% fewer |
Total tokens | ~2,000 | ~1,200 | 40% reduction |
Latency | Higher | Lower | 30-50% faster |
State & Local Government Use Cases
1. Multi-Source Permit Analysis
Scenario: Citizen asks about building permit requirements across zoning, environmental, and historical databases.
Traditional: 5-8 round trips querying each database sequentially
Programmatic: Single code execution queries all databases, filters relevant regulations, returns summary
2. Tax Assessment Workflows
Scenario: Calculate property tax based on assessment data, exemptions, and payment history.
Traditional: Multiple API calls to retrieve each data point
Programmatic: Code fetches all data, performs calculations in sandbox, returns final assessment
3. Citizen Service Routing
Scenario: Analyze citizen request, check eligibility across multiple systems, route to appropriate department.
Traditional: Sequential checks create delays
Programmatic: Parallel eligibility checks, immediate routing decision
4. Budget Analysis & Reporting
Scenario: Generate financial reports combining data from multiple fiscal systems.
Traditional: Large datasets bloat context window
Programmatic: Process and aggregate data in sandbox, return only summary statistics
When to Use Programmatic Tool Calling
✅ Use when:
- Multiple tool calls needed for single task
- Large datasets that need filtering before model sees them
- Complex calculations or data transformations required
- Latency is critical (citizen-facing applications)
❌ Stick with traditional when:
- Single tool call is sufficient
- Model needs to see full data to make decisions
- Simple, straightforward workflows
Getting Started
Prerequisites:
- Amazon Bedrock access with Nova Pro
- AgentCore Code Interpreter enabled
- IAM permissions for
bedrock:InvokeModelandbedrock-agentcore:*actions
Complete Demo Code
Copy this entire code and save as
bedrock_tool_calling_demo.py :"""Minimal demo comparing Traditional vs Programmatic Tool Calling with Amazon Nova Pro on BedrockUses AgentCore Code Interpreter for real sandbox execution"""import boto3import jsonimport timefrom bedrock_agentcore.tools.code_interpreter_client import code_session
# Initialize Bedrock clientbedrock = boto3.client('bedrock-runtime', region_name='us-east-1')MODEL_ID = 'us.amazon.nova-pro-v1:0'REGION = 'us-east-1'
# Simple tool definitionsTOOLS = [ { "toolSpec": { "name": "get_stock_price", "description": "Get current stock price for a symbol. Call this separately for each stock.", "inputSchema": { "json": { "type": "object", "properties": { "symbol": {"type": "string", "description": "Stock symbol (one at a time)"} }, "required": ["symbol"] } } } }, { "toolSpec": { "name": "get_company_info", "description": "Get company information for a symbol. Call this separately for each stock.", "inputSchema": { "json": { "type": "object", "properties": { "symbol": {"type": "string", "description": "Stock symbol (one at a time)"} }, "required": ["symbol"] } } } }, { "toolSpec": { "name": "calculate_metrics", "description": "Calculate financial metrics. Call this separately for each stock after getting price and info.", "inputSchema": { "json": { "type": "object", "properties": { "symbol": {"type": "string", "description": "Stock symbol"}, "price": {"type": "number"}, "market_cap": {"type": "number"} }, "required": ["symbol", "price", "market_cap"] } } } }]
# Mock tool implementationsdef execute_tool(tool_name, tool_input): """Execute tool and return mock data""" if tool_name == "get_stock_price": price = {"AAPL": 178.50, "MSFT": 420.30, "GOOGL": 142.80}.get(tool_input["symbol"], 100.0) return {"price": price, "symbol": tool_input["symbol"]} elif tool_name == "get_company_info": return {"AAPL": {"name": "Apple Inc.", "market_cap": 2800000000000, "sector": "Technology"}, "MSFT": {"name": "Microsoft Corp.", "market_cap": 3100000000000, "sector": "Technology"}, "GOOGL": {"name": "Alphabet Inc.", "market_cap": 1800000000000, "sector": "Technology"} }.get(tool_input["symbol"], {"name": "Unknown", "market_cap": 1000000000, "sector": "Unknown"}) elif tool_name == "calculate_metrics": pe_ratio = tool_input["market_cap"] / (tool_input["price"] * 1000000000) return {"symbol": tool_input["symbol"], "pe_ratio": round(pe_ratio, 2), "valuation": "high" if pe_ratio > 25 else "normal"} return {}
# ============= EXAMPLE 1: TRADITIONAL TOOL CALLING =============def traditional_approach(): """Traditional: Model calls tools one at a time with round trips""" print("\n" + "="*70) print("EXAMPLE 1: TRADITIONAL TOOL CALLING") print("="*70) start_time = time.time() total_tokens = 0 round_trips = 0 system_prompt = """You must call tools one at a time in sequence. For each stock comparison:1. First get_stock_price for stock 12. Then get_company_info for stock 1 3. Then calculate_metrics for stock 14. Then get_stock_price for stock 25. Then get_company_info for stock 26. Then calculate_metrics for stock 27. Finally provide comparison
Call only ONE tool at a time and wait for results."""
messages = [{"role": "user", "content": [{"text": "Compare AAPL and MSFT stocks. Get their prices, company info, and calculate PE ratios. Use the tools sequentially."}]}] max_iterations = 10 for iteration in range(max_iterations): round_trips += 1 print(f"\n--- Round Trip {round_trips} ---") response = bedrock.converse( modelId=MODEL_ID, messages=messages, toolConfig={"tools": TOOLS}, system=[{"text": system_prompt}] ) total_tokens += response['usage']['inputTokens'] + response['usage']['outputTokens'] print(f"Tokens: {response['usage']['inputTokens']} in, {response['usage']['outputTokens']} out") messages.append({"role": "assistant", "content": response['output']['message']['content']}) if response['stopReason'] == 'tool_use': tool_results = [] for content in response['output']['message']['content']: if 'toolUse' in content: tool_use = content['toolUse'] print(f"Tool called: {tool_use['name']} with {tool_use['input']}") result = execute_tool(tool_use['name'], tool_use['input']) tool_results.append({ "toolResult": { "toolUseId": tool_use['toolUseId'], "content": [{"json": result}] } }) messages.append({"role": "user", "content": tool_results}) else: final_text = next((c['text'] for c in response['output']['message']['content'] if 'text' in c), "") print(f"\nFinal response: {final_text[:200]}...") break elapsed = time.time() - start_time print(f"\n{'='*70}") print(f"TRADITIONAL RESULTS:") print(f" Round trips: {round_trips}") print(f" Total tokens: {total_tokens}") print(f" Time: {elapsed:.2f}s") print(f"{'='*70}") return {"round_trips": round_trips, "tokens": total_tokens, "time": elapsed}
# ============= EXAMPLE 2: PROGRAMMATIC TOOL CALLING =============def programmatic_approach(): """Programmatic: Model writes code that executes in AgentCore Code Interpreter sandbox""" print("\n" + "="*70) print("EXAMPLE 2: PROGRAMMATIC TOOL CALLING (AgentCore Code Interpreter)") print("="*70) start_time = time.time() total_tokens = 0 system_prompt = """You are an AI assistant that writes Python code to solve tasks.You have access to these tool functions that are available in the execution environment:- get_stock_price(symbol: str) -> dict with 'price' and 'symbol'- get_company_info(symbol: str) -> dict with 'name', 'market_cap', 'sector'- calculate_metrics(price: float, market_cap: float, symbol: str) -> dict with 'pe_ratio' and 'valuation'
Write Python code that:1. Calls these functions to get data2. Processes and filters the results3. Returns only the essential comparison data
Return ONLY executable Python code, no explanations."""
messages = [{"role": "user", "content": [{"text": "Compare AAPL and MSFT stocks. Get their prices, company info, and calculate PE ratios. Write Python code using the available functions."}]}] print("\n--- Step 1: Model Generates Code ---") response = bedrock.converse( modelId=MODEL_ID, messages=messages, system=[{"text": system_prompt}] ) total_tokens += response['usage']['inputTokens'] + response['usage']['outputTokens'] print(f"Tokens: {response['usage']['inputTokens']} in, {response['usage']['outputTokens']} out") response_text = next((c['text'] for c in response['output']['message']['content'] if 'text' in c), "") if "```python" in response_text: code = response_text.split("```python")[1].split("```")[0].strip() elif "```" in response_text: code = response_text.split("```")[1].split("```")[0].strip() else: code = response_text.strip() print(f"\nGenerated code:\n{code[:400]}...") print("\n--- Step 2: Execute Code in Secure Sandbox ---") print("Creating isolated AgentCore Code Interpreter session...") exec_start = time.time() tool_definitions = """def get_stock_price(symbol): prices = {"AAPL": 178.50, "MSFT": 420.30, "GOOGL": 142.80} return {"price": prices.get(symbol, 100.0), "symbol": symbol}
def get_company_info(symbol): companies = { "AAPL": {"name": "Apple Inc.", "market_cap": 2800000000000, "sector": "Technology"}, "MSFT": {"name": "Microsoft Corp.", "market_cap": 3100000000000, "sector": "Technology"}, "GOOGL": {"name": "Alphabet Inc.", "market_cap": 1800000000000, "sector": "Technology"} } return companies.get(symbol, {"name": "Unknown", "market_cap": 1000000000, "sector": "Unknown"})
def calculate_metrics(price, market_cap, symbol): pe_ratio = market_cap / (price * 1000000000) return {"symbol": symbol, "pe_ratio": round(pe_ratio, 2), "valuation": "high" if pe_ratio > 25 else "normal"}""" full_code = tool_definitions + "\n\n" + code + "\n\nprint(result)" try: with code_session(REGION) as code_client: print("✓ Sandbox session started") print("✓ Executing code with tool calls...") response = code_client.invoke("executeCode", { "code": full_code, "language": "python", "clearContext": False }) execution_result = None for event in response["stream"]: if "result" in event: result_data = event["result"] if "output" in result_data: execution_result = result_data["output"] elif "error" in result_data: print(f"Execution error: {result_data['error']}") execution_result = "Error in execution" print("✓ Code executed successfully in isolated sandbox") print("✓ Session automatically cleaned up") except Exception as e: print(f"Sandbox execution error: {str(e)}") execution_result = "Execution failed" exec_time = time.time() - exec_start print(f"\nSandbox execution time: {exec_time:.3f}s") print(f"Filtered result from sandbox: {execution_result}") messages.append({"role": "assistant", "content": [{"text": response_text}]}) messages.append({"role": "user", "content": [{"text": f"Code execution result: {execution_result}\n\nProvide a brief summary of the comparison."}]}) print("\n--- Step 3: Model Generates Final Response ---") final_response = bedrock.converse( modelId=MODEL_ID, messages=messages, system=[{"text": system_prompt}] ) total_tokens += final_response['usage']['inputTokens'] + final_response['usage']['outputTokens'] print(f"Tokens: {final_response['usage']['inputTokens']} in, {final_response['usage']['outputTokens']} out") final_text = next((c['text'] for c in final_response['output']['message']['content'] if 'text' in c), "") print(f"\nFinal response: {final_text[:200]}...") elapsed = time.time() - start_time print(f"\n{'='*70}") print(f"PROGRAMMATIC RESULTS:") print(f" Round trips: 2 (code generation + final response)") print(f" Total tokens: {total_tokens}") print(f" Time: {elapsed:.2f}s") print(f" Sandbox execution: {exec_time:.3f}s") print(f"{'='*70}") return {"round_trips": 2, "tokens": total_tokens, "time": elapsed}
# ============= COMPARISON =============def main(): print("\n" + "="*70) print("AMAZON NOVA PRO: TRADITIONAL vs PROGRAMMATIC TOOL CALLING") print("="*70) trad = traditional_approach() prog = programmatic_approach() print("\n" + "="*70) print("SIDE-BY-SIDE COMPARISON") print("="*70) print(f"\n{'Metric':<25} {'Traditional':<20} {'Programmatic':<20} {'Improvement'}") print("-" * 70) print(f"{'Round trips':<25} {trad['round_trips']:<20} {prog['round_trips']:<20} {trad['round_trips']/prog['round_trips']:.1f}x fewer") print(f"{'Total tokens':<25} {trad['tokens']:<20} {prog['tokens']:<20} {(1-prog['tokens']/trad['tokens'])*100:.0f}% reduction") print(f"{'Latency (seconds)':<25} {trad['time']:<20.2f} {prog['time']:<20.2f} {(1-prog['time']/trad['time'])*100:.0f}% faster") print("\n" + "="*70) print("KEY BENEFITS OF PROGRAMMATIC APPROACH:") print("="*70) print("✓ Fewer round trips = lower latency") print("✓ Code executes in SECURE ISOLATED SANDBOX (AgentCore Code Interpreter)") print("✓ Data filtering in sandbox = fewer tokens sent to model") print("✓ Multiple tool calls in single execution") print("✓ Complex data processing without context bloat") print("✓ Automatic session cleanup and resource management") print("="*70 + "\n")
if __name__ == "__main__": main()
Architecture Considerations for State/Local Gov
Security:
- Code executes in isolated sandbox (no network access by default)
- Configurable network policies for controlled external access
- Full CloudTrail audit logging
- IAM-based access controls
Compliance:
- Data stays within your AWS account
- Supports VPC endpoints for private connectivity
- Meets FedRAMP requirements (check current certification status)
Cost:
- Pay per second of compute (CPU/memory)
- Typically cheaper than multiple API round trips
- No infrastructure to manage
Try It Yourself
Step-by-Step Setup (5 minutes)
1. Create a project folder:
mkdir bedrock-tool-calling-democd bedrock-tool-calling-demo2. Create and activate virtual environment:
# macOS/Linuxpython3 -m venv venvsource venv/bin/activate
# Windowspython -m venv venvvenv\Scripts\activate3. Install dependencies:
pip install boto3 bedrock-agentcore4. Configure AWS credentials:
# Option A: Use AWS CLIaws configure
# Option B: Set environment variablesexport AWS_ACCESS_KEY_ID=your_access_keyexport AWS_SECRET_ACCESS_KEY=your_secret_keyexport AWS_DEFAULT_REGION=us-east-1
# Windows (Option B)set AWS_ACCESS_KEY_ID=your_access_keyset AWS_SECRET_ACCESS_KEY=your_secret_keyset AWS_DEFAULT_REGION=us-east-15. Run the demo:
python bedrock_tool_calling_demo.py6. Review the output:
You'll see side-by-side comparison showing round trips, tokens, and latency differences.
7. Deactivate when done:
deactivateTroubleshooting
Issue:
AccessDeniedException
Fix: Ensure your IAM user/role has these permissions:-
bedrock:InvokeModelfor Nova Pro
-
bedrock-agentcore:CreateCodeInterpreter
-
bedrock-agentcore:StartCodeInterpreterSession
-
bedrock-agentcore:InvokeCodeInterpreter
-
bedrock-agentcore:StopCodeInterpreterSession
Issue:
ResourceNotFoundException
Fix: Verify Nova Pro and AgentCore Code Interpreter are available in us-east-1Issue:
ModuleNotFoundError: bedrock_agentcore
Fix: Make sure virtual environment is activated and run pip install bedrock-agentcore Questions? Reach out on our internal Slack channel or schedule time with @maalapat.
Summary
Programmatic tool calling is a significant improvement for building responsive, efficient AI agents. For state and local government applications where citizens expect fast responses and data comes from multiple sources, this approach can dramatically improve user experience while reducing costs.
Next Steps:
- Review your current agentic AI implementations
- Identify multi-tool workflows that could benefit
- Test with the demo code
- Reach out for architecture review sessions
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article