PromptisePromptise
PlatformSoonEnterprise
DocsGitHub
Talk to usGet started
Promptise - AI Framework LogoPromptise

The full-stack framework for agentic systems. Build with the framework. Run it on the platform. Launch it with our engineers.

pip install promptise

[01] Product

  • Framework
  • Platform (coming soon)
  • Enterprise
  • How it works
  • Contact

[02] Framework

  • The Agent
  • The Interface
  • The Harness

[03] Resources

  • Documentation
  • GitHub
  • Why Promptise
  • Use cases
  • Roadmap
  • Guides
  • Learning Paths
  • Questions

[04] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

hello@promptise.com
← Learning paths> Agentic Engineering with Promptise Foundry
Lesson 50 / 100
50%

Code-Action Agents in Python: One Program vs 37 Tool Calls

Build a code-action agent in Python over an MCP server: the model writes one program that calls your tools in a Docker sandbox, within a budget you set.

Advanced15 minAgent Reasoning PatternsReActModel Context Protocol (MCP)Code Execution and Sandboxing
All 100 lessons↓
  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. ✓How to Connect MCP Servers to Your AI Agent in Python
  20. ✓Build a Production MCP Server in Python (Step by Step)
  21. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. ✓MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  25. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  26. ✓MCP Security Best Practices: A Checklist for MCP Servers
  27. ✓Testing MCP Servers in Python: pytest Without a Live Server
  28. ✓Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. ✓Idempotent Tool Calls: Make AI Agent Retries Safe
  30. ✓AI Agent Tool Failures: Stop Unsafe Workarounds
  31. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. ✓MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. ✓LangChain vs MCP: Differences and How They Work Together
  35. ✓FastMCP Alternatives for Production MCP Servers (2026)
  36. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  38. ✓AI Agent Prompt Injection: How to Defend Against It
  39. ✓Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. ✓Build a Multi-Agent System in Python (and When Not To)
  41. ✓Context Engineering for AI Agents: Context Window Management
  42. ✓Context Compaction for AI Agents: Trim vs Summarize
  43. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  44. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. ✓MCP Long-Running Tasks: Background Jobs in Python
  46. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. ✓Best AI Agent Frameworks (2026): Python Options Compared
  48. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  49. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  50. 50Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. 51Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. 52What Is Agentic RAG? How It Differs from Classic RAG
  53. 53AI Agent Memory in Python: Short-Term and Long-Term
  54. 54Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. 55Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. 56AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. 57Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. 58Self-Modifying AI Agent in Python: Open Mode & Limits
  59. 59CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. 60Migrate from AutoGen: Agent Framework, AG2 and More
  61. 61What Is an LLM Guardrail? Types, Examples and Limits
  62. 62Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. 63AI Agent Guardrails in Python: Block Injection, Redact PII
  64. 64NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. 65AI-Based PII Detection and Redaction Tools for LLM Apps
  66. 66Stop Secrets Leaking Into LLM Logs and Traces
  67. 67AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. 68AI Agent Network Egress: Limit Where Agents Can Connect
  69. 69AutoGen Docker Task Isolation: Secure the Code Executor
  70. 70SPIFFE for AI Agents: Workload Identity Without API Keys
  71. 71On-Behalf-Of Auth for AI Agents: Act as Each User
  72. 72AI Agent Production Checklist: What to Check Before Launch
  73. 73Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. 74What Is Human in the Loop AI? Approvals for AI Agents
  75. 75AI Agent Notifications: Webhook and Slack Alerts in Python
  76. 76AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. 77Best AI Agent Observability Tools (2026), Compared
  78. 78AI Agent Stuck in a Loop? How to Detect and Stop It
  79. 79How to Run, Debug and Deploy an AI Agent in Python
  80. 80AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. 81How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. 82AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. 83How to Test LLM Prompts and AI Agents in Python
  84. 84AI Agent Evals in CI: Run Them on Every Pull Request
  85. 85What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. 86Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. 87Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. 88AI Agent Cron Jobs: Run an Agent on a Schedule
  89. 89AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. 90AI Agent File Watcher: Process New Files Automatically
  91. 91Custom AI Agent Triggers: Wake an Agent From Any Source
  92. 92AI Agent Event Filters: Skip Runs Before the LLM
  93. 93AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained

