Skip to main content

What it does

The Execute Python tool runs Python code in a secure Jupyter notebook environment. Perfect for data analysis, calculations, visualizations, and any computational tasks your agents need to perform.

Key features

  • Execute Python code in isolated Jupyter notebook cells
  • Support for popular libraries (pandas, numpy, matplotlib, etc.)
  • Enhanced output display with separate sections for different output types
  • Smart output categorization - stdout, stderr, results, and text outputs are displayed distinctly
  • Automatic error handling with detailed tracebacks
  • Persistent session state across multiple executions

Parameters

ParameterTypeRequiredDescription
codestringYesThe Python code to execute in a single cell

Output types & display

The tool now intelligently categorizes and displays different types of output:

📤 Output (stdout)

Print statements and console output appear in a clean gray section:
print("Processing data...")
print("Results calculated successfully!")

📊 Result (expression results)

The final expression result is highlighted in a blue section:
# This result will be prominently displayed
42 + 8  # Shows: 50

⚠️ Warnings/Errors (stderr)

Non-fatal warnings and errors appear in an orange warning section:
import warnings
warnings.warn("This is a warning message")

🎨 Rich Media (charts, images, etc.)

Visual outputs like charts and images are displayed with full formatting:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()  # Chart appears as rich visual content

Common use cases

Data analysis with clear output

import pandas as pd
import numpy as np

# Create sample data
data = {'sales': [100, 150, 200, 175], 'month': ['Jan', 'Feb', 'Mar', 'Apr']}
df = pd.DataFrame(data)

print("Dataset created successfully!")  # Appears in Output section
print(f"Shape: {df.shape}")            # Appears in Output section

df.describe()  # Appears in Result section with rich formatting

Create visualizations with status updates

import matplotlib.pyplot as plt

print("Creating visualization...")  # Shows progress in Output

# Create a simple chart
plt.figure(figsize=(8, 6))
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.title('Sample Chart')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

print("Chart generated!")  # Confirms completion
plt.show()                 # Chart appears as rich visual

Mathematical calculations with explanations

import math

print("Calculating complex formula...")  # Process indicator

# Complex calculations
result = math.sqrt(144) + math.pow(2, 8)
print(f"Square root of 144: {math.sqrt(144)}")  # Step-by-step output
print(f"2 to the power of 8: {math.pow(2, 8)}")

result  # Final result prominently displayed

Error handling demonstration

import warnings

print("Starting calculation...")

# This generates a warning (appears in orange section)
warnings.warn("Using deprecated function")

# This works fine
result = 10 * 5
print(f"Calculation complete: {result}")

result  # Final result in blue section

Knowledge base file access

Knowledge base files appear in the sandbox at /home/user/kb/{kb_id}/ only when you request them via the kb_files parameter on the execute_python call (format kb/{kb_id}/{filename}). They are not pre-loaded — the directory does not exist until you request a file into it, so os.listdir('/home/user/kb/{kb_id}/') without a prior request will fail. Use list_kb_files to discover exact filenames first, then pass them in kb_files. You can request files from any knowledge base in your organization — the KB does not need to be in the agent’s accessible-KB list. Requesting a file mounts both the original binary and its .md companion.

What’s available in the sandbox

FilePathContainsHow it gets there
Original files/home/user/kb/{kb_id}/{filename}The uploaded PDFs, Excel files, .docx, etc. — use for binary work (re-rendering templates, opening with openpyxl)Named in kb_files
Markdown representations/home/user/kb/{kb_id}/{filename}.mdPre-extracted text content (same as what read_kb_file returns)Auto-included with each requested file
Structured extraction data/home/user/kb/{kb_id}/extracted_data.jsonArray of objects with fileId, fileName, uploadDate, plus all extraction schema fieldsWritten for each accessible KB even when no files are requested

When to use local files vs KB tools

ApproachBest for
Read .md files in PythonBulk processing — reading 10+ files at once (e.g., spreading financials, comparing documents, building reports)
Load extracted_data.json in PythonFiltering and indexing — finding which files to process based on structured fields
search_knowledge_base toolTargeted lookups — finding specific content when you don’t know which file has the answer
read_kb_file toolFocused reads — reading 1-3 specific files, or when you need page images
Performance tip for bulk operations: Reading .md files directly in Python is instant. Each read_kb_file tool call requires a round-trip. For agents that process many files (financial analysis, document comparison, portfolio reviews), guide your agent to read files locally instead of making dozens of tool calls.

Example: bulk processing with local KB files

import json

# Step 1: Load the structured index (extracted_data.json is available for accessible KBs
# without an explicit request)
with open('/home/user/kb/{kb_id}/extracted_data.json') as f:
    index = json.load(f)

# Step 2: Filter to the files you need
target_files = [f for f in index if f.get('status') == 'APPROVED']

# Step 3: Request those files via kb_files on THIS execute_python call, e.g.
#   kb_files=[f"kb/{kb_id}/{entry['fileName']}" for entry in target_files]
# then read their .md companions directly — no per-file tool calls needed
for entry in target_files:
    md_path = f"/home/user/kb/{kb_id}/{entry['fileName']}.md"
    with open(md_path) as f:
        content = f.read()
    # Process content...

Available libraries

Common Python libraries are pre-installed including:
  • Data Science: pandas, numpy, scipy, scikit-learn
  • Visualization: matplotlib, seaborn, plotly
  • Web: requests, beautifulsoup4
  • Utilities: json, csv, datetime, os, sys

Output formats

The tool supports rich output including:
  • Text: Standard print output and string representations
  • Images: PNG, JPEG, SVG graphics from matplotlib, plotly, etc.
  • HTML: Rich HTML content and tables
  • Charts: Interactive visualizations
  • Markdown: Formatted text with markdown syntax

Visual improvements

New in latest version:
  • Color-coded output sections for easy identification
  • Collapsible code view to focus on results
  • Success indicators for code that runs without visible output
  • Enhanced error display with structured error information
  • Rich media rendering for charts, images, and formatted data

Best practices

  • Use print() statements to show progress and intermediate results
  • Structure your code with clear steps and explanations
  • Handle errors gracefully with try/except blocks
  • Break complex operations into smaller, trackable steps
  • Import libraries at the beginning of your code

Troubleshooting

“Module not found” errors
  • Check if the library is in the available libraries list
  • Try importing alternative libraries with similar functionality
  • Use built-in Python modules when possible
“Code execution timeout”
  • Simplify complex operations
  • Avoid infinite loops or very long-running processes
  • Break large datasets into smaller chunks
“Memory errors”
  • Reduce dataset size or use sampling
  • Clear variables you no longer need with del variable
  • Use more memory-efficient data structures
“No output displayed”
  • Use print() statements to generate stdout output
  • Ensure your final line is an expression (not assignment) to see results
  • Check that your code doesn’t have syntax errors