A simple agent using LangGraph with RAG context and web search

In this article, I created a study assistant that helps prepare cheat sheets, notes, and plans for your time allocated. It uses the RAG context to help you study and uses the web search for creating mock tests, getting popular interview questions, and much more.

Pre-requisites

What is LangGraph?
A simple Lang Graph connected to Vector DB is optional, but this helps you give more context to this article.

Use case: Create a study plan based on the context

I thought about a use case where one wants to learn about Binary search trees based on the context provided. The context includes Red-Black trees and some information about AVL trees as well.

The context is here https://github.com/sushmasush/langGraph/blob/main/data/BinarySearchTrees.pdf
from the Book “Introduction to Algorithms by  Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein.

Logic flow

Step 1: Create a routing logic

This contains a question router chain that combines the LLM with the prompt and structures the output which returns whether the question requires an RAG context or a web search to generate an answer.
Review the code below and It returns “vectorstore” or “web_search”.

Step 2: Web search tool

Tavily Web search tool is one of the tools used in langchain community. Get the top 3 results.

Step 3: Create a chain to generate the answers

Create a rag_chain which is a combination of LLM+ prompt template+ output parser.
OutputParser that parses LLMResult into the top likely string.
Prompt Template is one of the templates that is in the lang chain hub.

Step 4: Define the graph state

Each node in the graph contains a data structure that has a question, generation, and documents when there is a RAG context.

Step 5: Retrieve from the database and generate answers

The following code generates based on the documents that are retrieved from the db retriever.
The retriever uses a Maximum marginal relevance retrieval mechanism to retrieve the documents.

Step 6: Web search tool invocation

Invoke the web search tool with the questions. Retrieve and generate answers.

Step 7: Graph design

Step 8: Queries

Query 1: “Give me a brief note on AVL trees?”

Response:

Question: Give me a brief note on AVL trees?
---ROUTE QUESTION---
---ROUTE QUESTION TO RAG---
---RETRIEVE---
---GENERATE---
"Node 'vectorstore':"
("Value: {'question': 'Give me a brief note on AVL trees?', 'generation': 'An "
 'AVL tree is a self-balancing binary search tree where the heights of the two '
 'child subtrees of any node differ by at most one. This property helps '
 'maintain a balanced tree structure, ensuring efficient search, insertion, '
 'and deletion operations. AVL trees are named after their inventors, '
 "Adelson-Velsky and Landis.', 'documents': [Document(metadata={'source': "
 "'data/BinarySearchTrees.pdf', 'page': 4}, page_content='12.1  What  is a "
 'binary  search  tree?  313 \\n5 2 5 5 \\n8 7 6 \\n(a) 6 8 7 5 2 \\n(b) 6 '
 '\\n5 7 \\n2 5 8 2 \\n5 \\n7 \\n6 8 \\n5 T: root T: root \\nFigure  12.1  '
 'Binary search trees. For any node x, the keys in the left subtree of x are '
 'at most x: key, \\nand the keys in the right subtree of x are at least x: '
 'key. Different binary search trees can represent \\nthe  same  set  of '
 'values.  The  worst-case  running  time  for  most  search-tree  operations  '
 "is proportional'), Document(metadata={'source': "
 "'data/BinarySearchTrees.pdf', 'page': 28}, page_content='arbitrary n-node  "
 'binary  search  tree  using  O.n/  rotations. ( Hint: First show that at '
 '\\nmost n \\ue003 1 right  rotations  sufûce  to transform  the  tree  into  '
 'a right-go ing chain.) \\n? 13.2-5  \\nWe say that a binary search tree T 1 '
 'can be right-converted  to binary search tree T 2 \\nif it is possible to '
 'obtain T 2 from T 1 via a series of calls to R IGHT-ROTATE. Give  \\nan '
 'example of two trees T 1 and T 2 such that T 1 cannot  be right-converted  '
 "to T 2 .'), Document(metadata={'source': 'data/BinarySearchTrees.pdf', "
 "'page': 3}, page_content='A binary search tree is organized, as the name "
 'sugg ests, in a binary tree, as shown \\nin Figure  12.1.  You  can  '
 'represent  such  a tree  with  a linked  data structure, as in \\nSection  '
 '10.3.  In addition  to a key  and satellite data, each node object contains '
 '\\nattributes left , right , and p that point to the nodes corresponding to '
 'its left c hild, \\nits right child, and its parent, respectively. If a  '
 "child or the parent is missing, the'), Document(metadata={'source': "
 "'data/BinarySearchTrees.pdf', 'page': 3}, page_content='won’t  prove  it "
 'here,  but  if you  build  a binary  search  tree  on  a random set of n '
 'keys, \\nits expected height is O.lg n/ even  if you  don’t  try  to limit  '
 'its  height.  \\nAfter presenting the basic properties of binary sea rch '
 'trees, the  following  sec-  \\ntions show how to walk a binary search tree '
 'to prin t its values in sorted order, how \\nto search  for  a value  in a '
 "binary  search  tree,  how  to ûnd  the  minimum or maximum')]}")