Lessons in this path

  1. ✓What Is an AI Agent? Definition, How It Works, Examples
  2. ✓How to Build an AI Agent in Python (2026 Guide)
  3. ✓Build a Personal AI Agent: Memory, Reminders, Chat
  4. ✓What Is an Agent Harness? Parts and How to Build One
  5. ✓System Prompt Best Practices for AI Agents in Python
  6. ✓Best LLM for AI Agents (2026): Picks, Prices, How to Test
  7. ✓AI Agent YAML: Define and Run an Agent From a Config File
  8. ✓Streaming LLM Responses with FastAPI: Tokens and Tool Calls
  9. ✓Best Local LLM for AI Agents: Ollama Models by GPU (2026)
  10. ✓Claude AI Agent with MCP: Use Anthropic Models in Promptise
  11. ✓Gemini AI Agent with MCP: Use Google Models in Promptise
  12. ✓Azure OpenAI Agent with MCP: Use Deployments in Promptise
  13. ✓OpenRouter AI Agent with MCP: Many Models in Promptise
  14. ✓Ollama AI Agent with MCP: Run Local Models in Promptise
  15. ✓LLM Semantic Cache and Model Fallback in Python
  16. ✓What Is MCP (Model Context Protocol)? A Developer's Guide
  17. ✓What Is Tool Calling? LLM Function Calling Explained
  18. ✓MCP Tools vs Resources vs Prompts (With Python Examples)
  19. ✓How to Connect MCP Servers to Your AI Agent in Python
  20. ✓Build a Production MCP Server in Python (Step by Step)
  21. ✓MCP Transports: stdio vs Streamable HTTP vs SSE (Python)
  22. ✓MCP 2026-07-28 Migration: Make Your MCP Server Stateless
  23. ✓OpenAPI to MCP: Turn Any REST API into an MCP Server
  24. ✓MCP Authentication in Python: API Keys, JWT and OAuth
  25. ✓Build an Authenticated MCP Server for Your AI Agent (Python)
  26. ✓MCP Security Best Practices: A Checklist for MCP Servers
  27. ✓Testing MCP Servers in Python: pytest Without a Live Server
  28. ✓Too Many MCP Tools? How to Fix LLM Tool Selection in Python
  29. ✓Idempotent Tool Calls: Make AI Agent Retries Safe
  30. ✓AI Agent Tool Failures: Stop Unsafe Workarounds
  31. ✓MCP Server Caching, Timeouts and Circuit Breakers in Python
  32. ✓MCP Middleware for Servers: Auth, Logging, Rate Limits
  33. ✓MCP vs CLI for AI Agents: Tokens, Security, When to Use Each
  34. ✓LangChain vs MCP: Differences and How They Work Together
  35. ✓FastMCP Alternatives for Production MCP Servers (2026)
  36. ✓AI Agent Audit Logging: Tamper-Evident Logs in Python
  37. ✓AI Agent Human in the Loop: Approve Tool Calls in Python
  38. ✓AI Agent Prompt Injection: How to Defend Against It
  39. ✓Hidden Text Prompt Injection: Sanitize Pages for AI Agents
  40. ✓Build a Multi-Agent System in Python (and When Not To)
  41. ✓Context Engineering for AI Agents: Context Window Management
  42. ✓Context Compaction for AI Agents: Trim vs Summarize
  43. ✓How to Deploy an AI Agent with Docker (2026 Guide)
  44. ✓LLM Tool Rate Limiting: Per-Client Limits for MCP Servers
  45. ✓MCP Long-Running Tasks: Background Jobs in Python
  46. ✓MCP Server Monitoring: Prometheus, OpenTelemetry and Logs
  47. ✓Best AI Agent Frameworks (2026): Python Options Compared
  48. ✓Self-Improving AI Agent: Learn From Tool Failures in Python
  49. ✓AI Agent Identity: Authenticate Agents to MCP Servers
  50. 50Code-Action Agents in Python: One Program vs 37 Tool Calls
  51. 51Multi-Tenant AI Agents: Keep Each Customer's Data Apart
  52. 52What Is Agentic RAG? How It Differs from Classic RAG
  53. 53AI Agent Memory in Python: Short-Term and Long-Term
  54. 54Per-User Agent Memory Isolation: Stop Leaks Between Users
  55. 55Agentic RAG in Python: Give Your AI Agent a Search Tool
  56. 56AI Agent Reasoning Patterns in Python: From ReAct to Debate
  57. 57Plan-and-Execute Agents in Python: Beyond the ReAct Loop
  58. 58Self-Modifying AI Agent in Python: Open Mode & Limits
  59. 59CrewAI Alternatives: 7 Options and How to Migrate (2026)
  60. 60Migrate from AutoGen: Agent Framework, AG2 and More
  61. 61What Is an LLM Guardrail? Types, Examples and Limits
  62. 62Best LLM Guardrails Tools (2026): 9 Platforms Compared
  63. 63AI Agent Guardrails in Python: Block Injection, Redact PII
  64. 64NeMo Guardrails vs Guardrails AI: Which to Choose (2026)
  65. 65AI-Based PII Detection and Redaction Tools for LLM Apps
  66. 66Stop Secrets Leaking Into LLM Logs and Traces
  67. 67AI Agent Code Execution Sandbox: Run LLM Code Safely
  68. 68AI Agent Network Egress: Limit Where Agents Can Connect
  69. 69AutoGen Docker Task Isolation: Secure the Code Executor
  70. 70SPIFFE for AI Agents: Workload Identity Without API Keys
  71. 71On-Behalf-Of Auth for AI Agents: Act as Each User
  72. 72AI Agent Production Checklist: What to Check Before Launch
  73. 73Approval Fatigue: Auto-Approve Safe AI Agent Actions
  74. 74What Is Human in the Loop AI? Approvals for AI Agents
  75. 75AI Agent Notifications: Webhook and Slack Alerts in Python
  76. 76AI Agent Observability: Trace Tool Calls, Tokens and Cost
  77. 77Best AI Agent Observability Tools (2026), Compared
  78. 78AI Agent Stuck in a Loop? How to Detect and Stop It
  79. 79How to Run, Debug and Deploy an AI Agent in Python
  80. 80AI Agent Cost Tracking: Tokens and Cost per Run and User
  81. 81How to Evaluate AI Agents: Evals, LLM Judges and pass^k
  82. 82AI Agent Cost Control: Budgets That Stop Runaway Spend
  83. 83How to Test LLM Prompts and AI Agents in Python
  84. 84AI Agent Evals in CI: Run Them on Every Pull Request
  85. 85What Is an Agentic Runtime? AI Agent Runtimes Explained
  86. 86Autonomous AI Agent Runtime: Budgets, Crash Recovery, API
  87. 87Event-Driven AI Agents: Webhook, Cron and File Triggers
  88. 88AI Agent Cron Jobs: Run an Agent on a Schedule
  89. 89AI Agent Webhook Trigger: Run an Agent on HTTP Events
  90. 90AI Agent File Watcher: Process New Files Automatically
  91. 91Custom AI Agent Triggers: Wake an Agent From Any Source
  92. 92AI Agent Event Filters: Skip Runs Before the LLM
  93. 93AI Agent Retries and a Dead Letter Queue for Failed Runs
  94. 94Run Multiple AI Agents: One Runtime, Many Processes
  95. 95AI Agent Manifest: Declare a Long-Running Agent in YAML
  96. 96AI Agent CLI: Start, Stop and Inspect Running Agents
  97. 97AI Agent Monitoring Dashboard in the Terminal
  98. 98Multi-Agent Event Bus: Chain Agents With Events
  99. 99Distributed AI Agents: Run Agents Across Many Machines
  100. 100Pause and Resume an AI Agent: Lifecycle States Explained
