{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "John Adeojo",
  "title_listed": "Build More Capable LLMs with Retrieval Augmented Generation",
  "keywords": "",
  "domain": "大模型算法",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/build-more-capable-llms-with-retrieval-augmented-generation-99d5f86e9779/",
  "publish_date": "2023-08-09",
  "corpus_stage": "",
  "notes": "",
  "id": "e5a51520cfd6",
  "collected_at": "2026-10-02T06:47:57",
  "title": "Build More Capable LLMs with Retrieval Augmented Generation | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# Build More Capable LLMs with Retrieval Augmented Generation\nHow Retrieval Augmented Generation Can Enhance Your LLMs by Integrating a Knowledge Base\n[John Adeojo](https://towardsdatascience.com/author/johnadeojo/)\nAugust 8, 202312 min read\n![Image by author: Generated with Midjourney](../images/000.png)\nImage by author: Generated with Midjourney\n## **The Limitations of ChatGPT**\nChatGPT is limited for many practical business use cases outside of code generation. The limitation arises from the training data, and the model's propensity to hallucinate. At the time of writing, if you try to ask the Chat-GPT questions about events occurring after September 2021, you will probably receive a response like this:\n![Image by author](../images/001.png)\nImage by author\nThis isn't helpful, so how can we go about rectifying it?\n**Option 1 - Train or fine-tune the model on up-to-date data.**\nFine-tuning or training a model can be impractical and expensive. Putting aside the costs, the effort required to prepare the data sets is enough to forgo this option.\n**Option 2 - Use retrieval augmented generation (RAG) methods.**\nRAG methods enable us to give the large language model access to an up-to-date knowledge base. This is much cheaper than training a model from scratch or fine-tuning, and much easier to implement. In this article, I show you how to leverage RAG with your OpenAI model. We will put the model to the test by conducting a short analysis of its ability to answer questions about the Russia-Ukraine conflict of 2022 from a [Wikipedia](https://en.wikipedia.org/wiki/Russian_invasion_of_Ukraine) knowledge base.\n_Note: This topic, although sensitive, was chosen for the obvious reason that the current ChatGPT model has no knowledge of it._\n* * *\n## **Libraries & Pre-requisites**\nYou will require an OpenAI API key, you can grab one directly from their website or follow this [tutorial](https://www.howtogeek.com/885918/how-to-get-an-openai-api-key/). The framework used for RAG is [Haystack](https://haystack.deepset.ai/) by Deepset, which is open source. They provide APIs enabling you to build applications on top of large language models. We also leverage sentence transformers and the transformers library from [Hugging Face](https://huggingface.co/).\n* * *\n## **Sentence Embeddings Help Models Interpret Text**\nBefore getting into the technical details around building, we should briefly cover sentence embedding. Understanding this concept is key to gaining an intuition into how RAG methods work.\nThis may be a cliché, especially for those from a data science background, but models don't actually understand text, they only understand numbers. Much of language modelling is about formulating ways to effectively encode text into numbers, and currently, we do this with sentence embeddings.\nSentence embeddings are a way for us to represent sentences as a dense vector while preserving the semantic structure. Embeddings are learnt from a dense layer in a deep neural network, the structure of which can vary from network to network.\nIn much simpler terms, sentence embeddings can be thought of as numeric representations of our sentences that preserve information about their meaning. We can get our sentence embeddings from pre-trained models. Hugging Face provides open-source models for this via their sentence transformers library.\n## **Pre-processing and Storage**\nBefore we can build our RAG-enabled model, we need to pre-process and store our documents. Let's explore how we do this, but first take note of the architecture of this process to help with your understanding.\n_Note: the architectural diagram also applies to the extractive question answer pipeline we define in the next section._\n![Image by author: High level architecture pre-processing, vectore store, and extractive question-answer pipeline](../images/002.png)\nImage by author: High level architecture pre-processing, vectore store, and extractive question-answer pipeline\n### Pre-processing our Documents\nHaystack provides us tools for easily pre-processing most types of text documents (.pdf, .txt, .docx included). The preprocessing steps are simple; we read in our knowledge base using the [convert_files_to_docs()](https://docs.haystack.deepset.ai/reference/utils-api#convert_files_to_docs:~:text=Module%20preprocessing-,convert_files_to_docs,-Python) function, which can automatically detect the file type and convert it to the format we need to work with downstream.\nHaystack also provides a [PreProcessor](https://docs.haystack.deepset.ai/reference/preprocessor-api#preprocessor::text=Module%20preprocessor-,PreProcessor,-Python:~:text=Module%20preprocessor-,PreProcessor,-Python) class that enables us to apply preprocessing steps to our documents. The steps you apply will depend very much on your specific application.\n_Note: the processor will enable you to split a long document into a list of smaller documents, defined as sentences. For question-and-answer applications, a common approach is to have some overlap between sentences; I have set this at roughly 30%._\n### **Vector Store**\nWe leverage [FAISS](https://engineering.fb.com/2017/03/29/data-infrastructure/faiss-a-library-for-efficient-similarity-search/), a library by Meta that enables efficient similarity search over our sentence embeddings. The importance of this will become more obvious in the coming sections. The script below shows how we can set up our pre-process for our text documents and set up the FAISS vector store.\nThe full pre-processing script is outlined below:\n* * *\n## **Defining an Extractive Question-Answer Pipeline**\nThe next step is to construct our extractive question answer pipeline. Our pipeline is defined by nodes which are run sequentially as a directed acyclic graph (DAG). In this case, the pipeline consists of two nodes, a retriever, and a reader.\n### Retriever\nRetrieval is the method used to find the relevant information from a knowledge base based on the user's query. When defining our retriever node, we specify a sentence embedding model from the sentence transformers library, in this case, we use [all-mpnet-base-v2](https://huggingface.co/sentence-transformers/all-mpnet-base-v2), which creates 768-dimensional embeddings.\nOnce we have fully defined our retrieval node, we can compute and store the sentence embeddings in our FAISS vector store. The same sentence embedding model is used to generate sentence embeddings for the user's query.\n_Note: when selecting your sentence embedding model, there is a trade-off between computational efficiency and information loss. In general, sentence embedding models with higher dimensions capture more information but are less computationally efficient._\nRemember, the ultimate purpose of the retriever node is to find the information that relates semantically to the query. This is done by performing a similarity search between the sentence embeddings from the query and the documents in our vector store. The top-k most relevant sentence embeddings are returned as an output from this node.\n### Reader\nThe reader node is a large language model that has been fine-tuned on question-answering tasks. For our use case, we leverage [Roberta-base-squad2](https://huggingface.co/deepset/roberta-base-squad2) as our reader model. The reader operates on the output from the retriever and the initial query from the user and returns the relevant span of text to answer the query. The reader will do this for each document in the retriever output, allocating a confidence score in each case. The answers are ranked by their score, and the top-k answers are returned.\nThe full script for the pipeline is outlined below:\n* * *\n## **Leveraging LLM-Powered Agents**\nNow that we have pre-processed our documents and defined our pipeline, we can construct our agent. An agent is powered by a large language model, in our case, OpenAI's gpt-4 (or gpt-3.5-turbo alternatively).\nThe agent we are using works on the basis of Zero-shot [ReAcT](https://www.promptingguide.ai/techniques/react) (Reason + Act) prompting. We prompt the large language model to return verbal reasoning traces and actions for a task. The agent can \"act\" on the verbal reasoning traces using a set of tools we provide it access to. The agent can observe and reason about the output from using the tools, helping it to inform its next action.\nThe animation below gives a simplified view of our ReAct agent at work.\n![Gif by author: Simplified view of a our agent at work](../images/003.gif)\nGif by author: Simplified view of a our agent at work\n _Note:_[_Research_](https://arxiv.org/pdf/2210.03629.pdf) _suggests that ReAct prompting has been shown to effectively reduce hallucinations by LLMs._\nThe script below shows how we construct our agent:\nIn this use case, the tool we have provided the agent is the extractive question-answer pipeline we defined earlier. Essentially the agent can interpret our query, use our pipeline as a tool to find the relevant responses in our knowledge base, reason to see if this answers the query, choose to respond, or perform the action again to get a better answer.\n### A Brief Note on Tools\nIt's important that we define our tools clearly. For our particular use case, we only have one tool, but we need to provide a description of that tool so that the LLM-powered agent knows how and when to use the tool. This becomes even more important when an agent has access to more than just one tool.\n* * *\n## **Putting it to the Test**\nSo we have defined our RAG-enabled model; let's put it to the test by asking it trivia on the Russia-Ukraine conflict of 2022. I have chosen two questions, each of which can be answered with information from the wikipedia knowledge base. As well as the responses I provide the workflow trace for each agent, you should inspect this carefully to gain a better insight into how the ReAct prompting works with the agent.\n> How did the international community respond to Russia's invasion of Ukraine in 2022?\nResponse from the RAG enabled model:\n> The international community responded to Russia's invasion of Ukraine in 2022 with condemnation and the imposition of new sanctions. These sanctions were comprehensive, affecting individuals, banks, businesses, and various types of economic activity including monetary exchanges, bank transfers, exports, and imports. Some of the specific measures included prison sentences of up to 15 years.\n_Note: The prison sentence for up to 15 years appears to be a hallucination. The model has mistakenly suggested this as a sanction measure._\n![Gif by author: Response to the question &quot;How did the international community respond to Russia&#039;s invasion of Ukraine in 2022?&quot;](../images/004.gif)\nGif by author: Response to the question \"How did the international community respond to Russia's invasion of Ukraine in 2022?\"\nResponse from Google search:\n![Image by author: Response from Google search for &quot;How did the international community respond to Russia&#039;s invasion of Ukraine in 2022?&quot;](../images/005.png)\nImage by author: Response from Google search for \"How did the international community respond to Russia's invasion of Ukraine in 2022?\"\nHere's the trace tracking the agent's workflow:\nbash\n\n```\nAgent custom-at-query-time started with \n{'query':\n'How did the international community respond to\nRussia's invasion of Ukraine in 2022?', 'params': None}\nThe 'transcript' parameter is missing from\nthe Agent's prompt template. All ReAct agents\nthat go through multiple steps to reach\na goal require this parameter. Please append\n{transcript} to the end of the Agent's\nprompt template to ensure its proper functioning.\nA temporary prompt template with {transcript} appended\nwill be used for this run.\nfind out the details about the international\ncommunity's response to Russia's invasion of Ukraine\nin 2022.\nI don't have this information readily available,\nso I will use the document_qa tool to\nfind it.\nTool: document_qa\nTool Input: \"International community response to Russia's invasion of Ukraine\nin 2022\"\nBatches: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 13.05it/s]\nInferencing Samples: 100%|█████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:09<00:00, 9.98s/ Batches]\nObservation: 308\nThought: The document_qa tool provided a response\ncode of 308, which is not informative.\nI need to try again to get\nthe required information.\nTool: document_qa\nTool Input: \"How did the international community respond to Russia's invasion\nof Ukraine in 2022?\"\nBatches: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 9.72it/s]\nInferencing Samples: 100%|█████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:07<00:00, 7.78s/ Batches]\nObservation: condemnation\nThought: The document_qa tool responded with \"condemnation\".\nThis suggests that the international community condemned\nRussia's invasion of Ukraine in 2022. However,\nthis is a very broad response and\ndoesn't provide specific details about the actions\ntaken by the international community. I need\nto find more detailed information.\nTool: document_qa\nTool Input: \"What specific actions did the international community take in response to Russia's invasion of Ukraine in 2022?\"\nBatches: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 13.41it/s]\nInferencing Samples: 100%|█████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:07<00:00, 7.95s/ Batches]\nObservation: new sanctions\nThought: The document_qa tool responded with \"new\nsanctions\". This suggests that the international community\nimposed new sanctions on Russia in response\nto their invasion of Ukraine in 2022.\nHowever, this still doesn't provide a comprehensive\npicture of the international community's response. I\nneed to find more detailed information.\nTool: document_qa\nTool Input: \"What were the new sanctions imposed by the international community on Russia in 2022?\"\nBatches: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 12.66it/s]\nInferencing Samples: 100%|█████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:10<00:00, 10.77s/ Batches]\nObservation: prison sentences of up to 15 years\nThought: The document_qa tool responded with \"prison\nsentences of up to 15 years\". This\nsuggests that part of the sanctions imposed\nby the international community on Russia in\n2022 included prison sentences of up to\n15 years. However, this seems to be\na specific measure and may not represent\nthe full range of sanctions. I need\nto find more detailed information.\nTool: document_qa\nTool Input: \"What other sanctions were imposed by the international community on Russia in 2022?\"\nObservation: individuals, banks, businesses, monetary     exchanges,\nbank transfers, exports, and imports\nObservation: individuals, banks, businesses, monetaryexchanges, bank transfers,\nexports, and importsThought: The document_qa tool responded\nwith \"individuals, banks, businesses, monetary exchanges, bank\ntransfers, exports, and imports\". This suggests that\nthe sanctions imposed by the international community\non Russia in 2022 were comprehensive, affecting\nindividuals, banks, businesses, and various types of\neconomic activity including monetary exchanges, bank transfers,\nexports, and imports.\nFinal Answer: The international community responded\nto Russia's invasion of Ukraine in 2022\nwith condemnation and the imposition of new\nsanctions. These sanctions were comprehensive, affecting individuals,\nbanks, businesses, and various types of economic\nactivity including monetary exchanges, bank transfers, exports,\nand imports. Some of the specific measures\nincluded prison sentences of up to 15 years.\n```\n\n> Who led the IAEA team that investigated the plant on 29 August 2022?\nResponse from the RAG enabled model:\n> Rafael Grossi led the IAEA team that investigated the plant on 29 August 2022.\n![Gif by author: Response to the question &quot;Who led the IAEA team that investigated the plant on 29 August 2022?&quot;](../images/006.gif)\nGif by author: Response to the question \"Who led the IAEA team that investigated the plant on 29 August 2022?\"\nResponse from Google search:\n![Image by author: Response from Google search for &quot;Who led the IAEA team that investigated the plant on 29 August 2022?&quot;](../images/007.png)\nImage by author: Response from Google search for \"Who led the IAEA team that investigated the plant on 29 August 2022?\"\nHere's the trace tracking the agent's workflow:\nbash\n\n```\nAgent custom-at-query-time started with {'query': 'Who\nled the IAEA team that investigated the\nplant on 29 Augustxa02022?', 'params': None}The 'transcript'\nparameter is missing from the Agent's prompt\ntemplate. All ReAct agents that go through\nmultiple steps to reach a goal require\nthis parameter. Please append {transcript} to the\nend of the Agent's prompt template to\nensure its proper functioning.\nA temporary prompt template with {transcript} appended will\nbe used for this run.\nfind out what the IAEA is and\nwhat plant was investigated on 29 August 2022.\nThen, I need to find out who led\nthe IAEA team during this investigation.\nI don't have this information at hand,\nso I will use the document_qa tool\nto find it.\nTool: document_qa\nTool Input: Who led the IAEA team that\ninvestigated the plant on 29 August 2022?\nObservation: Rafael Grossi\nThought: The document_qa tool has provided the name\nRafael Grossi in response to the query.\nThis suggests that Rafael Grossi led the\nIAEA team that investigated the plant on\n29 August 2022.\nFinal Answer: Rafael Grossi led the IAEA team\nthat investigated the plant on 29 August 2022.\n```\n\nFor your own curiosity, have a look at the [responses](https://chat.openai.com/share/af96d7f7-1408-422a-923f-ced160313828) from ChatGPT for the same questions. You can even try to ask the questions yourself to confirm the response.\n* * *\n## **Conclusion**\nRetrieval augmented generation (RAG) enables a large language model to connect with an existing knowledge base. RAG-enabled language models have access to up-to-date information, making them more useful across a variety of use cases.\nThe retriever and reader methods enable the models to query large corpuses of text, overcoming the issues faced by the limited context of large language models by themselves. Open-source frameworks like Haystack make it easy to build a RAG-enabled LLM prototype quickly.\nSome key points to note here are that the performance of this method is only as good as the knowledge base provided. Also, the inference time can be sped up dramatically by deploying the model on suitable infrastructure.\nFor more complex queries, agents may get into situations where they can't respond in the alotted amount of steps. It would be interesting to see how the quality of responses varies by increasing the amount of steps, or adding a memory component to make the pipeline more conversational. Leveraging a more heavy duty sentence embedding model could also serve to improve overall performance.\nThe code base is in the [GitHub](https://github.com/john-adeojo/haystack-lfqa) repo (including the front-end) and is available for you to experiment with.\nThere is also a [YouTube](https://youtu.be/-3MLqZppSCY) demo of project.\nThanks for reading.\n* * *\nIf you're keen to enhance your skills in artificial intelligence, join the waiting list for [my course](https://www.data-centric-solutions.com/course), where I will guide you through the process of developing large language model powered applications.\nIf you're seeking AI-transformation for your business, book a discovery call today.\n> [**Brainqub3 | AI software development**](https://www.brainqub3.com/)\nFor more insights on artificial intelligence, data science, and large language models you can subscribe to the [YouTube](https://www.youtube.com/channel/UCkXe-exqi25V4GnZendgEaA) channel.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-ead068aa953e7b688a96.png)\nWritten By\n## [John Adeojo](https://towardsdatascience.com/author/johnadeojo/)\n[See all from John Adeojo](https://towardsdatascience.com/author/johnadeojo/)\n[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Large Language Models](https://towardsdatascience.com/tag/large-language-models/)[NLP](https://towardsdatascience.com/tag/nlp/)[Prompt Engineering](https://towardsdatascience.com/tag/prompt-engineering/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-more-capable-llms-with-retrieval-augmented-generation-99d5f86e9779%2F&title=Build%20More%20Capable%20LLMs%20with%20Retrieval%20Augmented%20Generation)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-more-capable-llms-with-retrieval-augmented-generation-99d5f86e9779%2F&title=Build%20More%20Capable%20LLMs%20with%20Retrieval%20Augmented%20Generation)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-more-capable-llms-with-retrieval-augmented-generation-99d5f86e9779%2F&text=Build%20More%20Capable%20LLMs%20with%20Retrieval%20Augmented%20Generation)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/008.jpg)](https://towardsdatascience.com/functional-time-series-83b717cca12/)\n## [Functional Time Series](https://towardsdatascience.com/functional-time-series-83b717cca12/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nWhen we measure data more frequently, how can we best analyze it? Functional Data Analysis (FDA) can simplify the analysis drastically.\n[Florian Heinrichs](https://towardsdatascience.com/author/florian.heinrichs/)\nJanuary 5, 202111 min read\n  * [![](../images/009.jpeg)](https://towardsdatascience.com/bayesian-optimization-for-hyperparameter-tuning-how-and-why-655b0ee0b399/)\n## [Hyperparameter Tuning Methods - Grid, Random or Bayesian Search?](https://towardsdatascience.com/bayesian-optimization-for-hyperparameter-tuning-how-and-why-655b0ee0b399/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA practical guide to hyperparameter optimization using three methods: grid, random and bayesian search (with skopt)\n[Maria Gorodetski](https://towardsdatascience.com/author/maria.gorodetski/)\nAugust 28, 20214 min read\n  * [![](../images/010.png)](https://towardsdatascience.com/the-best-way-to-generate-indices-in-bigquery-f3a09f71b175/)\n## [The Best Way to Generate Indices in BigQuery](https://towardsdatascience.com/the-best-way-to-generate-indices-in-bigquery-f3a09f71b175/)\n[Programming](https://towardsdatascience.com/category/programming/)\nUsing GENERATE_ARRAY for Histograms and More\n[Jye Sawtell-Rickson](https://towardsdatascience.com/author/jyesr/)\nMay 30, 20204 min read\n  * [![](../images/011.jpg)](https://towardsdatascience.com/dating-algorithms-using-machine-learning-and-ai-814b68ecd75e/)\n## [How to Use Machine Learning and AI to Make a Dating App](https://towardsdatascience.com/dating-algorithms-using-machine-learning-and-ai-814b68ecd75e/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nUtilizing Unsupervised Learning as a Dating Algorithm\n[Marco Santos](https://towardsdatascience.com/author/marco-santos/)\nMarch 8, 20202 min read\n  * [![](../images/012.jpg)](https://towardsdatascience.com/faq-as-rag-when-you-get-to-design-the-corpus/)\n## [FAQ as RAG: When You Get to Design the Corpus](https://towardsdatascience.com/faq-as-rag-when-you-get-to-design-the-corpus/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nEnterprise Document Intelligence [Vol.1 #B2] - The FAQ inverts every brick of the standard RAG pipeline. Parsing is trivial, retrieval doubles as a cache, and few-shot prompting becomes a retrieval problem too\n[Kezhan Shi](https://towardsdatascience.com/author/kezhanshi/)\nAugust 31, 202619 min read\n  * [![](../images/013.png)](https://towardsdatascience.com/fine-tune-a-transformer-model-for-grammar-correction-b5c8ca49cc26/)\n## [Fine-Tune a Transformer Model for Grammar Correction](https://towardsdatascience.com/fine-tune-a-transformer-model-for-grammar-correction-b5c8ca49cc26/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLearn how to train a Transformer model called T5 to be your very own grammar corrector\n[Eric Fillion](https://towardsdatascience.com/author/ericfillion/)\nAugust 18, 20219 min read\n  * [![](../images/014.png)](https://towardsdatascience.com/train-a-custom-object-detector-with-detectron2-and-fiftyone-4dc451839958/)\n## [Train a Custom Object Detector with Detectron2 and FiftyOne](https://towardsdatascience.com/train-a-custom-object-detector-with-detectron2-and-fiftyone-4dc451839958/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nCombine the dataset curation of FiftyOne with the model training of Detectron2 to easily train custom detection models\n[Eric Hofesmann](https://towardsdatascience.com/author/eric.hofesmann/)\nOctober 13, 20226 min read\n  * [![](../images/015.jpeg)](https://towardsdatascience.com/python-done-the-r-markdown-way-d03bec4b96b/)\n## [Python done the R (Markdown) way](https://towardsdatascience.com/python-done-the-r-markdown-way-d03bec4b96b/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nAre you an R user flirting with the idea of doing Python? I wrote an article that may be of your interest!\n[Vít Gabrhel](https://towardsdatascience.com/author/vitgabrhel/)\nAugust 24, 202010 min read\n  * [![](../images/016.jpg)](https://towardsdatascience.com/integrate-bias-detection-in-your-data-science-skill-set-982a699653f2/)\n## [Integrate Bias Detection in Your Data Science Skill Set](https://towardsdatascience.com/integrate-bias-detection-in-your-data-science-skill-set-982a699653f2/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nDon't forget that bias could impact your project\n[Cornellius Wijaya](https://towardsdatascience.com/author/cornelliusyudhawijaya/)\nAugust 4, 20229 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "Build More Capable LLMs with Retrieval Augmented Generation | Towards Data Science",
    "description": "How Retrieval Augmented Generation Can Enhance Your LLMs by Integrating a Knowledge Base",
    "keywords": null,
    "author": "John Adeojo",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Build More Capable LLMs with Retrieval Augmented Generation",
    "og:description": "How Retrieval Augmented Generation Can Enhance Your LLMs by Integrating a Knowledge Base",
    "og:url": "https://towardsdatascience.com/build-more-capable-llms-with-retrieval-augmented-generation-99d5f86e9779/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1R7f2_WPN-a8Czav39c9pUA.png",
    "og:image:width": "1024",
    "og:image:height": "1024",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "John Adeojo",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "12 min read",
    "article:published_time": "2023-08-08T23:36:06.000Z",
    "article:modified_time": "2023-08-08T23:36:06.000Z",
    "article:author": "https://towardsdatascience.com/author/johnadeojo/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/e5a51520cfd6/code/block_000.txt",
      "chars": 4782
    },
    {
      "language": "txt",
      "file": "attachments/e5a51520cfd6/code/block_001.txt",
      "chars": 1130
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:11:35Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:11:35Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:11:35Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:11:35Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/watch?v=-3MLqZppSCY",
      "status": "ok",
      "local_path": "attachments/e5a51520cfd6/videos/-3MLqZppSCY.mp4",
      "bytes": 205716036,
      "valid": true,
      "height": 1080,
      "width": 1920,
      "duration": "3429.501000"
    },
    {
      "url": "https://www.youtube.com/channel/UCkXe-exqi25V4GnZendgEaA",
      "kind": "channel_reference",
      "status": "reference_only"
    },
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/johnadeojo/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/large-language-models/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/nlp/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/prompt-engineering/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/functional-time-series-83b717cca12/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/florian.heinrichs/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/bayesian-optimization-for-hyperparameter-tuning-how-and-why-655b0ee0b399/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/maria.gorodetski/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/the-best-way-to-generate-indices-in-bigquery-f3a09f71b175/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Russian_invasion_of_Ukraine"
    },
    {
      "type": "external",
      "href": "https://www.howtogeek.com/885918/how-to-get-an-openai-api-key/"
    },
    {
      "type": "external",
      "href": "https://haystack.deepset.ai/"
    },
    {
      "type": "external",
      "href": "https://huggingface.co/"
    },
    {
      "type": "external",
      "href": "https://docs.haystack.deepset.ai/reference/utils-api"
    },
    {
      "type": "external",
      "href": "https://docs.haystack.deepset.ai/reference/preprocessor-api"
    },
    {
      "type": "external",
      "href": "https://engineering.fb.com/2017/03/29/data-infrastructure/faiss-a-library-for-efficient-similarity-search/"
    },
    {
      "type": "external",
      "href": "https://huggingface.co/sentence-transformers/all-mpnet-base-v2"
    },
    {
      "type": "external",
      "href": "https://huggingface.co/deepset/roberta-base-squad2"
    },
    {
      "type": "external",
      "href": "https://www.promptingguide.ai/techniques/react"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/pdf/2210.03629.pdf"
    },
    {
      "type": "external",
      "href": "https://chat.openai.com/share/af96d7f7-1408-422a-923f-ced160313828"
    },
    {
      "type": "external",
      "href": "https://github.com/john-adeojo/haystack-lfqa"
    },
    {
      "type": "external",
      "href": "https://youtu.be/-3MLqZppSCY"
    },
    {
      "type": "external",
      "href": "https://www.data-centric-solutions.com/course"
    },
    {
      "type": "external",
      "href": "https://www.brainqub3.com/"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/channel/UCkXe-exqi25V4GnZendgEaA"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:34:51Z",
  "source_url": "https://towardsdatascience.com/build-more-capable-llms-with-retrieval-augmented-generation-99d5f86e9779/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [
    {
      "local_path": "attachments/e5a51520cfd6/videos/-3MLqZppSCY.mp4",
      "bytes": 205716036,
      "valid": true,
      "height": 1080,
      "width": 1920,
      "duration": "3429.501000",
      "status": "ok"
    }
  ],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# Build More Capable LLMs with Retrieval Augmented Generation\nHow Retrieval Augmented Generation Can Enhance Your LLMs by Integrating a Knowledge Base\n[John Adeojo](https://towardsdatascience.com/author/johnadeojo/)\nAugust 8, 202312 min read\n![Image by author: Generated with Midjourney](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1R7f2_WPN-a8Czav39c9pUA.png)\nImage by author: Generated with Midjourney\n## **The Limitations of ChatGPT**\nChatGPT is limited for many practical business use cases outside of code generation. The limitation arises from the training data, and the model's propensity to hallucinate. At the time of writing, if you try to ask the Chat-GPT questions about events occurring after September 2021, you will probably receive a response like this:\n![Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1ahwX1w9hXth2eHI3uSKjRg.png)\nImage by author\nThis isn't helpful, so how can we go about rectifying it?\n**Option 1 - Train or fine-tune the model on up-to-date data.**\nFine-tuning or training a model can be impractical and expensive. Putting aside the costs, the effort required to prepare the data sets is enough to forgo this option.\n**Option 2 - Use retrieval augmented generation (RAG) methods.**\nRAG methods enable us to give the large language model access to an up-to-date knowledge base. This is much cheaper than training a model from scratch or fine-tuning, and much easier to implement. In this article, I show you how to leverage RAG with your OpenAI model. We will put the model to the test by conducting a short analysis of its ability to answer questions about the Russia-Ukraine conflict of 2022 from a [Wikipedia](https://en.wikipedia.org/wiki/Russian_invasion_of_Ukraine) knowledge base.\n_Note: This topic, although sensitive, was chosen for the obvious reason that the current ChatGPT model has no knowledge of it._\n* * *\n## **Libraries & Pre-requisites**\nYou will require an OpenAI API key, you can grab one directly from their website or follow this [tutorial](https://www.howtogeek.com/885918/how-to-get-an-openai-api-key/). The framework used for RAG is [Haystack](https://haystack.deepset.ai/) by Deepset, which is open source. They provide APIs enabling you to build applications on top of large language models. We also leverage sentence transformers and the transformers library from [Hugging Face](https://huggingface.co/).\n* * *\n## **Sentence Embeddings Help Models Interpret Text**\nBefore getting into the technical details around building, we should briefly cover sentence embedding. Understanding this concept is key to gaining an intuition into how RAG methods work.\nThis may be a cliché, especially for those from a data science background, but models don't actually understand text, they only understand numbers. Much of language modelling is about formulating ways to effectively encode text into numbers, and currently, we do this with sentence embeddings.\nSentence embeddings are a way for us to represent sentences as a dense vector while preserving the semantic structure. Embeddings are learnt from a dense layer in a deep neural network, the structure of which can vary from network to network.\nIn much simpler terms, sentence embeddings can be thought of as numeric representations of our sentences that preserve information about their meaning. We can get our sentence embeddings from pre-trained models. Hugging Face provides open-source models for this via their sentence transformers library.\n## **Pre-processing and Storage**\nBefore we can build our RAG-enabled model, we need to pre-process and store our documents. Let's explore how we do this, but first take note of the architecture of this process to help with your understanding.\n_Note: the architectural diagram also applies to the extractive question answer pipeline we define in the next section._\n![Image by author: High level architecture pre-processing, vectore store, and extractive question-answer pipeline](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1KZkyRZ5MBlS-L-g2NRFOeA.png)\nImage by author: High level architecture pre-processing, vectore store, and extractive question-answer pipeline\n### Pre-processing our Documents\nHaystack provides us tools for easily pre-processing most types of text documents (.pdf, .txt, .docx included). The preprocessing steps are simple; we read in our knowledge base using the [convert_files_to_docs()](https://docs.haystack.deepset.ai/reference/utils-api#convert_files_to_docs:~:text=Module%20preprocessing-,convert_files_to_docs,-Python) function, which can automatically detect the file type and convert it to the format we need to work with downstream.\nHaystack also provides a [PreProcessor](https://docs.haystack.deepset.ai/reference/preprocessor-api#preprocessor::text=Module%20preprocessor-,PreProcessor,-Python:~:text=Module%20preprocessor-,PreProcessor,-Python) class that enables us to apply preprocessing steps to our documents. The steps you apply will depend very much on your specific application.\n_Note: the processor will enable you to split a long document into a list of smaller documents, defined as sentences. For question-and-answer applications, a common approach is to have some overlap between sentences; I have set this at roughly 30%._\n### **Vector Store**\nWe leverage [FAISS](https://engineering.fb.com/2017/03/29/data-infrastructure/faiss-a-library-for-efficient-similarity-search/), a library by Meta that enables efficient similarity search over our sentence embeddings. The importance of this will become more obvious in the coming sections. The script below shows how we can set up our pre-process for our text documents and set up the FAISS vector store.\nThe full pre-processing script is outlined below:\n* * *\n## **Defining an Extractive Question-Answer Pipeline**\nThe next step is to construct our extractive question answer pipeline. Our pipeline is defined by nodes which are run sequentially as a directed acyclic graph (DAG). In this case, the pipeline consists of two nodes, a retriever, and a reader.\n### Retriever\nRetrieval is the method used to find the relevant information from a knowledge base based on the user's query. When defining our retriever node, we specify a sentence embedding model from the sentence transformers library, in this case, we use [all-mpnet-base-v2](https://huggingface.co/sentence-transformers/all-mpnet-base-v2), which creates 768-dimensional embeddings.\nOnce we have fully defined our retrieval node, we can compute and store the sentence embeddings in our FAISS vector store. The same sentence embedding model is used to generate sentence embeddings for the user's query.\n_Note: when selecting your sentence embedding model, there is a trade-off between computational efficiency and information loss. In general, sentence embedding models with higher dimensions capture more information but are less computationally efficient._\nRemember, the ultimate purpose of the retriever node is to find the information that relates semantically to the query. This is done by performing a similarity search between the sentence embeddings from the query and the documents in our vector store. The top-k most relevant sentence embeddings are returned as an output from this node.\n### Reader\nThe reader node is a large language model that has been fine-tuned on question-answering tasks. For our use case, we leverage [Roberta-base-squad2](https://huggingface.co/deepset/roberta-base-squad2) as our reader model. The reader operates on the output from the retriever and the initial query from the user and returns the relevant span of text to answer the query. The reader will do this for each document in the retriever output, allocating a confidence score in each case. The answers are ranked by their score, and the top-k answers are returned.\nThe full script for the pipeline is outlined below:\n* * *\n## **Leveraging LLM-Powered Agents**\nNow that we have pre-processed our documents and defined our pipeline, we can construct our agent. An agent is powered by a large language model, in our case, OpenAI's gpt-4 (or gpt-3.5-turbo alternatively).\nThe agent we are using works on the basis of Zero-shot [ReAcT](https://www.promptingguide.ai/techniques/react) (Reason + Act) prompting. We prompt the large language model to return verbal reasoning traces and actions for a task. The agent can \"act\" on the verbal reasoning traces using a set of tools we provide it access to. The agent can observe and reason about the output from using the tools, helping it to inform its next action.\nThe animation below gives a simplified view of our ReAct agent at work.\n![Gif by author: Simplified view of a our agent at work](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1DA1iWS95HUvy-7r5DAWKQQ.gif)\nGif by author: Simplified view of a our agent at work\n _Note:_[_Research_](https://arxiv.org/pdf/2210.03629.pdf) _suggests that ReAct prompting has been shown to effectively reduce hallucinations by LLMs._\nThe script below shows how we construct our agent:\nIn this use case, the tool we have provided the agent is the extractive question-answer pipeline we defined earlier. Essentially the agent can interpret our query, use our pipeline as a tool to find the relevant responses in our knowledge base, reason to see if this answers the query, choose to respond, or perform the action again to get a better answer.\n### A Brief Note on Tools\nIt's important that we define our tools clearly. For our particular use case, we only have one tool, but we need to provide a description of that tool so that the LLM-powered agent knows how and when to use the tool. This becomes even more important when an agent has access to more than just one tool.\n* * *\n## **Putting it to the Test**\nSo we have defined our RAG-enabled model; let's put it to the test by asking it trivia on the Russia-Ukraine conflict of 2022. I have chosen two questions, each of which can be answered with information from the wikipedia knowledge base. As well as the responses I provide the workflow trace for each agent, you should inspect this carefully to gain a better insight into how the ReAct prompting works with the agent.\n> How did the international community respond to Russia's invasion of Ukraine in 2022?\nResponse from the RAG enabled model:\n> The international community responded to Russia's invasion of Ukraine in 2022 with condemnation and the imposition of new sanctions. These sanctions were comprehensive, affecting individuals, banks, businesses, and various types of economic activity including monetary exchanges, bank transfers, exports, and imports. Some of the specific measures included prison sentences of up to 15 years.\n_Note: The prison sentence for up to 15 years appears to be a hallucination. The model has mistakenly suggested this as a sanction measure._\n![Gif by author: Response to the question &quot;How did the international community respond to Russia&#039;s invasion of Ukraine in 2022?&quot;](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1f2O7SirOHPxF2gchRwTP8g.gif)\nGif by author: Response to the question \"How did the international community respond to Russia's invasion of Ukraine in 2022?\"\nResponse from Google search:\n![Image by author: Response from Google search for &quot;How did the international community respond to Russia&#039;s invasion of Ukraine in 2022?&quot;](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1Me6xCTcBM77qKcxgIFKPYw.png)\nImage by author: Response from Google search for \"How did the international community respond to Russia's invasion of Ukraine in 2022?\"\nHere's the trace tracking the agent's workflow:\nbash\n\n```\nAgent custom-at-query-time started with \n{'query':\n'How did the international community respond to\nRussia's invasion of Ukraine in 2022?', 'params': None}\nThe 'transcript' parameter is missing from\nthe Agent's prompt template. All ReAct agents\nthat go through multiple steps to reach\na goal require this parameter. Please append\n{transcript} to the end of the Agent's\nprompt template to ensure its proper functioning.\nA temporary prompt template with {transcript} appended\nwill be used for this run.\nfind out the details about the international\ncommunity's response to Russia's invasion of Ukraine\nin 2022.\nI don't have this information readily available,\nso I will use the document_qa tool to\nfind it.\nTool: document_qa\nTool Input: \"International community response to Russia's invasion of Ukraine\nin 2022\"\nBatches: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 13.05it/s]\nInferencing Samples: 100%|█████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:09<00:00, 9.98s/ Batches]\nObservation: 308\nThought: The document_qa tool provided a response\ncode of 308, which is not informative.\nI need to try again to get\nthe required information.\nTool: document_qa\nTool Input: \"How did the international community respond to Russia's invasion\nof Ukraine in 2022?\"\nBatches: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 9.72it/s]\nInferencing Samples: 100%|█████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:07<00:00, 7.78s/ Batches]\nObservation: condemnation\nThought: The document_qa tool responded with \"condemnation\".\nThis suggests that the international community condemned\nRussia's invasion of Ukraine in 2022. However,\nthis is a very broad response and\ndoesn't provide specific details about the actions\ntaken by the international community. I need\nto find more detailed information.\nTool: document_qa\nTool Input: \"What specific actions did the international community take in response to Russia's invasion of Ukraine in 2022?\"\nBatches: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 13.41it/s]\nInferencing Samples: 100%|█████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:07<00:00, 7.95s/ Batches]\nObservation: new sanctions\nThought: The document_qa tool responded with \"new\nsanctions\". This suggests that the international community\nimposed new sanctions on Russia in response\nto their invasion of Ukraine in 2022.\nHowever, this still doesn't provide a comprehensive\npicture of the international community's response. I\nneed to find more detailed information.\nTool: document_qa\nTool Input: \"What were the new sanctions imposed by the international community on Russia in 2022?\"\nBatches: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 12.66it/s]\nInferencing Samples: 100%|█████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:10<00:00, 10.77s/ Batches]\nObservation: prison sentences of up to 15 years\nThought: The document_qa tool responded with \"prison\nsentences of up to 15 years\". This\nsuggests that part of the sanctions imposed\nby the international community on Russia in\n2022 included prison sentences of up to\n15 years. However, this seems to be\na specific measure and may not represent\nthe full range of sanctions. I need\nto find more detailed information.\nTool: document_qa\nTool Input: \"What other sanctions were imposed by the international community on Russia in 2022?\"\nObservation: individuals, banks, businesses, monetary     exchanges,\nbank transfers, exports, and imports\nObservation: individuals, banks, businesses, monetaryexchanges, bank transfers,\nexports, and importsThought: The document_qa tool responded\nwith \"individuals, banks, businesses, monetary exchanges, bank\ntransfers, exports, and imports\". This suggests that\nthe sanctions imposed by the international community\non Russia in 2022 were comprehensive, affecting\nindividuals, banks, businesses, and various types of\neconomic activity including monetary exchanges, bank transfers,\nexports, and imports.\nFinal Answer: The international community responded\nto Russia's invasion of Ukraine in 2022\nwith condemnation and the imposition of new\nsanctions. These sanctions were comprehensive, affecting individuals,\nbanks, businesses, and various types of economic\nactivity including monetary exchanges, bank transfers, exports,\nand imports. Some of the specific measures\nincluded prison sentences of up to 15 years.\n```\n\n> Who led the IAEA team that investigated the plant on 29 August 2022?\nResponse from the RAG enabled model:\n> Rafael Grossi led the IAEA team that investigated the plant on 29 August 2022.\n![Gif by author: Response to the question &quot;Who led the IAEA team that investigated the plant on 29 August 2022?&quot;](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/19r4ovN1Ug2cODNl1F20Y8Q.gif)\nGif by author: Response to the question \"Who led the IAEA team that investigated the plant on 29 August 2022?\"\nResponse from Google search:\n![Image by author: Response from Google search for &quot;Who led the IAEA team that investigated the plant on 29 August 2022?&quot;](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/08/1_X6q0gmFz8b525d8PrNjpQ.png)\nImage by author: Response from Google search for \"Who led the IAEA team that investigated the plant on 29 August 2022?\"\nHere's the trace tracking the agent's workflow:\nbash\n\n```\nAgent custom-at-query-time started with {'query': 'Who\nled the IAEA team that investigated the\nplant on 29 Augustxa02022?', 'params': None}The 'transcript'\nparameter is missing from the Agent's prompt\ntemplate. All ReAct agents that go through\nmultiple steps to reach a goal require\nthis parameter. Please append {transcript} to the\nend of the Agent's prompt template to\nensure its proper functioning.\nA temporary prompt template with {transcript} appended will\nbe used for this run.\nfind out what the IAEA is and\nwhat plant was investigated on 29 August 2022.\nThen, I need to find out who led\nthe IAEA team during this investigation.\nI don't have this information at hand,\nso I will use the document_qa tool\nto find it.\nTool: document_qa\nTool Input: Who led the IAEA team that\ninvestigated the plant on 29 August 2022?\nObservation: Rafael Grossi\nThought: The document_qa tool has provided the name\nRafael Grossi in response to the query.\nThis suggests that Rafael Grossi led the\nIAEA team that investigated the plant on\n29 August 2022.\nFinal Answer: Rafael Grossi led the IAEA team\nthat investigated the plant on 29 August 2022.\n```\n\nFor your own curiosity, have a look at the [responses](https://chat.openai.com/share/af96d7f7-1408-422a-923f-ced160313828) from ChatGPT for the same questions. You can even try to ask the questions yourself to confirm the response.\n* * *\n## **Conclusion**\nRetrieval augmented generation (RAG) enables a large language model to connect with an existing knowledge base. RAG-enabled language models have access to up-to-date information, making them more useful across a variety of use cases.\nThe retriever and reader methods enable the models to query large corpuses of text, overcoming the issues faced by the limited context of large language models by themselves. Open-source frameworks like Haystack make it easy to build a RAG-enabled LLM prototype quickly.\nSome key points to note here are that the performance of this method is only as good as the knowledge base provided. Also, the inference time can be sped up dramatically by deploying the model on suitable infrastructure.\nFor more complex queries, agents may get into situations where they can't respond in the alotted amount of steps. It would be interesting to see how the quality of responses varies by increasing the amount of steps, or adding a memory component to make the pipeline more conversational. Leveraging a more heavy duty sentence embedding model could also serve to improve overall performance.\nThe code base is in the [GitHub](https://github.com/john-adeojo/haystack-lfqa) repo (including the front-end) and is available for you to experiment with.\nThere is also a [YouTube](https://youtu.be/-3MLqZppSCY) demo of project.\nThanks for reading.\n* * *\nIf you're keen to enhance your skills in artificial intelligence, join the waiting list for [my course](https://www.data-centric-solutions.com/course), where I will guide you through the process of developing large language model powered applications.\nIf you're seeking AI-transformation for your business, book a discovery call today.\n> [**Brainqub3 | AI software development**](https://www.brainqub3.com/)\nFor more insights on artificial intelligence, data science, and large language models you can subscribe to the [YouTube](https://www.youtube.com/channel/UCkXe-exqi25V4GnZendgEaA) channel.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657091747_phu3q1.png)\nWritten By\n## [John Adeojo](https://towardsdatascience.com/author/johnadeojo/)\n[See all from John Adeojo](https://towardsdatascience.com/author/johnadeojo/)\n[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Large Language Models](https://towardsdatascience.com/tag/large-language-models/)[NLP](https://towardsdatascience.com/tag/nlp/)[Prompt Engineering](https://towardsdatascience.com/tag/prompt-engineering/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-more-capable-llms-with-retrieval-augmented-generation-99d5f86e9779%2F&title=Build%20More%20Capable%20LLMs%20with%20Retrieval%20Augmented%20Generation)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-more-capable-llms-with-retrieval-augmented-generation-99d5f86e9779%2F&title=Build%20More%20Capable%20LLMs%20with%20Retrieval%20Augmented%20Generation)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-more-capable-llms-with-retrieval-augmented-generation-99d5f86e9779%2F&text=Build%20More%20Capable%20LLMs%20with%20Retrieval%20Augmented%20Generation)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/0wXV3ATP7O9Uu5BN0-scaled.jpg)](https://towardsdatascience.com/functional-time-series-83b717cca12/)\n## [Functional Time Series](https://towardsdatascience.com/functional-time-series-83b717cca12/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nWhen we measure data more frequently, how can we best analyze it? Functional Data Analysis (FDA) can simplify the analysis drastically.\n[Florian Heinrichs](https://towardsdatascience.com/author/florian.heinrichs/)\nJanuary 5, 202111 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/1wsFq6waE5H1DSfWAwNP8dQ.jpeg)](https://towardsdatascience.com/bayesian-optimization-for-hyperparameter-tuning-how-and-why-655b0ee0b399/)\n## [Hyperparameter Tuning Methods - Grid, Random or Bayesian Search?](https://towardsdatascience.com/bayesian-optimization-for-hyperparameter-tuning-how-and-why-655b0ee0b399/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA practical guide to hyperparameter optimization using three methods: grid, random and bayesian search (with skopt)\n[Maria Gorodetski](https://towardsdatascience.com/author/maria.gorodetski/)\nAugust 28, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/05/1x4Z1vOkwfzMUFrarkbDWzg.png)](https://towardsdatascience.com/the-best-way-to-generate-indices-in-bigquery-f3a09f71b175/)\n## [The Best Way to Generate Indices in BigQuery](https://towardsdatascience.com/the-best-way-to-generate-indices-in-bigquery-f3a09f71b175/)\n[Programming](https://towardsdatascience.com/category/programming/)\nUsing GENERATE_ARRAY for Histograms and More\n[Jye Sawtell-Rickson](https://towardsdatascience.com/author/jyesr/)\nMay 30, 20204 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/03/0_j0MQvO7rcWX_6Zn-scaled.jpg)](https://towardsdatascience.com/dating-algorithms-using-machine-learning-and-ai-814b68ecd75e/)\n## [How to Use Machine Learning and AI to Make a Dating App](https://towardsdatascience.com/dating-algorithms-using-machine-learning-and-ai-814b68ecd75e/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nUtilizing Unsupervised Learning as a Dating Algorithm\n[Marco Santos](https://towardsdatascience.com/author/marco-santos/)\nMarch 8, 20202 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/08/envelopes_toQNPpuDuwI_v3_card.jpg)](https://towardsdatascience.com/faq-as-rag-when-you-get-to-design-the-corpus/)\n## [FAQ as RAG: When You Get to Design the Corpus](https://towardsdatascience.com/faq-as-rag-when-you-get-to-design-the-corpus/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nEnterprise Document Intelligence [Vol.1 #B2] - The FAQ inverts every brick of the standard RAG pipeline. Parsing is trivial, retrieval doubles as a cache, and few-shot prompting becomes a retrieval problem too\n[Kezhan Shi](https://towardsdatascience.com/author/kezhanshi/)\nAugust 31, 202619 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/1AvCUUTzltFbUBxNGaaU33w.png)](https://towardsdatascience.com/fine-tune-a-transformer-model-for-grammar-correction-b5c8ca49cc26/)\n## [Fine-Tune a Transformer Model for Grammar Correction](https://towardsdatascience.com/fine-tune-a-transformer-model-for-grammar-correction-b5c8ca49cc26/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLearn how to train a Transformer model called T5 to be your very own grammar corrector\n[Eric Fillion](https://towardsdatascience.com/author/ericfillion/)\nAugust 18, 20219 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/10/1OYWh8tvesH2wYX2c-5ueJg.png)](https://towardsdatascience.com/train-a-custom-object-detector-with-detectron2-and-fiftyone-4dc451839958/)\n## [Train a Custom Object Detector with Detectron2 and FiftyOne](https://towardsdatascience.com/train-a-custom-object-detector-with-detectron2-and-fiftyone-4dc451839958/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nCombine the dataset curation of FiftyOne with the model training of Detectron2 to easily train custom detection models\n[Eric Hofesmann](https://towardsdatascience.com/author/eric.hofesmann/)\nOctober 13, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/08/1xIvHbmO_rjdGgpHIWw5LaA-scaled.jpeg)](https://towardsdatascience.com/python-done-the-r-markdown-way-d03bec4b96b/)\n## [Python done the R (Markdown) way](https://towardsdatascience.com/python-done-the-r-markdown-way-d03bec4b96b/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nAre you an R user flirting with the idea of doing Python? I wrote an article that may be of your interest!\n[Vít Gabrhel](https://towardsdatascience.com/author/vitgabrhel/)\nAugust 24, 202010 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/08/0uKspGGlE8o59P8UC-scaled.jpg)](https://towardsdatascience.com/integrate-bias-detection-in-your-data-science-skill-set-982a699653f2/)\n## [Integrate Bias Detection in Your Data Science Skill Set](https://towardsdatascience.com/integrate-bias-detection-in-your-data-science-skill-set-982a699653f2/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nDon't forget that bias could impact your project\n[Cornellius Wijaya](https://towardsdatascience.com/author/cornelliusyudhawijaya/)\nAugust 4, 20229 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "body_base_path": "attachments/e5a51520cfd6/pages/",
  "body_markdown_path": "attachments/e5a51520cfd6/pages/archived-body.md",
  "local_html": "attachments/e5a51520cfd6/pages/archived-body.html",
  "body_source": "prior_capture"
}