React Agent

Open in ColabOpen in GitHub## Overview

In this tutorial, we explore the concept and implementation of a ReAct Agent.

ReAct Agent stands for Reasoning + Action, meaning that the LLM explicitly goes through a reasoning phase, utilizes tools (or actions), and then generates the final answer based on the obtained results.

Throughout this tutorial, we will implement a ReAct Agent by covering the following:

  • Tool Setup: Utilizing various tools such as web search, file management, document search based on VectorStore, etc.

  • Agent Creation: Practice how to use the ReAct Agent in LangChain.

  • Graph Execution: Execute the agent to observe the answers to queries.

Please follow the sections below to go through the entire process.

Table of Contents

References


Environment Setup

Set up the environment. You may refer to Environment Setup for more details.

[Note]

  • langchain-opentutorial is a package that provides an easy-to-use environment setup, useful functions, and utilities for tutorials.

  • For more details, check out langchain-opentutorial.

You can alternatively set OPENAI_API_KEY in a .env file and load it.

[Note] This is not necessary if you've already set OPENAI_API_KEY previously.

How to Set Up Tavily Search

Tools

A ReAct Agent uses various tools to solve problems. In this tutorial, we will set up and use the following tools.

We use the TavilySearch tool for searching the latest information from the web. The code below creates a web search tool and tests it by retrieving some search results.

File Management

Using FileManagementToolkit, you can create, delete, and modify files.

Retriever Tool

To search for information within documents such as PDFs, we create a Retriever. First, we load the PDF, split the text, then embed it into a VectorStore.

Tesla's Revenue Forecast Based on Business Model and Financial Statement Analysis

Author: Chenhao Fang Institution: Intelligent Accounting Management Institute, Guangdong University of Finance and Economics Link: Tesla's revenue forecast base on business model and financial statement analysis File Name: shsconf_icdeba2023_02022.pdf

Please copy the downloaded file to the data folder for practice.

Combine these tools into a single list.

Create and Visualize the Agent

We will now create a ReAct Agent and visualize the agent graph. In LangChain, a ReAct agent generates answers through step-by-step reasoning and tool usage.

The code below uses create_react_agent from langgraph to easily build a ReAct Agent and visualize its structure as a graph.

The code below visualizes the agent's graph structure.

Execute Agent

Let's execute the created ReAct Agent. We can track the step-by-step process of generating an answer to a query.

The example code below uses stream_graph to stream the agent's execution process. We place the user's query in the messages key, and the agent's reasoning will be displayed.

Last updated