{"id":126611,"date":"2025-03-11T16:18:25","date_gmt":"2025-03-11T16:18:25","guid":{"rendered":"https:\/\/peraltafinancing.com\/analytics\/building-a-rag-based-query-resolution-system-with-langchain\/"},"modified":"2025-03-11T16:18:25","modified_gmt":"2025-03-11T16:18:25","slug":"building-a-rag-based-query-resolution-system-with-langchain","status":"publish","type":"post","link":"https:\/\/fivemor.com\/?p=126611","title":{"rendered":"Building a RAG-based Query Resolution System with LangChain"},"content":{"rendered":"<p> <br \/>\n<\/p>\n<div id=\"article-start\">\n<p>Businesses today handle a large volume of queries from customers, sales teams, and internal stakeholders. Manually responding to these queries is a slow and inefficient process, often leading to delays and inconsistent answers. A query resolution system powered by AI ensures fast, accurate, and scalable responses. It works by retrieving relevant information and generating precise answers using <a href=\"https:\/\/www.analyticsvidhya.com\/blog\/2023\/09\/retrieval-augmented-generation-rag-in-ai\/\" target=\"_blank\" rel=\"noreferrer noopener\">Retrieval-Augmented Generation<\/a> (RAG). In this article, I will be sharing with you my journey of building a RAG-based query resolution system using <a href=\"https:\/\/www.analyticsvidhya.com\/blog\/2024\/06\/langchain-guide\/\" target=\"_blank\" rel=\"noreferrer noopener\">LangChain<\/a>, <a href=\"https:\/\/www.analyticsvidhya.com\/blog\/2023\/07\/guide-to-chroma-db-a-vector-store-for-your-generative-ai-llms\/\" target=\"_blank\" rel=\"noreferrer noopener\">ChromaDB<\/a>, and <a href=\"https:\/\/www.analyticsvidhya.com\/blog\/2024\/01\/building-collaborative-ai-agents-with-crewai\/\" target=\"_blank\" rel=\"noreferrer noopener\">CrewAI<\/a>.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-why-do-we-need-an-ai-powered-query-resolution-system\">Why Do We Need an AI-powered Query Resolution System?<\/h2>\n<p>Now, manual responses take time and may, therefore, lead to delays. Customers expect instant replies, and businesses need quick access to accurate information. An AI-driven system automates query handling, reducing workload and improving consistency. It enhances productivity, speeds up decision-making, and provides reliable responses across different sectors.<\/p>\n<p>An AI-powered query resolution system is useful in customer support, where it automates responses and improves customer satisfaction. In sales and marketing, it provides real-time product details and customer insights. Industries like finance, healthcare, education, and e-commerce benefit from automated query handling, ensuring smooth operations and better user experiences.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-understanding-the-rag-workflow\">Understanding the RAG Workflow<\/h2>\n<p>Before diving into the implementation, let\u2019s first understand how a Retrieval-Augmented Generation (RAG) system works.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1744\" height=\"947\" src=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp\" alt=\"RAG-based Query Resolution System\" class=\"wp-image-225859\" srcset=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp 1744w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21-300x163.webp 300w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21-768x417.webp 768w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21-1536x834.webp 1536w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21-150x81.webp 150w\" sizes=\"(max-width: 1744px) 100vw, 1744px\"\/><figcaption class=\"wp-element-caption\">Source: Author<\/figcaption><\/figure>\n<\/div>\n<p>The architecture consists of three key stages: Indexing, Retrieval, and Generation.<\/p>\n<h4 class=\"wp-block-heading\" id=\"h-1-building-a-vector-store-document-processing-amp-storage\">1. Building a Vector Store (Document Processing &amp; Storage)<\/h4>\n<p>The system first processes and stores relevant documents to make them easily searchable. Here\u2019s how the indexing process works:<\/p>\n<ul class=\"wp-block-list\">\n<li><strong>Documents &amp; Chunking:<\/strong> Large documents are broken into smaller text chunks for efficient retrieval.<\/li>\n<li><strong>Embedding Model:<\/strong> These text chunks are converted into vector representations using an AI-based embedding model.<\/li>\n<li><strong>Vector Store:<\/strong> The vectorized data is indexed and stored in a database (e.g., ChromaDB) for fast lookup.<\/li>\n<\/ul>\n<h4 class=\"wp-block-heading\" id=\"h-2-query-processing-amp-retrieval\">2. Query Processing &amp; Retrieval<\/h4>\n<p>When a user submits a query, the system retrieves relevant data before generating a response. Here are the steps involved in query processing and retrieval:<\/p>\n<ul class=\"wp-block-list\">\n<li><strong>User Query Input:<\/strong> The user submits a question or request.<\/li>\n<li><strong>Vectorization:<\/strong> The query is converted into a numerical vector using the embedding model.<\/li>\n<li><strong>Search &amp; Retrieval:<\/strong> The system searches for the most relevant chunks in the vector store and retrieves them.<\/li>\n<\/ul>\n<h4 class=\"wp-block-heading\" id=\"h-3-augmentation-amp-response-generation\">3. Augmentation &amp; Response Generation<\/h4>\n<p>To generate a well-informed response, the system augments the query with retrieved data. Given below are the steps involved in response generation.<\/p>\n<ul class=\"wp-block-list\">\n<li><strong>Augment Query:<\/strong> The retrieved document chunks are combined with the original query.<\/li>\n<li><strong>LLM Processing:<\/strong> A large language model (LLM) generates a final response using both the query and the retrieved context.<\/li>\n<li><strong>Final Response:<\/strong> The system provides a factual and context-aware answer to the user.<\/li>\n<\/ul>\n<p>Now that you know how RAG systems work, let\u2019s learn how to build a RAG-based query resolution system.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-building-a-rag-based-query-resolution-system\">Building a RAG-based Query Resolution System<\/h2>\n<p>In this article, I will walk you through building a RAG-based Query Resolution System that efficiently answers learner queries using an AI agent. To keep things simple, I will demonstrate a simplified version of the project and explain how it works.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-selecting-the-right-data-for-query-resolution\">Selecting the Right Data for Query Resolution<\/h3>\n<p>Before building a RAG-based query resolution system, the most important factor to consider is data \u2013 specifically, the types of data required for effective retrieval. A well-structured knowledge base is essential, as the accuracy and relevance of responses depend on the quality of the data available. Below are the key data types that should be considered for different purposes:<\/p>\n<ul class=\"wp-block-list\">\n<li><strong>Customer Support Data:<\/strong> FAQs, troubleshooting guides, product manuals, and past customer interactions.<\/li>\n<li><strong>Sales &amp; Marketing Data:<\/strong> Product catalogs, pricing details, competitor analysis, and customer inquiries.<\/li>\n<li><strong>Internal Knowledge Base:<\/strong> Company policies, training documents, and standard operating procedures (SOPs).<\/li>\n<li><strong>Financial &amp; Legal Documents:<\/strong> Compliance guidelines, financial reports, and regulatory policies.<\/li>\n<li><strong>User-Generated Content:<\/strong> Forum discussions, chat logs, and feedback forms that provide real-world user queries.<\/li>\n<\/ul>\n<p>Selecting the right data sources was crucial for our learner query resolution system, to ensure accurate and relevant responses. Initially, I experimented with different types of data to determine which provided the best results. First, I used PowerPoint slides (PPTs), but they didn\u2019t yield comprehensive answers as expected. Next, I incorporated common queries, which improved response accuracy but lacked sufficient context. Then, I tested past discussions, which helped in making responses more relevant by leveraging previous learner interactions. However, the most effective approach turned out to be using subtitles from course videos, as they provided structured and detailed content directly related to learner queries. This approach helps in providing quick and relevant answers, making it useful for e-learning platforms and educational support systems.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-structuring-the-query-resolution-system\">Structuring the Query Resolution System<\/h3>\n<p>Before coding, it is important to structure the Query Resolution System. The best way to do this is by defining the key tasks it needs to perform.<\/p>\n<p>The system will handle three main tasks:<\/p>\n<ol class=\"wp-block-list\">\n<li>Extract and store course content from subtitles (SRT files).<\/li>\n<li>Retrieve relevant course materials based on learner queries.<\/li>\n<li>Use an AI-powered agent to generate structured responses.<\/li>\n<\/ol>\n<p>To achieve this, the system is divided into three components, each handling a specific function. This ensures efficiency and scalability.<\/p>\n<p>The system consists of:<\/p>\n<ul class=\"wp-block-list\">\n<li><strong>Subtitle Processing<\/strong>\u00a0 \u2013 Extracts text from SRT files, processes it, and stores embeddings in ChromaDB.<\/li>\n<li><strong>Retrieval<\/strong>\u00a0 \u2013 Searches and retrieves relevant course materials based on learner queries.<\/li>\n<li><strong>Query Answering Agent<\/strong> \u2013 Uses CrewAI to generate structured and accurate responses.<\/li>\n<\/ul>\n<p>Each component ensures efficient query resolution, personalized responses, and smooth content retrieval. Now that we have our structure, let\u2019s move on to implementation.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-implementation-steps\">Implementation Steps<\/h2>\n<p><span style=\"font-weight: 400;\">Now that we have our structure, let\u2019s move on to implementation.<\/span><\/p>\n<h3 class=\"wp-block-heading\" id=\"h-1-importing-libraries\">1. Importing Libraries<\/h3>\n<p>To build the AI-powered learning support system, we first need to import essential libraries.<\/p>\n<pre class=\"wp-block-code\"><code>import pysrt\nfrom langchain.text_splitter import RecursiveCharacterTextSplitter\nfrom langchain.schema import Document\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import Chroma\nfrom crewai import Agent, Task, Crew \nimport pandas as pd\nimport ast<\/code><\/pre>\n<p>Let\u2019s understand these libraries.<\/p>\n<ul class=\"wp-block-list\">\n<li>pysrt \u2013 For extracting text from SRT subtitle files.<\/li>\n<li>langchain.text_splitter.RecursiveCharacterTextSplitter \u2013 Splits large text into smaller chunks for better retrieval.<\/li>\n<li>langchain.schema.Document \u2013 Represents structured text documents.<\/li>\n<li>langchain.embeddings.OpenAIEmbeddings \u2013 Converts text into numerical vectors for similarity searches.<\/li>\n<li>langchain.vectorstores.Chroma \u2013 Stores embeddings in a vector database for efficient retrieval.<\/li>\n<li>crewai (Agent, Task, Crew) \u2013 Defines AI agents that process learner queries.<\/li>\n<li>pandas \u2013 Handles structured data in the form of DataFrames.<\/li>\n<li>ast \u2013 Helps in parsing string-based data structures into Python objects.<\/li>\n<li>os \u2013 Provides system-level operations like reading environment variables.<\/li>\n<li>tqdm \u2013 Displays progress bars during long-running tasks.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\" id=\"h-2-setting-up-the-environment\">2. Setting Up the Environment<\/h3>\n<p>To use OpenAI\u2019s API for embeddings, we must load the API key and configure the model settings.<\/p>\n<p><strong>Step 1:<\/strong> Read the API key from a local text file.<\/p>\n<pre class=\"wp-block-code\"><code>with open('\/home\/janvi\/Downloads\/openai.txt', 'r') as file:\n   openai_api_key = file.read()<\/code><\/pre>\n<p><strong>Step 2:<\/strong> Store the API key as an environment variable so it can be accessed by other components.<\/p>\n<pre class=\"wp-block-code\"><code>os.environ['OPENAI_API_KEY'] = openai_api_key\n<\/code><\/pre>\n<p><strong>Step3:<\/strong> Specify the OpenAI model to be used for processing embeddings.<\/p>\n<pre class=\"wp-block-code\"><code>os.environ[\"OPENAI_MODEL_NAME\"] = 'gpt-4o-mini'\n<\/code><\/pre>\n<p>By setting up these configurations, we ensure seamless integration with OpenAI\u2019s API, allowing our system to process and store embeddings efficiently.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-3-extracting-and-storing-subtitle-data\">3. Extracting and Storing Subtitle Data<\/h3>\n<p>Subtitles often contain valuable insights from video lectures, making them a rich source of structured content for AI-based retrieval systems. Extracting and processing subtitle data effectively allows for efficient search and retrieval of relevant information when answering learner queries.<\/p>\n<p>To preserve educational insights, we are using pysrt to read and preprocess text from SRT files. This ensures the extracted content is structured and ready for further processing and storage..<\/p>\n<pre class=\"wp-block-code\"><code>def extract_text_from_srt(srt_path):\n   \"\"\"Extracts text from an SRT subtitle file using pysrt.\"\"\"\n   subs = pysrt.open(srt_path)\n   text = \" \".join(sub.text for sub in subs)\n   return text<\/code><\/pre>\n<p>Since courses may have multiple subtitle files, we systematically organize and iterate through course materials stored in predefined folders. This allows for seamless text extraction and further processing.<\/p>\n<pre class=\"wp-block-code\"><code># Define course names and their respective folder paths\ncourse_folders = {\n   \"Introduction to Deep Learning using PyTorch\": \"C:\\M\\Code\\GAI\\Learn_queries\\Subtitle_Introduction_to_Deep_Learning_Using_Pytorch\",\n   \"Building Production-Ready RAG systems using LlamaIndex\": \"C:\\M\\Code\\GAI\\Learn_queries\\Subtitle of Building Production-Ready RAG systems using LlamaIndex\",\n   \"Introduction to LangChain - Building Generative AI Apps &amp; Agents\": \"C:\\M\\Code\\GAI\\Learn_queries\\Subtitle_introduction_to_langchain_using_agentic_ai\"\n}\n\n\n# Dictionary to store course names and their respective .srt file paths\ncourse_srt_files = {}\n\n\n# Iterate through course folder mappings\nfor course, folder_path in course_folders.items():\n   srt_files = []\n  \n   # Walk through the directory to find .srt files\n   for root, _, files in os.walk(folder_path):\n       srt_files.extend(os.path.join(root, file) for file in files if file.endswith(\".srt\"))\n  \n   # Add to dictionary if there are .srt files\n   if srt_files:\n       course_srt_files[course] = srt_files<\/code><\/pre>\n<p>This extracted text forms the foundation of our AI-driven learning support system, enabling advanced retrieval and query resolution.<\/p>\n<h4 class=\"wp-block-heading\" id=\"h-step-2-storing-subtitles-in-chromadb\">Step 2: Storing Subtitles in ChromaDB<\/h4>\n<p>In this part, we will break down the process of storing course subtitles in ChromaDB, including text chunking, embedding generation, persistence, and cost estimation.<\/p>\n<p><b>a. Persistent Directory for ChromaDB<\/b><\/p>\n<p>The persist_directory is a folder path where the stored data will be saved, allowing us to retain embeddings even after restarting the program. Without this, the database would reset after each execution.<\/p>\n<pre class=\"wp-block-code\"><code>persist_directory = \".\/subtitles_db\"\n<\/code><\/pre>\n<p>ChromaDB is used as a vector database to store and retrieve embeddings efficiently.<\/p>\n<p><b>b. Splitting Text into Smaller Chunks<\/b><\/p>\n<p>Large documents (like entire course subtitles) exceed token limits for embeddings. To handle this, we use RecursiveCharacterTextSplitter to break text into smaller, overlapping chunks to improve search accuracy.<\/p>\n<pre class=\"wp-block-code\"><code># Text splitter to break documents into smaller chunks\ntext_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<\/code><\/pre>\n<p>Each chunk is 1,000 characters long, ensuring that the text is broken into manageable pieces. To maintain context between chunks, 200 characters from the previous chunk are included in the next one. This overlap helps preserve important details and improves retrieval accuracy.<\/p>\n<p><b>c. Initializing OpenAI Embeddings and ChromaDB Vector Store<\/b><\/p>\n<p>We need to convert text into numerical vector representations for similarity search. OpenAI\u2019s embeddings allow us to encode our course content into a format that can be searched efficiently.<\/p>\n<pre class=\"wp-block-code\"><code># Initialize OpenAI embeddings\nembeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)<\/code><\/pre>\n<p>Here, OpenAIEmbeddings() initializes the embedding model using our OpenAI API key (openai_api_key). This ensures that every text chunk gets converted into a high-dimensional vector representation.<\/p>\n<p><b>d. Initializing ChromaDB<\/b><\/p>\n<p>Now, we store these vector embeddings in ChromaDB.<\/p>\n<pre class=\"wp-block-code\"><code># Initialize Chroma vectorstore with persistent directory\nvectorstore = Chroma(\n   collection_name=\"course_materials\",\n   embedding_function=embeddings,\n   persist_directory=persist_directory\n)\n<\/code><\/pre>\n<p>The collection_name=\u201dcourse_materials\u201d creates a dedicated collection in ChromaDB to organize all course-related embeddings. The embedding_function=embeddings specifies OpenAI embeddings for converting text into numerical vectors. The persist_directory=persist_directory ensures that all stored embeddings remain available in .\/subtitles_db\/, even after restarting the program.<\/p>\n<h4 class=\"wp-block-heading\" id=\"h-step-3-estimating-cost-of-storing-course-data\">Step 3: Estimating Cost of Storing Course Data<\/h4>\n<p>Before adding documents to the vector database, it is essential to estimate the cost of token usage. Since OpenAI charges per 1,000 tokens, we calculate the expected cost to manage expenses efficiently.<\/p>\n<p><b>a. Defining Pricing Parameters<\/b><\/p>\n<p>Since OpenAI charges per 1,000 tokens, we estimate the cost before adding documents.<\/p>\n<pre class=\"wp-block-code\"><code>import time\n\n\n# OpenAI Pricing (adjust based on the model being used)\nCOST_PER_1K_TOKENS = 0.0001  # Cost per 1K tokens for 'text-embedding-ada-002'\nTOKENS_PER_CHUNK_ESTIMATE = 750  # Approximate tokens per 1000-character chunk\n\n\n# Track total tokens and cost\ntotal_tokens = 0\ntotal_cost = 0\n\n\n# Start timing\nstart_time = time.time()\n<\/code><\/pre>\n<p>The COST_PER_1K_TOKENS = 0.0001 defines the cost per 1,000 tokens when using OpenAI embeddings. The TOKENS_PER_CHUNK_ESTIMATE = 750 estimates that each 1,000-character chunk contains about 750 tokens. The total_tokens and total_cost variables track the total processed data and cost incurred during execution. The start_time variable records the starting time to measure how long the process takes.<\/p>\n<h4 class=\"wp-block-heading\" id=\"h-b-checking-and-adding-courses-to-chromadb\">b. Checking and Adding Courses to ChromaDB<\/h4>\n<p>We want to avoid reprocessing courses that are already stored in the vector database. So for that we are querying ChromaDB to check if the course already exists. If the course is not found, we extract and store its subtitle data.<\/p>\n<pre class=\"wp-block-code\"><code># Add new courses to the vectorstore if they don't already exist\nfor course, srt_list in course_srt_files.items():\n   # Check if the course already exists in the vectorstore\n   existing_docs = vectorstore._collection.get(where={\"course\": course})\n   if not existing_docs['ids']:\n       # Course not found, add it\n       srt_texts = [extract_text_from_srt(srt) for srt in srt_list]\n       course_text = \"\\n\\n\\n\\n\".join(srt_texts)  # Join SRT texts with four new lines\n       doc = Document(page_content=course_text, metadata={\"course\": course})\n       chunks = text_splitter.split_documents([doc])<\/code><\/pre>\n<p>The subtitles are extracted using the extract_text_from_srt() function. Multiple subtitle files are then joined together using \\n\\n\\n\\n to improve readability. A Document object is created, storing the full subtitle text along with its metadata. Finally, the text is split into smaller chunks using text_splitter.split_documents() for efficient processing and retrieval.<\/p>\n<p><b>c. Estimating Token Usage and Cost<\/b><\/p>\n<p>Before adding the chunks to ChromaDB, we estimate the cost.<\/p>\n<pre class=\"wp-block-code\"><code>      # Estimate cost before adding documents\n       chunk_count = len(chunks)\n       batch_tokens = chunk_count * TOKENS_PER_CHUNK_ESTIMATE\n       batch_cost = (batch_tokens \/ 1000) * COST_PER_1K_TOKENS\n       total_tokens += batch_tokens\n       total_cost += batch_cost<\/code><\/pre>\n<p>The chunk_count represents the number of chunks generated after splitting the text. The batch_tokens estimates the total number of tokens based on the chunk count. The batch_cost calculates the estimated cost for processing the current course. The total_tokens and total_cost accumulate values across all courses to track overall processing and expenses.<\/p>\n<p><b>d. Adding Chunks to ChromaDB<\/b><\/p>\n<pre class=\"wp-block-code\"><code>       vectorstore.add_documents(chunks)\n       print(f\"Added course: {course} (Chunks: {chunk_count}, Cost: ${batch_cost:.4f})\")\n   else:\n       print(f\"Course already exists: {course}\")<\/code><\/pre>\n<p>The processed chunks are stored in ChromaDB for efficient retrieval. A message is displayed, indicating the number of chunks added and the estimated processing cost.<\/p>\n<p>Once all courses are processed, we calculate and display the final results.<\/p>\n<pre class=\"wp-block-code\"><code># End timing\nend_time = time.time()\n\n\n# Display cost and time\nprint(f\"\\nCourse Embeddings Update Completed! \ud83d\ude80\")\nprint(f\"Total Chunks Processed: {total_tokens \/\/ TOKENS_PER_CHUNK_ESTIMATE}\")\nprint(f\"Estimated Total Tokens: {total_tokens}\")\nprint(f\"Estimated Cost: ${total_cost:.4f}\")\nprint(f\"Total Time Taken: {end_time - start_time:.2f} seconds\")\n<\/code><\/pre>\n<p>The total processing time is calculated using (end_time \u2013 start_time). The system then displays the number of chunks processed, the estimated token usage, and the overall cost. Finally, it provides a summary of the entire embedding process.<\/p>\n<p><strong>Output:<\/strong><\/p>\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"937\" height=\"172\" src=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output1.webp\" alt=\"Building a RAG-based Query Resolution System with LangChain and CrewAI\" class=\"wp-image-225860\" srcset=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output1.webp 937w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output1-300x55.webp 300w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output1-768x141.webp 768w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output1-150x28.webp 150w\" sizes=\"auto, (max-width: 937px) 100vw, 937px\"\/><\/figure>\n<p>From the output, we can see that a total of 739 chunks were processed in 10 seconds, with an estimated cost of $0.0554.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-4-querying-and-responding-to-learner-queries\">4. Querying and Responding to Learner Queries<\/h3>\n<p>Once the subtitles are stored in ChromaDB, the system needs a way to retrieve relevant content when a learner submits a query. This retrieval process is handled using similarity search, which identifies stored text segments which are most relevant to the input query.<\/p>\n<p>How it Works:<\/p>\n<ol class=\"wp-block-list\">\n<li><strong>Query Input:<\/strong> The learner submits a question related to the course.<\/li>\n<li><strong>Filtering by Course:<\/strong> The system ensures that retrieval is restricted to the relevant course material.<\/li>\n<li><strong>Similarity Search in ChromaDB:<\/strong> The query is converted into an embedding, and ChromaDB retrieves the most similar stored text chunks.<\/li>\n<li><strong>Returning the Top Results:<\/strong> The system selects the top three most relevant text segments.<\/li>\n<li><strong>Formatting the Output:<\/strong> The retrieved text is formatted and presented as context for further processing.<\/li>\n<\/ol>\n<pre class=\"wp-block-code\"><code># Define retrieval tool with metadata filtering\ndef retrieve_course_materials(query: str, course = course):\n   \"\"\"Retrieves course materials filtered by course name.\"\"\"\n   filter_dict = {\"course\": course}\n   results = vectorstore.similarity_search(query, k=3, filter=filter_dict)\n   return \"\\n\\n\".join([doc.page_content for doc in results])<\/code><\/pre>\n<p>Example queries:<\/p>\n<pre class=\"wp-block-code\"><code>course_name = \"Introduction to Deep Learning using PyTorch\"\nquestion = \"What is gradient descent?\"\ncontext = retrieve_course_materials(query=question, course= course_name)\nprint(context)<\/code><\/pre>\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"969\" height=\"427\" src=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/output2-1.webp\" alt=\"Building a RAG-based Query Resolution System with ChromaDB\" class=\"wp-image-225861\" srcset=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/output2-1.webp 969w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/output2-1-300x132.webp 300w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/output2-1-768x338.webp 768w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/output2-1-150x66.webp 150w\" sizes=\"auto, (max-width: 969px) 100vw, 969px\"\/><\/figure>\n<p>The output consists of the retrieved content from ChromaDB, filtered by course name and question, using similarity search to find the most relevant information.<\/p>\n<h4 class=\"wp-block-heading\" id=\"h-why-is-similarity-search-used\">Why is Similarity Search Used?<\/h4>\n<ul class=\"wp-block-list\">\n<li><strong>Semantic Understanding:<\/strong> Unlike keyword searches, similarity search finds text semantically related to the query.<\/li>\n<li><strong>Efficient Retrieval:<\/strong> Instead of scanning entire documents, the system retrieves only the most relevant parts.<\/li>\n<li><strong>Improved Answer Quality:<\/strong> By filtering by course and ranking results by relevance, learners receive highly targeted content.<\/li>\n<\/ul>\n<p>This mechanism ensures that when a learner submits a question, they receive relevant and contextually accurate information from stored course materials.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-5-implementing-the-ai-query-answering-agent\">5. Implementing the AI Query Answering Agent<\/h3>\n<p>Once relevant course material is retrieved from ChromaDB, the next step is to use an AI-powered agent to formulate meaningful responses to learner queries. CrewAI is used to define an intelligent agent responsible for analyzing queries and generating well-structured responses.<\/p>\n<p>Now, let\u2019s see how it works.<\/p>\n<h4 class=\"wp-block-heading\" id=\"h-step-1-defining-the-agent\">Step 1: Defining the Agent<\/h4>\n<p>The query answering agent is created with a clear role and backstory to guide its behavior when responding to learner queries.<\/p>\n<pre class=\"wp-block-code\"><code># Define the agent with a well-structured role and backstory\nquery_answer_agent = Agent(\n   role = \"Learning Support Specialist\",\n   goal = \"You help learners with their queries with the best possible response\",\n   backstory = \"\"\"You lead the Learners Query resolution department of \n   an Ed tech company focussed on self paced courses on topics related to \n   Data Science, Machine Learning and Generative AI. You respond to learner\n    queries related to course content, assignments, technical and administrative issues. \n    You are polite, diplomatic and take ownership of things which could be \n    imporved in your oragnisation.\n  \n   \"\"\",\n   verbose = False,\n)\n<\/code><\/pre>\n<p>Let\u2019s understand what is happening in the code block. Firstly, we are providing the role as Learning Support Specialist since the agent acts as a virtual tutor that answers student queries. Then, we define the goal, ensuring that the agent prioritizes accuracy and clarity in its responses. Lastly, we set verbose=False, which keeps the execution silent unless debugging is needed. This well-defined agent role ensures that responses are helpful, structured, and aligned with the educational platform\u2019s tone.<\/p>\n<h4 class=\"wp-block-heading\" id=\"h-step-2-defining-the-task\">Step 2: Defining the Task<\/h4>\n<p>After defining the agent, we need to assign it a task<\/p>\n<pre class=\"wp-block-code\"><code>query_answering_task  = Task(\n   description= \"\"\"\n   Answer the learner queries to the best of your abilities. Try to keep your response concise with less than 100 words.\n   Here is the query: {query}\n\n\n   Here is similar content from the course extracted from subtitles, which you should use only when required: {relevant_content} .  \n   Since this content is extracted from course subtitles, there may be spelling errors, make sure to correct these, while using this information in your response.\n\n\n   There may be some previous discussion with the learner on this thread. Here is the python list of past discussions: {thread} . \n   In this thread, the content which starts with 'learner' is the question by the student and the content which starts with 'support' \n   is the response given by you. Use this past discussion appropriatly to come with a great reply.\n\n\n   This is the full name of the learner: {learner_name}\n   Address each learner by their first name, if you are not sure what the first name is, simply start with Hi.\n   Also mention some appropriate and encouraging comforting lines at the end of the reponse, like \"hope you found this helpful\", \n   \"I hope this information is useful. Keep up the great work!\", \"Glad to assist! Feel free to reach out anytime.\" etc.\n\n\n   If you are not sure about the answer mention - \"Sorry, I am not sure about this, I will get back to you\"\n\n\n   \"\"\",\n   expected_output = \"A crisp accurate response to the query\",\n   agent=query_answer_agent)\n<\/code><\/pre>\n<p>Let\u2019s break down the task provided to the AI agent. The query handling involves processing {query}, which represents the learner\u2019s question. The response should be concise (under 100 words) and accurate. When using course content, {relevant_content} is extracted from subtitles stored in ChromaDB, and the AI must correct any spelling errors before including the content in its response.<\/p>\n<p>If past discussions exist, {thread} helps maintain continuity. Learner queries start with \u201clearner\u201d, while past responses begin with \u201csupport\u201d, allowing the agent to provide context-aware answers. Personalization is achieved using {learner_name}\u2014the agent\u00a0 addresses students by their first name or defaults to \u201cHi\u201d if uncertain.<\/p>\n<p>To make responses more engaging, the AI adds a positive closing statement, such as \u201cHope you found this helpful!\u201d or \u201cFeel free to reach out anytime.\u201d If the AI is unsure about an answer, it explicitly states: \u201cSorry, I am not sure about this, I will get back to you.\u201d This approach ensures politeness, clarity, and a structured response format, enhancing learner engagement and trust.<\/p>\n<h4 class=\"wp-block-heading\" id=\"h-step-3-initializing-the-crewai-instance\">Step 3: Initializing the CrewAI Instance<\/h4>\n<p>Now that we have both the agent and the task, we initialize CrewAI, which enables the agent to process queries dynamically.<\/p>\n<pre class=\"wp-block-code\"><code># Create the Crew\nresponse_crew = Crew(\n   agents=[query_answer_agent],\n   tasks=[query_answering_task],\n   verbose=False\n)\n<\/code><\/pre>\n<p>The agents=[query_answer_agent] parameter adds the Learning Support Specialist agent to the crew. The tasks=[query_answering_task] assigns the query answering task to this agent. Setting verbose=False keeps the output minimal unless debugging is needed. CrewAI enables the system to process multiple learner queries simultaneously, making it scalable and efficient for dynamic query handling.<\/p>\n<p><strong>Why Use CrewAI for Query Answering?<\/strong><\/p>\n<ul class=\"wp-block-list\">\n<li><strong>Structured Responses:<\/strong> Ensures that each response is well-organized and informative.<\/li>\n<li><strong>Context Awareness:<\/strong> Utilizes retrieved course material and past discussions to improve response quality.<\/li>\n<li><strong>Scalability:<\/strong> Can handle multiple queries dynamically by processing them as tasks within CrewAI.<\/li>\n<li><strong>Efficiency:<\/strong> Reduces response time by streamlining the query resolution workflow.<\/li>\n<\/ul>\n<p>By implementing this AI-powered answering system, learners receive well-informed responses tailored to their specific queries.<\/p>\n<h4 class=\"wp-block-heading\" id=\"h-step-4-generating-responses-for-multiple-learner-s-queries\">Step 4: Generating Responses for Multiple Learner\u2019s Queries<\/h4>\n<p>Once the AI agent is set up, it needs to dynamically process learner queries stored in a structured dataset.<\/p>\n<p>The below code processes learner queries stored in a CSV file and generates responses using an AI agent. It first loads the dataset containing learner queries, course details, and discussion threads. The reply_to_query function extracts relevant details like the learner\u2019s name, course name, and current query. If previous discussions exist, they are retrieved for context. If the query contains an image, it is skipped. The function then fetches related course materials from ChromaDB and sends the query, relevant content, and past discussions to the AI agent for generating a structured response.<\/p>\n<pre class=\"wp-block-code\"><code>df = pd.read_csv(filepath_or_buffer=\"C:\\M\\Code\\GAI\\Learn_queries\/filtered_data_top3_courses.csv\")\ndef reply_to_query(df_new=df_new, index=1):\n   learner_name = df_new.iloc[index][\"thread_starter\"]\n   course_name = df_new.iloc[index][\"course\"]\n   if df_new.iloc[index]['number_of_replies']&gt;1:\n       thread = ast.literal_eval(df_new.iloc[index][\"modified_thread\"])\n   else:\n       thread = []\n   question = df_new.iloc[index][\"current_query\"]\n   if df_new.iloc[index]['has_image'] == True:\n       return \" \"\n  \n\n\n   context = retrieve_course_materials(query = question , course=course_name)\n\n\n   response_result = response_crew.kickoff(inputs={\"query\": question, \"relevant_content\": context, \"thread\": thread, \"learner_name\": learner_name})\n   print('Q: ', question)\n   print('\\n')\n   print('A: ', response_result)\n   print('\\n\\n')<\/code><\/pre>\n<p>Testing the function, it is executed for one query (index=1)<\/p>\n<pre class=\"wp-block-code\"><code>reply_to_query(df, index=1)<\/code><\/pre>\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"308\" src=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output3-1.webp\" alt=\"sample query output\" class=\"wp-image-225862\" srcset=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output3-1.webp 640w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output3-1-300x144.webp 300w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output3-1-150x72.webp 150w\" sizes=\"auto, (max-width: 640px) 100vw, 640px\"\/><\/figure>\n<p>From this we can see that it works fine just for one index.<\/p>\n<p>Now, iterating through all queries, processing each one while handling potential errors. This ensures efficient automation of query resolution, allowing multiple learner queries to be processed dynamically.<\/p>\n<pre class=\"wp-block-code\"><code>for i in range(len(df)):\n   try:\n       reply_to_query(df, index=i)\n   except:\n       print(\"Error in index number: \", i)\n       continue<\/code><\/pre>\n<p><strong>Why is This Step Important?<\/strong><\/p>\n<ul class=\"wp-block-list\">\n<li><strong>Automates Query Processing:<\/strong> The system can handle multiple learner queries efficiently.<\/li>\n<li><strong>Ensures Contextual Relevance:<\/strong> Responses are generated based on retrieved course materials and past discussions.<\/li>\n<li><strong>Scalability:<\/strong> The method allows the AI agent to process and respond to thousands of queries dynamically.<\/li>\n<li><strong>Improved Learning Support:<\/strong> Learners receive personalized, data-driven responses to their queries.<\/li>\n<\/ul>\n<p>This step ensures that every learner query is analyzed, contextualized, and answered effectively, enhancing the overall learning experience.<\/p>\n<p><strong>Output:<\/strong><\/p>\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"968\" height=\"456\" src=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output4-1.webp\" alt=\"sample output\" class=\"wp-image-225863\" srcset=\"https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output4-1.webp 968w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output4-1-300x141.webp 300w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output4-1-768x362.webp 768w, https:\/\/cdn.analyticsvidhya.com\/wp-content\/uploads\/2025\/03\/Output4-1-150x71.webp 150w\" sizes=\"auto, (max-width: 968px) 100vw, 968px\"\/><\/figure>\n<p>From the output we can see that the process of replying to the query has become automated\u00a0 followed by question and then answer.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-future-improvements\">Future Improvements<\/h2>\n<p>To upgrade the RAG-Based Query Resolution System, several enhancements can be made:<\/p>\n<ul class=\"wp-block-list\">\n<li><strong>Common Questions and Their Solutions:<\/strong> Implementing a structured FAQ system within the query resolution framework will help in providing instant answers to frequently asked questions, reducing dependency on live support.<\/li>\n<li><strong>Image Processing Ability:<\/strong> Adding the capability to analyze and extract relevant information from images (such as screenshots, charts, or scanned documents) will enhance the system\u2019s versatility, making it more useful in educational and customer support domains.<\/li>\n<li><strong>Improving the Image Column Boolean:<\/strong> Refining the logic behind the image column detection to correctly identify and process image-based queries with greater accuracy.<\/li>\n<li><strong>Semantic Chunking and Different Chunking Techniques:<\/strong> Experimenting with various chunking strategies, such as semantic chunking, fixed-length segmentation, and hybrid approaches, can improve retrieval accuracy and contextual understanding of responses.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"h-conclusion\">Conclusion<\/h2>\n<p>This RAG-Based Query Resolution System leverages LangChain, ChromaDB, and CrewAI to automate learner support efficiently. It extracts subtitles, stores them as embeddings in ChromaDB, and retrieves relevant content using similarity search. A CrewAI agent processes queries, references past discussions, and generates structured responses, ensuring accuracy and personalization.<\/p>\n<p>The system enhances scalability, retrieval efficiency, and response quality, making self-paced learning more interactive. Future improvements include multi-modal support, better retrieval optimization, and enhanced response generation. By automating query resolution, this system streamlines learning support, providing learners with faster, context-aware responses and improving overall engagement.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-frequently-asked-questions\">Frequently Asked Questions<\/h2>\n<div class=\"schema-faq wp-block-yoast-faq-block\">\n<div class=\"schema-faq-section\" id=\"faq-question-1741682428452\"><strong class=\"schema-faq-question\">Q1. What is LangChain, and why is it used in this project?<\/strong> <\/p>\n<p class=\"schema-faq-answer\">A. LangChain is a framework for building applications powered by language models (LLMs). It helps in processing, retrieving, and generating responses from text-based data. In this project, LangChain is used for splitting text into chunks, generating embeddings, and retrieving course materials efficiently.<\/p>\n<\/p><\/div>\n<div class=\"schema-faq-section\" id=\"faq-question-1741682437132\"><strong class=\"schema-faq-question\">Q2. How does ChromaDB store and retrieve course content?<\/strong> <\/p>\n<p class=\"schema-faq-answer\">A. ChromaDB is a vector database designed for storing and retrieving embeddings. It converts course materials into numerical representations, allowing similarity-based searches to find relevant content when a learner submits a query.<\/p>\n<\/p><\/div>\n<div class=\"schema-faq-section\" id=\"faq-question-1741682445499\"><strong class=\"schema-faq-question\">Q3. What role does CrewAI play in answering learner queries?<\/strong> <\/p>\n<p class=\"schema-faq-answer\">A. CrewAI enables the creation of AI agents that handle tasks dynamically. In this project, it powers a Learning Support Specialist agent that retrieves course materials, processes past discussions, and generates structured responses for learner queries.<\/p>\n<\/p><\/div>\n<div class=\"schema-faq-section\" id=\"faq-question-1741682466585\"><strong class=\"schema-faq-question\">Q4. Why are OpenAI embeddings used for text processing?<\/strong> <\/p>\n<p class=\"schema-faq-answer\">A. OpenAI embeddings convert text into numerical vectors, making it easier to perform similarity searches. This helps in efficiently retrieving relevant course materials based on a learner\u2019s query.<\/p>\n<\/p><\/div>\n<div class=\"schema-faq-section\" id=\"faq-question-1741682478830\"><strong class=\"schema-faq-question\">Q5. How does the system process subtitles (SRT files)?<\/strong> <\/p>\n<p class=\"schema-faq-answer\">A. The system uses pysrt to extract text from subtitle (SRT) files. The extracted content is then chunked, embedded using OpenAI embeddings, and stored in ChromaDB for retrieval when needed.<\/p>\n<\/p><\/div>\n<div class=\"schema-faq-section\" id=\"faq-question-1741682488381\"><strong class=\"schema-faq-question\">Q6. Can this system handle multiple queries at once?<\/strong> <\/p>\n<p class=\"schema-faq-answer\">A. Yes, the system is scalable and can process multiple learner queries dynamically using CrewAI\u2019s task management. This ensures quick and efficient responses.<\/p>\n<\/p><\/div>\n<div class=\"schema-faq-section\" id=\"faq-question-1741682498968\"><strong class=\"schema-faq-question\">Q7. What future improvements can be made to this system?<\/strong> <\/p>\n<p class=\"schema-faq-answer\">A. Future enhancements include multi-modal support for images and videos, better retrieval optimization, and improved response generation techniques to provide even more accurate and contextual answers.<\/p>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"border-top py-3 author-info my-4\">\n<div class=\"author-card d-flex align-items-center\">\n<div class=\"flex-shrink-0 overflow-hidden\">\n                                    <a href=\"https:\/\/www.analyticsvidhya.com\/blog\/author\/janvikumari01\/\" class=\"text-decoration-none active-avatar\"><br \/>\n                                                                       <img decoding=\"async\" src=\"https:\/\/av-eks-lekhak.s3.amazonaws.com\/media\/lekhak-profile-images\/converted_image_ToTu2tx.webp\" width=\"48\" height=\"48\" alt=\"Janvi Kumari\" loading=\"lazy\" class=\"rounded-circle\"\/><\/p>\n<p>                                <\/a>\n                                <\/div>\n<\/p><\/div>\n<p>Hi, I am Janvi, a passionate data science enthusiast currently working at Analytics Vidhya. My journey into the world of data began with a deep curiosity about how we can extract meaningful insights from complex datasets.<\/p>\n<\/p><\/div>\n<\/p><\/div>\n<p><h4 class=\"fs-24 text-dark\">Login to continue reading and enjoy expert-curated content.<\/h4>\n<p>                        <button class=\"btn btn-primary mx-auto d-table\" data-bs-toggle=\"modal\" data-bs-target=\"#loginModal\" id=\"readMoreBtn\">Keep Reading for Free<\/button>\n                    <\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>Businesses today handle a large volume of queries from customers, sales teams, and internal stakeholders. Manually responding to these queries is a slow and inefficient process, often leading to delays and inconsistent answers. A query resolution system powered by AI ensures fast, accurate, and scalable responses. It works by retrieving relevant information and generating precise [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":126612,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12033],"tags":[2539,37075,44762,41328,19578,2345],"dealstore":[],"offerexpiration":[],"class_list":["post-126611","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-analytics","tag-building","tag-langchain","tag-query","tag-ragbased","tag-resolution","tag-system"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Building a RAG-based Query Resolution System with LangChain - Som2ny Network<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/fivemor.com\/?p=126611\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Building a RAG-based Query Resolution System with LangChain - Som2ny Network\" \/>\n<meta property=\"og:description\" content=\"Businesses today handle a large volume of queries from customers, sales teams, and internal stakeholders. Manually responding to these queries is a slow and inefficient process, often leading to delays and inconsistent answers. A query resolution system powered by AI ensures fast, accurate, and scalable responses. It works by retrieving relevant information and generating precise [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/fivemor.com\/?p=126611\" \/>\n<meta property=\"og:site_name\" content=\"Som2ny Network\" \/>\n<meta property=\"article:published_time\" content=\"2025-03-11T16:18:25+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1744\" \/>\n\t<meta property=\"og:image:height\" content=\"947\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"admin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"23 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/fivemor.com\/?p=126611#article\",\"isPartOf\":{\"@id\":\"https:\/\/fivemor.com\/?p=126611\"},\"author\":{\"name\":\"admin\",\"@id\":\"https:\/\/fivemor.com\/#\/schema\/person\/b85e3c3dc0e1daea076524dc8810c371\"},\"headline\":\"Building a RAG-based Query Resolution System with LangChain\",\"datePublished\":\"2025-03-11T16:18:25+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/fivemor.com\/?p=126611\"},\"wordCount\":3469,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/fivemor.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/fivemor.com\/?p=126611#primaryimage\"},\"thumbnailUrl\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp\",\"keywords\":[\"Building\",\"LangChain\",\"Query\",\"RAGBased\",\"Resolution\",\"SYSTEM\"],\"articleSection\":[\"Analytics\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/fivemor.com\/?p=126611#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/fivemor.com\/?p=126611\",\"url\":\"https:\/\/fivemor.com\/?p=126611\",\"name\":\"Building a RAG-based Query Resolution System with LangChain - Som2ny Network\",\"isPartOf\":{\"@id\":\"https:\/\/fivemor.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/fivemor.com\/?p=126611#primaryimage\"},\"image\":{\"@id\":\"https:\/\/fivemor.com\/?p=126611#primaryimage\"},\"thumbnailUrl\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp\",\"datePublished\":\"2025-03-11T16:18:25+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/fivemor.com\/?p=126611#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/fivemor.com\/?p=126611\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/fivemor.com\/?p=126611#primaryimage\",\"url\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp\",\"contentUrl\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp\",\"width\":1744,\"height\":947},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/fivemor.com\/?p=126611#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/fivemor.com\/?bp_activities=1\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Building a RAG-based Query Resolution System with LangChain\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/fivemor.com\/#website\",\"url\":\"https:\/\/fivemor.com\/\",\"name\":\"Som2ny Network\",\"description\":\"Daily Deals\",\"publisher\":{\"@id\":\"https:\/\/fivemor.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/fivemor.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/fivemor.com\/#organization\",\"name\":\"Som2ny Network\",\"url\":\"https:\/\/fivemor.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/fivemor.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png\",\"contentUrl\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png\",\"width\":300,\"height\":86,\"caption\":\"Som2ny Network\"},\"image\":{\"@id\":\"https:\/\/fivemor.com\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/fivemor.com\/#\/schema\/person\/b85e3c3dc0e1daea076524dc8810c371\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/fivemor.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Ffivemor.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Ffivemor.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png\",\"caption\":\"admin\"},\"sameAs\":[\"https:\/\/fivemor.com\"],\"url\":\"https:\/\/fivemor.com\/?author=1\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Building a RAG-based Query Resolution System with LangChain - Som2ny Network","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/fivemor.com\/?p=126611","og_locale":"en_US","og_type":"article","og_title":"Building a RAG-based Query Resolution System with LangChain - Som2ny Network","og_description":"Businesses today handle a large volume of queries from customers, sales teams, and internal stakeholders. Manually responding to these queries is a slow and inefficient process, often leading to delays and inconsistent answers. A query resolution system powered by AI ensures fast, accurate, and scalable responses. It works by retrieving relevant information and generating precise [&hellip;]","og_url":"https:\/\/fivemor.com\/?p=126611","og_site_name":"Som2ny Network","article_published_time":"2025-03-11T16:18:25+00:00","og_image":[{"width":1744,"height":947,"url":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp","type":"image\/webp"}],"author":"admin","twitter_card":"summary_large_image","twitter_misc":{"Written by":"admin","Est. reading time":"23 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/fivemor.com\/?p=126611#article","isPartOf":{"@id":"https:\/\/fivemor.com\/?p=126611"},"author":{"name":"admin","@id":"https:\/\/fivemor.com\/#\/schema\/person\/b85e3c3dc0e1daea076524dc8810c371"},"headline":"Building a RAG-based Query Resolution System with LangChain","datePublished":"2025-03-11T16:18:25+00:00","mainEntityOfPage":{"@id":"https:\/\/fivemor.com\/?p=126611"},"wordCount":3469,"commentCount":0,"publisher":{"@id":"https:\/\/fivemor.com\/#organization"},"image":{"@id":"https:\/\/fivemor.com\/?p=126611#primaryimage"},"thumbnailUrl":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp","keywords":["Building","LangChain","Query","RAGBased","Resolution","SYSTEM"],"articleSection":["Analytics"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/fivemor.com\/?p=126611#respond"]}]},{"@type":"WebPage","@id":"https:\/\/fivemor.com\/?p=126611","url":"https:\/\/fivemor.com\/?p=126611","name":"Building a RAG-based Query Resolution System with LangChain - Som2ny Network","isPartOf":{"@id":"https:\/\/fivemor.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/fivemor.com\/?p=126611#primaryimage"},"image":{"@id":"https:\/\/fivemor.com\/?p=126611#primaryimage"},"thumbnailUrl":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp","datePublished":"2025-03-11T16:18:25+00:00","breadcrumb":{"@id":"https:\/\/fivemor.com\/?p=126611#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/fivemor.com\/?p=126611"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/fivemor.com\/?p=126611#primaryimage","url":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp","contentUrl":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/Artboard-1-copy-21.webp.webp","width":1744,"height":947},{"@type":"BreadcrumbList","@id":"https:\/\/fivemor.com\/?p=126611#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/fivemor.com\/?bp_activities=1"},{"@type":"ListItem","position":2,"name":"Building a RAG-based Query Resolution System with LangChain"}]},{"@type":"WebSite","@id":"https:\/\/fivemor.com\/#website","url":"https:\/\/fivemor.com\/","name":"Som2ny Network","description":"Daily Deals","publisher":{"@id":"https:\/\/fivemor.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/fivemor.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/fivemor.com\/#organization","name":"Som2ny Network","url":"https:\/\/fivemor.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/fivemor.com\/#\/schema\/logo\/image\/","url":"https:\/\/fivemor.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png","contentUrl":"https:\/\/fivemor.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png","width":300,"height":86,"caption":"Som2ny Network"},"image":{"@id":"https:\/\/fivemor.com\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/fivemor.com\/#\/schema\/person\/b85e3c3dc0e1daea076524dc8810c371","name":"admin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/fivemor.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Ffivemor.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Ffivemor.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png","caption":"admin"},"sameAs":["https:\/\/fivemor.com"],"url":"https:\/\/fivemor.com\/?author=1"}]}},"_links":{"self":[{"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/posts\/126611","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=126611"}],"version-history":[{"count":0,"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/posts\/126611\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/media\/126612"}],"wp:attachment":[{"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=126611"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=126611"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=126611"},{"taxonomy":"dealstore","embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fdealstore&post=126611"},{"taxonomy":"offerexpiration","embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fofferexpiration&post=126611"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}