Python 60줄로 첫 AI 에이전트 만들기 — 프레임워크 없이
발행: (2026년 4월 25일 AM 10:44 GMT+9)
5 분 소요
원문: Dev.to
Source: Dev.to
우리가 만들고 있는 것
간단한 AI 에이전트로 다음을 할 수 있습니다:
- 목표를 입력으로 받는다
- 목표를 하위 작업으로 나눈다
- 각 하위 작업을 도구를 사용해 실행한다
- 최종 결과를 반환한다
이를 최소 실행 가능한 에이전트, 즉 어떤 것으로든 확장할 수 있는 골격이라고 생각하세요.
아키텍처
우리 에이전트는 고전적인 Observe → Think → Act 루프를 따릅니다:
┌─────────────┐
│ USER GOAL │
└──────┬──────┘
│
▼
┌──────────────┐
│ THINK (LLM) │◄──────┐
└──────┬───────┘ │
│ │
▼ │
┌──────────────┐ │
│ ACT (Tool) │───────┘
└──────┬───────┘
│
▼
┌──────────────┐
│ RESULT │
└──────────────┘
코드 (60줄)
import json
import os
from anthropic import Anthropic
client = Anthropic()
# Define tools the agent can use
tools = [
{
"name": "calculator",
"description": "Performs arithmetic calculations",
"input_schema": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Math expression to evaluate"}
},
"required": ["expression"]
}
},
{
"name": "search_notes",
"description": "Search through local notes/files",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"}
},
"required": ["query"]
}
}
]
def execute_tool(name, input_data):
if name == "calculator":
try:
return str(eval(input_data["expression"]))
except:
return "Error: Invalid expression"
elif name == "search_notes":
# Simulate search — replace with real implementation
return f"Found 3 notes matching '{input_data['query']}'"
return "Unknown tool"
def run_agent(goal, max_steps=5):
messages = [{"role": "user", "content": goal}]
system = "You are an AI agent. Use the provided tools to accomplish the user's goal. When done, provide a final answer."
for step in range(max_steps):
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system=system,
tools=tools,
messages=messages
)
# Check if agent wants to use a tool
if response.stop_reason == "tool_use":
tool_block = next(b for b in response.content if b.type == "tool_use")
result = execute_tool(tool_block.name, tool_block.input)
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_block.id,
"content": result
}]
})
print(f"Step {step+1}: Used {tool_block.name} → {result}")
else:
# Agent is done
final = next(b.text for b in response.content if hasattr(b, "text"))
print(f"\nAgent Result: {final}")
return final
return "Max steps reached"
# Run it
run_agent("What is 15% of 847, then round to nearest integer?")
How It Works
- Lines 1‑4: 종속성(Anthropic SDK)을 가져옵니다.
- Lines 6‑30: 도구를 JSON 스키마로 정의합니다. Claude는 이를 네이티브로 이해하므로 래퍼가 필요 없습니다.
- Lines 32‑40: 간단한
if/elif논리로 도구를 실행합니다. 필요에 따라 실제 구현으로 교체하세요. - Lines 42‑65: 핵심 에이전트 루프: 메시지를 전송하고, 도구 사용을 감지하고, 도구를 실행한 뒤 결과를 다시 입력하고, LLM이 최종 답변을 반환할 때까지 반복합니다.
왜 이것이 중요한가
모든 “에이전트 프레임워크”는 본질적으로 이 정확한 루프를 추상화로 감쌉니다. 원시 패턴을 이해한다는 것은 다음을 의미합니다:
- 디버깅이 빨라집니다 – 풀어야 할 프레임워크 마법이 없습니다.
- 확장이 쉬워집니다 –
elif블록을 추가하여 도구를 추가합니다. - 코드를 직접 소유합니다 – 의존성 업데이트가 에이전트를 깨뜨리지 않습니다.
다음에 만들 것
이 60줄 스켈레톤을 기반으로 다음을 만들 수 있습니다:
- 개인 비서 – 캘린더, 이메일, 파일 도구를 추가합니다.
- 코드 리뷰어 – git diff와 린트 도구를 추가합니다.
- 콘텐츠 파이프라인 – 퍼블리싱 API를 도구로 추가합니다.
- 데이터 분석가 – SQL 및 차트 도구를 추가합니다.
요점
AI 에이전트를 만들기 위해 프레임워크가 필요하지 않습니다. 필요한 것은:
- 도구 사용을 지원하는 LLM (Claude, GPT‑4 등)
- 도구 결과를 모델에 다시 전달하는 루프
- JSON 스키마로 정의된 도구
그게 전부입니다. 60줄. 마법은 없습니다.