Skip to main content
Agents can execute code when the Code Execution capability is enabled. This gives your agent the best of both worlds—the intelligence of an AI agent combined with the speed and predictability of code.
Chat showing user asking to parse revenue CSV data, with agent executing code and displaying top 5 transactions in a table

Two ways to run code

1. Execute code in the chat The agent can write and run code on the fly during a conversation. Ask it to calculate something, transform data, or process a file—it writes the code, runs it, and shows you the result.
  • “Calculate the compound interest on these loan terms”
  • “Parse this CSV and show me the top 5 rows by revenue”
  • “Convert this JSON to a markdown table”
Here’s what the agent wrote to parse the CSV in the screenshot above:
const lines = csv.trim().split('\n');

const data = lines.slice(1).map(line => {
  const values = line.split(',');
  return {
    Date: values[0],
    Region: values[1],
    Product: values[2],
    Channel: values[3],
    Units: parseInt(values[4]),
    UnitPrice: parseFloat(values[5]),
    Revenue: parseFloat(values[6])
  };
});

// Sort by Revenue descending and get top 5
const top5 = data.sort((a, b) => b.Revenue - a.Revenue).slice(0, 5);
return top5;
The agent writes JavaScript, executes it, and presents the results—all in a single response. 2. Execute saved scripts For tasks you’ll run repeatedly, save the code as a script. Scripts are agent documents that store executable code—typically written by the agent itself.
  • “The data import you just did—save that script and run it every Saturday morning for that week’s sales data”
  • “Create a script that checks our inventory levels and alerts me when anything drops below 10 units”
  • “Save this report generation code so I can run it at the end of each month”
If the agent does something useful with code, ask it to save the script. Next time you need it, just ask—or schedule it to run automatically.

Why code instead of AI?

When an agent processes data “manually,” it reads each item, thinks about it, and produces output—one token at a time. That works fine for small datasets, but it’s slow, expensive, and unreliable for large datasets. Code runs instantly and costs a fraction of the price. Example: Suppose you ask your agent to analyze 500 customer feedback records—find sentiment trends, identify common issues, and calculate satisfaction scores.
  • Without code: The agent reads each record, thinks about it, and builds up its analysis token by token. This might take 5 minutes and cost $2.
  • With code: The agent writes a script to process all records, calculate statistics, and format the results. Runs in 2 seconds, costs $0.01.
The agent still uses its intelligence to write the analysis code—but the heavy lifting happens efficiently in code. That’s what we humans do too—if a task is predictable and repetitive, we write code for it instead of doing it manually every time. Your agent can do the same.

Scripts can use all agent tools

Here’s where it gets powerful: code execution has access to all the agent’s capabilities. If your agent can search the web, read a spreadsheet, send emails, or query a database—it can do all of that from within a script. Example use cases:
  • Customer enrichment: You have a customer list in a spreadsheet. A weekly script checks each customer’s website for updates (using web search), then updates the corresponding row with any new information.
  • Automated reporting: A script queries your agent database, generates a summary report, and emails it to stakeholders every Monday.
  • Data synchronization: Pull data from an external API, transform it, and update your internal records—all in a single scheduled script.
  • Competitive monitoring: Search for news about competitors, extract key insights, and log them to a tracking database.
This means you can build sophisticated automations by combining agent intelligence (to write the code) with agent capabilities (to take action).

When to use scripts

Scripts shine when:
ScenarioWhy scripts help
Large data volumesProcess thousands of records in seconds
Precise calculationsFinancial formulas, statistics, advanced math
Repeated tasksRun the same logic on a schedule without burning tokens each time
Format transformationsConvert between JSON, CSV, XML, Markdown reliably
Batch operationsUpdate many database records, send bulk notifications, process file collections
You don’t always need to tell the agent when to use code vs. AI. It often figures this out on its own—but you can guide it: “This will run on thousands of records, so write a script for efficiency.”

Creating and managing scripts

Scripts are stored as agent documents. You can:
  • View the code: Open the script document to see exactly what it does
  • Edit manually: Modify the code yourself if needed
  • Ask the agent to update it: “Add error handling to the import script”
  • Track versions: Every change is saved in version history, just like other documents
  • Schedule execution: Combine with scheduling to run scripts automatically
To enable code execution, go to your agent’s capabilities and turn on Code Execution.

Connecting to other documents

Scripts work naturally with other agent documents:
  • Agent databases: Query, insert, update, and delete records programmatically
  • Other scripts: Scripts can call other scripts to perform complex tasks
Example workflow: A support ticket comes in via email.
  1. The agent reads the ticket and reasons about it—what’s the priority? Which category? Is this a VIP customer?
  2. The agent calls a saved script, passing in those parameters: routeTicket({ priority: "high", category: "billing", customerTier: "enterprise" })
  3. The script handles the mechanical work—updates the database, notifies the right team, logs the action
The AI handles the judgment call, then delegates the repetitive execution to code. Fast, cheap, and consistent.

Learn more