← Path overview

A code-action agent answers a question by writing one Python program that calls your tools and computes the result, instead of making one tool call per model turn. For questions that need dozens of tool calls, that means one model call instead of several, and tool results that never enter the model's context. This guide explains how a code-action agent works and builds one in Python with Promptise Foundry on top of a real MCP server. You'll run it next to a ReAct agent on the same question, size its tool budget so a run never returns a partial answer, and learn the mistakes to watch for. The code runs on Promptise Foundry 1.9.0 with GPT-5 mini and Docker, and the outputs come from real runs.

[01]

What is a code-action agent?

A code-action agent (the idea is often called CodeAct, or code as action) changes what the model's action is. A ReAct agent acts by calling one tool, reading the result, and deciding the next call. A code-action agent acts by writing a program: loops, filters and sums run as Python, and the tools are ordinary functions the program calls. One model turn can stand for dozens of tool calls.

In Promptise Foundry it's one argument on build_agent:

Pythoncode_action_agent.py
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"shop": StdioServerSpec(command=sys.executable, args=["shop_server.py"])},
        agent_pattern="code-action",  # starts a Docker sandbox for the program
    )

[02]

How does a code-action agent work?

Promptise starts a Docker container for the program with no network, gives it a Python stub for each tool, and runs the real tools on your side when the program calls them. MCP results that are JSON arrive in the program as lists and dicts. The answer is the line the program prints after RESULT:.

