root layout

패스트캠퍼스

  1. 강의 질문
  2. AI TECH

langgraph ch2 memory에서 코드 질문

2025.09.03 15:27 작성

from typing import Annotated

from typing_extensions import TypedDict

from langchain_openai import ChatOpenAI

from langchain_teddynote.tools.tavily import TavilySearch

from langgraph.graph import StateGraph, START, END

from langgraph.graph.message import add_messages

from langgraph.prebuilt import ToolNode, tools_condition




########## 1. 상태 정의 ##########

# 상태 정의

class State(TypedDict):

    # 메시지 목록 주석 추가

    messages: Annotated[list, add_messages]




########## 2. 도구 정의 및 바인딩 ##########

# 도구 초기화

tool = TavilySearch(max_results=3)

tools = [tool]



from langchain_ollama import ChatOllama



# LLM 정의

llm = ChatOllama(model="qwen3")



# 도구와 LLM 결합

llm_with_tools = llm.bind_tools(tools)




########## 3. 노드 추가 ##########

# 챗봇 함수 정의

def chatbot(state: State):

    # 메시지 호출 및 반환

    return {"messages": [llm_with_tools.invoke(state["messages"])]}




# 상태 그래프 생성

graph_builder = StateGraph(State)



# 챗봇 노드 추가

graph_builder.add_node("chatbot", chatbot)



# 도구 노드 생성 및 추가

tool_node = ToolNode(tools=[tool])



# 도구 노드 추가

graph_builder.add_node("tools", tool_node)



# 조건부 엣지

graph_builder.add_conditional_edges(

    "chatbot",

    tools_condition,

)



########## 4. 엣지 추가 ##########



# tools > chatbot

graph_builder.add_edge("tools", "chatbot")



# START > chatbot

graph_builder.add_edge(START, "chatbot")



# chatbot > END

graph_builder.add_edge("chatbot", END)

해당 코드에서 llm에 tool을 bind를 하고 또 tool node를 별도로 만드는 이유는 뭔가요??


답변 

연관 질문

커뮤니티 질문보기