Code Interpreter Pattern for Data Analysis
Sandboxed Python execution: running pandas/matplotlib in agent tools.
The Code Interpreter Pattern
The code interpreter pattern lets an agent generate Python code to answer data analysis questions, execute that code in a sandbox, capture the output, and interpret the results.
Instead of hardcoding every analysis operation, the agent writes custom code for each question — making it infinitely flexible for data tasks.
Core Loop: Generate → Execute → Interpret
The pattern has three steps that can repeat:
- Generate — LLM writes Python code to answer the question
- Execute — run the code in a sandbox, capture stdout and files
- Interpret — pass output back to LLM to explain the results
def code_interpreter_agent(question, data_path):
# Step 1: Generate code
code = generate_analysis_code(question, data_path)
print('Generated code:', code[:200])
# Step 2: Execute in sandbox
result = execute_in_sandbox(code)
if result['error']:
# Try to fix the error
fixed_code = fix_code(code, result['error'])
result = execute_in_sandbox(fixed_code)
# Step 3: Interpret output
return interpret_output(question, result)
print(code_interpreter_agent(
'What is the average order value by customer segment?',
'data/orders.csv'
))All lessons in this course
- Code Interpreter Pattern for Data Analysis
- Pandas-Driven Data Agent Tools
- Automated Chart and Visualization Generation
- Statistical Summary Agents