Skip to content

Commit c698484

Browse files
authored
Merge pull request #310620 from craigshoemaker/sre/code-interpreter
[SRE Agent] New: Code interpreter
2 parents a1a2cd4 + 2498c5b commit c698484

2 files changed

Lines changed: 266 additions & 0 deletions

File tree

Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
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/26/2026
11+
---
12+
13+
# Run code by using code interpreter in Azure SRE Agent
14+
15+
The SRE Agent 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+
The SRE Agent 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 or 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 by 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 code interpreter to transform raw incident data into actionable insights and visualizations.
81+
82+
1. Ask SRE Agent to create a CSV file of all the incidents that have occurred within the last month using the following prompt:
83+
84+
```text
85+
Create a CSV file of all the incidents that
86+
occurred in the last month.
87+
88+
Name the file `incidents.csv` and save it
89+
to `/mnt/data`.
90+
```
91+
92+
1. Use Python to analyze incident patterns and identify trends:
93+
94+
```python
95+
import pandas as pd
96+
97+
# Load incident data
98+
df = pd.read_csv('/mnt/data/incidents.csv')
99+
100+
# Calculate summary statistics
101+
summary = df.groupby('category').agg({
102+
'id': 'count',
103+
'resolution_time': 'mean'
104+
}).rename(columns={'id': 'count', 'resolution_time': 'avg_resolution_hours'})
105+
106+
# Export results
107+
summary.to_csv('/mnt/data/incident_summary.csv')
108+
print(summary)
109+
```
110+
111+
### Create visualizations
112+
113+
Generate charts to communicate insights.
114+
115+
```python
116+
import matplotlib.pyplot as plt
117+
import seaborn as sns
118+
119+
# Load data
120+
df = pd.read_csv('/mnt/data/incidents.csv')
121+
122+
# Create visualization
123+
plt.figure(figsize=(12, 6))
124+
sns.barplot(data=df, x='category', y='count', palette='viridis')
125+
plt.title('Incidents by Category')
126+
plt.xticks(rotation=45)
127+
plt.tight_layout()
128+
plt.savefig('/mnt/data/category_chart.png', dpi=150)
129+
```
130+
131+
### Generate PDF reports
132+
133+
Create formatted PDF documents for stakeholders.
134+
135+
```python
136+
from reportlab.pdfgen import canvas
137+
from reportlab.lib.pagesizes import letter
138+
139+
# Create PDF
140+
c = canvas.Canvas('/mnt/data/weekly_report.pdf', pagesize=letter)
141+
142+
# Add content
143+
c.setFont('Helvetica-Bold', 18)
144+
c.drawString(72, 750, 'Weekly Incident Report')
145+
146+
c.setFont('Helvetica', 12)
147+
c.drawString(72, 720, 'Period: January 10-17, 2026')
148+
c.drawString(72, 700, 'Total incidents: 90')
149+
c.drawString(72, 680, 'Critical incidents: 5')
150+
c.drawString(72, 660, 'Average resolution time: 4.2 hours')
151+
152+
c.save()
153+
```
154+
155+
The agent returns a download link for the generated PDF.
156+
157+
### Process log files
158+
159+
Search and analyze log files by using shell commands.
160+
161+
```bash
162+
# Count error occurrences by type
163+
grep -E "ERROR|WARN|FATAL" application.log | sort | uniq -c | sort -rn
164+
```
165+
166+
```bash
167+
# Find the most recent log entries
168+
tail -100 application.log
169+
```
170+
171+
## Tool reference
172+
173+
Code Interpreter provides the following tools:
174+
175+
### ExecutePythonCode
176+
177+
Runs Python code in an isolated sandbox.
178+
179+
| Parameter | Type | Required | Description |
180+
|-----------|------|----------|-------------|
181+
| `pythonCode` | string | Yes | Python code to run (up to 20,000 characters) |
182+
| `timeoutSeconds` | integer | No | Execution timeout in seconds (default: 120, maximum: 900) |
183+
184+
**Output**: Images show inline as markdown. Data files return as download links.
185+
186+
### GeneratePdfReport
187+
188+
Creates PDF documents from Python code.
189+
190+
| Parameter | Type | Required | Description |
191+
|-----------|------|----------|-------------|
192+
| `pythonCode` | string | Yes | Python code that creates a PDF file |
193+
| `expectedOutputFilename` | string | Yes | Path where the PDF is saved (for example, `report.pdf`) |
194+
| `saveAsFilename` | string | Yes | Download filename (for example, `daily_summary.pdf`) |
195+
| `timeoutSeconds` | integer | No | Execution timeout in seconds (default: 180, maximum: 900) |
196+
197+
### RunShellCommand
198+
199+
Runs shell commands in the sandbox.
200+
201+
| Parameter | Type | Required | Description |
202+
|-----------|------|----------|-------------|
203+
| `command` | string | Yes | Shell command to run |
204+
| `explanation` | string | No | Description to log with the command |
205+
| `isBackground` | boolean | No | Must be `false` (background jobs aren't supported) |
206+
| `timeoutSeconds` | integer | No | Execution timeout (default: 120, max: 240) |
207+
208+
> [!NOTE]
209+
> The commands run from `/mnt/data/`. Use relative paths and chain commands by using `;` instead of `&&`.
210+
211+
### File operations
212+
213+
| Tool | Description |
214+
|------|-------------|
215+
| `ReadSessionFile` | Reads the contents of a file from `/mnt/data/`. |
216+
| `SearchSessionFiles` | Searches for text within files using grep-style patterns. |
217+
| `ListSessionFiles` | Lists all files in the session with metadata. |
218+
| `GetSessionFile` | Downloads a file from the session. |
219+
| `UploadFileToSession` | Uploads a file for further processing. |
220+
221+
#### Supported file types
222+
223+
- **Images**: PNG, JPG, GIF, SVG, WebP, BMP, TIFF, EPS
224+
- **Data**: CSV, TSV, Excel, JSON, XML, YAML, HDF5, NetCDF, pickle
225+
- **Documents**: PDF, HTML, Markdown, Office formats
226+
- **Code**: Python, Jupyter notebooks, R, SQL
227+
- **Archives**: ZIP, TAR, GZ
228+
229+
## Limitations
230+
231+
For security reasons, the system blocks the following operations:
232+
233+
| Category | Blocked operations |
234+
|----------|-------------------|
235+
| Process spawning | `subprocess`, `os.system`, `os.popen`, `os.spawn*` |
236+
| Network access | Outbound HTTP/HTTPS requests |
237+
| Package installation | `pip install`, `conda install` |
238+
| File system | Access outside `/mnt/data/` |
239+
240+
## Troubleshoot code interpreter
241+
242+
### Code execution fails
243+
244+
- Verify your code doesn't use blocked operations like `subprocess` or network calls.
245+
- Check that all file paths point to `/mnt/data/`.
246+
- Ensure your code is under 20,000 characters.
247+
248+
### Files don't appear in output
249+
250+
- Confirm you save files to `/mnt/data/`.
251+
- Use `ListSessionFiles` to verify file creation.
252+
- Check that the file extension is supported.
253+
254+
### Timeout errors
255+
256+
- Increase the `timeoutSeconds` parameter (maximum 900 seconds).
257+
- Optimize your code to reduce execution time.
258+
- Split large operations into smaller chunks.
259+
260+
## Related content
261+
262+
- [Memory system](memory-system.md)
263+
- [Build subagents](subagent-builder-scenarios.md)
264+
- [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)