{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Iulia Brezeanu",
  "title_listed": "Advanced Query Transformations to Improve RAG",
  "keywords": "",
  "domain": "大模型算法",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/advanced-query-transformations-to-improve-rag-11adca9b19d1/",
  "publish_date": "2024-01-10",
  "corpus_stage": "",
  "notes": "",
  "id": "3455f990759a",
  "collected_at": "2026-10-02T09:48:00",
  "title": "Advanced Query Transformations to Improve RAG | 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[ChatGPT](https://towardsdatascience.com/category/artificial-intelligence/chatgpt/)\n# Advanced Query Transformations to Improve RAG\nDifferent approaches to query transformations\n[Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\nJanuary 10, 20249 min read\n![Image by author. AI Generated.](../images/000.jpg)\nImage by author. AI Generated.\nRetrieval augmented generation has become one of the most discussed topics in generative AI literature. With the daily influx of blog articles and scientific papers, it can be challenging to stay updated. However, the popularity of RAG is well-deserved, as no other solution has proven as efficient for mitigating hallucinations in large language models.\nRAG enhances a language model's general knowledge with reliable external sources like Wikipedia pages, private PDFs, etc. That's why the most important step for RAG is to ensure that our retrieval finds the right documents to feed into the model.\nWe need RAG so much because we currently face limitations in fitting full documents into the context window. Reasons include restricted token length for model inputs, the proportional increase in computational cost, and issues like \"lost in the middle\" which refers to a phenomenon where models struggle to use information found in the middle of a long input context [2].\nLearn this step by step with the interactive [Prompt Engineering](https://roadmap.sh/prompt-engineering) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n![Relationship between model performance and the position of the relevant information in the context window.\\[2\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1EQ_JERWU7eiVyLLoScAKeg.png)\nRelationship between model performance and the position of the relevant information in the context window.[2]\nIf the retrieved documents are too long or irrelevant, as the saying goes, garbage in, garbage out.\nThere are many techniques for enhancing RAG, creating the additional challenge of knowing when to apply each. In this article, we will analyze query transformations and how to use a router to select the appropriate transformation based on the input prompt.\nThe idea behind query transformations is that the retriever may not consider a user's initial prompt particularly similar to the relevant documents in the database. In these cases, we can modify the query to increase its relevance to our sources before retrieving and feeding them to the language model.\nWe will start with a simple RAG application by loading three Wikipedia pages about Nicolas Cage, The Best of Times (the television pilot in which Nicolas Cage made his acting debut), and Leonardo DiCaprio.\nWe will then split the documents into chunks of 256 characters with no overlap. These chunks will be embedded and indexed in a Vector Store, which stores everything in memory by default, but if you want persistent options, dozens of options are available.\npython\n\n```\nWikipediaReader = download_loader(\"WikipediaReader\")\n\nloader = WikipediaReader()\npages = ['Nicolas_Cage', 'The_Best_of_Times_(1981_film)', 'Leonardo DiCaprio']\ndocuments = loader.load_data(pages=pages, auto_suggest=False, redirect = False)\n\nllm = OpenAI(temperature=0, model=\"gpt-3.5-turbo\")\ngpt3 = OpenAI(temperature=0, model=\"text-davinci-003\")\n\nembed_model = OpenAIEmbedding(model= OpenAIEmbeddingModelType.TEXT_EMBED_ADA_002)\nservice_context_gpt3 = ServiceContext.from_defaults(llm=gpt3, chunk_size = 256, chunk_overlap=0, embed_model=embed_model)\n\nindex = VectorStoreIndex.from_documents(documents, service_context=service_context_gpt3)\nretriever = index.as_retriever(similarity_top_k=3)\n```\n\nNow, we have to make sure that the model answers only based on the context and does not rely on its training data, even if it may have previously learned the answer.\npython\n\n```\n# The response from original prompt\nfrom llama_index.prompts import PromptTemplate\n\ntemplate = (\n\"We have provided context information below. n\"\n    \"---------------------n\"\n    \"{context_str}\"\n    \"n---------------------n\"\n    \"Given this information, please answer the question: {query_str}n\"\n    \"Don't give an answer unless it is supported by the context above.n\"\n)\n\nqa_template = PromptTemplate(template)\n```\n\nWe will test the RAG application we just created using two more complex queries. Let's take a look at the first one.\n**Query 1 - \"Who directed the pilot that marked the acting debut of Nicolas Cage?\"**\nThe first challenging query requires linking multiple pieces of information: Nicolas Cage's acting debut and the director of that specific film. The prompt mentions only Nicolas Cage, while the director's name is not included anywhere.\nSince the model doesn't know the name of the television pilot that marked Cage's debut, called \"The Best of Times\", it cannot retrieve the relevant details from the documents we indexed.\npython\n\n```\nquestion = \"Who directed the pilot that marked the acting debut of Nicolas Cage?\"\n\ncontexts = retriever.retrieve(question)\ncontext_list = [n.get_content() for n in contexts]\n\nprompt = qa_template.format(context_str=\"nn\".join(context_list), query_str=question)\nresponse = llm.complete(prompt)\n\nprint(str(response))\n```\n\n![Simple RAG output for the first query. Image by author](../images/002.png)\nSimple RAG output for the first query. Image by author\n**Query 2 - \"Compare the education received by Nicolas Cage and Leonardo DiCaprio.\"**\nFor the second query, the retriever selects relevant chunks of text only about Leonardo DiCaprio's education. The chunks about Nicolas Cage are irrelevant, so we cannot get an accurate comparison.\npython\n\n```\nquestion = \"Compare the education received by Nicolas Cage and Leonardo DiCaprio.\"\n\ncontexts = retriever.retrieve(question)\n\ncontext_list = [n.get_content() for n in contexts]\n\nprompt = qa_template.format(context_str=\"nn\".join(context_list), query_str=question)\n\nresponse = llm.complete(prompt)\nprint(str(response))\n```\n\n![Simple RAG output for the second query. Image by author.](../images/003.png)\nSimple RAG output for the second query. Image by author.\nLet's analyze some query transformation techniques and see which works best in each case.\n## HyDE\n![HyDE. Image by the author.](../images/004.png)\nHyDE. Image by the author.\nHypothetical Document Embeddings (HyDE) is a technique for generating document embeddings to retrieve relevant documents without needing actual training data. First, an LLM creates a hypothetical answer in response to a query. While reflecting patterns of relevance to the query, this answer includes information that might not be factually accurate.\nNext, both the query and the generated answer are transformed into embeddings. The system then identifies and retrieves actual documents from a predefined database that are closest to these embeddings in the vector space.\n![Illustration of the HyDE model \\[3\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1dZnaxSGEvZlNJtiLQ5nDNg.png)\nIllustration of the HyDE model [3]\npython\n\n```\nfrom llama_index.indices.query.query_transform import HyDEQueryTransform\nfrom llama_index.query_engine.transform_query_engine import (\n    TransformQueryEngine,\n)\n\nindex = VectorStoreIndex.from_documents(documents, service_context=service_context_gpt3)\nquery_engine = index.as_query_engine(similarity_top_k=3)\n\nhyde = HyDEQueryTransform(include_original=True)\nhyde_query_engine = TransformQueryEngine(query_engine, hyde)\n```\n\n**Query 1**\npython\n\n```\nresponse = hyde_query_engine.query(\"Who directed the pilot that marked the acting debut of Nicolas Cage?\")\nprint(response)\n```\n\n![HyDE RAG output for the first query. Image by author.](../images/006.png)\nHyDE RAG output for the first query. Image by author.\nWe have made some partial progress - the model's answer is still incorrect, but it has moved closer to the right response. Specifically, it was now able to identify the name of the television pilot (\"Best of Times\"). Let's see what the hallucinated answer looks like.\npython\n\n```\nquery_bundle = hyde(\"Who directed the pilot that marked the acting debut of Nicolas Cage?\")\nhyde_doc = query_bundle.embedding_strs[0]\nhyde_doc\n```\n\n![HyDE output for the first query. Image by author.](../images/007.png)\nHyDE output for the first query. Image by author.\nWhile it is not true that Francis Coppola directed \"The Best of Times\", at least the hallucination included the movie's name.\n**Query 2**\npython\n\n```\nresponse = hyde_query_engine.query(\"Compare the education received by Nicolas Cage and Leonardo DiCaprio.\")\nprint(response)\n```\n\n![HyDE RAG output for the second query. Image by author.](../images/008.png)\nHyDE RAG output for the second query. Image by author.\nThe answer is correct because the hallucinated answer improved the output significantly. The LLM already had information about the actors' education in the training data.\n![HyDE output for the second query. Image by author.](../images/009.png)\nHyDE output for the second query. Image by author.\n## Sub Questions\nThe Sub Questions technique uses a divide-and-conquer approach to handle complex questions. It first analyzes the questions and breaks them down into simpler sub-questions. Each sub-question targets different relevant documents that can provide part of the answer.\nThe engine then gathers the intermediate responses and synthesizes all the partial results into a final response.\npython\n\n```\n# setup base query engine as tool\nquery_engine_tools = [\n    QueryEngineTool(\n        query_engine=vector_query_engine,\n        metadata=ToolMetadata(\n            name=\"Sub-question query engine\",\n            description=\"Questions about actors\",\n        ),\n    ),\n]\n\nquery_engine = SubQuestionQueryEngine.from_defaults(\n    query_engine_tools=query_engine_tools,\n    service_context=service_context,\n    use_async= False\n)\n```\n\n**Query 1**\n![Sub Questions RAG output for the first query. Image by author.](../images/010.png)\nSub Questions RAG output for the first query. Image by author.\n![Generated Sub Questions for the first query. Image by author.](../images/011.png)\nGenerated Sub Questions for the first query. Image by author.\nThere are no ways to break down this question into simpler sub-questions that would make it easier to answer. The model tried to generate one sub-question but didn't provide any additional context beyond the original query, wasting computation on ineffective transformations.\n**Query 2**\n![Sub Questions RAG output for the second query. Image by author.](../images/012.png)\nSub Questions RAG output for the second query. Image by author.\n![Generated Sub Questions for the second query. Image by author.](../images/013.png)\nGenerated Sub Questions for the second query. Image by author.\nThis time, generating sub-questions was extremely useful because we needed to compare two distinct pieces of information - the educational backgrounds of two different people. Each sub-question can be answered independently using the retrieved context.\n## Multi-Step Query Transformation\n![Self-ask + Search Engine \\[1\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1Nen6WVH8sfr-Oudxk_wwRw.png)\nSelf-ask + Search Engine [1]\nThe multi-step query transformation approach is based on the self-ask method, where the language model asks and answers follow-up questions to itself before answering the original question. This helps the model combine facts and insights it learned separately during pretraining.\nThe original paper showed that LLMs often fail to compose two facts together, even if they know each one independently. For example, a model may know Fact A and Fact B but fail to deduce the implication of A and B together.\nThe self-ask method aims to overcome this limitation. At test time, we simply provide the prompt and question to the model. Then, it automatically generates any necessary follow-up questions to connect facts, compose reasoning steps, and decide when to stop [1].\npython\n\n```\nquery_engine = MultiStepQueryEngine(\n    query_engine=query_engine,\n    query_transform=step_decompose_transform_gpt3,\n    index_summary=index_summary\n)\n```\n\n**Query 1**\n> Don Mischer directed the pilot that marked the acting debut of Nicolas Cage.\nThis is the first time we have had a correct answer to this query! Let's see the intermediate questions.\n![MultiStepQueryEngine output for the first query. Image by author.](../images/015.png)\nMultiStepQueryEngine output for the first query. Image by author.\nThe output of the first sub-question was the following:\n> The Best of Times pilot that marked the acting debut of Nicolas Cage was not directed by anyone in the Coppola family. It was directed by Rod Amateau.\nHaving identified the pilot name, the second sub-question now asks specifically about the director:\n> Who directed the Best of Times pilot that marked the acting debut of Nicolas Cage?\nThis multi-step approach helped the model build on the additional context from the prior question and led us to the correct answer.\n**Query 2**\n> Nicolas Cage received education in the field of theater, film, and television at UCLA School of Theater, Film and Television. On the other hand, Leonardo DiCaprio attended the Los Angeles Center for Enriched Studies, Seeds Elementary School, and John Marshall High School. However, DiCaprio dropped out of high school and later earned a general equivalency diploma.\n![MultiStepQueryEngine output for the second query. Image by author.](../images/body-2b8eee8f59677586e6fb.png)\nMultiStepQueryEngine output for the second query. Image by author.\nThe multi-step approach was also useful in this case. Our opinion is that for the second query, the sub-question technique from before is a better fit because it can be parallelized. The questions are independent and don't need to build on top of each other. But a multi-step approach can also be useful.\n## RouterQueryEngine\nEach query transformation proved useful for different cases. The sub-question decomposition works best for questions that can be broken into simpler sub-questions, like comparing Nicolas Cage and Leonardo DiCaprio's education.\nMulti-step transformation works best for queries that require exploring context iteratively, like linking multiple facets of information.\nSimple queries might not need any transformations at all, and applying them would be a waste of resources.\nTo handle choosing between all these cases, we can use a _RouterQueryEngine_ - we give an LLM a set of tools for query transformations and let it decide the best one to apply based on the input prompt.\nmakefile\n\n```\nquery_engine = RouterQueryEngine(\n    selector=PydanticSingleSelector.from_defaults(),\n    query_engine_tools=[\n        simple_tool,\n        multi_step_tool,\n        sub_question_tool,\n    ],\n)\n```\n\nWe created a router that allows selection between no transformation, sub-question decomposition, or multi-step transformations as needed for each unique query. Let's examine how the router reasons about which approach to take.\nFirst of all, we will choose a very simple question that needs no transformations.\nini\n\n```\nresponse_1 = query_engine.query(\"What is Nicolas Cage's profession?\")\n```\n\n![RouterQueryEngine output choosing simple_tool. Image by author.](../images/body-2455bf1207b999b234a7.png)\nRouterQueryEngine output choosing simple_tool. Image by author.\nThe router made the right choice by assessing that the query is relatively simple. No query transformations are needed to decompose or expand this question since it asks directly about a single fact regarding Nicolas Cage's occupation.\nini\n\n```\nresponse_2 = query_engine.query(\"Compare the education received by Nicolas Cage and Leonardo DiCaprio.\")\n```\n\n![RouterQueryEngine output choosing sub_question_tool. Image by author.](../images/body-8718a0aec79e9b4bb497.png)\nRouterQueryEngine output choosing sub_question_tool. Image by author.\nTo answer a comparative question, the router accurately broke it down into simpler sub-questions about each individual.\nini\n\n```\nresponse_3 = query_engine.query(\"Who directed the pilot that marked the acting debut of Nicolas Cage?\")\n```\n\n![RouterQueryEngine output choosing multi_step_tool. Image by author.](../images/body-e44a3c66a9dc4b37f2e2.png)\nRouterQueryEngine output choosing multi_step_tool. Image by author.\nFor the third query, the router recognizes that answering correctly requires linking multiple pieces of contextual information - specifically, identifying the pilot episode that marked Cage's acting debut and then determining who directed that particular pilot.\n## **Conclusion**\nAs we have explored, enhancing RAG through advanced query transformations can significantly improve model performance.\nWhile query transformation is just one of many techniques for improving retrieval, it demonstrates the potential and need for customized analysis that merges retrieval with the reasoning capabilities inherent to LLMs.\n. . .\n_If you enjoyed this article, join_[ _**Text Generation**_](https://textgeneration.substack.com/) _- our newsletter has two weekly posts with the latest insights on Generative AI and Large Language Models._\n_You can find the full code for this project on[ GitHub](https://github.com/partycia/query_transformations)._\n_You can also find me on_[ _LinkedIn_](https://www.linkedin.com/in/ibrezeanu/) _._\n. . .\n**References**\n  1. [Measuring and Narrowing the Compositionality Gap in Language Models](https://arxiv.org/abs/2210.03350)\n  2. [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172)\n  3. [Precise Zero-Shot Dense Retrieval without Relevance Labels](https://arxiv.org/abs/2212.10496)\n\n\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-f993dd42b2e293ffbc34.png)\nWritten By\n## [Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[See all from Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[ChatGPT](https://towardsdatascience.com/tag/chatgpt/)[Generative Ai Tools](https://towardsdatascience.com/tag/generative-ai-tools/)[Hands On Tutorials](https://towardsdatascience.com/tag/hands-on-tutorials/)[Llm](https://towardsdatascience.com/tag/llm/)[NLP](https://towardsdatascience.com/tag/nlp/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fadvanced-query-transformations-to-improve-rag-11adca9b19d1%2F&title=Advanced%20Query%20Transformations%20to%20Improve%20RAG)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fadvanced-query-transformations-to-improve-rag-11adca9b19d1%2F&title=Advanced%20Query%20Transformations%20to%20Improve%20RAG)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fadvanced-query-transformations-to-improve-rag-11adca9b19d1%2F&text=Advanced%20Query%20Transformations%20to%20Improve%20RAG)\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/016.jpg)](https://towardsdatascience.com/how-we-reduced-llm-cost-by-90-with-5-lines-of-code/)\n## [How We Reduced LLM Costs by 90% with 5 Lines of Code](https://towardsdatascience.com/how-we-reduced-llm-cost-by-90-with-5-lines-of-code/)\n[Programming](https://towardsdatascience.com/category/programming/)\nWhen clean code hides inefficiencies: what we learned from fixing a few lines of code and saving 90% in LLM cost.\n[Uri Peled](https://towardsdatascience.com/author/uri.peled/)\nAugust 21, 20258 min read\n  * [![](../images/017.png)](https://towardsdatascience.com/llms-txt-414d5121bcb3/)\n## [LLMs.txt Explained](https://towardsdatascience.com/llms-txt-414d5121bcb3/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nYour guide to the web's new LLM-ready content standard\n[Derick Ruiz](https://towardsdatascience.com/author/dericksozo/)\nNovember 28, 20245 min read\n  * [![](../images/018.webp)](https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0/)\n## [Evaluate Topic Models: Latent Dirichlet Allocation (LDA)](https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA step-by-step guide to building interpretable topic models\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nAugust 19, 201912 min read\n  * [![](../images/019.png)](https://towardsdatascience.com/transformers-numeracy-pt-1-calculators-for-natural-language-e09a471c5ebe/)\n## [NLP & Numeracy (Pt 1) - Calculators for Natural Language](https://towardsdatascience.com/transformers-numeracy-pt-1-calculators-for-natural-language-e09a471c5ebe/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWhat is numeracy in NLP and why it matters?\n[Misho Dungarov](https://towardsdatascience.com/author/mihail.dungarov/)\nNovember 22, 202013 min read\n  * [![](../images/020.png)](https://towardsdatascience.com/going-beyond-keywords-with-nlp-42395f7e7c67/)\n## [Going Beyond Keywords with NLP](https://towardsdatascience.com/going-beyond-keywords-with-nlp-42395f7e7c67/)\n[NLP](https://towardsdatascience.com/category/artificial-intelligence/nlp/)\nMany NLP tasks can be solved with keyword-based approaches. For those that can't, try spaCy's linguistic features or a Transformer model.\n[Jared Rand](https://towardsdatascience.com/author/chiefastro/)\nNovember 30, 20207 min read\n  * [![](../images/021.png)](https://towardsdatascience.com/large-language-models-structbert-incorporating-language-structures-into-pretraining-be3058ab23b3/)\n## [Large Language Models, StructBERT - Incorporating Language Structures into Pretraining](https://towardsdatascience.com/large-language-models-structbert-incorporating-language-structures-into-pretraining-be3058ab23b3/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nMaking models smarter by incorporating better learning objectives\n[Slava Efimov](https://towardsdatascience.com/author/slavahead/)\nNovember 22, 20234 min read\n  * [![](../images/022.png)](https://towardsdatascience.com/tool-use-agents-and-the-voyager-paper-5a0e548f8b38/)\n## [Tool Use, Agents, and the Voyager Paper](https://towardsdatascience.com/tool-use-agents-and-the-voyager-paper-5a0e548f8b38/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA detailed exploration of the Voyager Paper and its findings on tool usage\n[Matthew Gunton](https://towardsdatascience.com/author/mgunton7/)\nMay 1, 20248 min read\n  * [![](../images/023.jpg)](https://towardsdatascience.com/text-classification-in-just-20-lines-of-code-8baf9c2a0a53/)\n## [Text Classification in Just 20 Lines of Code](https://towardsdatascience.com/text-classification-in-just-20-lines-of-code-8baf9c2a0a53/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nTraining a state of the art text classifier with Pytorch and Fastai with minimal setup!\n[Yash Prakash](https://towardsdatascience.com/author/ipom/)\nJanuary 5, 20213 min read\n  * [![](../images/024.png)](https://towardsdatascience.com/context-aided-forecasting-enhancing-forecasting-with-textual-data-c9af2ab057c1/)\n## [Context-Aided Forecasting: Enhancing Forecasting with Textual Data](https://towardsdatascience.com/context-aided-forecasting-enhancing-forecasting-with-textual-data-c9af2ab057c1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA promising alternative approach to improve forecasting\n[Nikos Kafritsas](https://towardsdatascience.com/author/nikoskafritsas/)\nDecember 2, 20248 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/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  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "Advanced Query Transformations to Improve RAG | Towards Data Science",
    "description": "Different approaches to query transformations",
    "keywords": null,
    "author": "Iulia Brezeanu",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Advanced Query Transformations to Improve RAG",
    "og:description": "Different approaches to query transformations",
    "og:url": "https://towardsdatascience.com/advanced-query-transformations-to-improve-rag-11adca9b19d1/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0w3tdm3HuG3tbGOxX.jpg",
    "og:image:width": "1792",
    "og:image:height": "1024",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Iulia Brezeanu",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "9 min read",
    "article:published_time": "2024-01-10T15:49:23.000Z",
    "article:modified_time": "2024-01-10T15:49:23.000Z",
    "article:author": "https://towardsdatascience.com/author/brezeanu.iulia/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_000.txt",
      "chars": 693
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_001.txt",
      "chars": 410
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_002.txt",
      "chars": 314
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_003.txt",
      "chars": 316
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_004.txt",
      "chars": 421
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_005.txt",
      "chars": 123
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_006.txt",
      "chars": 143
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_007.txt",
      "chars": 124
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_008.txt",
      "chars": 424
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_009.txt",
      "chars": 153
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_010.txt",
      "chars": 194
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_011.txt",
      "chars": 70
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_012.txt",
      "chars": 105
    },
    {
      "language": "txt",
      "file": "attachments/3455f990759a/code/block_013.txt",
      "chars": 104
    }
  ],
  "images": [
    {
      "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-20T17:38:37Z"
    },
    {
      "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-20T17:38:37Z"
    },
    {
      "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-20T17:38:37Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:39:19Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "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/chatgpt/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/brezeanu.iulia/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/chatgpt/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/generative-ai-tools/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/hands-on-tutorials/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/llm/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/nlp/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-we-reduced-llm-cost-by-90-with-5-lines-of-code/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/uri.peled/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/llms-txt-414d5121bcb3/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/dericksozo/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0/"
    },
    {
      "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://roadmap.sh/prompt-engineering"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://textgeneration.substack.com/"
    },
    {
      "type": "external",
      "href": "https://github.com/partycia/query_transformations"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/ibrezeanu/"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/2210.03350"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/2307.03172"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/2212.10496"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Advanced+Query+Transformations+to+Improve+RAG&u=https%3A%2F%2Ftowardsdatascience.com%2Fadvanced-query-transformations-to-improve-rag-11adca9b19d1%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Advanced+Query+Transformations+to+Improve+RAG&url=https%3A%2F%2Ftowardsdatascience.com%2Fadvanced-query-transformations-to-improve-rag-11adca9b19d1%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Advanced+Query+Transformations+to+Improve+RAG&url=https%3A%2F%2Ftowardsdatascience.com%2Fadvanced-query-transformations-to-improve-rag-11adca9b19d1%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:24:03Z",
  "source_url": "https://towardsdatascience.com/advanced-query-transformations-to-improve-rag-11adca9b19d1/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "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[ChatGPT](https://towardsdatascience.com/category/artificial-intelligence/chatgpt/)\n# Advanced Query Transformations to Improve RAG\nDifferent approaches to query transformations\n[Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\nJanuary 10, 20249 min read\n![Image by author. AI Generated.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/0w3tdm3HuG3tbGOxX.jpg)\nImage by author. AI Generated.\nRetrieval augmented generation has become one of the most discussed topics in generative AI literature. With the daily influx of blog articles and scientific papers, it can be challenging to stay updated. However, the popularity of RAG is well-deserved, as no other solution has proven as efficient for mitigating hallucinations in large language models.\nRAG enhances a language model's general knowledge with reliable external sources like Wikipedia pages, private PDFs, etc. That's why the most important step for RAG is to ensure that our retrieval finds the right documents to feed into the model.\nWe need RAG so much because we currently face limitations in fitting full documents into the context window. Reasons include restricted token length for model inputs, the proportional increase in computational cost, and issues like \"lost in the middle\" which refers to a phenomenon where models struggle to use information found in the middle of a long input context [2].\nLearn this step by step with the interactive [Prompt Engineering](https://roadmap.sh/prompt-engineering) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n![Relationship between model performance and the position of the relevant information in the context window.\\[2\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1EQ_JERWU7eiVyLLoScAKeg.png)\nRelationship between model performance and the position of the relevant information in the context window.[2]\nIf the retrieved documents are too long or irrelevant, as the saying goes, garbage in, garbage out.\nThere are many techniques for enhancing RAG, creating the additional challenge of knowing when to apply each. In this article, we will analyze query transformations and how to use a router to select the appropriate transformation based on the input prompt.\nThe idea behind query transformations is that the retriever may not consider a user's initial prompt particularly similar to the relevant documents in the database. In these cases, we can modify the query to increase its relevance to our sources before retrieving and feeding them to the language model.\nWe will start with a simple RAG application by loading three Wikipedia pages about Nicolas Cage, The Best of Times (the television pilot in which Nicolas Cage made his acting debut), and Leonardo DiCaprio.\nWe will then split the documents into chunks of 256 characters with no overlap. These chunks will be embedded and indexed in a Vector Store, which stores everything in memory by default, but if you want persistent options, dozens of options are available.\npython\n\n```\nWikipediaReader = download_loader(\"WikipediaReader\")\n\nloader = WikipediaReader()\npages = ['Nicolas_Cage', 'The_Best_of_Times_(1981_film)', 'Leonardo DiCaprio']\ndocuments = loader.load_data(pages=pages, auto_suggest=False, redirect = False)\n\nllm = OpenAI(temperature=0, model=\"gpt-3.5-turbo\")\ngpt3 = OpenAI(temperature=0, model=\"text-davinci-003\")\n\nembed_model = OpenAIEmbedding(model= OpenAIEmbeddingModelType.TEXT_EMBED_ADA_002)\nservice_context_gpt3 = ServiceContext.from_defaults(llm=gpt3, chunk_size = 256, chunk_overlap=0, embed_model=embed_model)\n\nindex = VectorStoreIndex.from_documents(documents, service_context=service_context_gpt3)\nretriever = index.as_retriever(similarity_top_k=3)\n```\n\nNow, we have to make sure that the model answers only based on the context and does not rely on its training data, even if it may have previously learned the answer.\npython\n\n```\n# The response from original prompt\nfrom llama_index.prompts import PromptTemplate\n\ntemplate = (\n\"We have provided context information below. n\"\n    \"---------------------n\"\n    \"{context_str}\"\n    \"n---------------------n\"\n    \"Given this information, please answer the question: {query_str}n\"\n    \"Don't give an answer unless it is supported by the context above.n\"\n)\n\nqa_template = PromptTemplate(template)\n```\n\nWe will test the RAG application we just created using two more complex queries. Let's take a look at the first one.\n**Query 1 - \"Who directed the pilot that marked the acting debut of Nicolas Cage?\"**\nThe first challenging query requires linking multiple pieces of information: Nicolas Cage's acting debut and the director of that specific film. The prompt mentions only Nicolas Cage, while the director's name is not included anywhere.\nSince the model doesn't know the name of the television pilot that marked Cage's debut, called \"The Best of Times\", it cannot retrieve the relevant details from the documents we indexed.\npython\n\n```\nquestion = \"Who directed the pilot that marked the acting debut of Nicolas Cage?\"\n\ncontexts = retriever.retrieve(question)\ncontext_list = [n.get_content() for n in contexts]\n\nprompt = qa_template.format(context_str=\"nn\".join(context_list), query_str=question)\nresponse = llm.complete(prompt)\n\nprint(str(response))\n```\n\n![Simple RAG output for the first query. Image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1pZBMEZgifPkbYdF7F5YCCQ.png)\nSimple RAG output for the first query. Image by author\n**Query 2 - \"Compare the education received by Nicolas Cage and Leonardo DiCaprio.\"**\nFor the second query, the retriever selects relevant chunks of text only about Leonardo DiCaprio's education. The chunks about Nicolas Cage are irrelevant, so we cannot get an accurate comparison.\npython\n\n```\nquestion = \"Compare the education received by Nicolas Cage and Leonardo DiCaprio.\"\n\ncontexts = retriever.retrieve(question)\n\ncontext_list = [n.get_content() for n in contexts]\n\nprompt = qa_template.format(context_str=\"nn\".join(context_list), query_str=question)\n\nresponse = llm.complete(prompt)\nprint(str(response))\n```\n\n![Simple RAG output for the second query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/10l0YICNvGEaTpZ89z1na7w.png)\nSimple RAG output for the second query. Image by author.\nLet's analyze some query transformation techniques and see which works best in each case.\n## HyDE\n![HyDE. Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1dS6SZzjcQU83er977WAW0g.png)\nHyDE. Image by the author.\nHypothetical Document Embeddings (HyDE) is a technique for generating document embeddings to retrieve relevant documents without needing actual training data. First, an LLM creates a hypothetical answer in response to a query. While reflecting patterns of relevance to the query, this answer includes information that might not be factually accurate.\nNext, both the query and the generated answer are transformed into embeddings. The system then identifies and retrieves actual documents from a predefined database that are closest to these embeddings in the vector space.\n![Illustration of the HyDE model \\[3\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1dZnaxSGEvZlNJtiLQ5nDNg.png)\nIllustration of the HyDE model [3]\npython\n\n```\nfrom llama_index.indices.query.query_transform import HyDEQueryTransform\nfrom llama_index.query_engine.transform_query_engine import (\n    TransformQueryEngine,\n)\n\nindex = VectorStoreIndex.from_documents(documents, service_context=service_context_gpt3)\nquery_engine = index.as_query_engine(similarity_top_k=3)\n\nhyde = HyDEQueryTransform(include_original=True)\nhyde_query_engine = TransformQueryEngine(query_engine, hyde)\n```\n\n**Query 1**\npython\n\n```\nresponse = hyde_query_engine.query(\"Who directed the pilot that marked the acting debut of Nicolas Cage?\")\nprint(response)\n```\n\n![HyDE RAG output for the first query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/15g_m6v7ueATMOLsVIG9NQQ.png)\nHyDE RAG output for the first query. Image by author.\nWe have made some partial progress - the model's answer is still incorrect, but it has moved closer to the right response. Specifically, it was now able to identify the name of the television pilot (\"Best of Times\"). Let's see what the hallucinated answer looks like.\npython\n\n```\nquery_bundle = hyde(\"Who directed the pilot that marked the acting debut of Nicolas Cage?\")\nhyde_doc = query_bundle.embedding_strs[0]\nhyde_doc\n```\n\n![HyDE output for the first query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/13oTouqMYtXILfMnRnp2k_Q.png)\nHyDE output for the first query. Image by author.\nWhile it is not true that Francis Coppola directed \"The Best of Times\", at least the hallucination included the movie's name.\n**Query 2**\npython\n\n```\nresponse = hyde_query_engine.query(\"Compare the education received by Nicolas Cage and Leonardo DiCaprio.\")\nprint(response)\n```\n\n![HyDE RAG output for the second query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1SXqCYqIV9zbuw6VnVy4v3g.png)\nHyDE RAG output for the second query. Image by author.\nThe answer is correct because the hallucinated answer improved the output significantly. The LLM already had information about the actors' education in the training data.\n![HyDE output for the second query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1GjvarL1brFGH2NIifJWldA.png)\nHyDE output for the second query. Image by author.\n## Sub Questions\nThe Sub Questions technique uses a divide-and-conquer approach to handle complex questions. It first analyzes the questions and breaks them down into simpler sub-questions. Each sub-question targets different relevant documents that can provide part of the answer.\nThe engine then gathers the intermediate responses and synthesizes all the partial results into a final response.\npython\n\n```\n# setup base query engine as tool\nquery_engine_tools = [\n    QueryEngineTool(\n        query_engine=vector_query_engine,\n        metadata=ToolMetadata(\n            name=\"Sub-question query engine\",\n            description=\"Questions about actors\",\n        ),\n    ),\n]\n\nquery_engine = SubQuestionQueryEngine.from_defaults(\n    query_engine_tools=query_engine_tools,\n    service_context=service_context,\n    use_async= False\n)\n```\n\n**Query 1**\n![Sub Questions RAG output for the first query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1AtE1cHKjDPFw_Z_Ux-XdMw.png)\nSub Questions RAG output for the first query. Image by author.\n![Generated Sub Questions for the first query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1TY6mSNzUFEn52X7_EOFbXg.png)\nGenerated Sub Questions for the first query. Image by author.\nThere are no ways to break down this question into simpler sub-questions that would make it easier to answer. The model tried to generate one sub-question but didn't provide any additional context beyond the original query, wasting computation on ineffective transformations.\n**Query 2**\n![Sub Questions RAG output for the second query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1WHYG2Z6nzfgLlwec2R6JCQ.png)\nSub Questions RAG output for the second query. Image by author.\n![Generated Sub Questions for the second query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1XQew-KOEOVmC-A8TMavVag.png)\nGenerated Sub Questions for the second query. Image by author.\nThis time, generating sub-questions was extremely useful because we needed to compare two distinct pieces of information - the educational backgrounds of two different people. Each sub-question can be answered independently using the retrieved context.\n## Multi-Step Query Transformation\n![Self-ask + Search Engine \\[1\\]](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1Nen6WVH8sfr-Oudxk_wwRw.png)\nSelf-ask + Search Engine [1]\nThe multi-step query transformation approach is based on the self-ask method, where the language model asks and answers follow-up questions to itself before answering the original question. This helps the model combine facts and insights it learned separately during pretraining.\nThe original paper showed that LLMs often fail to compose two facts together, even if they know each one independently. For example, a model may know Fact A and Fact B but fail to deduce the implication of A and B together.\nThe self-ask method aims to overcome this limitation. At test time, we simply provide the prompt and question to the model. Then, it automatically generates any necessary follow-up questions to connect facts, compose reasoning steps, and decide when to stop [1].\npython\n\n```\nquery_engine = MultiStepQueryEngine(\n    query_engine=query_engine,\n    query_transform=step_decompose_transform_gpt3,\n    index_summary=index_summary\n)\n```\n\n**Query 1**\n> Don Mischer directed the pilot that marked the acting debut of Nicolas Cage.\nThis is the first time we have had a correct answer to this query! Let's see the intermediate questions.\n![MultiStepQueryEngine output for the first query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/16xvRn0CjRJQJpwh4XuEy4Q.png)\nMultiStepQueryEngine output for the first query. Image by author.\nThe output of the first sub-question was the following:\n> The Best of Times pilot that marked the acting debut of Nicolas Cage was not directed by anyone in the Coppola family. It was directed by Rod Amateau.\nHaving identified the pilot name, the second sub-question now asks specifically about the director:\n> Who directed the Best of Times pilot that marked the acting debut of Nicolas Cage?\nThis multi-step approach helped the model build on the additional context from the prior question and led us to the correct answer.\n**Query 2**\n> Nicolas Cage received education in the field of theater, film, and television at UCLA School of Theater, Film and Television. On the other hand, Leonardo DiCaprio attended the Los Angeles Center for Enriched Studies, Seeds Elementary School, and John Marshall High School. However, DiCaprio dropped out of high school and later earned a general equivalency diploma.\n![MultiStepQueryEngine output for the second query. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1bY6EvGD7cqvN8BMz3APmsA.png)\nMultiStepQueryEngine output for the second query. Image by author.\nThe multi-step approach was also useful in this case. Our opinion is that for the second query, the sub-question technique from before is a better fit because it can be parallelized. The questions are independent and don't need to build on top of each other. But a multi-step approach can also be useful.\n## RouterQueryEngine\nEach query transformation proved useful for different cases. The sub-question decomposition works best for questions that can be broken into simpler sub-questions, like comparing Nicolas Cage and Leonardo DiCaprio's education.\nMulti-step transformation works best for queries that require exploring context iteratively, like linking multiple facets of information.\nSimple queries might not need any transformations at all, and applying them would be a waste of resources.\nTo handle choosing between all these cases, we can use a _RouterQueryEngine_ - we give an LLM a set of tools for query transformations and let it decide the best one to apply based on the input prompt.\nmakefile\n\n```\nquery_engine = RouterQueryEngine(\n    selector=PydanticSingleSelector.from_defaults(),\n    query_engine_tools=[\n        simple_tool,\n        multi_step_tool,\n        sub_question_tool,\n    ],\n)\n```\n\nWe created a router that allows selection between no transformation, sub-question decomposition, or multi-step transformations as needed for each unique query. Let's examine how the router reasons about which approach to take.\nFirst of all, we will choose a very simple question that needs no transformations.\nini\n\n```\nresponse_1 = query_engine.query(\"What is Nicolas Cage's profession?\")\n```\n\n![RouterQueryEngine output choosing simple_tool. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1qyx6eSFN6aLLmv8z46cmdA.png)\nRouterQueryEngine output choosing simple_tool. Image by author.\nThe router made the right choice by assessing that the query is relatively simple. No query transformations are needed to decompose or expand this question since it asks directly about a single fact regarding Nicolas Cage's occupation.\nini\n\n```\nresponse_2 = query_engine.query(\"Compare the education received by Nicolas Cage and Leonardo DiCaprio.\")\n```\n\n![RouterQueryEngine output choosing sub_question_tool. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1ViMKHBXW_fcU_LLzdaCLgA.png)\nRouterQueryEngine output choosing sub_question_tool. Image by author.\nTo answer a comparative question, the router accurately broke it down into simpler sub-questions about each individual.\nini\n\n```\nresponse_3 = query_engine.query(\"Who directed the pilot that marked the acting debut of Nicolas Cage?\")\n```\n\n![RouterQueryEngine output choosing multi_step_tool. Image by author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1cCM4xZ5zMVBuCrWqpFeYkA.png)\nRouterQueryEngine output choosing multi_step_tool. Image by author.\nFor the third query, the router recognizes that answering correctly requires linking multiple pieces of contextual information - specifically, identifying the pilot episode that marked Cage's acting debut and then determining who directed that particular pilot.\n## **Conclusion**\nAs we have explored, enhancing RAG through advanced query transformations can significantly improve model performance.\nWhile query transformation is just one of many techniques for improving retrieval, it demonstrates the potential and need for customized analysis that merges retrieval with the reasoning capabilities inherent to LLMs.\n. . .\n_If you enjoyed this article, join_[ _**Text Generation**_](https://textgeneration.substack.com/) _- our newsletter has two weekly posts with the latest insights on Generative AI and Large Language Models._\n_You can find the full code for this project on[ GitHub](https://github.com/partycia/query_transformations)._\n_You can also find me on_[ _LinkedIn_](https://www.linkedin.com/in/ibrezeanu/) _._\n. . .\n**References**\n  1. [Measuring and Narrowing the Compositionality Gap in Language Models](https://arxiv.org/abs/2210.03350)\n  2. [Lost in the Middle: How Language Models Use Long Contexts](https://arxiv.org/abs/2307.03172)\n  3. [Precise Zero-Shot Dense Retrieval without Relevance Labels](https://arxiv.org/abs/2212.10496)\n\n\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/1787657516549_c8nzry.png)\nWritten By\n## [Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[See all from Iulia Brezeanu](https://towardsdatascience.com/author/brezeanu.iulia/)\n[ChatGPT](https://towardsdatascience.com/tag/chatgpt/)[Generative Ai Tools](https://towardsdatascience.com/tag/generative-ai-tools/)[Hands On Tutorials](https://towardsdatascience.com/tag/hands-on-tutorials/)[Llm](https://towardsdatascience.com/tag/llm/)[NLP](https://towardsdatascience.com/tag/nlp/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fadvanced-query-transformations-to-improve-rag-11adca9b19d1%2F&title=Advanced%20Query%20Transformations%20to%20Improve%20RAG)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fadvanced-query-transformations-to-improve-rag-11adca9b19d1%2F&title=Advanced%20Query%20Transformations%20to%20Improve%20RAG)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fadvanced-query-transformations-to-improve-rag-11adca9b19d1%2F&text=Advanced%20Query%20Transformations%20to%20Improve%20RAG)\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/2025/08/museums-victoria-jc_WMrSJ8EY-unsplash.jpg)](https://towardsdatascience.com/how-we-reduced-llm-cost-by-90-with-5-lines-of-code/)\n## [How We Reduced LLM Costs by 90% with 5 Lines of Code](https://towardsdatascience.com/how-we-reduced-llm-cost-by-90-with-5-lines-of-code/)\n[Programming](https://towardsdatascience.com/category/programming/)\nWhen clean code hides inefficiencies: what we learned from fixing a few lines of code and saving 90% in LLM cost.\n[Uri Peled](https://towardsdatascience.com/author/uri.peled/)\nAugust 21, 20258 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/11/1SUhj4n10S8PWllp3-yQZtw.png)](https://towardsdatascience.com/llms-txt-414d5121bcb3/)\n## [LLMs.txt Explained](https://towardsdatascience.com/llms-txt-414d5121bcb3/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nYour guide to the web's new LLM-ready content standard\n[Derick Ruiz](https://towardsdatascience.com/author/dericksozo/)\nNovember 28, 20245 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA.webp)](https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0/)\n## [Evaluate Topic Models: Latent Dirichlet Allocation (LDA)](https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA step-by-step guide to building interpretable topic models\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nAugust 19, 201912 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/0EdW1YRwPSi4skGYV.png)](https://towardsdatascience.com/transformers-numeracy-pt-1-calculators-for-natural-language-e09a471c5ebe/)\n## [NLP & Numeracy (Pt 1) - Calculators for Natural Language](https://towardsdatascience.com/transformers-numeracy-pt-1-calculators-for-natural-language-e09a471c5ebe/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWhat is numeracy in NLP and why it matters?\n[Misho Dungarov](https://towardsdatascience.com/author/mihail.dungarov/)\nNovember 22, 202013 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/13CkXN9qcHevOATmMUpLyEQ.png)](https://towardsdatascience.com/going-beyond-keywords-with-nlp-42395f7e7c67/)\n## [Going Beyond Keywords with NLP](https://towardsdatascience.com/going-beyond-keywords-with-nlp-42395f7e7c67/)\n[NLP](https://towardsdatascience.com/category/artificial-intelligence/nlp/)\nMany NLP tasks can be solved with keyword-based approaches. For those that can't, try spaCy's linguistic features or a Transformer model.\n[Jared Rand](https://towardsdatascience.com/author/chiefastro/)\nNovember 30, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/11/1nBupXcoHdHGJPjSaFsZdWA.png)](https://towardsdatascience.com/large-language-models-structbert-incorporating-language-structures-into-pretraining-be3058ab23b3/)\n## [Large Language Models, StructBERT - Incorporating Language Structures into Pretraining](https://towardsdatascience.com/large-language-models-structbert-incorporating-language-structures-into-pretraining-be3058ab23b3/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nMaking models smarter by incorporating better learning objectives\n[Slava Efimov](https://towardsdatascience.com/author/slavahead/)\nNovember 22, 20234 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1TKIy7zGD_CS03xOGt3D_fA.png)](https://towardsdatascience.com/tool-use-agents-and-the-voyager-paper-5a0e548f8b38/)\n## [Tool Use, Agents, and the Voyager Paper](https://towardsdatascience.com/tool-use-agents-and-the-voyager-paper-5a0e548f8b38/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA detailed exploration of the Voyager Paper and its findings on tool usage\n[Matthew Gunton](https://towardsdatascience.com/author/mgunton7/)\nMay 1, 20248 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/0oO0twlaC4qGzG3wq-scaled.jpg)](https://towardsdatascience.com/text-classification-in-just-20-lines-of-code-8baf9c2a0a53/)\n## [Text Classification in Just 20 Lines of Code](https://towardsdatascience.com/text-classification-in-just-20-lines-of-code-8baf9c2a0a53/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nTraining a state of the art text classifier with Pytorch and Fastai with minimal setup!\n[Yash Prakash](https://towardsdatascience.com/author/ipom/)\nJanuary 5, 20213 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/12/0rGq-SGlFah9tQ_G2.png)](https://towardsdatascience.com/context-aided-forecasting-enhancing-forecasting-with-textual-data-c9af2ab057c1/)\n## [Context-Aided Forecasting: Enhancing Forecasting with Textual Data](https://towardsdatascience.com/context-aided-forecasting-enhancing-forecasting-with-textual-data-c9af2ab057c1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA promising alternative approach to improve forecasting\n[Nikos Kafritsas](https://towardsdatascience.com/author/nikoskafritsas/)\nDecember 2, 20248 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/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  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/3455f990759a/pages/",
  "body_markdown_path": "attachments/3455f990759a/pages/archived-body.md",
  "local_html": "attachments/3455f990759a/pages/archived-body.html",
  "body_source": "prior_capture"
}