Skip to content

Effortlessly Create an Amazing ReAct Agent with LangGraph

  • 4 min read
  • by
React agent with LangGraph

Langgraph is a powerful library that helps build AI Agents for your goal-specific tasks. Due to its flexibility and robustness, anyone can make any AI agent easily. Today, in this blog you will learn exactly how to create a simple React agent using LangGraph.

If you are new to LangGraph, I suggest first understanding the core concepts of LangGraph from here.

What is ReAct Agent?

React agent processing diagram

The ReACT (Reasoning and Action) agent model is a framework designed to integrate the reasoning capabilities of large language models (LLMs) with the ability to take actionable steps, creating a more sophisticated system that can understand and process information, evaluate situations, take appropriate actions, communicate responses, and track ongoing situations.

The ReAct framework allows you to call your internal agent logic(functions) multiple times until the Agent gets its required answer based on input.

Check out this blog If you want to learn more about the ReAct Agent framework.

Let’s Build ReAct Agent using LangGraph

Here we are going to create a simple React Agent that will do the following tasks:

  1. gives the weather of the given city
  2. Does Arithmetic operations( addition, division, multiplications)
from IPython.display import Image,display
from langgraph.graph import StateGraph,START
from langchain_openai import ChatOpenAI
import requests
from langchain_core.messages import SystemMessage, HumanMessage
from langgraph.graph import MessagesState
from langgraph.prebuilt import ToolNode, tools_condition

To get the weather of the given city, I used Weatherstack’s API. ( You can choose any other weather service as per your preference.)

First, we’ll need to define LangGraph’s state.

class State(MessagesState):
    pass

Now, let’s define functions for our logic.

weather_api_key="YOUR_API_KEY"

def weather_api(city:str)-> str:
    """Gives the temprature of the given city"""

    url = f"<https://api.weatherstack.com/current?access_key={weather_api_key}>"

    querystring = {"query":city}

    response = requests.get(url, params=querystring)

    return response.json()['current']['temperature']

Let’s also create functions for arithmetic operations.

def multiply(a:int,b:int) -> int:
    """
    Multiply a and b
    """
    return a* b

def add(a:int,b:int) -> int:
    """
    Adds a and b
    """
    return a + b

def divide(a:int,b:int) -> int:
    """
    Divides a and b
    """
    return a/b

Remember, we need to encapsulate the above functions to use them as tools for the LLM.

llm=ChatOpenAI()

tools=[weather_api,add,divide,multiply]
llm_with_tools=llm.bind_tools(tools)

Now let’s create an assistant function that will do reasoning.

sys_msg=SystemMessage(content="You are a helpful assistant who is expert in arithmetic operations and also tells the weather of city.")
def assistant(state:State):
    return {"messages":[llm_with_tools.invoke([sys_msg]+state['messages'])]}

Now our logic part is done. So we will process with graph creation.

builder=StateGraph(State)

# Define nodes
builder.add_node("assistant",assistant)
builder.add_node("tools",ToolNode(tools))

#define edges
builder.add_edge(START,"assistant")
builder.add_conditional_edges("assistant",tools_condition)
builder.add_edge("tools","assistant")
react_graph=builder.compile()

In the above code, the ToolNode is a predefined function in the LangGraph that lets you create a node of tools. Which will be used by our agent.

tools_condition is another functionality in the LangGraph that invokes the tools as per the processing flow.

To see the graph’s connection visually, run the following code:

display(Image(react_graph.get_graph().draw_mermaid_png()))

The key edge of our ReAct Agent is the builder.add_edge("tools", "assistant"). This edge, as illustrated in the diagram, enables the assistant to reason based on the tools’ outputs and invoke additional tools if needed.

Now let’s run our ReAct Agent.

message=HumanMessage(content="Give me a temprature of Ahmedabad. Multiply it by 2 and add 5.")

output=react_graph.invoke({"messages":message})
print(output['messages'][-1].content)

---Output---
The temperature in Ahmedabad is 27°C. 

When multiplied by 2, it becomes 54°C. 

Adding 5 to it gives 59°C.

Let’s verify this by checking all the processing messages handled by our agent.

for m in output['messages']:
    m.pretty_print()
    
---Output---
================================ Human Message =================================

Give me a temprature of Ahmedabad. Multiply it by 2 and add 5.
================================== Ai Message ==================================
Tool Calls:
  weather_api (call_NctZGeA1J7bejT8orTSRX6Py)
 Call ID: call_NctZGeA1J7bejT8orTSRX6Py
  Args:
    city: Ahmedabad
================================= Tool Message =================================
Name: weather_api

27
================================== Ai Message ==================================
Tool Calls:
  multiply (call_hbGWJNQGWR060RafFXkiO1La)
 Call ID: call_hbGWJNQGWR060RafFXkiO1La
  Args:
    a: 27
    b: 2
  add (call_134maQOUiMHvLv5rLXIc5UYX)
 Call ID: call_134maQOUiMHvLv5rLXIc5UYX
  Args:
    a: 54
    b: 5
================================= Tool Message =================================
Name: multiply

54
================================= Tool Message =================================
Name: add

59
================================== Ai Message ==================================

The temperature in Ahmedabad is 27°C. 

When multiplied by 2, it becomes 54°C. 

Adding 5 to it gives 59°C.

Yes. It’s correct! Our agent called the weather_api tool then it invoked multiply and add tools for the processing.

So this is how you can easily create ReAct agent in LangGraph.

Also Read: LangGraph: An Introduction to the LangGraph Components

Leave a Reply

Your email address will not be published. Required fields are marked *