Gemini 2.5 और LangGraph की मदद से, ReAct एजेंट को फिर से बनाना

LangGraph, स्टेटफ़ुल एलएलएम ऐप्लिकेशन बनाने के लिए एक फ़्रेमवर्क है. इसकी मदद से, ReAct (Reasoning and Acting) एजेंट बनाए जा सकते हैं.

ReAct एजेंट, एलएलएम के तर्क को कार्रवाई को लागू करने के साथ जोड़ते हैं. वे उपयोगकर्ता के लक्ष्यों को हासिल करने के लिए, बार-बार सोचते हैं, टूल का इस्तेमाल करते हैं, और अपने तरीके को डाइनैमिक तौर पर अडजस्ट करते हैं. "ReAct: Synergizing Reasoning and Acting in Language Models" (2023) में पेश किए गए इस पैटर्न का मकसद, सख्त वर्कफ़्लो के बजाय, समस्याओं को हल करने के लिए इंसानों की तरह लचीले तरीके अपनाना है.

LangGraph, पहले से तैयार ReAct एजेंट (create_react_agent) की सुविधा देता है. हालांकि, ReAct को लागू करने के लिए ज़्यादा कंट्रोल और कस्टमाइज़ेशन की ज़रूरत होने पर, यह सबसे अच्छा विकल्प है.

LangGraph, एजेंट को ग्राफ़ के तौर पर मॉडल करता है. इसके लिए, तीन मुख्य कॉम्पोनेंट का इस्तेमाल किया जाता है:

  • State: शेयर किया गया डेटा स्ट्रक्चर (आम तौर पर TypedDict या Pydantic BaseModel), जो ऐप्लिकेशन के मौजूदा स्नैपशॉट को दिखाता है.
  • Nodes: आपके एजेंट के लॉजिक को कोड में बदलता है. इनमें मौजूदा स्टेटस को इनपुट के तौर पर लिया जाता है, कुछ कैलकुलेशन या साइड-इफ़ेक्ट किए जाते हैं, और अपडेट की गई स्टेटस दी जाती है. जैसे, एलएलएम कॉल या टूल कॉल.
  • Edges: मौजूदा State के आधार पर, अगला Node तय करें. इससे शर्तों के हिसाब से लॉजिक और तय किए गए ट्रांज़िशन की सुविधा मिलती है.

अगर आपके पास अब तक एपीआई पासकोड नहीं है, तो Google AI Studio पर जाकर, मुफ़्त में एपीआई पासकोड पाएं.

pip install langgraph langchain-google-genai geopy requests

