Code Interpreter
A general-purpose code execution environment powered by AWS Bedrock AgentCore Code Interpreter. Run code, execute shell commands, and manage files in a secure sandbox.
Available Tools
- execute_code(code, language, output_filename): Execute Python, JavaScript, or TypeScript code.
- execute_command(command): Execute shell commands.
- file_operations(operation, paths, content): Read, write, list, or remove files in the mounted session workspace.
Tool Parameters
execute_code
| Parameter |
Type |
Required |
Default |
Description |
code |
string |
Yes |
|
Code to execute. Use print() for text output. |
language |
string |
No |
"python" |
"python", "javascript", or "typescript" |
output_filename |
string |
No |
"" |
File to publish as a durable session file. Code must save a file with this exact name. |
execute_command
| Parameter |
Type |
Required |
Description |
command |
string |
Yes |
Shell command to execute (e.g., "ls -la", "pip install requests"). |
file_operations
| Parameter |
Type |
Required |
Description |
operation |
string |
Yes |
"read", "write", "list", or "remove" |
paths |
list |
For read/list/remove |
File paths. read: ["file.txt"], list: ["."], remove: ["old.txt"] |
content |
list |
For write |
Entries with path and text: [{"path": "out.txt", "text": "hello"}] |
tool_input Examples
execute_code — text output
{
"code": "import pandas as pd\ndf = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})\nprint(df.describe())",
"language": "python"
}
execute_code — generate chart
{
"code": "import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.linspace(0, 10, 100)\nplt.figure(figsize=(10,6))\nplt.plot(x, np.sin(x))\nplt.title('Sine Wave')\nplt.savefig('sine.png', dpi=300, bbox_inches='tight')\nprint('Done')",
"language": "python",
"output_filename": "sine.png"
}
execute_command — install a package
{
"command": "pip install yfinance"
}
execute_command — check environment
{
"command": "python --version && pip list | head -20"
}
file_operations — write a file
{
"operation": "write",
"content": [{"path": "config.json", "text": "{\"key\": \"value\"}"}]
}
file_operations — list files
{
"operation": "list",
"paths": ["."]
}
file_operations — read a file
{
"operation": "read",
"paths": ["output.csv"]
}
When to Use This Skill
Use code-interpreter as a sandbox for testing and prototyping code.
For production tasks (creating documents, charts, presentations), prefer specialized skills.
Do NOT use for:
- Formatting or displaying code examples (respond directly with markdown code blocks)
- Explaining code or algorithms (respond directly with text)
- Simple calculations you can do mentally (just provide the answer)
- Any task that doesn't require actual code execution
| Task |
Recommended Skill |
Notes |
| Create charts/diagrams |
visual-design |
Use this first for production charts |
| Create Word documents |
word-documents |
Has template support and styling |
| Create Excel spreadsheets |
excel-spreadsheets |
Has formatting pipeline and validation |
| Create PowerPoint |
powerpoint-presentations |
Has layout system and design patterns |
| Test code snippets |
code-interpreter |
Debug, verify logic, check output |
| Prototype algorithms |
code-interpreter |
Experiment before implementing |
| Install/test packages |
code-interpreter |
Check compatibility, test APIs |
| Debug code logic |
code-interpreter |
Isolate and test specific functions |
| Verify calculations |
code-interpreter |
Quick math or data checks |
Code Interpreter vs Code Agent
|
Code Interpreter |
Code Agent |
| Nature |
Sandboxed execution environment |
Autonomous agent (Claude Code) |
| Best for |
Quick scripts, data analysis, prototyping |
Multi-file projects, refactoring, test suites |
| File persistence |
Files in /mnt/workspace persist across interpreter restarts |
All files auto-synced to S3 |
| Session state |
Variables persist within one interpreter session; workspace files persist for the chat session |
Files + conversation persist across sessions |
| Autonomy |
You write the code |
Agent plans, writes, runs, and iterates |
| Use when |
You need to run a specific piece of code |
You need an engineer to solve a problem end-to-end |
Workspace Integration
The chat session has a persistent filesystem mounted at /mnt/workspace.
Relative file paths used by Code Interpreter tools resolve inside this directory.
Files written there are scratch files and remain available when the interpreter
session is restarted. They are not user-downloadable artifacts unless
output_filename is supplied.
The mount is required. If it cannot be configured or attached, Code Interpreter
returns an error instead of starting an isolated non-persistent session.
Create persistent files directly:
{
"tool": "execute_code",
"code": "from pathlib import Path\nPath('/mnt/workspace/results.json').write_text('{\"ok\": true}')"
}
Use output_filename whenever a generated file must appear in Generated Files
or be downloadable by the user. The tool publishes and verifies that file before
returning success. Do not create Markdown links to /mnt/workspace or describe
raw workspace paths as download links; the application renders the file action.
Uploaded files:
Files uploaded by the user are available in the mounted workspace without
manual loading or base64 transfer under /mnt/workspace/inputs. JSON, JSONL,
and NDJSON attachments may be represented by a bounded text excerpt in the
conversation; use the mounted file when the full dataset is needed.
Use file_operations for scratch-file inspection. Published files are surfaced
by the application and should be referenced by their displayed filename.
Environment
- Languages: Python (recommended, 200+ libraries), JavaScript, TypeScript
- Shell: Full shell access via
execute_command
- File system:
/mnt/workspace persists across Code Interpreter restarts for the chat session
- Session state: Variables persist within one interpreter session; files persist in the mounted workspace
- Network: Internet access available (can use
requests, urllib, curl)
Supported Languages
- Python (recommended) — 200+ pre-installed libraries covering data science, ML, visualization, file processing
- JavaScript — Node.js runtime, useful for JSON manipulation, async operations
- TypeScript — TypeScript runtime with type checking
Pre-installed Python Libraries
Data Analysis & Visualization
| Library |
Common Use |
pandas |
DataFrames, CSV/Excel I/O, groupby, pivot |
numpy |
Arrays, linear algebra, random, statistics |
matplotlib |
Line, bar, scatter, histogram, subplots |
plotly |
Interactive charts, 3D plots |
bokeh |
Interactive visualization |
scipy |
Optimization, interpolation, signal processing |
statsmodels |
Regression, time series, hypothesis tests |
sympy |
Algebra, calculus, equation solving |
Machine Learning & AI
| Library |
Common Use |
scikit-learn |
Classification, regression, clustering, pipelines |
torch / torchvision / torchaudio |
Deep learning, computer vision, audio |
xgboost |
High-performance gradient boosting |
spacy / nltk / textblob |
NLP, tokenization, NER, sentiment |
scikit-image |
Image processing, filters, segmentation |
Mathematical & Optimization
| Library |
Common Use |
cvxpy |
Convex optimization, portfolio optimization |
ortools |
Scheduling, routing, constraint programming |
pulp |
Linear programming |
z3-solver |
SAT solving, formal verification |
networkx / igraph |
Graph algorithms, network analysis |
File Processing & Documents
| Library |
Common Use |
openpyxl / xlrd / XlsxWriter |
Excel read/write with formatting |
python-docx |
Word document creation/modification |
python-pptx |
PowerPoint creation/modification |
PyPDF2 / pdfplumber / reportlab |
PDF read/write/generate |
lxml / beautifulsoup4 |
XML/HTML parsing |
markitdown |
Convert various formats to Markdown |
Image & Media
| Library |
Common Use |
pillow (PIL) |
Image resize, crop, filter, conversion |
opencv-python (cv2) |
Computer vision, feature detection |
imageio / moviepy |
Image/video I/O and editing |
pydub |
Audio manipulation |
svgwrite / Wand |
SVG creation, ImageMagick |
Data Storage & Formats
| Library |
Common Use |
duckdb |
SQL queries on DataFrames and files |
SQLAlchemy |
SQL ORM and database abstraction |
pyarrow |
Parquet and Arrow format processing |
orjson / ujson / PyYAML |
Fast JSON/YAML parsing |
Web & API
| Library |
Common Use |
requests / httpx |
HTTP requests, API calls |
beautifulsoup4 |
Web scraping |
fastapi / Flask / Django |
Web frameworks |
Utilities
| Library |
Common Use |
pydantic |
Data validation, schema definition |
Faker |
Test data generation |
rich |
Pretty printing, tables |
cryptography |
Encryption, hashing |
qrcode |
QR code generation |
boto3 |
AWS SDK |
For the full list of 200+ libraries with versions, run: execute_command(command="pip list")
Usage Patterns
Pattern 1: Data Analysis
import pandas as pd
import numpy as np
df = pd.DataFrame({
'date': pd.date_range('2024-01-01', periods=100),
'revenue': np.random.normal(1000, 200, 100),
'costs': np.random.normal(700, 150, 100),
})
df['profit'] = df['revenue'] - df['costs']
print("=== Summary Statistics ===")
print(df.describe())
print(f"\nTotal Profit: ${df['profit'].sum():,.2f}")
print(f"Profit Margin: {df['profit'].mean() / df['revenue'].mean() * 100:.1f}%")
Pattern 2: Visualization (with output_filename)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
categories = ['Q1', 'Q2', 'Q3', 'Q4']
values = [120, 150, 180, 210]
axes[0,0].bar(categories, values, color='#2196F3')
axes[0,0].set_title('Quarterly Revenue')
x = np.linspace(0, 10, 50)
axes[0,1].plot(x, np.sin(x), 'b-', linewidth=2)
axes[0,1].set_title('Trend')
sizes = [35, 30, 20, 15]
axes[1,0].pie(sizes, labels=['A','B','C','D'], autopct='%1.1f%%')
axes[1,0].set_title('Market Share')
x = np.random.normal(50, 10, 200)
y = x * 1.5 + np.random.normal(0, 15, 200)
axes[1,1].scatter(x, y, alpha=0.5, c='#FF5722')
axes[1,1].set_title('Correlation')
plt.tight_layout()
plt.savefig('dashboard.png', dpi=300, bbox_inches='tight')
print('Dashboard saved')
Pattern 3: Machine Learning
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.datasets import load_iris
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3, random_state=42
)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred, target_names=iris.target_names))
Pattern 4: SQL with DuckDB
import duckdb
import pandas as pd
orders = pd.DataFrame({
'order_id': range(1, 101),
'customer': [f'Customer_{i%20}' for i in range(100)],
'amount': [round(50 + i * 3.5, 2) for i in range(100)],
})
result = duckdb.sql("""
SELECT customer, COUNT(*) as cnt, ROUND(SUM(amount), 2) as total
FROM orders GROUP BY customer
HAVING COUNT(*) >= 3 ORDER BY total DESC LIMIT 10
""").df()
print(result.to_string(index=False))
Pattern 5: Fetch Data from Web
import requests
import pandas as pd
response = requests.get("https://api.example.com/data")
data = response.json()
df = pd.DataFrame(data)
print(df.head())
Pattern 6: Multi-step Workflow (session state persists)
Call 1: execute_code → load and clean data, store in variable `df`
Call 2: execute_code → analyze `df`, generate chart, save as PNG
Call 3: execute_code → export results to CSV
Call 4: file_operations(operation="read") → download the CSV
Variables (df) and files persist across calls in the same session.
Important Rules
matplotlib.use('Agg') before import matplotlib.pyplot — sandbox has no display.
- Use
print() for text output — stdout is how results are returned.
output_filename must match exactly — the filename in plt.savefig() or wb.save() must match the output_filename parameter.
- Use
execute_command for shell tasks — ls, pip install, curl, etc.
- Use
file_operations for file management — read/write/list/remove files explicitly.
- Session state persists — variables and files remain across calls. Use this for multi-step workflows.
Common Mistakes to Avoid
- Forgetting
matplotlib.use('Agg') before import matplotlib.pyplot as plt
- Using
plt.show() instead of plt.savefig() — there is no display
- Typo in
output_filename — must match the file saved by the code exactly
- Using
execute_code for shell tasks — use execute_command instead
- Writing binary files via
file_operations — use execute_code to generate binary files, then download with output_filename
1---2name: code-interpreter3description: Test and prototype code in a sandboxed environment. Use for debugging, verifying logic, or installing packages.4---56# Code Interpreter78A general-purpose code execution environment powered by AWS Bedrock AgentCore Code Interpreter. Run code, execute shell commands, and manage files in a secure sandbox.910## Available Tools1112- **execute_code(code, language, output_filename)**: Execute Python, JavaScript, or TypeScript code.13- **execute_command(command)**: Execute shell commands.14- **file_operations(operation, paths, content)**: Read, write, list, or remove files in the mounted session workspace.1516## Tool Parameters1718### execute_code1920| Parameter | Type | Required | Default | Description |21|-----------|------|----------|---------|-------------|22| `code` | string | Yes | | Code to execute. Use `print()` for text output. |23| `language` | string | No | `"python"` | `"python"`, `"javascript"`, or `"typescript"` |24| `output_filename` | string | No | `""` | File to publish as a durable session file. Code must save a file with this exact name. |2526### execute_command2728| Parameter | Type | Required | Description |29|-----------|------|----------|-------------|30| `command` | string | Yes | Shell command to execute (e.g., `"ls -la"`, `"pip install requests"`). |3132### file_operations3334| Parameter | Type | Required | Description |35|-----------|------|----------|-------------|36| `operation` | string | Yes | `"read"`, `"write"`, `"list"`, or `"remove"` |37| `paths` | list | For read/list/remove | File paths. read: `["file.txt"]`, list: `["."]`, remove: `["old.txt"]` |38| `content` | list | For write | Entries with `path` and `text`: `[{"path": "out.txt", "text": "hello"}]` |3940## tool_input Examples4142### execute_code — text output4344```json45{46 "code": "import pandas as pd\ndf = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})\nprint(df.describe())",47 "language": "python"48}49```5051### execute_code — generate chart5253```json54{55 "code": "import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.linspace(0, 10, 100)\nplt.figure(figsize=(10,6))\nplt.plot(x, np.sin(x))\nplt.title('Sine Wave')\nplt.savefig('sine.png', dpi=300, bbox_inches='tight')\nprint('Done')",56 "language": "python",57 "output_filename": "sine.png"58}59```6061### execute_command — install a package6263```json64{65 "command": "pip install yfinance"66}67```6869### execute_command — check environment7071```json72{73 "command": "python --version && pip list | head -20"74}75```7677### file_operations — write a file7879```json80{81 "operation": "write",82 "content": [{"path": "config.json", "text": "{\"key\": \"value\"}"}]83}84```8586### file_operations — list files8788```json89{90 "operation": "list",91 "paths": ["."]92}93```9495### file_operations — read a file9697```json98{99 "operation": "read",100 "paths": ["output.csv"]101}102```103104## When to Use This Skill105106Use code-interpreter as a **sandbox for testing and prototyping code**.107For production tasks (creating documents, charts, presentations), prefer specialized skills.108109**Do NOT use for:**110- Formatting or displaying code examples (respond directly with markdown code blocks)111- Explaining code or algorithms (respond directly with text)112- Simple calculations you can do mentally (just provide the answer)113- Any task that doesn't require actual code execution114115| Task | Recommended Skill | Notes |116|------|-------------------|-------|117| Create charts/diagrams | **visual-design** | Use this first for production charts |118| Create Word documents | **word-documents** | Has template support and styling |119| Create Excel spreadsheets | **excel-spreadsheets** | Has formatting pipeline and validation |120| Create PowerPoint | **powerpoint-presentations** | Has layout system and design patterns |121| **Test code snippets** | **code-interpreter** | Debug, verify logic, check output |122| **Prototype algorithms** | **code-interpreter** | Experiment before implementing |123| **Install/test packages** | **code-interpreter** | Check compatibility, test APIs |124| Debug code logic | code-interpreter | Isolate and test specific functions |125| Verify calculations | code-interpreter | Quick math or data checks |126127## Code Interpreter vs Code Agent128129| | Code Interpreter | Code Agent |130|---|---|---|131| **Nature** | Sandboxed execution environment | Autonomous agent (Claude Code) |132| **Best for** | Quick scripts, data analysis, prototyping | Multi-file projects, refactoring, test suites |133| **File persistence** | Files in `/mnt/workspace` persist across interpreter restarts | All files auto-synced to S3 |134| **Session state** | Variables persist within one interpreter session; workspace files persist for the chat session | Files + conversation persist across sessions |135| **Autonomy** | You write the code | Agent plans, writes, runs, and iterates |136| **Use when** | You need to run a specific piece of code | You need an engineer to solve a problem end-to-end |137138## Workspace Integration139140The chat session has a persistent filesystem mounted at `/mnt/workspace`.141Relative file paths used by Code Interpreter tools resolve inside this directory.142Files written there are scratch files and remain available when the interpreter143session is restarted. They are not user-downloadable artifacts unless144`output_filename` is supplied.145146The mount is required. If it cannot be configured or attached, Code Interpreter147returns an error instead of starting an isolated non-persistent session.148149**Create persistent files directly:**150151```json152{153 "tool": "execute_code",154 "code": "from pathlib import Path\nPath('/mnt/workspace/results.json').write_text('{\"ok\": true}')"155}156```157158Use `output_filename` whenever a generated file must appear in Generated Files159or be downloadable by the user. The tool publishes and verifies that file before160returning success. Do not create Markdown links to `/mnt/workspace` or describe161raw workspace paths as download links; the application renders the file action.162163**Uploaded files:**164165Files uploaded by the user are available in the mounted workspace without166manual loading or base64 transfer under `/mnt/workspace/inputs`. JSON, JSONL,167and NDJSON attachments may be represented by a bounded text excerpt in the168conversation; use the mounted file when the full dataset is needed.169170Use `file_operations` for scratch-file inspection. Published files are surfaced171by the application and should be referenced by their displayed filename.172173## Environment174175- **Languages:** Python (recommended, 200+ libraries), JavaScript, TypeScript176- **Shell:** Full shell access via `execute_command`177- **File system:** `/mnt/workspace` persists across Code Interpreter restarts for the chat session178- **Session state:** Variables persist within one interpreter session; files persist in the mounted workspace179- **Network:** Internet access available (can use `requests`, `urllib`, `curl`)180181## Supported Languages182183- **Python** (recommended) — 200+ pre-installed libraries covering data science, ML, visualization, file processing184- **JavaScript** — Node.js runtime, useful for JSON manipulation, async operations185- **TypeScript** — TypeScript runtime with type checking186187## Pre-installed Python Libraries188189### Data Analysis & Visualization190191| Library | Common Use |192|---------|------------|193| `pandas` | DataFrames, CSV/Excel I/O, groupby, pivot |194| `numpy` | Arrays, linear algebra, random, statistics |195| `matplotlib` | Line, bar, scatter, histogram, subplots |196| `plotly` | Interactive charts, 3D plots |197| `bokeh` | Interactive visualization |198| `scipy` | Optimization, interpolation, signal processing |199| `statsmodels` | Regression, time series, hypothesis tests |200| `sympy` | Algebra, calculus, equation solving |201202### Machine Learning & AI203204| Library | Common Use |205|---------|------------|206| `scikit-learn` | Classification, regression, clustering, pipelines |207| `torch` / `torchvision` / `torchaudio` | Deep learning, computer vision, audio |208| `xgboost` | High-performance gradient boosting |209| `spacy` / `nltk` / `textblob` | NLP, tokenization, NER, sentiment |210| `scikit-image` | Image processing, filters, segmentation |211212### Mathematical & Optimization213214| Library | Common Use |215|---------|------------|216| `cvxpy` | Convex optimization, portfolio optimization |217| `ortools` | Scheduling, routing, constraint programming |218| `pulp` | Linear programming |219| `z3-solver` | SAT solving, formal verification |220| `networkx` / `igraph` | Graph algorithms, network analysis |221222### File Processing & Documents223224| Library | Common Use |225|---------|------------|226| `openpyxl` / `xlrd` / `XlsxWriter` | Excel read/write with formatting |227| `python-docx` | Word document creation/modification |228| `python-pptx` | PowerPoint creation/modification |229| `PyPDF2` / `pdfplumber` / `reportlab` | PDF read/write/generate |230| `lxml` / `beautifulsoup4` | XML/HTML parsing |231| `markitdown` | Convert various formats to Markdown |232233### Image & Media234235| Library | Common Use |236|---------|------------|237| `pillow` (PIL) | Image resize, crop, filter, conversion |238| `opencv-python` (cv2) | Computer vision, feature detection |239| `imageio` / `moviepy` | Image/video I/O and editing |240| `pydub` | Audio manipulation |241| `svgwrite` / `Wand` | SVG creation, ImageMagick |242243### Data Storage & Formats244245| Library | Common Use |246|---------|------------|247| `duckdb` | SQL queries on DataFrames and files |248| `SQLAlchemy` | SQL ORM and database abstraction |249| `pyarrow` | Parquet and Arrow format processing |250| `orjson` / `ujson` / `PyYAML` | Fast JSON/YAML parsing |251252### Web & API253254| Library | Common Use |255|---------|------------|256| `requests` / `httpx` | HTTP requests, API calls |257| `beautifulsoup4` | Web scraping |258| `fastapi` / `Flask` / `Django` | Web frameworks |259260### Utilities261262| Library | Common Use |263|---------|------------|264| `pydantic` | Data validation, schema definition |265| `Faker` | Test data generation |266| `rich` | Pretty printing, tables |267| `cryptography` | Encryption, hashing |268| `qrcode` | QR code generation |269| `boto3` | AWS SDK |270271> For the full list of 200+ libraries with versions, run: `execute_command(command="pip list")`272273## Usage Patterns274275### Pattern 1: Data Analysis276277```python278import pandas as pd279import numpy as np280281df = pd.DataFrame({282 'date': pd.date_range('2024-01-01', periods=100),283 'revenue': np.random.normal(1000, 200, 100),284 'costs': np.random.normal(700, 150, 100),285})286df['profit'] = df['revenue'] - df['costs']287288print("=== Summary Statistics ===")289print(df.describe())290print(f"\nTotal Profit: ${df['profit'].sum():,.2f}")291print(f"Profit Margin: {df['profit'].mean() / df['revenue'].mean() * 100:.1f}%")292```293294### Pattern 2: Visualization (with output_filename)295296```python297import matplotlib298matplotlib.use('Agg')299import matplotlib.pyplot as plt300import numpy as np301302fig, axes = plt.subplots(2, 2, figsize=(14, 10))303304categories = ['Q1', 'Q2', 'Q3', 'Q4']305values = [120, 150, 180, 210]306axes[0,0].bar(categories, values, color='#2196F3')307axes[0,0].set_title('Quarterly Revenue')308309x = np.linspace(0, 10, 50)310axes[0,1].plot(x, np.sin(x), 'b-', linewidth=2)311axes[0,1].set_title('Trend')312313sizes = [35, 30, 20, 15]314axes[1,0].pie(sizes, labels=['A','B','C','D'], autopct='%1.1f%%')315axes[1,0].set_title('Market Share')316317x = np.random.normal(50, 10, 200)318y = x * 1.5 + np.random.normal(0, 15, 200)319axes[1,1].scatter(x, y, alpha=0.5, c='#FF5722')320axes[1,1].set_title('Correlation')321322plt.tight_layout()323plt.savefig('dashboard.png', dpi=300, bbox_inches='tight')324print('Dashboard saved')325```326327### Pattern 3: Machine Learning328329```python330from sklearn.model_selection import train_test_split331from sklearn.ensemble import RandomForestClassifier332from sklearn.metrics import classification_report333from sklearn.datasets import load_iris334335iris = load_iris()336X_train, X_test, y_train, y_test = train_test_split(337 iris.data, iris.target, test_size=0.3, random_state=42338)339340model = RandomForestClassifier(n_estimators=100, random_state=42)341model.fit(X_train, y_train)342y_pred = model.predict(X_test)343344print(classification_report(y_test, y_pred, target_names=iris.target_names))345```346347### Pattern 4: SQL with DuckDB348349```python350import duckdb351import pandas as pd352353orders = pd.DataFrame({354 'order_id': range(1, 101),355 'customer': [f'Customer_{i%20}' for i in range(100)],356 'amount': [round(50 + i * 3.5, 2) for i in range(100)],357})358359result = duckdb.sql("""360 SELECT customer, COUNT(*) as cnt, ROUND(SUM(amount), 2) as total361 FROM orders GROUP BY customer362 HAVING COUNT(*) >= 3 ORDER BY total DESC LIMIT 10363""").df()364print(result.to_string(index=False))365```366367### Pattern 5: Fetch Data from Web368369```python370import requests371import pandas as pd372373response = requests.get("https://api.example.com/data")374data = response.json()375df = pd.DataFrame(data)376print(df.head())377```378379### Pattern 6: Multi-step Workflow (session state persists)380381```382Call 1: execute_code → load and clean data, store in variable `df`383Call 2: execute_code → analyze `df`, generate chart, save as PNG384Call 3: execute_code → export results to CSV385Call 4: file_operations(operation="read") → download the CSV386```387388Variables (`df`) and files persist across calls in the same session.389390## Important Rules3913921. **`matplotlib.use('Agg')` before `import matplotlib.pyplot`** — sandbox has no display.3932. **Use `print()` for text output** — stdout is how results are returned.3943. **`output_filename` must match exactly** — the filename in `plt.savefig()` or `wb.save()` must match the `output_filename` parameter.3954. **Use `execute_command` for shell tasks** — `ls`, `pip install`, `curl`, etc.3965. **Use `file_operations` for file management** — read/write/list/remove files explicitly.3976. **Session state persists** — variables and files remain across calls. Use this for multi-step workflows.398399## Common Mistakes to Avoid400401- Forgetting `matplotlib.use('Agg')` before `import matplotlib.pyplot as plt`402- Using `plt.show()` instead of `plt.savefig()` — there is no display403- Typo in `output_filename` — must match the file saved by the code exactly404- Using `execute_code` for shell tasks — use `execute_command` instead405- Writing binary files via `file_operations` — use `execute_code` to generate binary files, then download with `output_filename`