당신의 AI 에이전트가 Python을 무료로 실행할 수 있습니다. 방법은 다음과 같습니다.
Source: Dev.to
위에 제공된 내용 외에 번역할 텍스트가 없습니다. 번역을 원하는 본문을 알려주시면 한국어로 번역해 드리겠습니다.
sandpy가 해결하는 문제
- Zero‑cost execution – 완전히 클라이언트 측에서 실행됩니다.
- Safety – 타임아웃이 무한 루프가 탭을 멈추게 하는 것을 방지합니다.
- Streaming output – 결과가 출력되는 즉시 확인할 수 있습니다.
- State persistence – 스냅샷을 통해 파이썬 세션을 저장하고 복원할 수 있습니다.
- Visualization support – Matplotlib 플롯을 자동으로 base64 이미지로 캡처합니다.
- Vision hook – 생성된 이미지를 비전 모델(e.g., GPT‑4V)에 전달합니다.
- Ready‑made integrations – LangChain 및 Vercel AI SDK 어댑터가 포함되어 있습니다.
설치
npm install sandpy
기본 사용법
import { Sandpy } from 'sandpy';
const sandbox = await Sandpy.create();
const result = await sandbox.run('print(2 + 2)');
console.log(result.stdout); // "4"
이게 전부입니다—Python이 브라우저에서 실행됩니다.
LangChain 통합
import { createLangChainTool } from 'sandpy';
import { DynamicTool } from 'langchain/tools';
const pythonTool = new DynamicTool(
createLangChainTool({ timeout: 30_000 })
);
// Add to your agent
const agent = new Agent({
tools: [pythonTool],
});
생성된 코드가 오작동하면, 샌드박스가 영원히 멈추는 대신 타임아웃됩니다.
Vercel AI SDK 통합
import { createVercelAITool } from 'sandpy';
import { generateText } from 'ai';
const pythonTool = createVercelAITool({ timeout: 30_000 });
const result = await generateText({
model: yourModel,
tools: { python: pythonTool },
prompt: 'Calculate the first 20 Fibonacci numbers',
});
시각화 캡처 및 비전 모델 사용
Matplotlib 플롯이 생성되면, sandbox는 base64‑인코딩된 이미지를 반환하며 이를 비전 모델에 보낼 수 있습니다:
const result = await sandbox.run(plotCode, {
describeArtifact: async (artifact) => {
const response = await openai.chat.completions.create({
model: 'gpt-4-vision-preview',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: 'Describe this chart.' },
{
type: 'image_url',
image_url: {
url: `data:${artifact.type};base64,${artifact.content}`,
},
},
],
},
],
});
return response.choices[0].message.content;
},
});
artifact.alt에는 다음과 같은 내용이 들어 있을 수 있습니다: “0에서 100까지의 지수적 성장을 보여주는 선 차트.”
그런 다음 에이전트는 설명을 기반으로 스스로 교정할 수 있습니다.
파일 시스템 및 영속성
// Preload pandas (optional)
const sandbox = await Sandpy.create({ preload: ['pandas'] });
// Write a CSV file
await sandbox.writeFile('/sandbox/data.csv', csvContent);
// Read it from Python
const result = await sandbox.run(`
import pandas as pd
df = pd.read_csv('/sandbox/data.csv')
print(df.describe())
`);
/sandbox/ 아래의 파일은 Origin‑Private File System (OPFS)와 IndexedDB 폴백을 통해 페이지 새로고침 후에도 유지됩니다.
스냅샷 및 세션 복원
// Build some state
await sandbox.run('x = 42');
await sandbox.run('data = [1, 2, 3]');
// Save snapshot
const snapshot = await sandbox.snapshot();
localStorage.setItem('session', JSON.stringify(snapshot));
// Later (even after a refresh)
const saved = JSON.parse(localStorage.getItem('session'));
await sandbox.restore(saved);
await sandbox.run('print(x)'); // "42"
브라우저 vs. 서버 샌드박스 비교
| Feature | Server Sandbox | Browser Sandbox |
|---|---|---|
| Cost | ~ $0.10 / session | 무료 |
| Latency | 네트워크 왕복 | 즉시 |
| Privacy | 코드가 서버로 전송됨 | 브라우저에 머무름 |
| Offline | 아니오 | 예 |
| Scale | 사용량 기반 요금 | 무제한 |
소비자용 AI 에이전트의 경우, 브라우저 기반 접근 방식이 합리적인 기본값입니다.
데모 및 소스
- 실시간 데모:
- GitHub 저장소:
- npm 패키지:
npm install sandpy
AI 에이전트를 위한 코드 실행이 필요하다면, sandpy를 사용해 보세요. 댓글에 자유롭게 질문을 남겨 주세요.