Rendering diagram…

Three parts of the design shape how a code-action agent behaves:

  • The model sees each tool as one line. The prompt lists every tool as a Python signature followed by the first line of its description. Parameter descriptions and return types never reach the model, so that first line has to name the fields the tool returns.

  • Every program gets a new container. That's the safe choice, and a repair attempt pays for another one. build_agent also starts and removes one up front to check that Docker works. Starting and removing a container takes well under a second.

  • Bridged calls are served one at a time. The program writes a request file and waits. A loop on your side polls the container for request files, runs the tool, and writes the response back. Each call adds a fraction of a second, so a program that makes 30 calls spends about five seconds on the bridge. A ReAct agent can run the same 30 calls in parallel in one step.

When a program crashes, Promptise sends the last 800 characters of its error output back to the model with the program it wrote, and the model answers with a corrected program. max_repairs sets how many times that can happen.

The sandbox guide covers the container itself: what it blocks, how to set limits, and what happened when an agent was asked to break out. This guide is about the other half: building a code-action agent over your MCP tools, and where it goes wrong.


[03]

What you need

  • Python 3.10 or newer.

  • Docker, installed and running. There's no fallback: without a working sandbox, build_agent raises RuntimeError instead of running model-written code on your machine. The first run pulls the python:3.11-slim image. Since 1.10.0 the pull logs a warning when it starts (Pulling Docker image python:3.11-slim (first use, this can take a few minutes)), a progress line every 10 seconds and one when it ends; a failed pull raises with Docker's error.

  • Promptise Foundry 1.9.0 or newer with the sandbox extra, which adds the Docker SDK for Python.

  • An API key for a model provider. The examples use openai:gpt-5-mini.

>_Terminal
pip install "promptise[sandbox]>=1.9.0"
export OPENAI_API_KEY="sk-..."

[04]

How to build a code-action agent in Python, step by step

Step 01

Give the agent a job that takes many tool calls

A code-action agent earns its keep on gather-then-compute work, so the MCP server below makes the agent gather. list_orders returns 30 order IDs, get_order returns one order with its lines, and get_price returns one product's price. Any question about September revenue means one call per order, plus prices.

Pythonshop_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import random

from promptise.mcp.server import MCPServer

server = MCPServer("shop")

# Sample data: 30 September orders, generated the same way on every run.
PRICES = {"KB-101": 89, "MS-220": 35, "MN-270": 249, "HD-330": 119, "DK-410": 179, "CB-055": 13}
CUSTOMERS = ["Acme Corp", "Birchwood Ltd", "Cobalt Labs", "Dunmore Studio",
             "Elmfield Cafe", "Fjordline Design", "Granite Health", "Halcyon Books"]

rng = random.Random(2)
ORDERS = {}
for n in range(1, 31):
    order_id = f"SO-{9000 + n}"
    skus = rng.sample(list(PRICES), rng.randint(1, 3))
    ORDERS[order_id] = {
        "id": order_id,
        "customer": rng.choice(CUSTOMERS),
        "status": rng.choice(["shipped"] * 6 + ["refunded", "pending"]),
        "discount_pct": rng.choice([0, 0, 5, 10, 15]),
        "lines": [{"sku": sku, "qty": rng.randint(1, 12)} for sku in skus],
    }


@server.tool()
async def list_orders(month: str) -> list[str]:
    """List the IDs of the orders placed in a month, e.g. "2026-09".

    Args:
        month: The month as YYYY-MM.
    """
    return list(ORDERS) if month == "2026-09" else []


@server.tool()
async def get_order(order_id: str) -> dict:
    """Get one order as {id, customer, status, discount_pct, lines: [{sku, qty}]}.

    Args:
        order_id: An order ID from list_orders, e.g. "SO-9001".
    """
    order = ORDERS.get(order_id)
    if order is None:
        raise ValueError(f"No order {order_id}")
    return order


@server.tool()
async def get_price(sku: str) -> dict:
    """Get a product's unit price in USD as {sku, unit_price}.

    Args:
        sku: A product SKU from an order line, e.g. "KB-101".
    """
    if sku not in PRICES:
        raise ValueError(f"No product {sku}")
    return {"sku": sku, "unit_price": PRICES[sku]}


