LangGraph는 상태 저장 LLM 애플리케이션을 빌드하기 위한 프레임워크이므로 ReAct (추론 및 행동) 에이전트를 구성하는 데 적합합니다.
ReAct 에이전트는 LLM 추론과 작업 실행을 결합합니다. 사용자 목표를 달성하기 위해 반복적으로 생각하고 도구를 사용하며 관찰에 따라 행동하여 접근 방식을 동적으로 조정합니다. '"ReAct: Synergizing Reasoning and Acting in Language Models"'(2023)에서 소개된 이 패턴은 엄격한 워크플로를 통해 인간과 유사한 유연한 문제 해결을 반영하려고 합니다.
LangGraph는 ReAct 구현에 더 많은 제어 및 맞춤설정이 필요한 경우에 유용한 사전 빌드된 ReAct 에이전트 (
create_react_agent)를 제공합니다. 이 가이드에서는 간소화된 버전을 보여줍니다.
LangGraph는 세 가지 주요 구성요소를 사용하여 에이전트를 그래프로 모델링합니다.
State: 애플리케이션의 현재 스냅샷을 나타내는 공유 데이터 구조 (일반적으로TypedDict또는Pydantic BaseModel).Nodes: 에이전트의 로직을 인코딩합니다. 현재 상태를 입력으로 받고 일부 계산 또는 부작용을 실행하며 LLM 호출 또는 도구 호출과 같은 업데이트된 상태를 반환합니다.Edges: 현재State를 기반으로 실행할 다음Node를 정의하여 조건부 로직 및 고정 전환을 허용합니다.
아직 API 키가 없는 경우 Google AI Studio에서 API 키를 가져올 수 있습니다.
pip install langgraph langchain-google-genai geopy requests
환경 변수 GEMINI_API_KEY에서 API 키를 설정합니다.
import os
# Read your API key from the environment variable or set it manually
api_key = os.getenv("GEMINI_API_KEY")
LangGraph를 사용하여 ReAct 에이전트를 구현하는 방법을 더 잘 이해할 수 있도록 이 가이드에서는 실제 예시를 안내합니다. 목표가 도구를 사용하여 지정된 위치의 현재 날씨를 찾는 에이전트를 만듭니다.
이 날씨 에이전트의 경우 State는 진행 중인 대화 기록(메시지 목록)과 수행된 단계 수의 카운터(정수)를 유지합니다(설명을 위해).
LangGraph는 상태 메시지 목록을 업데이트하기 위한 도우미 함수 add_messages를 제공합니다. 현재 목록과 새 메시지를 가져와 결합된 목록을 반환하는 리듀서 역할을 합니다. 메시지 ID별로 업데이트를 처리하고 기본적으로 새 메시지에는 '추가 전용' 동작을 사용합니다.
from typing import Annotated,Sequence, TypedDict
from langchain_core.messages import BaseMessage
from langgraph.graph.message import add_messages # helper function to add messages to the state
class AgentState(TypedDict):
"""The state of the agent."""
messages: Annotated[Sequence[BaseMessage], add_messages]
number_of_steps: int
다음으로 날씨 도구를 정의합니다.
from langchain_core.tools import tool
from geopy.geocoders import Nominatim
from pydantic import BaseModel, Field
import requests
geolocator = Nominatim(user_agent="weather-app")
class SearchInput(BaseModel):
location:str = Field(description="The city and state, e.g., San Francisco")
date:str = Field(description="the forecasting date for when to get the weather format (yyyy-mm-dd)")
@tool("get_weather_forecast", args_schema=SearchInput, return_direct=True)
def get_weather_forecast(location: str, date: str):
"""Retrieves the weather using Open-Meteo API.
Takes a given location (city) and a date (yyyy-mm-dd).
Returns:
A dict with the time and temperature for each hour.
"""
# Note that Colab may experience rate limiting on this service. If this
# happens, use a machine to which you have exclusive access.
location = geolocator.geocode(location)
if location:
try:
response = requests.get(f"https://api.open-meteo.com/v1/forecast?latitude={location.latitude}&longitude={location.longitude}&hourly=temperature_2m&start_date={date}&end_date={date}")
data = response.json()
return dict(zip(data["hourly"]["time"], data["hourly"]["temperature_2m"]))
except Exception as e:
return {"error": str(e)}
else:
return {"error": "Location not found"}
tools = [get_weather_forecast]
이제 모델을 초기화하고 도구를 모델에 바인딩합니다.
from datetime import datetime
from langchain_google_genai import ChatGoogleGenerativeAI
# Create LLM class
llm = ChatGoogleGenerativeAI(
model=