2025.04.03 - [Data & Research] - [Langchain & Langgraph] Table of Contents
1. Agent의 필요조건
Agent는 단순히 Tool에 바인딩된 대상을 넘어, 자율적인 판단과 계획 능력을 가진 시스템 구성 요소를 의미합니다. Agent라고 불리려면, 다음과 같은 기능(Reasoning and Action; ReAct)적 업그레이드가 필수적입니다.
1) 계획 및 추론 (Planning & Reasoning)
단순히 질문에 대한 지식 기반 답변을 하는 것을 넘어, 문제를 분석하고, 해결을 위한 단계적 계획(Tool Calling)을 세우고, 중간 결과를 평가하고, 필요하면 계획을 수정하는 능력
2. 자율성 (Autonomy)
사용자의 명시적인 지시 없이도, 주어진 Tool들을 활용하여 목표를 달성할 때까지 반복적인 실행 루프(Action/Observation/Reasoning)를 수행
3. 기억/상태 관리 (Memory/State Management)
이전 단계의 실행 결과(Tool의 출력)를 기억하고, 이를 바탕으로 다음 행동을 결정하는 상태(State)를 관리하는 능력
LangGraph에서는 이러한 기능을 구현한 pre-built 모듈 creat_react_agent를 제공합니다.
from langchain.agents import create_react_agent, AgentExecutor
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
# LLM
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# 툴
tools = [get_table_info_tool, run_query_tool]
# 프롬프트
prompt = ChatPromptTemplate.from_messages([
("system", "You are a SQL expert."),
("user", "{question}"),
MessagesPlaceholder("agent_scratchpad"),
])
# Agent 정의 (실행은 아직 안 함)
# create_react_agent가 반환하는 것은 “실행 가능한 agent”가 아님 : invoke로 바로 실행불가
agent = create_react_agent(llm, tools, prompt)
# Executor로 감싸기 (실행 엔진)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# 이제 실행
response = executor.invoke({"question": "최근 3개월 데이터 알려줘"})
print(response)
이 pre-built 템플릿은 말하자면 아래 내용처럼 수동 구현한 것과 비슷한 기능을 하는 겁니다.
https://langchain-ai.github.io/langgraph/how-tos/react-agent-from-scratch/
How to create a ReAct agent from scratch
How to create a ReAct agent from scratch Using the prebuilt ReAct agent create_react_agent is a great way to get started, but sometimes you might want more control and customization. In those cases, you can create a custom ReAct agent. This guide shows how
langchain-ai.github.io
from langgraph.graph import StateGraph, START, END
from langgraph.graph.state import State
from langchain_openai import ChatOpenAI
from langgraph.tools import tool
# -------------------------------
# Tool 정의
# -------------------------------
@tool
def calculator(expression: str) -> str:
"""간단한 수식을 계산합니다."""
try:
return str(eval(expression))
except Exception as e:
return f"Error: {e}"
# -------------------------------
# LLM과 State 정의
# -------------------------------
model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
class ReActState(State):
input: str
reasoning: list[str] = []
observations: list[str] = []
# -------------------------------
# Reason 노드
# -------------------------------
def reason_node(state: ReActState):
context = "\n".join(state.observations)
prompt = f"""
당신은 ReAct 에이전트입니다.
이전 관찰:
{context}
사용자 질문: {state.input}
다음 행동을 Thought, Action 형식으로 제시하세요.
예시:
Thought: (생각)
Action: calculator(2*18)
또는
Final Answer: (최종 답변)
"""
result = model.invoke(prompt)
state.reasoning.append(result.content)
return state
# -------------------------------
# Action 노드
# -------------------------------
def act_node(state: ReActState):
last_thought = state.reasoning[-1]
if "Action:" not in last_thought:
return state
try:
expr = last_thought.split("Action: calculator(")[1].split(")")[0]
result = calculator(expr)
state.observations.append(f"Observation: {result}")
except Exception as e:
state.observations.append(f"Observation: Error parsing action → {e}")
return state
# -------------------------------
# 조건 분기 함수 (loop vs 종료)
# -------------------------------
def should_continue(state: ReActState) -> str:
last_reasoning = state.reasoning[-1]
if "Final Answer" in last_reasoning:
return "end"
return "continue"
# -------------------------------
# 그래프 구성
# -------------------------------
graph = StateGraph(ReActState)
graph.add_node("reason", reason_node)
graph.add_node("act", act_node)
graph.add_edge(START, "reason")
graph.add_edge("act", "reason")
# 핵심: conditional edge
graph.add_conditional_edges(
"reason",
should_continue,
{
"continue": "act",
"end": END
}
)
agent = graph.compile()
# -------------------------------
# 실행
# -------------------------------
result = agent.invoke({"input": "18의 제곱근을 계산해줘"})
print("\n최종 상태:")
print(result)
'Data & Research' 카테고리의 다른 글
| [Deep Learning/Python 일반] Magic Method (0) | 2025.11.03 |
|---|---|
| [LangGraph] LangGraph에서의 Loop (0) | 2025.11.02 |
| [LangGraph] Tool/Tool binding (0) | 2025.11.02 |
| [LangGraph] Reducer (0) | 2025.11.01 |
| [LangGraph] Graph 구성 (0) | 2025.11.01 |