간단한 그래프
그래프 실행
- 입력 : State 딕셔너리 형식. 특정 키만 입력
- 출력 : STate 딕셔너리 형식
State 다루기
State 정의
- State는 Agent의 각 단계에서 주고 받는 정보
- State의 구조를 설계하고 정보를 기록하는 일은 매우 중요합니다
class State(TypedDict):
text: str
user_id: str
step: int
history: list[str]
Node 정의
- text에 값 붙이기
- step에 값 증가
- history 리스트에 값 추가
def node_1(state: State):
print("node_1 실행 전 상태:", state)
state["text"] += " → node_1 처리 완료"
state["step"] += 1
state["history"].append(f"node_1 완료 (step {state['step']})")
print("node_1 실행 후 상태:", state)
return state
def node_2(state: State):
print("node_2 실행 전 상태:", state)
state["text"] += " → node_2 처리 완료"
state["step"] += 1
state["history"].append(f"node_2 완료 (step {state['step']})")
print("node_2 실행 후 상태:", state)
return state
그래프 실행
# 실행
initial_state = {
"text": "처음 요청 도착",
"user_id": "user_1234",
"step": 0,
"history": [] }
result = graph.invoke(initial_state)
print("\\n 최종 결과 상태:", result)
주의
- State의 key 이름과 node 이름은 겹치면 안 됨
Graph Routing
State 정의
- 그래프 구성
- 홀수, 짝수를 체크해서 분기(conditional_edge)
- 홀수일 때 노드, 짝수일 때 노드를 각각 실행 후 종료
class State(TypedDict):
number: int
result: str
Node 정의
# 노드: 짝/홀수 판별
def check_parity(state: State):
print(f"check_parity: 입력된 숫자 = {state['number']}")
returnstate # 입력만 받고, 분기는 conditional_edge에서 처리
# 짝수 노드
def even_node(state: State):
print("짝수입니다!")
state["result"] = "짝수입니다!"
returnstate
# 홀수 노드
def odd_node(state: State):
print("홀수입니다!")
state["result"] = "홀
그래프 정의
# 그래프 생성
builder = StateGraph(State)
# 노드 등록
builder.add_node("check_parity", check_parity)
builder.add_node("even_node", even_node)
uilder.add_node("odd_node", odd_node)
# 조건 분기 연결
def parity_condition(state: State):
return "even" if state["number"] % 2 == 0 else "odd"
builder.add_conditional_edges("check_parity", parity_condition, {"even": "even_node", "odd": "odd_node"})
# 나머지 연결
builder.add_edge(START, "check_parity")
builder.add_edge("even_node", END)
builder.add_edge("odd_node", END)
# 그래프 컴파일
graph = builder.compile()
Router
- 입력을 받아 조건에 따라 분기 하는 노드
# 노드: 짝/홀수 판별
def check_parity(state: State):
print(f”check_parity: 입력된 숫자 = {state[‘number’]}”)
return state # 입력만 받고, 분기는 conditional_edge에서 처리
# 조건 분기 연결
def parity_condition(state: State):
return"even" ifstate["number"] % 2== 0else"odd"
builder.add_conditional_edges("check_parity", parity_condition, {"even": "even_node", "odd": "odd_node"})
- 라우터 노드(check_parity)는 입력 받아 그대로 pass
- 실제 분기는 분기 함수(parity_condition)에서 처리
그래프 실행
- 입력 : State 딕셔너리 형식
- 출력 : State 딕셔너리 형식
state = {"number": 7, "result": ""}
result = graph.invoke(state)
print("최종 결과:", result)
Graph Reflection
State 정의
- 그래프 구성
- 입력 문장을 요약하고(summarize)
- 만족해? 아니면 다시 생각해봐(요약을 2번 반복)
- 만족하면 END
class State(TypedDict):
input: str
summary: str
is_satisfied: bool
log: list[str]
Node 정의
- Node : 두 개의 노드 필요
# 요약 노드: 간단히 결과 요약 + 만족 여부 결정
def summary_node(state: State):
state["summary"] += " → 요약됨"
state["log"].append("요약 수행")
# 만족 여부 판단 (2회 이상 요약되면 만족했다고 가정)
if state["summary"].count("요약됨") >= 2:
state["is_satisfied"] = True
else:
state["is_satisfied"] = False
print(state)
return state
# 반추 노드: 추가 아이디어 도출 시도 (다시 생각해보기)
def reflect_node(state: State):
state["log"].append("반추 수행")
state["summary"] += " → 다시 생각해봄"
print(state)
그래프 구조
# 그래프 구성
builder = StateGraph(State)
builder.add_node("summarize", summary_node)
builder.add_node("reflect", reflect_node)
# 흐름 정의
builder.add_edge(START, "summarize")
# 조건 분기: 만족 여부에 따라 흐름 결정
def check_satisfaction(state: State):
return "satisfied" if state["is_satisfied"] else "retry"
builder.add_conditional_edges("summarize", check_satisfaction, {"satisfied": END, "retry": "reflect"})
# 반추 후 → 요약 다시 시도 (루프)
builder.add_edge("reflect", "summarize")
# 컴파일
graph = builder.compile()
그래프 실행
- 입력 : State 딕셔너리 형식
- 출력 : State 딕셔너리 형식
# 실행
input = {"input": "오늘 하루 요약해줘", "summary": "", "is_satisfied": False, "log": [] }
result = graph.invoke(input)
print("최종 상태:")
print(result)
AI_Agent/AI_Agent_Basic/07_LangGraph기반_Agent기초2_도구_실습.ipynb at main · 427paul/AI_Agent
Contribute to 427paul/AI_Agent development by creating an account on GitHub.
github.com
'AI Agent > AI Agent의 이해' 카테고리의 다른 글
| 8. LangGraph 기초3 메모리 (0) | 2026.06.02 |
|---|---|
| 7. LangGraph 기초2 도구 (0) | 2026.05.31 |
| 5. LangGraph 기초1 기본 그래프 (0) | 2026.05.29 |
| 4. Memory (1) | 2026.05.28 |
| 3. RAG 개념 이해 (0) | 2026.05.27 |