if __name__ == "__main__":
    server.run()

The first line of each docstring matters more than usual here. The code-action prompt shows the model each tool as a Python signature followed by that line, and nothing else, so the line names the fields the tool returns.

The question in the next steps asks for the customer who spent the most on shipped orders, which needs prices and discounts. Computed straight from the data, these are the answers an agent has to reach for this question and two others:

Pythontruth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""The right answers, computed straight from the server's data."""
from collections import Counter, defaultdict

from shop_server import ORDERS, PRICES


def order_total(order):
    gross = sum(line["qty"] * PRICES[line["sku"]] for line in order["lines"])
    return gross * (100 - order["discount_pct"]) / 100


shipped = [o for o in ORDERS.values() if o["status"] == "shipped"]
print(f"orders: {len(ORDERS)}, shipped: {len(shipped)}")
print(f"net revenue, shipped: ${sum(order_total(o) for o in shipped):,.2f}")

by_customer = defaultdict(float)
for o in shipped:
    by_customer[o["customer"]] += order_total(o)
top = max(by_customer, key=by_customer.get)
print(f"top customer, shipped: {top} ${by_customer[top]:,.2f}")

units = Counter()
for o in ORDERS.values():
    if o["status"] != "refunded":
        for line in o["lines"]:
            units[line["sku"]] += line["qty"]
(sku, qty), (second, second_qty) = units.most_common(2)
print(f"most units, not refunded: {sku} {qty} (next: {second} {second_qty})")
Output
orders: 30, shipped: 24
net revenue, shipped: $34,959.30
top customer, shipped: Elmfield Cafe $7,452.85
most units, not refunded: MN-270 105 (next: CB-055 74)
Step 02

Run a ReAct agent first

Start with what you'd get anyway. A small LangChain callback counts model calls and tokens for any pattern, because Promptise passes the run's config to every model call, including the one that writes the program:

Pythonusage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from langchain_core.callbacks import BaseCallbackHandler


class Usage(BaseCallbackHandler):
    """Count model calls and tokens for one run."""

    def __init__(self):
        self.calls = self.input_tokens = self.output_tokens = 0

    def on_llm_end(self, response, **kwargs):
        self.calls += 1
        usage = response.generations[0][0].message.usage_metadata or {}
        self.input_tokens += usage.get("input_tokens", 0)
        self.output_tokens += usage.get("output_tokens", 0)

    def __str__(self):
        return f"{self.calls} model calls, {self.input_tokens:,} input + {self.output_tokens:,} output tokens"
Pythonreact_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import asyncio
import sys
import time

from promptise import build_agent
from promptise.config import StdioServerSpec

from usage import Usage

QUESTION = (
    "Which customer spent the most on shipped orders in September 2026, after discounts, "
    "and how much? An order's total is qty x unit price over its lines, minus its discount."
)


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"shop": StdioServerSpec(command=sys.executable, args=["shop_server.py"])},
        agent_pattern="react",  # the default
    )
    try:
        usage = Usage()
        start = time.perf_counter()
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": QUESTION}]},
            config={"callbacks": [usage]},
        )
        report = agent.last_report
        print(">>>", result["messages"][-1].content)
        print(f"tool calls: {report.tool_calls}, path: {' -> '.join(report.nodes_visited)}")
        print(f"usage: {usage}, {time.perf_counter() - start:.1f} s")
    finally:
        await agent.shutdown()


asyncio.run(main())
Output
>>> Elmfield Cafe — $7,452.85
…
Total = 3,640.00 + 1,819.85 + 820.00 + 1,173.00 = 7,452.85
…
tool calls: 37, path: reason -> reason -> reason -> reason
usage: 4 model calls, 7,324 input + 4,050 output tokens, 31.3 s

Right answer, from 37 tool calls (the list, 30 orders and each of the six prices once) in four model calls: when the model asks for several tools in one turn, Promptise runs them in parallel. The arithmetic happened in the model's head, and on 30 orders it came out right. Every result went through the model's context, though, which is where the 7,324 input tokens come from.

Step 03

Switch to code-action

code_action_agent.py is react_agent.py with agent_pattern="code-action" and two logging lines that print the program the model writes. Promptise logs it at DEBUG level:

Pythoncode_action_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import asyncio
import logging
import sys
import time

from promptise import build_agent
from promptise.config import StdioServerSpec

from usage import Usage