'\n---\n'
Key:vectorstore
('An AVL tree is a self-balancing binary search tree where the heights of the '
 'two child subtrees of any node differ by at most one. This property helps '
 'maintain a balanced tree structure, ensuring efficient search, insertion, '
 'and deletion operations. AVL trees are named after their inventors, '
 'Adelson-Velsky and Landis.')
Query 2: “Tutor me about binary search trees in 300 words.

Response:

Question: Tutor me about binary search trees in 300 words. 
---ROUTE QUESTION---
---ROUTE QUESTION TO RAG---
---RETRIEVE---
---GENERATE---
"Node 'vectorstore':"
("Value: {'question': 'Tutor me about binary search trees in 300 words. ', "
 '\'generation\': "A binary search tree is organized in a binary tree '
 'structure where the keys in the left subtree of a node are less than the '
 "node's key, and the keys in the right subtree are greater. Operations on "
 'binary search trees include searching for a value, finding the minimum or '
 'maximum element, finding the predecessor or successor of an element, and '
 'inserting or deleting nodes. Different binary search trees can represent the '
 'same set of values, and the worst-case running time for most search-tree '
 'operations is proportional.", \'documents\': [Document(metadata={\'source\': '
 "'data/BinarySearchTrees.pdf', 'page': 6}, page_content='12.1  What  is a "
 'binary  search  tree?  315 \\nSince I NORDER-TREE-WALK  takes a small, '
 'constant amount of time on an \\nempty subtree (for the test x ¤ NIL), we '
 'have T.0/  D c for some constant c>0 . \\nFor n > 0 , suppose that I '
 'NORDER-TREE-WALK  is called on a node x whose \\nleft subtree has k nodes '
 'and whose right subtree has n \\ue003 k \\ue003 1 nodes. The time to '
 '\\nperform I NORDER-TREE-WALK  .x/  is bounded by T.n/  හ T.k/ CT.n\\ue003k '
 "\\ue0031/Cd'), Document(metadata={'source': 'data/BinarySearchTrees.pdf', "
 "'page': 3}, page_content='to search  for  a value  in a binary  search  "
 'tree,  how  to ûnd  the  minimum or maximum \\nelement,  how  to ûnd  the  '
 'predecessor  or successor  of an elemen t, and how to insert \\ninto or '
 'delete from a binary search tree. The basic  mathematical properties of '
 'trees \\nappear in Appendix B. \\n12.1  What  is a binary  search  tree?  '
 '\\nA binary search tree is organized, as the name sugg ests, in a binary '
 "tree, as shown'), Document(metadata={'source': 'data/BinarySearchTrees.pdf', "
 "'page': 4}, page_content='12.1  What  is a binary  search  tree?  313 \\n5 2 "
 '5 5 \\n8 7 6 \\n(a) 6 8 7 5 2 \\n(b) 6 \\n5 7 \\n2 5 8 2 \\n5 \\n7 \\n6 8 '
 '\\n5 T: root T: root \\nFigure  12.1  Binary search trees. For any node x, '
 'the keys in the left subtree of x are at most x: key, \\nand the keys in the '
 'right subtree of x are at least x: key. Different binary search trees can '
 'represent \\nthe  same  set  of values.  The  worst-case  running  time  '
 "for  most  search-tree  operations  is proportional'), "
 "Document(metadata={'source': 'data/BinarySearchTrees.pdf', 'page': 11}, "
 "page_content='320  Chapter  12  Binary  Search  Trees  \\n12.2-2  \\nWrite "
 'recursive versions of T REE-MINIMUM and T REE-MAXIMUM . \\n12.2-3  \\nWrite '
 'the T REE-PREDECESSOR  procedure. \\n12.2-4  \\nProfessor  Kilmer  claims  '
 'to have  discovered  a remarkable  property of binary search \\ntrees. '
 'Suppose that the search for key k in a binary search tree ends up at a leaf. '
 '\\nConsider three sets: A, the keys to the left of the search path; B , the '
 "keys on')]}")
'\n---\n'
Key:vectorstore
('A binary search tree is organized in a binary tree structure where the keys '
 "in the left subtree of a node are less than the node's key, and the keys in "
 'the right subtree are greater. Operations on binary search trees include '
 'searching for a value, finding the minimum or maximum element, finding the '
 'predecessor or successor of an element, and inserting or deleting nodes. '
 'Different binary search trees can represent the same set of values, and the '
 'worst-case running time for most search-tree operations is proportional.')
Query 3: “Give me 2 MCQ’s interview questions along with 4 options in Binary Search tree topic from the web. State the correct answer. Let the difficulty level be Easy

Response:

