Agentic RAG
Author: Heesun Moon
Design: LeeYuChul
Peer Review:
Proofread : Chaeyoon Kim
This is a part of LangChain Open Tutorial
Overview
An Agent is useful when deciding whether to use a search tool. For more details about agents, refer to the Agent page.
To implement a search agent, simply grant the LLM access to the search tool.
This can be integrated into LangGraph.

Table of Contents
References
Environment Setup
Set up the environment. You may refer to Environment Setup for more details.
[Note]
langchain-opentutorialis a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.You can checkout the
langchain-opentutorialfor more details.
You can alternatively set API keys such as OPENAI_API_KEY in a .env file and load them.
[Note] This is not necessary if you've already set the required API keys in previous steps.
Create a basic PDF-based Retrieval Chain
Here, we create a Retrieval Chain based on a PDF document. This is the Retrieval Chain with the simplest structure.
However, in LangGraph, Retirever and Chain are created separately. Only then can detailed processing be performed for each node.
[Note]
As this was covered in the previous tutorial, detailed explanation will be omitted.
Next, create the retriever_tool tool.
[Note]
The document_prompt is a prompt used to represent the retrieved document.
Available Keys
page_contentKeys in
metadata: (e.g.)source,page
Example Usage
"<document><context>{page_content}</context><metadata><source>{source}</source><page>{page}</page></metadata></document>"
Defining AgentState
AgentStateWe will define the AgentState .
Each node is passed a state object. The state consists of a list of messages .
Each node in the graph adds content to this list.
Nodes and Edges
An agent-based RAG graph can be structured as follows:
stateis a collection of messages.Each node updates (adds to) the
state.Conditional edges determine the next node to visit.
Now, let's create a simple Grader.
Graph
Start with the
call_modelagent.The agent decides whether to call a function.
If a function call is decided, an
actionis executed to invoke the tool (retriever).The tool's output is added to the messages (
state), and the agent is called again.
Visualize the compiled graph.

Execute the Graph
Now, let's run the graph.
The following are examples of questions where document retrieval is unnecessary.
Below are some examples of questions where document retrieval is not possible.
As a result, a GraphRecursionError occurred during the continuous document retrieval process.
The next tutorial will cover how to resolve this issue.
Last updated