页面简介
Vibe Coding을 처음부터 체계적으로 학습합니다 - AI 프로그래밍을 처음부터 고급까지
正文摘录
AI 에이전트 원리 💡 학습 가이드: 이 장에서는 프로그래밍 기초 지식이 필요하지 않습니다. 인터랙티브 데모를 통해 AI Agent(에이전트)의 작동 원리를 깊이 있게 이해할 수 있습니다. 가장 기본적인 "도구 호출"부터 Agent가 어떻게 계획하고, 기억하고, 협업하는지까지 알아봅니다.🤖 Agent first experience: from “can say” to “can do”See how an Agent automatically calls tools to complete tasks🌤️Weather🧮Calculation📈Stock analysis✈️Travel plan🛒Shopping📊Research report💻Code run📉Data analysis 👤 What is the weather in Beijing today? What should I wear? 🤖 Plain LLMI cannot fetch live weather. Beijing is usually mild in spring, so a light jacket is a reasonable guess. 🦾 Agent▶ Let the Agent run💡 Core difference:The Agent calls a weather API for live data, while the LLM can only infer from training data.0. 서론: "말하는 것"에서 "행동하는 것"으로 여러분은 ChatGPT, Claude와 같은 챗봇을 사용해 보셨을 것입니다. 이들은 매우 강력하지만, 한 가지 분명한 한계가 있습니다:"말"만 할 수 있고 "행동"할 수는 없다사용자: 오늘 베이징 날씨를 알려줘 ChatGPT: 실시간 날씨 정보를 가져올 수 없습니다. 날씨 예보 사이트를 확인해 보세요...ChatGPT는 마치 지식은 풍부하지만 거동이 불편한 현자와 같습니다. 많은 것을 알고 있지만, 실제 작업을 대신 실행해 줄 수는 없습니다.0.1 핵심 과제: AI를"채팅"에서 "행동"으로 전환 접근법 이 목표를 달성하려면 세 가지 핵심 과제를 해결해야 합니다:도구: AI가 어떻게 외부 도구(검색, 계산, 파일 조작)를 호출하게 할 것인가?계획: AI가 어떻게 복잡한 작업을 실행 가능한 단계로 분해할 것인가?기억: AI가 어떻게 컨텍스트를 기억하고 "금붕어 기억력"을 피할 것인가?이 튜토리얼은 처음부터 시작하여 Agent의 구축 과정을 단계별로 분석해 나갑니다.1. 첫 번째 단계: 도구 호출 (Tool Calling) 컴퓨터는 많은 일을 할 수 있습니다: 웹 검색, 코드 실행, 파일 조작, 이메일 발송...하지만 LLM 자체는 이러한 능력이 없습니다. LLM의 핵심 능력은 오직 하나뿐입니다: 텍스트 생성.1.1 왜 LLM은 직접 작업을 실행할 수 없을까 동기 LLM은 순수한 텍스트 처리기입니다:입력: 텍스트 (당신의 질문)처리: 내부 연산, 다음 단어 예측출력: 텍스트 (응답 내용)LLM은 격리된 환경에서 실행되며, 인터넷에 접근할 수도, 코드를 실행할 수도, 로컬 파일을 읽을 수도 없습니다.1.2 해결책: Tool Calling (도구 호출) LLM이 "직접 행동"할 수 있도록, 우리는 Tool Calling 메커니즘을 발명했습니다:핵심 아이디어: LLM이 직접 작업을 실행하는 것이 아니라, "호출 명령"을 생성하고 외부 시스템이 이를 실행합니다.사용자: 오늘 베이징 날씨 어때? LLM 생각: 사용자가 날씨를 물어봤으니 날씨 API를 호출해야겠다 LLM 호출 명령 생성: { "tool": "weather_api", "params": { "city": "베이징", "date": "today" } } 외부 시스템이 도구 실행 → 결과 반환: "맑음, 25°C" LLM 최종 응답 생성: "오늘 베이징 날씨는 맑고 기온은 25도입니다..."🔧 How does an Agent call tools?🌤️Check weather🧮Calculate🔍Search👤"Will I need an umbrella in Shanghai tomorrow?" 1 Analyze need → 2 Choose tool → 3 Build parameters → 4 Execute and return▶ Start demo💡Tool Calling means the LLM generates structured text (JSON), then an external system executes it and returns the result.핵심 포인트: Tool Calling의 본질은 LLM이 구조화된 텍스트를 생성하여 외부 시스템에 무엇을 해야 할지 알려주는 것입니다.2. 핵심 난제:복잡한 작업을 완료 접근법 도구 호출은 LLM에 "행동 능력"을 부여했지만, 현실의 작업은 종종 매우 복잡합니다:사용자: 최근 AI Agent 발전 동향을 조사해서 간략한 보고서를 작성해 줘이 작업은 여러 단계를 포함합니다:최신 정보 검색관련 기사 읽기핵심 정보 추출정리 및 분석보고서 작성2.1 계획 도입 동기 LLM이 "한 번에" 보고서를 생성하도록 하면, 결과는 대개:정보 부족: 훈련 데이터에만 기반하여 최신 정보가 누락됨구조 혼란: 명확한 논리적 프레임워크 부재품질 통제 불가: 중간 단계의 정확성을 검증할 수 없음2.2 해결책: Planning (계획 능력) Agent는 프로젝트 관리자처럼 큰 작업을 먼저 작은 단계로 분해합니다:📋 Agent Planning Ability🌤️Check weatherEasy📊Data analysisMedium🔬Research reportComplex🎯Check today’s weather in Beijing1Call weather API2Format result📝 Execution logClick “Start execution” to see the process▶ Start execution💡Planning means splitting complex tasks into atomic operations, then dynamically adjusting later steps based on previous results계획의 핵심 프로세스:목표 이해: 사용자 요구 분석작업 분해: 복잡한 작업을 원자적 작업으로 분할단계 실행: 하나씩 도구를 호출하여 완료동적 조정: 중간 결과에 따라 후속 계획 조정3. 기억 시스템: 현재 대화 그 이상 인간은 오래전 일을 기억할 수 있지만, LLM의 "기억"은 매우 제한적입니다:컨텍스트 윈도우 제한: 보통 수천에서 수만 자까지세션 격리: 매 대화는 완전히 새로운 시작지속 불가: 페이지를 닫으면 "기억 상실"3.1 기억 도입 동기 다음과 같은 시나리오를 상상해 보세요:사용자: 제 이름은 홍길동입니다 Agent: 안녕하세요 홍길동님, 만나서 반갑습니다! ...(다른 많은 주제를 이야기함)... 사용자: 아까 제 이름이 뭐라고 했죠? Agent: 죄송합니다, 기억나지 않습니다...기억이 없으면 Agent는 개인화된 서비스를 제공할 수 없습니다.3.2 해결책: 3계층 기억 아키텍처 Agent는 일반적으로 세 가지 유형의 기억을 함께 사용합니다:💾 Agent Memory SystemMy name is Zhang SanI like PythonRecommend a programming bookWhat is my name?🔄 Reset💬 ConversationClick a button above to start the conversation⏱️ Short-term memory0Empty📝 Working memory0Empty🗄️ Long-term memory0Empty💡Short-term=current conversation, working=temporary variables, long-term=cross-session knowledge세 가지 기억의 역할 분담:기억 유형역할저장 내용지속성단기 기억현재 대화 컨텍스트전체 대화 기록❌ 세션 종료 시 삭제작업 기억임시 변수와 상태작업 진행률, 사용자 선호도❌ 작업 종료 시 삭제장기 기억크로스 세션 지식사용자 프로필, 히스토리✅ 영구 저장4. Agent의 핵심 루프 이제 세 가지 핵심 능력을 통합하여 Agent의 전체 작업 흐름을 살펴보겠습니다:Try it first: an Agent is not chat, it is an action loopIt repeats: observe → plan → use tools → check results.ResetNext round (1/3)👀Observe🧩Plan🔧Act✅CheckTaskFind 3 beginner articles about “Agent” and output: title + one-sentence summary.What happened in this round?Saw the user goal: 3 beginner articles plus short summaries.Agent run log (example)--- Round 1 --- OBS: Saw the user goal: 3 beginner articles plus short summaries. PLAN: Plan: 1) search keywords 2) open top results 3) extract titles and key points. ACT: Call tool: web_search(query="agent introduction"). CHECK: Check: 3 usable links found, but one-sentence summaries are still missing. 인지-결정-행동-관찰의 루프는 작업이 완료될 때까지 계속됩니다.5. Agent의 능력 등급 모든 Agent가 똑같이 강력한 것은 아닙니다. 능력에 따라 Agent는 여러 등급으로 나눌 수 있습니다:Agent Capability Levels: from chat to collaborationDrag the slider: higher levels feel more like an independent coworker.Current: L2: multiple tools012345What it can doChoose among toolsCombine calls as neededCommon problemsTool choice may be unstablePermissions and safety need controlTypical taskSearch + open web page + summarize각 등급 설명:등급명칭핵심 능력대표적 응용L0도구 없음대화만 가능, 실행 불가챗봇L1단일 도구하나의 고정된 도구 사용코드 인터프리터L2다중 도구여러 도구 선택 가능Web AgentL3다단계복잡한 작업 계획 가능데이터 분석 AgentL4자율 반복능동적 성찰과 개선연구 AgentL5다중 Agent 협업여러 Agent 협력엔터프라이즈 시스템6. Agent의 핵심 아키텍처 전형적인 Agent는 다음 모듈로 구성됩니다:What modules make up an Agent?Click a module to see what it is responsible for.🧠LLM (brain)🔧Tools (hands)💾Memory🧩Planning🛡️GuardrailsUser goal → plan → tool call → result → re-plan…(Memory runs through the whole process)🧠 LLM (brain)Understands goals, generates plans, chooses actions, and writes final responses.Typical inputUser goal + current state + available tool listTypical outputNext-step plan / tool call arguments / final answer각 모듈 상세 설명:1. LLM (두뇌) 목표 이해, 계획 생성, 동작 선택, 언어 출력 구성 담당.입력: 사용자 목표 + 현재 상태 + 사용 가능한 도구 목록출력: 다음 단계 계획 / 도구 호출 매개변수 / 최종 응답2. Tools (손과 발) 실제로 "일을 하는" 부분: 검색, 파일 읽기/쓰기, API 호출, 명령 실행.입력: tool_name + input_schema 매개변수출력: 도구 실행 결과 (텍스트/데이터/파일 변경)3. Memory (기억) "이미 무엇을 했고, 어떤 결과를 얻었는지"를 저장하여 중복과 이탈을 방지.입력: 대화 기록 / 도구 결과 / 현재 작업 상태출력: 검색 가능한 컨텍스트 (단기/장기/작업 기억)4. Planning (계획) 큰 목표를 작은 단계로 나누고, 실패 시 계획을 변경.입력: 목표 + 제약 (예산/시간/보안) + 현재 진행 상황출력: 단계 목록 / 다음 동작 / 중지 조건5. Guardrails (가드레일) 위험 제한: 권한 화이트리스트, 예산 상한, 민감한 작업 확인, 샌드박스 실행.7. 주요 프레임워크 비교 현재 주류 Agent 개발 프레임워크로는 LangChain, LlamaIndex, CrewAI, AutoGen, 그리고 Anthropic이 공식 출시한 Claude Agent SDK 등이 있습니다. 각각 고유한 특징을 가지고 있으며 다양한 시나리오에 적합합니다.Mainstream framework comparison: start with fitChoose your priority first, then read the recommendation.Quick startControl/debuggingMulti-Agent collaborationFrameworkLearningControlMulti-AgentBest forLangChain / LangGraphMediumHighMediumControllable tool calls, workflows, and enterprise integrationAutoGenMediumMediumHighMulti-agent conversation, programming, and analysis assistantsCrewAILowMediumHighTeam tasks with clear role divisionRecommended now: LangChain / LangGraphRepresenting flows as graphs or steps makes debugging, launch, and maintenance easier.7.1 핵심 차이: 공식 네이티브 vs 서드파티 래퍼 비교 항목Claude Agent SDKLangChain / LlamaIndex / CrewAI 등개발 주체Anthropic 공식서드파티 오픈소스 커뮤니티모델 최적화Claude에 딥 최적화다중 모델 범용, 자체 튜닝 필요내장 도구파일 읽기/쓰기, Bash, 검색 등 즉시 사용 가능자체 통합 또는 구성 필요Agent Loop내장, 구현 불필요직접 조립하거나 프레임워크 추상화에 의존코드 생성 품질코드 시나리오 특화 최적화범용 설계, 코드 능력은 모델 자체에 의존학습 곡선낮음, API 간결중간~높음, 개념이 많고 추상화 계층이 복잡7.2 Claude Agent SDK vs LangChain LangChain은 가장 인기 있는 Agent 프레임워크 중 하나로, 풍부한 컴포넌트와 체인 호출 능력을 제공합니다:python# LangChain: 여러 컴포넌트를 조립해야 함 from langchain.agents import AgentExecutor, create_react_agent from langchain.tools import tool from langchain import hub @tool def read_file(path: str) -> str: """파일 내용 읽기""" with open(path) as f: return f.read() # 프롬프트 정의, Agent 조립, 도구 루프 처리를 직접 해야 함 prompt = hub.pull("hwchase17/react") agent = create_react_agent(llm, [read_file], prompt) agent_executor = AgentExecutor(agent=agent, tools=[read_file]) result = agent_executor.invoke({"input": "auth.py의 버그 수정"})python# Claude Agent SDK: 한 줄로 해결, 도구 내장 from claude_agent_sdk import query, ClaudeAgentOptions async for message in query( prompt="auth.py의 버그 수정", options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]), ): print(message)핵심 차이:LangChain은 도구 상자로, 직접 컴포넌트를 선택하고 프로세스를 조립해야 함Agent SDK는 완제품으로, 코드 시나리오에 맞게 이미 튜닝되어 바로 사용 가능7.3 Claude Agent SDK vs CrewAI CrewAI는 다중 Agent 협업에 초점을 맞추고, 역할극과 작업 할당을 강조합니다:python# CrewAI: 여러 역할의 협업 정의 from crewai import Agent, Task, Crew coder = Agent(role="프로그래머", goal="코드 작성", backstory="...") reviewer = Agent(role="리뷰어", goal="코드 검토", backstory="...") task = Task(description="기능 개발", agent=coder) crew = Crew(agents=[coder, reviewer], tasks=[task]) result = crew.kickoff()핵심 차이:CrewAI는 역할극과 협업 프로세스 설계에 강하며, 팀 워크플로우 시뮬레이션에 적합Agent SDK는 코드 실행과 도구 호출에 집중하며, 실제 개발 작업에 적합7.4 Claude Agent SDK vs LlamaIndex LlamaIndex의 핵심은 RAG(검색 증강 생성)로, LLM과 외부 데이터를 연결하는 데 중점을 둡니다:python# LlamaIndex: 지식 베이스 쿼리 구축 from llama_index import VectorStoreIndex, SimpleDirectoryReader documents = SimpleDirectoryReader("data").load_data() index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine() response = query_engine.query("이 문서를 요약해 줘")핵심 차이:LlamaIndex는 데이터 커넥터로, "어떻게 LLM이 내 데이터에 접근하게 할 것인가"를 해결Agent SDK는 작업 실행기로, "어떻게 LLM이 복잡한 개발 작업을 완료하게 할 것인가"를 해결7.5 종합 비교표 특성Claude Agent SDKLangChainCrewAILlamaIndexAutoGen개발 주체Anthropic 공식서드파티서드파티서드파티Microsoft핵심 포지셔닝코드 개발 Agent범용 LLM 프레임워크역할 중심 팀데이터 검색 증강다중 Agent 협업학습 곡선완만중간완만중간가파름내장 도구✅ 풍부 (파일, Bash, 검색)구성 필요구성 필요구성 필요✅ 코드 실행다중 Agent✅ 지원LangGraph 통해✅ 네이티브❌✅ 네이티브코드 시나리오✅ 딥 최적화보통보통해당 없음✅ 프로그래밍 지원모델 종속Claude 전용다중 모델다중 모델다중 모델다중 모델적용 시나리오자동화 개발, CI/CD엔터프라이즈 맞춤화콘텐츠 제작/연구지식 베이스 Q&A프로그래밍/데이터 분석7.6 프레임워크 선택 가이드 요구 사항이...추천 프레임워크코드 개발, 자동화 수정, CI/CD 통합Claude Agent SDK고도로 맞춤화된 프로세스, 다중 모델 지원LangChain다중 Agent 역할극, 팀 협업 시뮬레이션CrewAI엔터프라이즈 지식 베이스 구축, 문서 Q&ALlamaIndex프로그래밍 작업, 데이터 분석, 다중 Agent 협업AutoGen연구 프로젝트, 완전 자율 AI 탐색AutoGPT8. 실전: 첫 번째 Agent 구축하기 Python으로 간단한 Agent를 만들어 봅시다:8.1 기본 버전: 단일 도구 Agent pythonimport json class SimpleAg