Question: Give me 2 MCQ's interview questions along with 4 options in Binary Search tree topic from the web. State the correct answer. Let the difficulty level be Easy
---ROUTE QUESTION---
---ROUTE QUESTION TO WEB SEARCH---
---WEB SEARCH---
Web Documents: page_content='May 13, 2024 · Introduction to Binary Search Trees (BST) · 1. How to Check if a Binary Tree is a Binary Search Tree? · 2. How to Perform Inorder Traversal of a ...Missing:  MCQ 08/10/2024
Aug 23, 2018 · Determine whether a binary tree is a subtree of another binary tree · Find the diameter of a binary tree · Check if a binary tree is symmetric ...Missing:  MCQ 08/10/2024
Jun 22, 2024 · Commonly asked binary tree interview questions 1. What are the applications of binary trees? 2. Explain the difference between full and ...Missing:  MCQ | Show results with:MCQ
Aug 31, 2023 · This 5+ hours long video is all you need to be able to solve any binary tree interview question ...Duration: 5:01:51Posted: Aug 31, 2023Missing:  08/10/2024
Binary Search Tree Questions and Answers - Sanfoundry Data Structure Questions and Answers – Binary Search Tree c) The left and right sub-trees should also be binary search trees Explanation: As a binary search tree consists of elements lesser than the node to the left and the ones greater than the node to the right, an inorder traversal will give the elements in an increasing order. Java Program to Perform Right and Left Rotation on a Binary Search Tree C++ Program to Search for an Element in a Binary Search Tree C Program to Search a Node in Binary Tree Data Structure Questions and Answers – Threaded Binary Tree'
---GENERATE---
"Node 'web_search':"
('Value: {\'question\': "Give me 2 MCQ\'s interview questions along with 4 '
 'options in Binary Search tree topic from the web. State the correct answer. '
 'Let the difficulty level be Easy", \'generation\': \'1. What is the main '
 'property of a Binary Search Tree?\\na) Elements are in decreasing order\\nb) '
 'Elements are in random order\\nc) Elements are in increasing order\\nd) '
 'Elements are in no specific order\\nCorrect Answer: c) Elements are in '
 'increasing order\\n\\n2. What is the result of an inorder traversal of a '
 'Binary Search Tree?\\na) Elements in random order\\nb) Elements in '
 'decreasing order\\nc) Elements in increasing order\\nd) Elements in no '
 "specific order\\nCorrect Answer: c) Elements in increasing order', "
 "'documents': Document(metadata={}, page_content='May 13, 2024 · Introduction "
 'to Binary Search Trees (BST) · 1. How to Check if a Binary Tree is a Binary '
 'Search Tree? · 2. How to Perform Inorder Traversal of a\\xa0...Missing:  MCQ '
 '08/10/2024\\nAug 23, 2018 · Determine whether a binary tree is a subtree of '
 'another binary tree · Find the diameter of a binary tree · Check if a binary '
 'tree is symmetric\\xa0...Missing:  MCQ 08/10/2024\\nJun 22, 2024 · Commonly '
 'asked binary tree interview questions 1. What are the applications of binary '
 'trees? 2. Explain the difference between full and\\xa0...Missing:  MCQ | '
 'Show results with:MCQ\\nAug 31, 2023 · This 5+ hours long video is all you '
 'need to be able to solve any binary tree interview question ...Duration: '
 '5:01:51Posted: Aug 31, 2023Missing:  08/10/2024\\nBinary Search Tree '
 'Questions and Answers - Sanfoundry Data Structure Questions and Answers – '
 'Binary Search Tree c) The left and right sub-trees should also be binary '
 'search trees Explanation: As a binary search tree consists of elements '
 'lesser than the node to the left and the ones greater than the node to the '
 'right, an inorder traversal will give the elements in an increasing order. '
 'Java Program to Perform Right and Left Rotation on a Binary Search Tree C++ '
 'Program to Search for an Element in a Binary Search Tree C Program to Search '
 'a Node in Binary Tree Data Structure Questions and Answers – Threaded Binary '
 "Tree')}")
'\n---\n'
Key:web_search
('1. What is the main property of a Binary Search Tree?\n'
 'a) Elements are in decreasing order\n'
 'b) Elements are in random order\n'
 'c) Elements are in increasing order\n'
 'd) Elements are in no specific order\n'
 'Correct Answer: c) Elements are in increasing order\n'
 '\n'
 '2. What is the result of an inorder traversal of a Binary Search Tree?\n'
 'a) Elements in random order\n'
 'b) Elements in decreasing order\n'
 'c) Elements in increasing order\n'
 'd) Elements in no specific order\n'
 'Correct Answer: c) Elements in increasing order')

Conclusion

We have successfully created an assisted powered by a RAG context and the ability to web search for tailored scenarios.

Review my portfolio here

References

  1. LangGraph examples

Leave a Reply