This article explains how to create a simple ReAct agent application using LangGraph. The app will feature an agent (LLM) that determines when to utilize external tools, such as fetching weather information, to fulfill user requests.
Overview
The ReAct agent workflow follows a structured loop:
- The agent first decides if a tool (e.g., weather API) is needed.
- If action is required, it calls the tool and sends the output back to the agent.
- If no action is needed, the agent directly responds to the user.
This tutorial utilizes a prebuilt ReAct agent, which simplifies the initial setup process. However, LangGraph also supports custom agent architectures for more advanced use cases.
Getting Started
1. Install Required Packages
%pip install -U langgraph langchain-openai
2. Set Up Environment Variables
Define and secure your OpenAI API key:
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
You can also integrate LangSmith for debugging and monitoring your LangGraph projects. LangSmith enables you to test and optimize agent performance efficiently.
Code Implementation
1. Initialize the Model
The app uses the GPT-4 model provided by LangChain’s OpenAI integration:
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
2. Create a Custom Weather Tool
This example includes a custom tool to provide weather information for NYC and SF:
from typing import Literal
from langchain_core.tools import tool
@tool
def get_weather(city: Literal["nyc", "sf"]):
"""Use this to get weather information."""
if city == "nyc":
return "It might be cloudy in nyc"
elif city == "sf":
return "It's always sunny in sf"
else:
raise AssertionError("Unknown city")
tools = [get_weather]
3. Define the ReAct Agent
Use LangGraph’s prebuilt create_react_agent
to define the agent and its tools:
from langgraph.prebuilt import create_react_agent
graph = create_react_agent(model, tools=tools)
Visualizing the Graph
To visualize the graph structure, you can render it using the following code:
from IPython.display import Image, display
display(Image(graph.get_graph().draw_mermaid_png()))
Usage Examples
1. Query Requiring a Tool
When the user asks for weather information in San Francisco:
inputs = {"messages": [("user", "what is the weather in sf")]}
graph.stream(inputs, stream_mode="values")
Expected output:
- The agent determines the need to call the
get_weather
tool. - The tool provides the response: “It’s always sunny in sf.”
- The agent returns the final message: “The weather in San Francisco is currently sunny.”
2. Query Not Requiring a Tool
For a general question like “Who built you?”:
inputs = {"messages": [("user", "who built you?")]}
graph.stream(inputs, stream_mode="values")
In this case, the agent responds directly without calling external tools.
Benefits and Next Steps
Starting with prebuilt agents is an efficient way to familiarize yourself with LangGraph. As you grow more comfortable, consider building custom agents to leverage LangGraph’s full potential.
To further explore LangGraph’s features, check the official documentation for ChatOpenAI
, tool
, and create_react_agent
.
By customizing and optimizing agents, you can unlock advanced workflows tailored to your specific use cases.
Source link
lol