LangChain · LangGraph 맛보기 (60분)
LangChain 과 LangGraph 는 무엇을 대신해 주나
에이전트 프레임워크를 오래 다루지는 않습니다. 오늘 예제는 프레임워크 없이 SDK 로 만들지만, 실무 코드에서 자주 보게 되므로 무엇을 대신해 주는지만 손으로 확인합니다.
| LangChain | LangGraph | |
|---|---|---|
| 한 줄 요약 | 모델·프롬프트·도구를 같은 모양으로 다루게 해 주는 부품 상자 | 에이전트 실행 흐름을 그래프(State·Node·Edge)로 그리는 실행기 |
| 핵심 개념 | @tool, 메시지, bind_tools, 구조화 출력 | StateGraph, 노드, 엣지, 조건부 엣지, 체크포인터, interrupt |
| 오늘 볼 것 | 함수가 LLM 에게 어떤 스키마로 보이는지 | 검증 실패 시 다시 쓰는 루프, 사람 승인으로 멈췄다가 이어 가기 |
시작 전 설치. 위의 taste.zip 을 받아(다운로드 폴더에 있다고 가정) agent-8h 폴더에 풀면 agent-8h/taste/ 가 생깁니다. 그 폴더에 가상환경을 만들고 라이브러리를 설치한 뒤, 그 폴더에서 Claude Code 를 엽니다.
mkdir C:\agent-8h -Force
Expand-Archive $HOME\Downloads\taste.zip -DestinationPath C:\agent-8h -Force
cd C:\agent-8h\taste
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install langchain-core langgraph claude-agent-sdk
claude --version
claude
mkdir -p ~/agent-8h
unzip -o ~/Downloads/taste.zip -d ~/agent-8h
cd ~/agent-8h/taste
python3 -m venv .venv
source .venv/bin/activate
pip install langchain-core langgraph claude-agent-sdk
claude --version
claude
claude --version 이 안 되면 Claude Code 부터 설치·로그인합니다. PowerShell 에서 Activate.ps1 이 막히면 Set-ExecutionPolicy -Scope CurrentUser RemoteSigned 를 한 번 실행합니다. 마지막 claude 는 이 폴더에서 Claude Code 를 여는 명령입니다. 만든 코드는 이 가상환경의 Python 으로 실행합니다 (PyCharm·VS Code 라면 인터프리터를 .venv 로 지정).맛보기 1 · LangChain Tool — 함수가 LLM 에게 어떻게 보이나 (10분)
에이전트의 도구는 결국 이름 + 설명 + 인자 스키마를 가진 함수입니다. LLM 은 코드를 보지 못하고 이 세 가지만 보고 도구를 고릅니다. 그래서 docstring 과 타입 힌트가 곧 프롬프트입니다.
"""맛보기 1 · LangChain 도구(Tool) — 함수가 LLM 에게 어떻게 보이는가."""
from langchain_core.tools import tool
from langchain_core.utils.function_calling import convert_to_openai_tool
SALES = {"2026-01": 1_000_000, "2026-02": 700_000, "2026-03": 820_000}
@tool
def monthly_sales(month: str) -> int:
"""월(YYYY-MM)을 받아 그 달 매출 합계를 돌려준다."""
if month not in SALES:
raise ValueError(f"{month} 데이터가 없습니다")
return SALES[month]
print("이름:", monthly_sales.name)
print("설명:", monthly_sales.description)
print("인자:", monthly_sales.args)
print("LLM 에 전달되는 스키마:", convert_to_openai_tool(monthly_sales)["function"]["parameters"])
print("직접 실행:", monthly_sales.invoke({"month": "2026-02"}))
이름: monthly_sales
설명: 월(YYYY-MM)을 받아 그 달 매출 합계를 돌려준다.
인자: {'month': {'title': 'Month', 'type': 'string'}}
LLM 에 전달되는 스키마: {'properties': {'month': {'type': 'string'}}, 'required': ['month'], 'type': 'object'}
직접 실행: 700000
- docstring 을 지우고 다시 실행해 본다 → 설명이 비면 LLM 이 언제 이 도구를 써야 할지 모른다.
monthly_sales.invoke({"month": "2026-09"})→ 오류. 에이전트에서는 이 오류가 관찰로 LLM 에게 돌아간다 (예제 1 3단계).
맛보기 2 · LangGraph — State·Node·Edge 와 검증 재시도 (20분)
State 는 노드들이 함께 보는 딕셔너리, Node 는 State 를 받아 바꿀 부분만 돌려주는 함수, Edge 는 다음에 갈 노드입니다. 조건부 엣지로 "검증 실패면 다시 쓰기, 단 최대 2번" 같은 루프를 그립니다. 예제 1 의 자기 검증을 그래프로 그린 것과 같습니다.
"""맛보기 2 · LangGraph — State, Node, Edge, 조건부 분기(재시도)."""
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
ROWS = [("2026-01", "노트북", 1_000_000), ("2026-02", "노트북", 700_000),
("2026-01", "웹캠", 550_000), ("2026-02", "웹캠", 510_000)]
class State(TypedDict, total=False):
rows: list
change: dict
report: str
ok: bool
retry: int
def load(state: State) -> State:
return {"rows": ROWS, "retry": 0}
def statistics(state: State) -> State:
by = {}
for month, product, revenue in state["rows"]:
by.setdefault(product, {})[month] = revenue
change = {p: round((m["2026-02"] - m["2026-01"]) / m["2026-01"] * 100, 1) for p, m in by.items()}
return {"change": change}
def write_report(state: State) -> State:
# 일부러 첫 번째 시도에서는 틀린 숫자를 쓴다 (LLM 이 숫자를 잘못 옮긴 상황 흉내)
wrong = state["retry"] == 0
lines = [f"- {p}: {v - 5 if wrong else v}%" for p, v in state["change"].items()]
return {"report": "\n".join(lines)}
def validate(state: State) -> State:
ok = all(f"{p}: {v}%" in state["report"] for p, v in state["change"].items())
return {"ok": ok, "retry": state["retry"] + (0 if ok else 1)}
def route(state: State) -> str:
if state["ok"]:
return "done"
return "retry" if state["retry"] <= 2 else "done"
g = StateGraph(State)
g.add_node("load", load)
g.add_node("statistics", statistics)
g.add_node("write_report", write_report)
g.add_node("validate", validate)
g.add_edge(START, "load")
g.add_edge("load", "statistics")
g.add_edge("statistics", "write_report")
g.add_edge("write_report", "validate")
g.add_conditional_edges("validate", route, {"retry": "write_report", "done": END})
app = g.compile()
for update in app.stream({}, stream_mode="updates"):
print(update)
print(app.get_graph().draw_mermaid())
{'load': {'rows': [...], 'retry': 0}}
{'statistics': {'change': {'노트북': -30.0, '웹캠': -7.3}}}
{'write_report': {'report': '- 노트북: -35.0%\n- 웹캠: -12.3%'}} ← 일부러 틀린 숫자
{'validate': {'ok': False, 'retry': 1}} ← 검증 실패
{'write_report': {'report': '- 노트북: -30.0%\n- 웹캠: -7.3%'}} ← 다시 쓰기
{'validate': {'ok': True, 'retry': 1}}
(아래로 mermaid 그래프 텍스트: validate -. retry .-> write_report, validate -. done .-> __end__)
stream_mode="updates"는 노드가 끝날 때마다 그 노드가 바꾼 값만 보여 준다. 대시보드의 노드 상태 표시가 이것으로 만들어진다.route의retry <= 2를 지우면 어떻게 되나? → 검증이 계속 실패하면 끝나지 않는다. 루프에는 상한이 필요하다.- 출력 끝의 mermaid 텍스트를 mermaid.live 에 붙여 그래프 그림을 본다.
맛보기 3 · 노드에서 Claude 부르기 + 사람 승인 interrupt (20분)
그래프의 노드 하나가 LLM 을 부릅니다. 여기서는 Claude Agent SDK 의 query() 로 부르므로 API 키가 필요 없습니다. 마지막 노드는 interrupt() 로 실행을 멈추고 사람의 답을 기다렸다가, 같은 thread_id 로 이어서 실행합니다.
"""맛보기 3 · LangGraph 노드 안에서 LLM 부르기 + 사람 승인(interrupt).
LLM 은 API 키 대신 이 PC 에 로그인된 Claude 구독을 쓰는 Claude Agent SDK 로 부른다.
"""
import asyncio
from typing import TypedDict
from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, TextBlock, query
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt
async def ask_claude(prompt: str) -> str:
options = ClaudeAgentOptions(tools=[], max_turns=1, setting_sources=[], strict_mcp_config=True,
env={"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1"},
system_prompt="너는 매출 보고서를 쓰는 분석가다. 주어진 숫자만 쓴다.")
parts = []
async for msg in query(prompt=prompt, options=options):
if isinstance(msg, AssistantMessage):
parts += [b.text for b in msg.content if isinstance(b, TextBlock)]
return "".join(parts).strip()
class State(TypedDict, total=False):
change: dict
summary: str
approved: bool
def statistics(state: State) -> State:
return {"change": {"노트북": -30.0, "웹캠": -7.3}}
def summarize(state: State) -> State:
text = asyncio.run(ask_claude(f"전월 대비 변동률: {state['change']}. 20% 이상 하락 품목을 한 문장으로 요약해."))
return {"summary": text}
def approval(state: State) -> State:
answer = interrupt({"질문": "이 요약을 저장할까요?", "요약": state["summary"]})
return {"approved": answer == "y"}
g = StateGraph(State)
g.add_node("statistics", statistics)
g.add_node("summarize", summarize)
g.add_node("approval", approval)
g.add_edge(START, "statistics")
g.add_edge("statistics", "summarize")
g.add_edge("summarize", "approval")
g.add_edge("approval", END)
app = g.compile(checkpointer=InMemorySaver()) # interrupt 를 쓰려면 체크포인터가 필요하다
config = {"configurable": {"thread_id": "run-001"}}
for update in app.stream({}, config, stream_mode="updates"):
print(update)
answer = input("승인하려면 y: ").strip()
for update in app.stream(Command(resume=answer), config, stream_mode="updates"):
print(update)
print("최종 상태:", app.get_state(config).values)
{'statistics': {'change': {'노트북': -30.0, '웹캠': -7.3}}}
{'summarize': {'summary': '전월 대비 20% 이상 하락한 품목은 노트북 하나이며, 감소율은 -30.0%입니다.'}}
{'__interrupt__': (Interrupt(value={'질문': '이 요약을 저장할까요?', ...}),)}
승인하려면 y: y
{'approval': {'approved': True}}
최종 상태: {'change': {...}, 'summary': '...', 'approved': True}
tools=[]: Claude Code 의 내장 도구(파일 읽기·명령 실행)를 끄고 글만 쓰게 한다.max_turns=1: 한 번만 답한다.setting_sources=[],strict_mcp_config=True: 내 PC 의 Claude Code 설정과 계정에 연결된 커넥터(Gmail·Drive 등)를 불러오지 않는다. 예제에서도 항상 넣는다.- 체크포인터(
InMemorySaver)와thread_id가 있어야 멈춘 지점부터 이어 갈 수 있다. 이것이 LangGraph 의 기억(State 저장)이다. - y 대신 n 을 넣어 본다 →
approved: False. 승인 전에는 저장·발송 같은 실행을 하지 않는 것이 원칙이다.
LangChain 자체(체인·프롬프트·출력 파서·메모리·RAG)를 더 보고 싶으면 마지막 부록 · LangChain 핵심 축약 에서 같은 방식(API 키 없이 Claude 구독)으로 짧게 따라 할 수 있습니다.