QUESTION = (
    "Which customer spent the most on shipped orders in September 2026, after discounts, "
    "and how much? An order's total is qty x unit price over its lines, minus its discount."
)

# Print the program the model writes (Promptise logs it at DEBUG level).
logging.basicConfig(format="%(message)s")
logging.getLogger("promptise.engine.code_action").setLevel(logging.DEBUG)


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"shop": StdioServerSpec(command=sys.executable, args=["shop_server.py"])},
        agent_pattern="code-action",  # starts a Docker sandbox for the program
    )
    try:
        usage = Usage()
        start = time.perf_counter()
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": QUESTION}]},
            config={"callbacks": [usage]},
        )
        print(">>>", result["messages"][-1].content)
        print(f"usage: {usage}, {time.perf_counter() - start:.1f} s")
    finally:
        await agent.shutdown()


asyncio.run(main())

Here's a run with every default, trimmed to the lines that matter:

Output
[promptise] Initializing sandbox environment...
[promptise] Sandbox ready for code-action (backend: docker)
code-action program:
…
def main():
    month = "2026-09"
    order_ids = list_orders(month)
    # Ensure it's a list
    if order_ids is None:
        order_ids = []
    # totals per customer
    totals = defaultdict(float)
    price_cache = {}
    for oid in order_ids:
        order_raw = get_order(oid)
        order = normalize_order(order_raw)
…
            # get price from cache or fetch
            if sku not in price_cache:
                p_raw = get_price(sku)
                p = normalize_price(p_raw)
…
code-action exit=0 stdout='RESULT: Elmfield Cafe, $7452.85\n' stderr=''
>>> Elmfield Cafe, $7452.85
usage: 1 model calls, 467 input + 1,969 output tokens, 25.1 s

One model call, about a fifth of ReAct's tokens, and the right answer. list_orders returned a real list, so the loop worked on the first try, and the program kept a price cache, so it made the same 37 calls ReAct did. It calls the tools without try, so a tool error stops the program instead of becoming a zero. It still wrote helpers for results that might be strings: it can't know the shape of the data until the program runs, so it writes defensively.

The program also reads every order. The prompt says each program has a cap on tool calls but not its value, and tells the model never to skip records or stop early to stay under it. A model that knows the number counts its own calls and stops short of it, and the partial result becomes the answer. Step 4 shows what a cap that's too small does instead.

Step 04

Size the tool budget with CodeActionConfig

Code-action has three settings. Pass them to build_agent as code_action=, either a dict or a CodeActionConfig from promptise.engine. An unknown key raises, and so does code_action= with any other pattern:

Setting

Default

What it does

What to watch

exec_timeout

120

Seconds a program may run in the sandbox; then its processes are killed

Bridged calls count against it, a fraction of a second each

max_repairs

1

How many times a failed program goes back to the model for a fix

Each repair is another model call and another container

max_tool_calls

50

Bridged tool calls each program may make; every call counts, failed ones too

Size it above what a correct program needs, never below

The budget is per program: a repaired program starts with a fresh one, so a run makes at most (max_repairs + 1) × max_tool_calls calls. A call beyond it raises ToolBudgetExceeded inside the program. Promptise logs a warning and discards the program's output, even if the program caught the error. The repair prompt then asks for a program that does the whole job with fewer calls, or the reply CANNOT_FINISH_WITHIN_CALL_CAP. That reply, or a budget hit with no repair left, raises CodeActionBudgetError from promptise.engine, a GraphExecutionError.

To see it at work, limits_demo.py gives the agent a budget of 20 tool calls for the top-customer question, which needs 37, and two repairs:

Pythonlimits_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import asyncio
import logging
import sys

from promptise import build_agent
from promptise.config import StdioServerSpec
from promptise.engine import CodeActionConfig, GraphExecutionError

QUESTION = (
    "Which customer spent the most on shipped orders in September 2026, after discounts, "
    "and how much? An order's total is qty x unit price over its lines, minus its discount."
)

logging.basicConfig(format="%(message)s")
logging.getLogger("promptise.engine.code_action").setLevel(logging.DEBUG)


async def main():
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"shop": StdioServerSpec(command=sys.executable, args=["shop_server.py"])},
        agent_pattern="code-action",
        code_action=CodeActionConfig(exec_timeout=60, max_repairs=2, max_tool_calls=20),
        trace_tools=True,  # print every tool call
    )
    try:
        result = await agent.ainvoke({"messages": [{"role": "user", "content": QUESTION}]})
        print(">>>", result["messages"][-1].content)
    except GraphExecutionError as exc:
        print("GraphExecutionError:", exc)
    finally:
        await agent.shutdown()


