데이터 분석을 위한 코드 인터프리터 패턴
샌드박스 Python 실행: 에이전트 도구에서 pandas/matplotlib를 실행합니다.
데이터 분석을 위한 코드 인터프리터 패턴은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
코드 실행 및 해석 패턴
코드 실행 및 해석 패턴을 사용하면 에이전트가 데이터 분석 질문에 답하기 위한 Python 코드를 생성하고, 해당 코드를 샌드박스에서 실행하며, 결과를 수집하고, 결과를 해석할 수 있습니다.
모든 분석 작업을 미리 하드코딩하는 대신 에이전트가 질문마다 맞춤 코드를 작성하므로 데이터 작업에 무한한 유연성을 제공합니다.
핵심 순환: 생성 → 실행 → 해석
이 패턴은 다음 세 단계를 반복할 수 있습니다.
- 생성 — LLM이 질문에 답하기 위한 Python 코드를 작성합니다
- 실행 — 샌드박스에서 코드를 실행하고 표준 출력과 파일을 수집합니다
- 해석 — 결과를 설명하도록 출력 결과를 LLM에 다시 전달합니다
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'
))코드 생성 프롬프트
코드 생성 프롬프트에는 데이터 경로와 스키마, 질문, 제약 조건(외부 API를 사용하지 않음, pandas 사용, 차트를 파일로 저장)을 포함해야 합니다.
CODE_GEN_PROMPT = """You are a Python data analyst. Write Python code to answer the question.
Data available at: {data_path}
Question: {question}
Write ONLY Python code (no markdown, no explanation):"""
def llm_call(prompt):
return "```python\nprint('df.describe() results')\n```"
def generate_analysis_code(question, data_path):
response = llm_call(CODE_GEN_PROMPT.format(question=question, data_path=data_path))
code = response.strip()
if code.startswith('```'):
code = code.split('```')[1]
if code.startswith('python'):
code = code[6:]
return code.strip()
print(generate_analysis_code('What is the average price?', 'data.csv'))하위 프로세스 샌드박스 실행
가장 간단한 샌드박스는 제한 시간과 함께 별도의 하위 프로세스에서 코드를 실행하는 방식입니다. 이렇게 하면 프로세스가 격리되므로 코드가 중단되더라도 에이전트 전체가 중단되지 않습니다.
import subprocess
import tempfile
import os
def execute_in_sandbox(code, timeout=30):
# Write code to temp file
with tempfile.NamedTemporaryFile(suffix='.py', mode='w', delete=False) as f:
f.write(code)
script_path = f.name
try:
result = subprocess.run(
['python3', script_path],
capture_output=True,
text=True,
timeout=timeout,
env={**os.environ, 'MPLBACKEND': 'Agg'} # non-interactive matplotlib
)
return {
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode,
'error': result.stderr if result.returncode != 0 else None
}
except subprocess.TimeoutExpired:
return {'stdout': '', 'stderr': 'Timeout', 'returncode': -1, 'error': 'Code timed out'}
finally:
os.unlink(script_path)
if __name__ == '__main__':
result = execute_in_sandbox('print(2 + 2)')
print('Sandbox stdout:', result['stdout'].strip())
print('Return code :', result['returncode'])
E2B 클라우드 샌드박스
E2B는 안전한 코드 실행을 위한 관리형 클라우드 샌드박스를 제공합니다. 하위 프로세스보다 보안성이 높으며, 파일 시스템에 접근할 수 있는 격리된 컨테이너에서 코드를 실행합니다.
pip install e2b-code-interpreter로 설치합니다.
from e2b_code_interpreter import Sandbox
import os
def execute_with_e2b(code, data_bytes=None):
with Sandbox(api_key=os.getenv('E2B_API_KEY')) as sandbox:
# Upload data file if provided
if data_bytes:
sandbox.files.write('/home/user/data.csv', data_bytes)
# Execute code
execution = sandbox.run_code(code)
result = {
'stdout': '\n'.join(execution.logs.stdout),
'stderr': '\n'.join(execution.logs.stderr),
'error': None
}
# Check for errors
if execution.error:
result['error'] = str(execution.error)
# Download any generated files
result['files'] = []
for output in execution.results:
if hasattr(output, 'png'):
result['files'].append({
'type': 'image/png',
'data': output.png # base64 encoded
})
return result생성된 파일 수집
코드에서 차트, CSV 내보내기 결과 또는 기타 파일을 생성할 수 있습니다. 샌드박스의 파일 시스템에서 이러한 파일을 수집하여 해석하거나 표시할 수 있도록 에이전트에 전달합니다.
import os
import glob
import base64
OUTPUT_DIR = '/tmp/chart_output'
def execute_and_capture(code, timeout=30):
# Create output dir
os.makedirs(OUTPUT_DIR, exist_ok=True)
result = execute_in_sandbox(code, timeout=timeout)
# Capture any generated image files
generated_files = []
for filepath in glob.glob(os.path.join(OUTPUT_DIR, '*.png')):
with open(filepath, 'rb') as f:
encoded = base64.b64encode(f.read()).decode('utf-8')
generated_files.append({
'filename': os.path.basename(filepath),
'type': 'image/png',
'base64': encoded
})
os.unlink(filepath) # clean up
result['generated_files'] = generated_files
print(f'Captured {len(generated_files)} file(s) from sandbox')
return result오류 복구 반복 과정
생성된 코드에는 첫 실행에서 버그가 있는 경우가 많습니다. 복구 반복 과정을 구현하여 원래 코드와 함께 오류를 LLM에 보내고 수정을 요청합니다. 재시도 횟수는 2~3회로 제한합니다.
FIX_PROMPT = '''The following Python code raised an error. Fix it.
Original code:
{code}
Error:
{error}
Return ONLY the fixed Python code (no explanation, no markdown):'''
def fix_code(code, error):
return llm_call(FIX_PROMPT.format(code=code, error=error)).strip()
def execute_with_retry(code, max_retries=2):
for attempt in range(max_retries + 1):
result = execute_and_capture(code)
if not result['error']:
return result
print(f'Attempt {attempt + 1} failed: {result["error"][:100]}')
if attempt < max_retries:
code = fix_code(code, result['error'])
return result # return last result even if errored코드 출력 해석
원시 코드 출력(숫자, 표)은 자연어 답변으로 다시 변환해야 합니다. 표준 출력을 LLM에 전달하고 원래 질문의 맥락에서 결과를 설명하도록 요청합니다.
INTERPRET_PROMPT = '''A Python script was executed to answer a data analysis question.
Explain the results in clear, non-technical language.
Original question: {question}
Code output (stdout):
{output}
Provide a clear, concise answer that directly addresses the question.
Highlight the most important numbers or findings.
Answer:'''
def interpret_output(question, execution_result):
stdout = execution_result.get('stdout', '').strip()
error = execution_result.get('error')
if error and not stdout:
return f'The analysis failed with error: {error}'
if not stdout:
return 'The code ran successfully but produced no output.'
return llm_call(INTERPRET_PROMPT.format(
question=question,
output=stdout[:3000] # truncate very long outputs
))코드 생성의 보안 제약 조건
생성된 코드에서 네트워크 호출, 민감한 파일에 대한 접근, 시스템 명령 실행을 수행해서는 안 됩니다. 프롬프트와 샌드박스 제한을 모두 사용하여 이를 강제합니다.
BLOCKED_IMPORTS = ['requests', 'httpx', 'urllib', 'socket', 'subprocess', 'os.system']
def pre_validate_code(code):
errors = []
for blocked in BLOCKED_IMPORTS:
if f'import {blocked}' in code or f'from {blocked}' in code:
errors.append(f'Blocked import: {blocked}')
# Block shell execution
import re
if re.search(r'os\.system|subprocess\.run|subprocess\.call|eval\(|exec\(', code):
errors.append('Blocked: shell execution or eval/exec')
# Block reading outside allowed paths
if re.search(r'open\([^)]*\.\./|open\([^)]*\/etc\/', code):
errors.append('Blocked: unauthorized file access')
if errors:
raise ValueError('Security check failed:\n' + '\n'.join(errors))
return True
if __name__ == '__main__':
try:
pre_validate_code('import requests\nrequests.get("http://x")')
except ValueError as e:
print('Rejected:', e)
print('Safe code passed:', pre_validate_code('print(1 + 1)'))
데이터 스키마 주입
LLM은 열 이름, 형식, 샘플 행 등 데이터 스키마를 미리 알고 있을 때 더 나은 코드를 생성합니다. 코드 생성 프롬프트에 스키마 설명을 포함합니다.
import pandas as pd
def get_data_schema(data_path):
df = pd.read_csv(data_path, nrows=5)
schema_lines = []
for col in df.columns:
dtype = str(df[col].dtype)
sample = df[col].dropna().iloc[0] if len(df[col].dropna()) > 0 else 'N/A'
schema_lines.append(f' - {col} ({dtype}): sample={sample!r}')
schema_text = '\n'.join(schema_lines)
return f'CSV columns:\n{schema_text}\nTotal rows: {len(pd.read_csv(data_path))}'
ENHANCED_PROMPT = CODE_GEN_PROMPT + '\n\nData schema:\n{schema}'
def generate_analysis_code_with_schema(question, data_path):
schema = get_data_schema(data_path)
response = llm_call(ENHANCED_PROMPT.format(
question=question, data_path=data_path, schema=schema
))
return response.strip()실행 기록 추적
세션에서 실행된 모든 코드를 기록으로 남깁니다. 그러면 에이전트가 이전 결과를 참조하고, 앞선 계산을 바탕으로 작업하며, 사용자에게 분석 단계를 설명할 수 있습니다.
from datetime import datetime
execution_history = []
def record_execution(question, code, result):
execution_history.append({
'timestamp': datetime.now().isoformat(),
'question': question,
'code_lines': len(code.splitlines()),
'stdout_preview': result.get('stdout', '')[:200],
'success': result.get('error') is None,
'generated_files': len(result.get('generated_files', []))
})
def get_session_summary():
total = len(execution_history)
successful = sum(1 for e in execution_history if e['success'])
return {
'total_executions': total,
'successful': successful,
'failed': total - successful,
'success_rate': f'{successful/max(total,1)*100:.0f}%',
'questions_answered': [e['question'][:60] for e in execution_history]
}
# Usage in agent loop
def code_interpreter_agent_tracked(question, data_path):
code = generate_analysis_code_with_schema(question, data_path)
result = execute_with_retry(code)
record_execution(question, code, result)
return interpret_output(question, result)지식 확인
특정 데이터 분석 작업을 에이전트 도구로 하드코딩하는 대신 코드 인터프리터 패턴을 사용할 때의 가장 큰 장점은 무엇입니까?
요약: 데이터 분석을 위한 코드 인터프리터 패턴
코드 인터프리터 패턴은 다음과 같이 작동합니다. Python 코드 생성(스키마 맥락과 보안 제약 조건 포함) → 샌드박스에서 실행(하위 프로세스 또는 E2B) → 표준 출력과 파일 수집 → 오류 발생 시 재시도 → 결과를 자연어로 해석.
주요 고려 사항은 더 나은 코드 생성을 위해 데이터 스키마를 주입하고, 차단된 가져오기와 셸 명령을 대상으로 코드를 사전 검증하며, 무한 실행을 방지하도록 하위 프로세스에 제한 시간을 설정하고, 생성된 차트를 표시할 수 있도록 base64로 수집하는 것입니다.
자주 묻는 질문
“데이터 분석을 위한 코드 인터프리터 패턴” 강의는 무료인가요?
네 — “데이터 분석을 위한 코드 인터프리터 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
“데이터 분석을 위한 코드 인터프리터 패턴”에서 뭘 배우나요?
샌드박스 Python 실행: 에이전트 도구에서 pandas/matplotlib를 실행합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“데이터 분석을 위한 코드 인터프리터 패턴” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 데이터 분석을 위한 코드 인터프리터 패턴
- Pandas 기반 데이터 에이전트 도구
- 자동화된 차트 및 시각화 생성
- 통계 요약 에이전트