জেমিনি এবং ল্যাংগ্রাফের সাথে শুরু থেকেই রিঅ্যাক্ট এজেন্ট

ল্যাংগ্রাফ হল স্টেটফুল এলএলএম অ্যাপ্লিকেশন তৈরির জন্য একটি কাঠামো, যা এটিকে রিঅ্যাক্ট (যুক্তি এবং ভারপ্রাপ্ত) এজেন্ট তৈরির জন্য একটি ভাল পছন্দ করে তোলে।

ReAct এজেন্টরা LLM যুক্তি এবং অ্যাকশন এক্সিকিউশনকে একত্রিত করে। তারা ব্যবহারকারীর লক্ষ্য অর্জনের জন্য পুনরাবৃত্তিমূলকভাবে চিন্তা করে, সরঞ্জাম ব্যবহার করে এবং পর্যবেক্ষণের উপর কাজ করে, তাদের পদ্ধতিকে গতিশীলভাবে অভিযোজিত করে। "ReAct: Synergizing Reasoning and Acting in Language Models" (2023) এ উপস্থাপিত, এই প্যাটার্নটি কঠোর কর্মপ্রবাহের উপর মানুষের মতো, নমনীয় সমস্যা সমাধানের প্রতিফলন ঘটানোর চেষ্টা করে।

ল্যাংগ্রাফ একটি পূর্বনির্মিত রিঅ্যাক্ট এজেন্ট ( create_react_agent ) অফার করে, যা আপনার রিঅ্যাক্ট বাস্তবায়নের জন্য আরও নিয়ন্ত্রণ এবং কাস্টমাইজেশনের প্রয়োজন হলে উজ্জ্বল হয়। এই নির্দেশিকা আপনাকে একটি সরলীকৃত সংস্করণ দেখাবে।

ল্যাংগ্রাফ তিনটি মূল উপাদান ব্যবহার করে এজেন্টদের গ্রাফ হিসেবে মডেল করে:

  • State : শেয়ার্ড ডেটা স্ট্রাকচার (সাধারণত TypedDict বা Pydantic BaseModel ) যা অ্যাপ্লিকেশনের বর্তমান স্ন্যাপশট উপস্থাপন করে।
  • Nodes : আপনার এজেন্টদের লজিক এনকোড করে। তারা বর্তমান অবস্থা ইনপুট হিসেবে গ্রহণ করে, কিছু গণনা বা পার্শ্ব প্রতিক্রিয়া সম্পাদন করে এবং একটি আপডেট করা অবস্থা ফেরত দেয়, যেমন LLM কল বা টুল কল।
  • Edges : বর্তমান State উপর ভিত্তি করে পরবর্তী Node কার্যকর করার জন্য সংজ্ঞায়িত করুন, যা শর্তসাপেক্ষ লজিক এবং স্থির ট্রানজিশনের জন্য অনুমতি দেয়।

যদি আপনার কাছে এখনও API কী না থাকে, তাহলে আপনি Google AI Studio থেকে একটি পেতে পারেন।

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")

ল্যাংগ্রাফ ব্যবহার করে কীভাবে একটি রিঅ্যাক্ট এজেন্ট বাস্তবায়ন করতে হয় তা আরও ভালোভাবে বোঝার জন্য, এই নির্দেশিকাটি একটি ব্যবহারিক উদাহরণের মধ্য দিয়ে যাবে। আপনি এমন একটি এজেন্ট তৈরি করবেন যার লক্ষ্য হবে একটি নির্দিষ্ট স্থানের বর্তমান আবহাওয়া খুঁজে বের করার জন্য একটি টুল ব্যবহার করা।

এই আবহাওয়া এজেন্টের জন্য, 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.

    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= "gemini-3-flash-preview",
    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)
    # This returns a list, which combines with 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 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 the 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 warmer in Munich?"))

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