asyncio.run(main())

Here's a run, trimmed:

Output
[promptise] Initializing sandbox environment...
[promptise] Sandbox ready for code-action (backend: docker)
→ Invoking tool: list_orders with {'month': '2026-09'}
…
→ Invoking tool: get_order with {'order_id': 'SO-9019'}
✔ Tool result from get_order: {"id": "SO-9019", "customer": "Granite Health", "status": "shipped", "discount_pct": 10, "lines": [{"sku": "CB-055", "qty": 4}, {"sku": "KB-101", "qty": 2}, {"sku": "MN-270", "qty": 11}]}
code-action node 'reason': tool-call budget exhausted: the program already made 20 tool call(s) (max_tool_calls=20); the call to 'get_order' was refused and the program's output will be discarded
code-action program:
…
code-action exit=1 stdout='' stderr='Traceback (most recent call last):\n  File "/workspace/program.py", line 151, in <module>\n    main()\n …
GraphExecutionError: Graph 'code-action' failed at node 'reason': program failed after 2 attempt(s); last attempt: the job needs more tool calls than the per-program budget (max_tool_calls=20) allows: a program reached it, and the model reported that the whole job cannot be done in fewer calls

The first program made 20 calls, and the 21st was refused. The warning went to the log, and the program crashed. The repair prompt asked for the whole job in fewer calls. This server has no tool that returns many orders at once, so the model replied that it couldn't, and the run raised CodeActionBudgetError. limits_demo.py catches GraphExecutionError, which covers it.

In a second run, two programs caught the refused call and printed a partial total, Elmfield Cafe spent $3640.00 and then Acme Corp spent $296.15. Promptise discarded both, and that run raised too. A budget that's too small costs you a failed run, not a wrong answer. Size it anyway:

  • Size the budget above what a correct program needs. Count the calls one honest pass over the data takes and leave room. The default of 50 fits this question with 13 to spare.

  • Watch the log. A tool-call budget exhausted warning on promptise.engine.code_action means a program hit the cap. A second warning says when an answer came from a program written after a budget hit. Send that logger to your monitoring.

  • Give the model a bulk tool. A tool that returns many records at once lets a program do the same job in a few calls.

Warning

CodeActionBudgetError ends the run without an answer. Catch it, or GraphExecutionError, wherever a code-action agent runs unattended, and raise max_tool_calls or add a tool that returns many records at once.

With max_tool_calls set to 20 for a question that needs 37 calls, call 21 is refused and the program's output discarded even if it caught the error; the repair prompt asks for the whole job with fewer calls or the reply CANNOT_FINISH_WITHIN_CALL_CAP, and either way the run raises CodeActionBudgetError instead of returning a partial total.
FigureHow a tool budget below what the job needs ends a code-action run with an error

[05]

Code-action vs ReAct: which should you use?

Both agents in this guide reached the right answer. Where they differ is what each one sends to the model, and what you can see afterwards:

  • Tokens. ReAct read every tool result, so its input grows with the data. The code-action agent's results never enter the model's context, and nearly all of its tokens are the program it writes. Output tokens cost more than input tokens (eight times as much for GPT-5 mini), so the cost gap is smaller than the token gap, but code-action still comes out cheaper on jobs like this one.

  • Accuracy. On 30 orders, a ReAct agent with GPT-5 mini gets the arithmetic right. The gap opens as the data grows: the sandbox guide shows the same model getting two of four totals wrong over 500 rows in one tool result. A program sums 500 rows as easily as 30.

  • Time. About the same here. The code-action agent saves model calls, and spends that time on the container and the sequential bridge. It wins when the model would otherwise read a lot of results, and loses when a few quick tool calls would do.

  • Visibility. A ReAct agent shows its work in the transcript. A code-action agent shows you one line, and whether that line is right depends on code nobody reviewed.

Use code-action when

Stay with ReAct when

The answer is computed from many records: sums, joins, counts, top-N

A few tool calls answer the question

Tool results are big, and you'd rather they never enter the context

Tools return prose the model has to read and judge

You can size the tool budget and validate the one-line result

You can't predict how many calls the job takes

Token cost matters

You need the reasoning visible in the transcript

Docker is available where the agent runs

There's no container runtime

