Skip to content

Commit 20e960c

Browse files
Craig ShoemakerCraig Shoemaker
authored andcommitted
initial draft
1 parent 26fd215 commit 20e960c

2 files changed

Lines changed: 254 additions & 0 deletions

File tree

Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
---
2+
title: Run code with code interpreter in Azure SRE Agent
3+
description: Learn how to use code interpreter to execute Python code, run shell commands, and generate reports in an isolated sandbox environment.
4+
#customer intent: As a developer, I want to execute Python code in a secure sandbox so that I can analyze data and create visualizations without leaving the Azure SRE Agent interface.
5+
author: craigshoemaker
6+
ms.author: cshoe
7+
ms.reviewer: cshoe
8+
ms.service: azure-sre-agent
9+
ms.topic: how-to
10+
ms.date: 01/17/2026
11+
---
12+
13+
# Run code with Code Interpreter in Azure SRE Agent
14+
15+
Code Interpreter enables you to execute Python code and shell commands in a secure, isolated sandbox environment. Use Code Interpreter to analyze data, create visualizations, generate PDF reports, and automate file operations without leaving your SRE Agent conversation.
16+
17+
In this article, you learn how to:
18+
19+
> [!div class="checklist"]
20+
> - Execute Python code to analyze data and create visualizations
21+
> - Run shell commands for file operations
22+
> - Generate and download PDF reports
23+
> - Work with files in the sandbox environment
24+
25+
## Prerequisites
26+
27+
[!INCLUDE [prerequisites](includes/prerequisites.md)]
28+
29+
## How Code Interpreter works
30+
31+
Code Interpreter runs in an isolated Azure Container Apps session with the following characteristics:
32+
33+
- **No network access**: The sandbox can't make outbound HTTP/HTTPS requests
34+
- **No process spawning**: Commands like `subprocess` and `os.system` are blocked
35+
- **No package installation**: `pip install` and `conda install` aren't available
36+
- **Isolated file system**: All files must be saved to `/mnt/data/`
37+
38+
These restrictions ensure that code execution is secure and predictable. Common data science libraries like pandas, matplotlib, and seaborn are preinstalled.
39+
40+
## Get started with Code Interpreter
41+
42+
Code Interpreter tools are automatically available in your SRE Agent conversations. Ask the agent to perform tasks using natural language.
43+
44+
### Example prompts
45+
46+
Try these prompts to get started:
47+
48+
- "Analyze this CSV data and create a chart showing incidents by category"
49+
- "Generate a PDF summary of today's incidents"
50+
- "Parse this JSON file and extract the error patterns"
51+
- "List all files in the session and show their sizes"
52+
53+
### Your first Python script
54+
55+
The following example demonstrates how to create a visualization:
56+
57+
```python
58+
import matplotlib.pyplot as plt
59+
import numpy as np
60+
61+
# Generate sample data
62+
categories = ['Critical', 'High', 'Medium', 'Low']
63+
counts = [5, 12, 28, 45]
64+
65+
# Create bar chart
66+
plt.figure(figsize=(10, 6))
67+
plt.bar(categories, counts, color=['red', 'orange', 'yellow', 'green'])
68+
plt.title('Incidents by Severity')
69+
plt.xlabel('Severity Level')
70+
plt.ylabel('Count')
71+
plt.savefig('/mnt/data/incidents_by_severity.png', dpi=150)
72+
```
73+
74+
When the code runs successfully, the agent returns the image inline in the conversation.
75+
76+
## Scenarios
77+
78+
### Analyze incident data
79+
80+
Use Python to analyze incident patterns and identify trends:
81+
82+
```python
83+
import pandas as pd
84+
85+
# Load incident data
86+
df = pd.read_csv('/mnt/data/incidents.csv')
87+
88+
# Calculate summary statistics
89+
summary = df.groupby('category').agg({
90+
'id': 'count',
91+
'resolution_time': 'mean'
92+
}).rename(columns={'id': 'count', 'resolution_time': 'avg_resolution_hours'})
93+
94+
# Export results
95+
summary.to_csv('/mnt/data/incident_summary.csv')
96+
print(summary)
97+
```
98+
99+
### Create visualizations
100+
101+
Generate charts to communicate insights:
102+
103+
```python
104+
import matplotlib.pyplot as plt
105+
import seaborn as sns
106+
107+
# Load data
108+
df = pd.read_csv('/mnt/data/incidents.csv')
109+
110+
# Create visualization
111+
plt.figure(figsize=(12, 6))
112+
sns.barplot(data=df, x='category', y='count', palette='viridis')
113+
plt.title('Incidents by Category')
114+
plt.xticks(rotation=45)
115+
plt.tight_layout()
116+
plt.savefig('/mnt/data/category_chart.png', dpi=150)
117+
```
118+
119+
### Generate PDF reports
120+
121+
Create formatted PDF documents for stakeholders:
122+
123+
```python
124+
from reportlab.pdfgen import canvas
125+
from reportlab.lib.pagesizes import letter
126+
127+
# Create PDF
128+
c = canvas.Canvas('/mnt/data/weekly_report.pdf', pagesize=letter)
129+
130+
# Add content
131+
c.setFont('Helvetica-Bold', 18)
132+
c.drawString(72, 750, 'Weekly Incident Report')
133+
134+
c.setFont('Helvetica', 12)
135+
c.drawString(72, 720, 'Period: January 10-17, 2026')
136+
c.drawString(72, 700, 'Total incidents: 90')
137+
c.drawString(72, 680, 'Critical incidents: 5')
138+
c.drawString(72, 660, 'Average resolution time: 4.2 hours')
139+
140+
c.save()
141+
```
142+
143+
The agent returns a download link for the generated PDF.
144+
145+
### Process log files
146+
147+
Search and analyze log files using shell commands:
148+
149+
```bash
150+
# Count error occurrences by type
151+
grep -E "ERROR|WARN|FATAL" application.log | sort | uniq -c | sort -rn
152+
```
153+
154+
```bash
155+
# Find the most recent log entries
156+
tail -100 application.log
157+
```
158+
159+
## Tool reference
160+
161+
Code Interpreter provides the following tools:
162+
163+
### ExecutePythonCode
164+
165+
Execute Python code in the isolated sandbox.
166+
167+
| Parameter | Type | Required | Description |
168+
|-----------|------|----------|-------------|
169+
| `pythonCode` | string | Yes | Python code to execute (max 20,000 characters) |
170+
| `timeoutSeconds` | integer | No | Execution timeout (default: 120, max: 900) |
171+
172+
**Output**: Images display inline as markdown. Data files return as download links.
173+
174+
### GeneratePdfReport
175+
176+
Generate PDF documents from Python code.
177+
178+
| Parameter | Type | Required | Description |
179+
|-----------|------|----------|-------------|
180+
| `pythonCode` | string | Yes | Python code that creates a PDF file |
181+
| `expectedOutputFilename` | string | Yes | Path where the PDF is saved (for example, `report.pdf`) |
182+
| `saveAsFilename` | string | Yes | Download filename (for example, `daily_summary.pdf`) |
183+
| `timeoutSeconds` | integer | No | Execution timeout (default: 180, max: 900) |
184+
185+
### RunShellCommand
186+
187+
Execute shell commands in the sandbox.
188+
189+
| Parameter | Type | Required | Description |
190+
|-----------|------|----------|-------------|
191+
| `command` | string | Yes | Shell command to execute |
192+
| `explanation` | string | No | Description logged with the command |
193+
| `isBackground` | boolean | No | Must be `false` (background jobs aren't supported) |
194+
| `timeoutSeconds` | integer | No | Execution timeout (default: 120, max: 240) |
195+
196+
> [!NOTE]
197+
> Commands run from `/mnt/data/`. Use relative paths and chain commands with `;` instead of `&&`.
198+
199+
### File operations
200+
201+
| Tool | Description |
202+
|------|-------------|
203+
| `ReadSessionFile` | Read contents of a file from `/mnt/data/` |
204+
| `SearchSessionFiles` | Search for text within files using grep-style patterns |
205+
| `ListSessionFiles` | List all files in the session with metadata |
206+
| `GetSessionFile` | Download a file from the session |
207+
| `UploadFileToSession` | Upload a file for further processing |
208+
209+
#### Supported file types
210+
211+
- **Images**: PNG, JPG, GIF, SVG, WebP, BMP, TIFF, EPS
212+
- **Data**: CSV, TSV, Excel, JSON, XML, YAML, HDF5, NetCDF, pickle
213+
- **Documents**: PDF, HTML, Markdown, Office formats
214+
- **Code**: Python, Jupyter notebooks, R, SQL
215+
- **Archives**: ZIP, TAR, GZ
216+
217+
## Limitations
218+
219+
The following operations are blocked for security:
220+
221+
| Category | Blocked operations |
222+
|----------|-------------------|
223+
| Process spawning | `subprocess`, `os.system`, `os.popen`, `os.spawn*` |
224+
| Network access | Outbound HTTP/HTTPS requests |
225+
| Package installation | `pip install`, `conda install` |
226+
| File system | Access outside `/mnt/data/` |
227+
228+
## Troubleshoot Code Interpreter
229+
230+
### Code execution fails
231+
232+
- Verify your code doesn't use blocked operations like subprocess or network calls
233+
- Check that all file paths point to `/mnt/data/`
234+
- Ensure your code is under 20,000 characters
235+
236+
### Files don't appear in output
237+
238+
- Confirm files are saved to `/mnt/data/`
239+
- Use `ListSessionFiles` to verify file creation
240+
- Check that the file extension is supported
241+
242+
### Timeout errors
243+
244+
- Increase the `timeoutSeconds` parameter (maximum 900 seconds)
245+
- Optimize your code to reduce execution time
246+
- Split large operations into smaller chunks
247+
248+
## Related content
249+
250+
- [Memory system](memory-system.md)
251+
- [Build subagents](subagent-builder-scenarios.md)
252+
- [Starter prompts](prompts.md)

articles/sre-agent/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ items:
3030
href: troubleshoot-azure-container-apps.md
3131
- name: Features
3232
items:
33+
- name: Code Interpreter
34+
href: code-interpreter.md
3335
- name: Memory system
3436
href: memory-system.md
3537
- name: Subagents

0 commit comments

Comments
 (0)