एनवायरमेंट वैरिएबल GEMINI_API_KEY में अपनी एपीआई पासकोड सेट करें.

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 नाम का एक आसान टूल उपलब्ध कराता है. यह रिड्यूसर के तौर पर काम करता है. इसका मतलब है कि यह मौजूदा सूची और नए मैसेज को लेकर, एक नई सूची बनाता है. यह मैसेज आईडी के हिसाब से अपडेट को बेहतर तरीके से मैनेज करता है. साथ ही, नए और यूनीक मैसेज के लिए, डिफ़ॉल्ट रूप से "सिर्फ़ जोड़ें" मोड में काम करता है.

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 for a given location (city) and a date (yyyy-mm-dd). Returns a list dictionary with the time and temperature for each hour."""
    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 {time: temp for time, temp in 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= "gemini-2.5-pro",
    temperature=1.0,
    max_retries=2,
    google_api_key=api_key,
)

# Bind tools to the model
model = llm.bind_tools([get_weather_forecast])

# Test the model with tools
res=model.invoke(f"What is the weather in Berlin on {datetime.today()}?")

print(res)

एजेंट को चलाने से पहले, अपने नोड और किनारों को तय करना ज़रूरी है. इस उदाहरण में, आपके पास दो नोड और एक एज है. - call_tool वह नोड जो आपके टूल के तरीके को लागू करता है. LangGraph में, इसके लिए पहले से बना एक नोड है, जिसे ToolNode कहा जाता है. - call_model नोड, जो मॉडल को कॉल करने के लिए model_with_tools का इस्तेमाल करता है. - should_continue एज, जो यह तय करता है कि टूल को कॉल करना है या मॉडल को.

नोड और किनारों की संख्या तय नहीं होती. अपने ग्राफ़ में जितने चाहें उतने नोड और एज जोड़े जा सकते हैं. उदाहरण के लिए, टूल या मॉडल को कॉल करने से पहले, मॉडल के आउटपुट की जांच करने के लिए, स्ट्रक्चर्ड आउटपुट जोड़ने के लिए कोई नोड या खुद की पुष्टि करने/रिफ़्लेक्शन नोड जोड़ा जा सकता है.

from langchain_core.messages import ToolMessage
from langchain_core.runnables import RunnableConfig

tools_by_name = {tool.name: tool for tool in tools}

# Define our tool node
def call_tool(state: AgentState):
    outputs = []
    # Iterate over the tool calls in the last message
    for tool_call in state["messages"][-1].tool_calls:
        # Get the tool by name
        tool_result = tools_by_name[tool_call["name"]].invoke(tool_call["args"])
        outputs.append(
            ToolMessage(
                content=tool_result,
                name=tool_call["name"],
                tool_call_id=tool_call["id"],
            )
        )
    return {"messages": outputs}

def call_model(
    state: AgentState,
    config: RunnableConfig,
):
    # Invoke the model with the system prompt and the messages
    response = model.invoke(state["messages"], config)
    # We return a list, because this will get added to the existing messages state using the add_messages reducer
    return {"messages": [response]}


# Define the conditional edge that determines whether to continue or not
def should_continue(state: AgentState):
    messages = state["messages"]
    # If the last message is not a tool call, then we finish
    if not messages[-1].tool_calls:
        return "end"
    # default to continue
    return "continue"

अब आपके पास अपना एजेंट बनाने के लिए सभी कॉम्पोनेंट हैं. आइए, इन दोनों को एक साथ जोड़ते हैं.

from langgraph.graph import StateGraph, END

# Define a new graph with our state
workflow = StateGraph(AgentState)

# 1. Add our nodes 
workflow.add_node("llm", call_model)
workflow.add_node("tools",  call_tool)
# 2. Set the entrypoint as `agent`, this is the first node called
workflow.set_entry_point("llm")
# 3. Add a conditional edge after the `llm` node is called.
workflow.add_conditional_edges(
    # Edge is used after the `llm` node is called.
    "llm",
    # The function that will determine which node is called next.
    should_continue,
    # Mapping for where to go next, keys are strings from the function return, and the values are other nodes.
    # END is a special node marking that the graph is finish.
    {
        # If `tools`, then we call the tool node.
        "continue": "tools",
        # Otherwise we finish.
        "end": END,
    },
)
# 4. Add a normal edge after `tools` is called, `llm` node is called next.
workflow.add_edge("tools", "llm")

# Now we can compile and visualize our graph
graph = workflow.compile()

draw_mermaid_png तरीके का इस्तेमाल करके, अपने ग्राफ़ को विज़ुअलाइज़ किया जा सकता है.

from IPython.display import Image, display

display(Image(graph.get_graph().draw_mermaid_png()))

png

अब एजेंट को चलाएं.

from datetime import datetime
# Create our initial message dictionary
inputs = {"messages": [("user", f"What is the weather in Berlin on {datetime.today()}?")]}

# call our graph with streaming to see the steps
for state in graph.stream(inputs, stream_mode="values"):
    last_message = state["messages"][-1]
    last_message.pretty_print()

अब बातचीत जारी रखी जा सकती है. उदाहरण के लिए, किसी दूसरे शहर का मौसम पूछा जा सकता है या मौसम की तुलना की जा सकती है.

state["messages"].append(("user", "Would it be in Munich warmer?"))

for state in graph.stream(state, stream_mode="values"):
    last_message = state["messages"][-1]
    last_message.pretty_print()