The reasoning patterns guide runs code-action on a different kind of task, expense rules written as sentences, next to the other eight built-in patterns. Two neighbours are worth knowing too. agent_pattern="managed" keeps a ReAct loop but replaces the growing transcript with a deduplicated ledger of facts, and the context engineering guide shows that approach. And if what you want is a plan or a checking step rather than a program, the plan-and-execute guide builds those.


[06]

Common mistakes with code-action agents

A crash is the easy failure: the repair loop sends the error back, and the model fixes the program. A program that starts with a stray line reading python, for example, crashes with NameError, and the repaired program runs. The hard failure is a program that doesn't crash: it catches an error, skips a record or stops early, and prints a number. These are the mistakes that lead there:

  • Trusting the one-line answer without checks. Promptise can't tell whether a program that stayed within the cap read all the data. A total that's too small, zero or None points to a program that skipped records. A few lines of validation on the RESULT line catch what the program hid.

  • Assuming the program lets errors raise. Models wrap tool calls in try often, even when the instructions say not to. A refused call over the budget is discarded even when caught. Any other tool error that a program catches makes those records count as zero.

  • Not reading the programs. Log them with one logging line, as in step 3, and read a sample. That's the price of the token savings.

  • Vague tool descriptions. The model sees only the signature and the first line of each tool's description. If that line doesn't name the fields a tool returns, the program guesses.

  • Expecting a prose answer. The answer is whatever the program prints after RESULT: (or its last line), with no prose around it. Ask for the format you want in the question, or pass the result to a second call.

  • Giving the program write tools. The sandbox contains the code, not your tools. The program can call every tool the agent has, as often as the budget allows. Keep that tool set small and read-only where you can. The human-in-the-loop guide covers approvals for the rest.

  • Planning for hundreds of bridged calls. Calls are sequential, so hundreds of them add up to a minute or more, and they count against exec_timeout. Add a tool that returns many records at once instead.


[07]

Frequently asked questions

What is a code-action agent?

An agent whose action is a program. Instead of calling tools one at a time, the model writes Python that calls them as functions and computes the answer, and the program runs in a sandbox. The approach is often called CodeAct after the 2024 paper Executable Code Actions Elicit Better LLM Agents.

Is a code-action agent better than ReAct?

For gather-then-compute jobs it uses far fewer tokens, because tool results never enter the model's context, and it does exact arithmetic over any amount of data. ReAct is the better default for short, conversational tasks, for tools that return prose, and when you can't predict how many tool calls a job takes.

Does a code-action agent need Docker?

In Promptise, yes. agent_pattern="code-action" turns on a Docker sandbox with no network, and if it can't start one, build_agent raises RuntimeError rather than running model-written code on your machine. The gVisor runtime is an option for stronger isolation.

Can a code-action agent call MCP tools?

Yes. Tools from servers= are bridged into the program like any other tool, and each call runs on your side through the normal MCP client. A result that is JSON arrives as a list or dict, other text as a string, and a tool error raises inside the program.

How do I stop a generated program from calling a tool too often?

Set max_tool_calls in code_action=. It counts every call each program makes, failed ones included, and a run makes at most (max_repairs + 1) × max_tool_calls. Size it above what a correct program needs: a budget below that ends the run with CodeActionBudgetError instead of an answer. Keep exec_timeout as a second limit on time.

How do I see the program a code-action agent wrote?

Set the promptise.engine.code_action logger to DEBUG, as code_action_agent.py does. Promptise logs each program, its exit code and its output. agent.last_report.tool_calls counts the bridged calls.


[08]

Where to go next

  • Code-Action: Agents that Write Programs: the pattern's reference, including the bridge, the tool-call budget and the security model.

  • Sandbox: container settings, limits and the gVisor backend.

  • AI Agent Reasoning Patterns in Python: all nine built-in patterns, code-action included, on three expense questions.

  • Reasoning Patterns and Prebuilt Patterns: every built-in agent_pattern and how each is wired.

  • AI Agent Code Execution Sandbox: the container, escape attempts and resource limits, with a CSV analysis agent.

  • Plan-and-Execute Agents in Python: when you want structure around a tool loop instead of a program.

  • Build a Production MCP Server in Python: design tools that return the structured data a program can use.

  • Trace Every Tool Call: see what an agent did, call by call.

← PreviousAI Agent Identity: Authenticate Agents to MCP ServersNext lesson →Multi-Tenant AI Agents: Keep Each Customer's Data Apart