{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Angela Shi & Kezhan Shi",
  "title_listed": "Prompt Engineering Isn't Enough: How Four Bricks of Context Engineering Stop RAG Hallucinations",
  "keywords": "",
  "domain": "大模型算法",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/prompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations/",
  "publish_date": "2026-07-21",
  "corpus_stage": "",
  "notes": "",
  "id": "387867f19833",
  "collected_at": "2026-10-02T01:20:46",
  "title": "Prompt Engineering Isn’t Enough: How Four Bricks of Context Engineering Stop RAG Hallucinations | 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[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\n# Prompt Engineering Isn’t Enough: How Four Bricks of Context Engineering Stop RAG Hallucinations\nEnterprise Document Intelligence [Vol.1 #9bis] - Your RAG isn’t hallucinating, it’s answering the wrong context faithfully. On real NIST and World Bank documents, watch each of the four bricks break, and the contract that closes it\n[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\nJuly 21, 20269 min read\n![](../images/000.jpg)\n[Photo](https://www.pexels.com/photo/14059293/) by Tibor Szabo, via Pexels.\nIn the previous two articles ([Part A](https://towardsdatascience.com/a-production-rag-pipeline-for-pdfs-relational-parsing-toc-retrieval-typed-answers/) and Part B) we built the upgraded pipeline and watched it work: pointed at a research paper, a NIST standard, and a report with a broken table of contents, it returned a typed, cited answer each time. So why does it work? And would a naive RAG, the kind almost everyone builds first, embed the pages, keep the closest few, ask, have done the same?\nThis article runs the two side by side. The short answer is no, and the useful part is where the naive one breaks: not in one place, but at each of the four bricks in turn, document parsing, question parsing, retrieval, and generation, each time for a reason you can name and fix.\nIt is also why the usual reflexes — rewrite the prompt, shrink the chunks, swap the embedding model — do not help. The wrong answer does not come from the prompt. It comes from a brick upstream handing the model the wrong context, which the model then answers faithfully. Getting all four bricks right, not just the prompt, is what this series calls **context engineering**. Every failure below is a real run, never an assumed one; the companion notebook reproduces each one. Article 7quinquies (most RAG hallucinations are retrieval failures) makes the same case at the retrieval level on one document; this one shows it across all four bricks.\nLearn this step by step with the interactive [AI Engineer](https://roadmap.sh/ai-engineer) roadmap.\n![](../images/001.png)\n_where this article sits: a companion to Article 9 (the upgraded pipeline), in Part III - Image by author_\n📓 **The runnable notebook for this article is on GitHub** : [doc-intel/notebooks-vol1](https://github.com/doc-intel/notebooks-vol1). It runs the naive baseline and the upgraded `pdf_qa` side by side on each document below, prints both answers with their confidence, and reproduces every cross in the figures on your own machine.\n![](../images/002.png)\n_The public companion-code repo at doc-intel/notebooks-vol1 - Image by author_\n## 1. The naive baseline, brick by brick\nThe baseline is the 100-line pipeline from Article 1 (minimal RAG): parse the PDF, turn the question into keywords, keep the top few pages by match, ask the model to answer. On a short, clean, prose paper it works, and Article 9’s own tests confirmed it: on _Attention Is All You Need_ and the RAG paper, naive and upgraded both answer correctly.\nThe upgraded pipeline is the _same_ four bricks, each with a tighter contract: parsing returns a relational `line_df` instead of flat text, question parsing expands the query into the document’s vocabulary, retrieval routes on the table of contents, generation returns a typed answer. A naive RAG runs the loose version of every brick. The gap opens exactly where each loose brick hands the model the wrong thing. Each section below isolates one brick: it swaps that brick for its naive version and leaves the others reasonable, so the failure, and the fix, belong to the brick named in the heading.\n![](../images/003.png)\n_The same symptom, a confident wrong answer, arrives four ways, one per brick, each closed by a different contract - Image by author_\nRead it top to bottom: the same symptom, a confident wrong answer, arrives four different ways, and a different brick closes each. The rest of the article walks the four, each on a real document.\n## 2. Parsing: a table flattened into noise\n**Document:** World Bank Commodity Markets Outlook (a report built around price tables). **Question:** _What is the 2025 annual average price forecast for U.S. natural gas (Henry Hub)?_\n![](../images/body-da798c1256aa0eaa6e6a.png)\n_Real runs on the same table question: what each pipeline does, the answer it returns, and why - Image by author_\nA naive pipeline parses a PDF the common way: dump flat text with `get_text()` and cut it into fixed-size chunks. That is fine for prose and fatal for tables. A price table is a grid; flat extraction linearises it, and a fixed-size chunker then cuts the stream wherever the character budget runs out. The row label _Henry Hub_ lands in one chunk and its _3.5_ cell in another. Retrieval hands the model chunks that never carry both, and it answers honestly: _“not stated in these lines,”_ confidence **0.00**.\nNothing was hallucinated. The number was in the document; the parser destroyed the one thing that made it an answer, the alignment between the label and the cell.\n**The fix is relational parsing.** Instead of flat text, the upgraded brick returns a `line_df`: one row per text line, each with its bounding box. The table’s row stays intact, the model reads _Henry Hub_ and _3.5_ on the same line, and returns _“$3.5 per mmbtu”_ at confidence **0.99**. This is the whole argument of the parsing brick (Article 5): stop returning flat text, keep the relational shape the answer lives in.\n## 3. Question: a word the document never uses\n**Document:** NIST SP 800-207, Zero Trust Architecture. **Question:** _What are the pillars of zero trust architecture?_\n![](../images/body-8dbcd1c5dc6e76c613f4.png)\n_Real runs on the same question: what each pipeline does, the answer it returns, and why - Image by author_\nThe document never uses the word _pillars_. It calls them _tenets_. A naive pipeline searches the pages for the query’s own words, _pillars_ scores against nothing, and the model reports _“the specific pillars are not listed,”_ confidence **0.20**. The answer is right there, under a different name; the right pages were never even searched.\nThis is not a ranking problem, and no bigger top-k fixes it: the query word simply is not in the document. It is a vocabulary problem, and it lives one brick before retrieval, in question parsing. The user’s word and the document’s word are synonyms the raw string cannot bridge.\n**The fix is question parsing.** Before retrieval runs, the brick normalizes and expands the query, mapping domain synonyms (_pillars_ → _tenets_ , _principles_) so retrieval searches for the words the document actually uses. It then anchors the tenets section, and generation returns all seven at confidence **0.95** , noting the document’s own term. The same expansion lets a user ask about a _dog_ and match a policy that only ever says _animal_ , the case Article 7quinquies (most RAG hallucinations are retrieval failures) walks in detail.\n## 4. Retrieval: the answer below the cutoff\n**Document:** NIST Cybersecurity Framework 2.0 (32 pages, native table of contents). **Question:** _How is a Profile defined in CSF 2.0?_\n![](../images/body-aa15ca9b853471176750.png)\n_Real runs on the same question: what each pipeline does, the answer it returns, and why - Image by author_\nThe word _Profile_ is on many pages of CSF 2.0: it names a section, recurs in prose, heads examples. Only one section defines it. Keyword and cosine retrieval rank a page by how relevant it looks to the term, and every _Profile_ page looks equally relevant. The naive pipeline keeps the top few by frequency, none of which is the defining page, and the model reports _“not defined in these lines,”_ confidence **0.10**. The answering page fell below the top-k cutoff.\n**The fix is retrieval that routes on structure.** The upgraded brick reads the document’s own table of contents through a small LLM, sees the section titled _CSF Profiles_ , and anchors retrieval there instead of on raw frequency. Generation sees the defining paragraph and returns the full definition with a citable span, confidence **0.95**.\nThe same routing scales where naive retrieval gets worse. On the 400-plus-page NIST SP 800-53 control catalog, asked for the single AU-2 Event Logging control, naive retrieval dilutes it past the cutoff among a thousand near-identical siblings and returns _“NA”_ at **0.00** ; the router locates the AU family and the AU-2 entry directly and returns the full requirement, clause by clause, at **0.98**. Routing on structure does not degrade as the document grows; ranking on frequency does.\n## 5. Generation: a confident answer with no self-check\n**Document:** World Bank Commodity Markets Outlook, April 2024 (its forecasts stop at 2025). **Question:** _What is the 2026 annual average price forecast for crude oil (Brent)?_\n![](../images/body-3fefa380adb769f582f7.png)\n_Real runs on the same question: what each pipeline does, the answer it returns, and why - Image by author_\nThis time both pipelines retrieve the same, correct context: the energy pages with the price table. The document simply has no 2026 row. A naive pipeline’s generation brick asks the model for a free-text answer, and a free-text model asked a question tends to answer. It grabs the nearest number, the 2025 value of $79, and returns _“the 2026 Brent forecast is $79 per barrel”_ , confident, fluent, and wrong. Nothing in a prose answer could have said _“this is not in the document.”_ This is the hallucination readers report, and it happened at the last brick, with good context in hand.\n**The fix is a typed generation contract.** The upgraded brick does not ask for prose; it asks for a schema with a `complete_answer_found` field the model must set, an evidence span it must cite, and a confidence it must justify. Faced with a value that is not in the lines, the model cannot quietly fill the gap: it sets `complete_answer_found: false` and returns _“the 2026 forecast is not provided; the latest is 2025.”_ The generation brick does not make the answer smarter. It makes a missing or partial answer visible, so a wrong one cannot ship as done. The same `complete_answer_found` field guards partial answers in general: whenever retrieval surfaces only part of what the question asked, it is the difference between shipping a fragment as if it were whole and flagging the gap.\n## 6. One root, four doors\nThe four failures are one thing seen four ways. In none of them did the model invent from nothing. Each time it answered the context it was handed, faithfully, and the context was wrong: a table the parser scrambled, pages found for a word the document never uses, the answering page left below the cutoff, or a value that was never there and got filled in anyway. The label _hallucination_ points at the model; the cause was a brick upstream.\nThe common fix is not a better prompt, a bigger model, or a larger top-k. It is **context engineering** , one contract per brick: keep the document’s relational shape (parsing), search in the document’s own vocabulary (question), route on the document’s own map (retrieval), and bind the answer to a typed, checkable contract (generation). Get the context right and a confident wrong answer has nowhere to come from, because the model is no longer being asked to answer the wrong context.\nTwo honest caveats. First, naive RAG is not always wrong: on short, clean, prose documents it keeps up, and the honest figure in Article 9 shows it. The gap opens exactly where enterprise documents live: tables, house vocabulary, length, structure. Second, these four crosses are the ones that held up. We ran the naive baseline and the upgraded pipeline on many more (document, question) pairs, and where naive did fine we say so rather than manufacture a failure. Each cross above is a real run, not a manufactured one.\n![](../images/body-10b9d2b754e646544736.png)\n_The upgraded pipeline is rung 2 of 5; getting the context right is what every rung above builds on - Image by author_\n## 7. Sources and further reading\nThe failure cases are real runs of the naive baseline (`pdf_qa_baseline`, plus a flat-chunk parser and a free-text generator for the parsing and generation bricks) against the upgraded `pdf_qa` (Article 9); each one is a real run, reproducible in the companion notebook, not an assumed result. The `responses.parse(text_format=Schema)` pattern behind the typed answer uses OpenAI’s [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs).\n**Earlier in the series:**\n  * [Document Intelligence: series intro](https://towardsdatascience.com/document-intelligence-a-series-on-building-rag-brick-by-brick-from-minimal-to-corpus-scale/). What the series builds, brick by brick, and in what order.\n  * [The minimal Enterprise RAG that never lies about its source: PDF in, highlighted answer out](https://towardsdatascience.com/baseline-enterprise-rag-from-pdf-to-highlighted-answer-enterprise-document-intelligence-vol-1-1/). The naive four-brick baseline this article stress-tests.\n  * [Retrieval is filtering, not search: a mental model for enterprise RAG](https://towardsdatascience.com/retrieval-is-filtering-not-search-a-mental-model-for-enterprise-rag/). Retrieval reframed as filtering, the idea behind TOC routing.\n  * _Most RAG hallucinations are retrieval failures_ (Article 7quinquies, link to come). The same argument at the retrieval level, on one document, including the vocabulary-mismatch case.\n  * _A production RAG pipeline for PDFs: relational parsing, TOC retrieval, typed answers_ (Article 9, link to come). The upgraded pipeline these cases run on.\n\n\n**Documents used (all openly licensed):**\n  * World Bank, [_Commodity Markets Outlook_](https://www.worldbank.org/en/research/commodity-markets), April 2024. The price-table parsing case (section 2) and the absent-value generation case (section 5). CC BY 3.0 IGO.\n  * NIST, [_Zero Trust Architecture_](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-207.pdf), SP 800-207, August 2020. The vocabulary-mismatch case (section 3). US Government work, public domain in the US.\n  * NIST, [_The NIST Cybersecurity Framework (CSF) 2.0_](https://nvlpubs.nist.gov/nistpubs/CSWP/NIST.CSWP.29.pdf), NIST CSWP 29, February 2024 ([DOI 10.6028/NIST.CSWP.29](https://doi.org/10.6028/NIST.CSWP.29)). The buried-definition retrieval case (section 4). US Government work, public domain in the US.\n  * NIST, [_Security and Privacy Controls for Information Systems and Organizations_](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-53r5.pdf), SP 800-53 Rev. 5. The diluted-control retrieval case at scale (section 4). US Government work, public domain in the US.\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-249d024535392fb76067.jpeg)\nWritten By\n## [Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\n[See all from Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\n[Context Engineering](https://towardsdatascience.com/tag/context-engineering/)[Document Processing](https://towardsdatascience.com/tag/document-processing/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Rag](https://towardsdatascience.com/tag/rag/)[Rag Architecture](https://towardsdatascience.com/tag/rag-architecture/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fprompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations%2F&title=Prompt%20Engineering%20Isn%E2%80%99t%20Enough%3A%20How%20Four%20Bricks%20of%20Context%20Engineering%20Stop%20RAG%20Hallucinations)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fprompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations%2F&title=Prompt%20Engineering%20Isn%E2%80%99t%20Enough%3A%20How%20Four%20Bricks%20of%20Context%20Engineering%20Stop%20RAG%20Hallucinations)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fprompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations%2F&text=Prompt%20Engineering%20Isn%E2%80%99t%20Enough%3A%20How%20Four%20Bricks%20of%20Context%20Engineering%20Stop%20RAG%20Hallucinations)\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/004.png)](https://towardsdatascience.com/why-retrieval-augmented-generation-is-still-relevant-in-the-era-of-long-context-language-models-e36f509abac5/)\n## [Why Retrieval-Augmented Generation Is Still Relevant in the Era of Long-Context Language Models](https://towardsdatascience.com/why-retrieval-augmented-generation-is-still-relevant-in-the-era-of-long-context-language-models-e36f509abac5/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIn this article we will explore why 128K tokens and more models can't fully replace using RAG.\n[Jérôme DIAZ](https://towardsdatascience.com/author/jerome.o.diaz/)\nDecember 12, 20247 min read\n  * [![](../images/005.jpg)](https://towardsdatascience.com/fp-growth-frequent-pattern-generation-in-data-mining-with-python-implementation-244e561ab1c3/)\n## [FP Growth: Frequent Pattern Generation in Data Mining with Python Implementation](https://towardsdatascience.com/fp-growth-frequent-pattern-generation-in-data-mining-with-python-implementation-244e561ab1c3/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIn this article, an advanced method called the FP Growth algorithm will be revealed. We will walk through the whole process of the FP...\n[Chonyy](https://towardsdatascience.com/author/chonyy/)\nOctober 30, 20208 min read\n  * [![](../images/006.jpg)](https://towardsdatascience.com/optimizing-marketing-campaigns-with-budgeted-multi-armed-bandits-a65fccd61878/)\n## [Optimizing Marketing Campaigns with Budgeted Multi-Armed Bandits](https://towardsdatascience.com/optimizing-marketing-campaigns-with-budgeted-multi-armed-bandits-a65fccd61878/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nWith demos, our new solution, and a video\n[Vadim Arzamasov](https://towardsdatascience.com/author/vadim.arzamasov/)\nAugust 16, 20249 min read\n  * [![](../images/007.jpg)](https://towardsdatascience.com/top-5-statistical-concepts-every-data-scientist-must-know-d4bc8740a55d/)\n## [Top 5 Statistical Concepts Every Data Scientist Must Know](https://towardsdatascience.com/top-5-statistical-concepts-every-data-scientist-must-know-d4bc8740a55d/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nEssential pillars of statistics and data science\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nAugust 29, 20207 min read\n  * [![](../images/008.jpg)](https://towardsdatascience.com/geoparsing-with-python-and-natural-language-processing-4762a7c92f08/)\n## [Geoparsing with Python and Natural Language Processing](https://towardsdatascience.com/geoparsing-with-python-and-natural-language-processing-4762a7c92f08/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nExtracting place names and assigning coordinates - Tutorial\n[Abdishakur](https://towardsdatascience.com/author/shakasom/)\nJune 11, 20204 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/enhancing-e-commerce-with-generative-ai-part-1-9e402fb30e7b/)\n## [Enhancing E-Commerce with Generative AI - Part 1](https://towardsdatascience.com/enhancing-e-commerce-with-generative-ai-part-1-9e402fb30e7b/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nFrom Data to Product Recommendations\n[Mina Ghashami](https://towardsdatascience.com/author/mina.ghashami/)\nJuly 31, 202417 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/you-need-this-to-thrive-as-a-data-scientist-in-a-business-environment-4be7de4f7afd/)\n## [You Need This to Thrive as a Data Scientist - In a Business Environment](https://towardsdatascience.com/you-need-this-to-thrive-as-a-data-scientist-in-a-business-environment-4be7de4f7afd/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nDrastically Increment Your Value Contribution and Business Understanding with this Must-Read Book\n[Victor Roman](https://towardsdatascience.com/author/rromanss23/)\nDecember 14, 20206 min read\n  * [![](../images/011.png)](https://towardsdatascience.com/deep-dive-into-llamaindex-workflow-event-driven-llm-architecture-8011f41f851a/)\n## [Deep Dive into LlamaIndex Workflow: Event-Driven LLM Architecture](https://towardsdatascience.com/deep-dive-into-llamaindex-workflow-event-driven-llm-architecture-8011f41f851a/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nWhat I think about the progress and shortcomings after practice\n[Peng Qian](https://towardsdatascience.com/author/qtalen/)\nDecember 17, 202415 min read\n  * [![](../images/012.png)](https://towardsdatascience.com/reinforcement-learning-part-5-temporal-difference-learning-cacf7854fe0c/)\n## [Reinforcement Learning, Part 5: Temporal-Difference Learning](https://towardsdatascience.com/reinforcement-learning-part-5-temporal-difference-learning-cacf7854fe0c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIntelligently synergizing dynamic programming and Monte Carlo algorithms\n[Slava Efimov](https://towardsdatascience.com/author/slavahead/)\nJuly 13, 202416 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/607631/image?etag=1781543525510&width=500&height=500) Critical Mistakes Companies Make When Integrating AI/ML into Their Processes ](https://towardsdatascience.com/critical-mistakes-companies-make-when-integrating-ai-ml-into-their-processes/ \"Critical Mistakes Companies Make When Integrating AI/ML into Their Processes\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n\n\n",
  "metadata": {
    "title": "Prompt Engineering Isn’t Enough: How Four Bricks of Context Engineering Stop RAG Hallucinations | Towards Data Science",
    "description": "Enterprise Document Intelligence [Vol.1 #9bis] - Your RAG isn’t hallucinating, it’s answering the wrong context faithfully. On real NIST and World Bank documents, watch each of the four bricks break, and the contract that closes it",
    "keywords": null,
    "author": "Angela and Kezhan Shi",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Prompt Engineering Isn’t Enough: How Four Bricks of Context Engineering Stop RAG Hallucinations",
    "og:description": "Enterprise Document Intelligence [Vol.1 #9bis] - Your RAG isn’t hallucinating, it’s answering the wrong context faithfully. On real NIST and World Bank documents, watch each of the four bricks break, and the contract that closes it",
    "og:url": "https://towardsdatascience.com/prompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/signpost_14059293_card.jpg",
    "og:image:width": "1200",
    "og:image:height": "630",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Angela and Kezhan Shi",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "9 min read",
    "article:published_time": "2026-07-21T10:30:07.000Z",
    "article:modified_time": "2026-07-21T10:30:07.000Z",
    "article:author": "https://towardsdatascience.com/author/angela.shi/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607631/image?etag=1781543525510&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607631/image?etag=1781543525510&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:45:41Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:45:41Z"
    },
    {
      "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:45:41Z"
    },
    {
      "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:45:41Z"
    }
  ],
  "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/large-language-models/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/angela.shi/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/a-production-rag-pipeline-for-pdfs-relational-parsing-toc-retrieval-typed-answers/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/document-intelligence-a-series-on-building-rag-brick-by-brick-from-minimal-to-corpus-scale/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/baseline-enterprise-rag-from-pdf-to-highlighted-answer-enterprise-document-intelligence-vol-1-1/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/retrieval-is-filtering-not-search-a-mental-model-for-enterprise-rag/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/context-engineering/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/document-processing/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/rag/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/rag-architecture/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/why-retrieval-augmented-generation-is-still-relevant-in-the-era-of-long-context-language-models-e36f509abac5/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/jerome.o.diaz/"
    },
    {
      "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://www.pexels.com/photo/14059293/"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-engineer"
    },
    {
      "type": "external",
      "href": "https://github.com/doc-intel/notebooks-vol1"
    },
    {
      "type": "external",
      "href": "https://platform.openai.com/docs/guides/structured-outputs"
    },
    {
      "type": "external",
      "href": "https://www.worldbank.org/en/research/commodity-markets"
    },
    {
      "type": "external",
      "href": "https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-207.pdf"
    },
    {
      "type": "external",
      "href": "https://nvlpubs.nist.gov/nistpubs/CSWP/NIST.CSWP.29.pdf"
    },
    {
      "type": "external",
      "href": "https://doi.org/10.6028/NIST.CSWP.29"
    },
    {
      "type": "external",
      "href": "https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-53r5.pdf"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Prompt+Engineering+Isn%E2%80%99t+Enough%3A+How+Four+Bricks+of+Context+Engineering+Stop+RAG+Hallucinations&u=https%3A%2F%2Ftowardsdatascience.com%2Fprompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Prompt+Engineering+Isn%E2%80%99t+Enough%3A+How+Four+Bricks+of+Context+Engineering+Stop+RAG+Hallucinations&url=https%3A%2F%2Ftowardsdatascience.com%2Fprompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Prompt+Engineering+Isn%E2%80%99t+Enough%3A+How+Four+Bricks+of+Context+Engineering+Stop+RAG+Hallucinations&url=https%3A%2F%2Ftowardsdatascience.com%2Fprompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations%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"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:25:32Z",
  "source_url": "https://towardsdatascience.com/prompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations/",
  "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[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\n# Prompt Engineering Isn’t Enough: How Four Bricks of Context Engineering Stop RAG Hallucinations\nEnterprise Document Intelligence [Vol.1 #9bis] - Your RAG isn’t hallucinating, it’s answering the wrong context faithfully. On real NIST and World Bank documents, watch each of the four bricks break, and the contract that closes it\n[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\nJuly 21, 20269 min read\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/signpost_14059293_card.jpg)\n[Photo](https://www.pexels.com/photo/14059293/) by Tibor Szabo, via Pexels.\nIn the previous two articles ([Part A](https://towardsdatascience.com/a-production-rag-pipeline-for-pdfs-relational-parsing-toc-retrieval-typed-answers/) and Part B) we built the upgraded pipeline and watched it work: pointed at a research paper, a NIST standard, and a report with a broken table of contents, it returned a typed, cited answer each time. So why does it work? And would a naive RAG, the kind almost everyone builds first, embed the pages, keep the closest few, ask, have done the same?\nThis article runs the two side by side. The short answer is no, and the useful part is where the naive one breaks: not in one place, but at each of the four bricks in turn, document parsing, question parsing, retrieval, and generation, each time for a reason you can name and fix.\nIt is also why the usual reflexes — rewrite the prompt, shrink the chunks, swap the embedding model — do not help. The wrong answer does not come from the prompt. It comes from a brick upstream handing the model the wrong context, which the model then answers faithfully. Getting all four bricks right, not just the prompt, is what this series calls **context engineering**. Every failure below is a real run, never an assumed one; the companion notebook reproduces each one. Article 7quinquies (most RAG hallucinations are retrieval failures) makes the same case at the retrieval level on one document; this one shows it across all four bricks.\nLearn this step by step with the interactive [AI Engineer](https://roadmap.sh/ai-engineer) roadmap.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/image-147-1024x572.png)\n_where this article sits: a companion to Article 9 (the upgraded pipeline), in Part III - Image by author_\n📓 **The runnable notebook for this article is on GitHub** : [doc-intel/notebooks-vol1](https://github.com/doc-intel/notebooks-vol1). It runs the naive baseline and the upgraded `pdf_qa` side by side on each document below, prints both answers with their confidence, and reproduces every cross in the figures on your own machine.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/image-150-1024x658.png)\n_The public companion-code repo at doc-intel/notebooks-vol1 - Image by author_\n## 1. The naive baseline, brick by brick\nThe baseline is the 100-line pipeline from Article 1 (minimal RAG): parse the PDF, turn the question into keywords, keep the top few pages by match, ask the model to answer. On a short, clean, prose paper it works, and Article 9’s own tests confirmed it: on _Attention Is All You Need_ and the RAG paper, naive and upgraded both answer correctly.\nThe upgraded pipeline is the _same_ four bricks, each with a tighter contract: parsing returns a relational `line_df` instead of flat text, question parsing expands the query into the document’s vocabulary, retrieval routes on the table of contents, generation returns a typed answer. A naive RAG runs the loose version of every brick. The gap opens exactly where each loose brick hands the model the wrong thing. Each section below isolates one brick: it swaps that brick for its naive version and leaves the others reasonable, so the failure, and the fix, belong to the brick named in the heading.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/image-154-1024x854.png)\n_The same symptom, a confident wrong answer, arrives four ways, one per brick, each closed by a different contract - Image by author_\nRead it top to bottom: the same symptom, a confident wrong answer, arrives four different ways, and a different brick closes each. The rest of the article walks the four, each on a real document.\n## 2. Parsing: a table flattened into noise\n**Document:** World Bank Commodity Markets Outlook (a report built around price tables). **Question:** _What is the 2025 annual average price forecast for U.S. natural gas (Henry Hub)?_\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/image-152-1024x378.png)\n_Real runs on the same table question: what each pipeline does, the answer it returns, and why - Image by author_\nA naive pipeline parses a PDF the common way: dump flat text with `get_text()` and cut it into fixed-size chunks. That is fine for prose and fatal for tables. A price table is a grid; flat extraction linearises it, and a fixed-size chunker then cuts the stream wherever the character budget runs out. The row label _Henry Hub_ lands in one chunk and its _3.5_ cell in another. Retrieval hands the model chunks that never carry both, and it answers honestly: _“not stated in these lines,”_ confidence **0.00**.\nNothing was hallucinated. The number was in the document; the parser destroyed the one thing that made it an answer, the alignment between the label and the cell.\n**The fix is relational parsing.** Instead of flat text, the upgraded brick returns a `line_df`: one row per text line, each with its bounding box. The table’s row stays intact, the model reads _Henry Hub_ and _3.5_ on the same line, and returns _“$3.5 per mmbtu”_ at confidence **0.99**. This is the whole argument of the parsing brick (Article 5): stop returning flat text, keep the relational shape the answer lives in.\n## 3. Question: a word the document never uses\n**Document:** NIST SP 800-207, Zero Trust Architecture. **Question:** _What are the pillars of zero trust architecture?_\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/image-153-1024x378.png)\n_Real runs on the same question: what each pipeline does, the answer it returns, and why - Image by author_\nThe document never uses the word _pillars_. It calls them _tenets_. A naive pipeline searches the pages for the query’s own words, _pillars_ scores against nothing, and the model reports _“the specific pillars are not listed,”_ confidence **0.20**. The answer is right there, under a different name; the right pages were never even searched.\nThis is not a ranking problem, and no bigger top-k fixes it: the query word simply is not in the document. It is a vocabulary problem, and it lives one brick before retrieval, in question parsing. The user’s word and the document’s word are synonyms the raw string cannot bridge.\n**The fix is question parsing.** Before retrieval runs, the brick normalizes and expands the query, mapping domain synonyms (_pillars_ → _tenets_ , _principles_) so retrieval searches for the words the document actually uses. It then anchors the tenets section, and generation returns all seven at confidence **0.95** , noting the document’s own term. The same expansion lets a user ask about a _dog_ and match a policy that only ever says _animal_ , the case Article 7quinquies (most RAG hallucinations are retrieval failures) walks in detail.\n## 4. Retrieval: the answer below the cutoff\n**Document:** NIST Cybersecurity Framework 2.0 (32 pages, native table of contents). **Question:** _How is a Profile defined in CSF 2.0?_\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/image-149-1024x378.png)\n_Real runs on the same question: what each pipeline does, the answer it returns, and why - Image by author_\nThe word _Profile_ is on many pages of CSF 2.0: it names a section, recurs in prose, heads examples. Only one section defines it. Keyword and cosine retrieval rank a page by how relevant it looks to the term, and every _Profile_ page looks equally relevant. The naive pipeline keeps the top few by frequency, none of which is the defining page, and the model reports _“not defined in these lines,”_ confidence **0.10**. The answering page fell below the top-k cutoff.\n**The fix is retrieval that routes on structure.** The upgraded brick reads the document’s own table of contents through a small LLM, sees the section titled _CSF Profiles_ , and anchors retrieval there instead of on raw frequency. Generation sees the defining paragraph and returns the full definition with a citable span, confidence **0.95**.\nThe same routing scales where naive retrieval gets worse. On the 400-plus-page NIST SP 800-53 control catalog, asked for the single AU-2 Event Logging control, naive retrieval dilutes it past the cutoff among a thousand near-identical siblings and returns _“NA”_ at **0.00** ; the router locates the AU family and the AU-2 entry directly and returns the full requirement, clause by clause, at **0.98**. Routing on structure does not degrade as the document grows; ranking on frequency does.\n## 5. Generation: a confident answer with no self-check\n**Document:** World Bank Commodity Markets Outlook, April 2024 (its forecasts stop at 2025). **Question:** _What is the 2026 annual average price forecast for crude oil (Brent)?_\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/image-151-1024x378.png)\n_Real runs on the same question: what each pipeline does, the answer it returns, and why - Image by author_\nThis time both pipelines retrieve the same, correct context: the energy pages with the price table. The document simply has no 2026 row. A naive pipeline’s generation brick asks the model for a free-text answer, and a free-text model asked a question tends to answer. It grabs the nearest number, the 2025 value of $79, and returns _“the 2026 Brent forecast is $79 per barrel”_ , confident, fluent, and wrong. Nothing in a prose answer could have said _“this is not in the document.”_ This is the hallucination readers report, and it happened at the last brick, with good context in hand.\n**The fix is a typed generation contract.** The upgraded brick does not ask for prose; it asks for a schema with a `complete_answer_found` field the model must set, an evidence span it must cite, and a confidence it must justify. Faced with a value that is not in the lines, the model cannot quietly fill the gap: it sets `complete_answer_found: false` and returns _“the 2026 forecast is not provided; the latest is 2025.”_ The generation brick does not make the answer smarter. It makes a missing or partial answer visible, so a wrong one cannot ship as done. The same `complete_answer_found` field guards partial answers in general: whenever retrieval surfaces only part of what the question asked, it is the difference between shipping a fragment as if it were whole and flagging the gap.\n## 6. One root, four doors\nThe four failures are one thing seen four ways. In none of them did the model invent from nothing. Each time it answered the context it was handed, faithfully, and the context was wrong: a table the parser scrambled, pages found for a word the document never uses, the answering page left below the cutoff, or a value that was never there and got filled in anyway. The label _hallucination_ points at the model; the cause was a brick upstream.\nThe common fix is not a better prompt, a bigger model, or a larger top-k. It is **context engineering** , one contract per brick: keep the document’s relational shape (parsing), search in the document’s own vocabulary (question), route on the document’s own map (retrieval), and bind the answer to a typed, checkable contract (generation). Get the context right and a confident wrong answer has nowhere to come from, because the model is no longer being asked to answer the wrong context.\nTwo honest caveats. First, naive RAG is not always wrong: on short, clean, prose documents it keeps up, and the honest figure in Article 9 shows it. The gap opens exactly where enterprise documents live: tables, house vocabulary, length, structure. Second, these four crosses are the ones that held up. We ran the naive baseline and the upgraded pipeline on many more (document, question) pairs, and where naive did fine we say so rather than manufacture a failure. Each cross above is a real run, not a manufactured one.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/image-148-1024x866.png)\n_The upgraded pipeline is rung 2 of 5; getting the context right is what every rung above builds on - Image by author_\n## 7. Sources and further reading\nThe failure cases are real runs of the naive baseline (`pdf_qa_baseline`, plus a flat-chunk parser and a free-text generator for the parsing and generation bricks) against the upgraded `pdf_qa` (Article 9); each one is a real run, reproducible in the companion notebook, not an assumed result. The `responses.parse(text_format=Schema)` pattern behind the typed answer uses OpenAI’s [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs).\n**Earlier in the series:**\n  * [Document Intelligence: series intro](https://towardsdatascience.com/document-intelligence-a-series-on-building-rag-brick-by-brick-from-minimal-to-corpus-scale/). What the series builds, brick by brick, and in what order.\n  * [The minimal Enterprise RAG that never lies about its source: PDF in, highlighted answer out](https://towardsdatascience.com/baseline-enterprise-rag-from-pdf-to-highlighted-answer-enterprise-document-intelligence-vol-1-1/). The naive four-brick baseline this article stress-tests.\n  * [Retrieval is filtering, not search: a mental model for enterprise RAG](https://towardsdatascience.com/retrieval-is-filtering-not-search-a-mental-model-for-enterprise-rag/). Retrieval reframed as filtering, the idea behind TOC routing.\n  * _Most RAG hallucinations are retrieval failures_ (Article 7quinquies, link to come). The same argument at the retrieval level, on one document, including the vocabulary-mismatch case.\n  * _A production RAG pipeline for PDFs: relational parsing, TOC retrieval, typed answers_ (Article 9, link to come). The upgraded pipeline these cases run on.\n\n\n**Documents used (all openly licensed):**\n  * World Bank, [_Commodity Markets Outlook_](https://www.worldbank.org/en/research/commodity-markets), April 2024. The price-table parsing case (section 2) and the absent-value generation case (section 5). CC BY 3.0 IGO.\n  * NIST, [_Zero Trust Architecture_](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-207.pdf), SP 800-207, August 2020. The vocabulary-mismatch case (section 3). US Government work, public domain in the US.\n  * NIST, [_The NIST Cybersecurity Framework (CSF) 2.0_](https://nvlpubs.nist.gov/nistpubs/CSWP/NIST.CSWP.29.pdf), NIST CSWP 29, February 2024 ([DOI 10.6028/NIST.CSWP.29](https://doi.org/10.6028/NIST.CSWP.29)). The buried-definition retrieval case (section 4). US Government work, public domain in the US.\n  * NIST, [_Security and Privacy Controls for Information Systems and Organizations_](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-53r5.pdf), SP 800-53 Rev. 5. The diluted-control retrieval case at scale (section 4). US Government work, public domain in the US.\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/1787657699750_yw6uqg.jpeg)\nWritten By\n## [Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\n[See all from Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\n[Context Engineering](https://towardsdatascience.com/tag/context-engineering/)[Document Processing](https://towardsdatascience.com/tag/document-processing/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Rag](https://towardsdatascience.com/tag/rag/)[Rag Architecture](https://towardsdatascience.com/tag/rag-architecture/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fprompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations%2F&title=Prompt%20Engineering%20Isn%E2%80%99t%20Enough%3A%20How%20Four%20Bricks%20of%20Context%20Engineering%20Stop%20RAG%20Hallucinations)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fprompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations%2F&title=Prompt%20Engineering%20Isn%E2%80%99t%20Enough%3A%20How%20Four%20Bricks%20of%20Context%20Engineering%20Stop%20RAG%20Hallucinations)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fprompt-engineering-isnt-enough-how-four-bricks-of-context-engineering-stop-rag-hallucinations%2F&text=Prompt%20Engineering%20Isn%E2%80%99t%20Enough%3A%20How%20Four%20Bricks%20of%20Context%20Engineering%20Stop%20RAG%20Hallucinations)\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/2024/12/1K0UbUgMYYMDBjw9N_dlVKg.png)](https://towardsdatascience.com/why-retrieval-augmented-generation-is-still-relevant-in-the-era-of-long-context-language-models-e36f509abac5/)\n## [Why Retrieval-Augmented Generation Is Still Relevant in the Era of Long-Context Language Models](https://towardsdatascience.com/why-retrieval-augmented-generation-is-still-relevant-in-the-era-of-long-context-language-models-e36f509abac5/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIn this article we will explore why 128K tokens and more models can't fully replace using RAG.\n[Jérôme DIAZ](https://towardsdatascience.com/author/jerome.o.diaz/)\nDecember 12, 20247 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/03dLedvJFBh7iD7RZ.jpg)](https://towardsdatascience.com/fp-growth-frequent-pattern-generation-in-data-mining-with-python-implementation-244e561ab1c3/)\n## [FP Growth: Frequent Pattern Generation in Data Mining with Python Implementation](https://towardsdatascience.com/fp-growth-frequent-pattern-generation-in-data-mining-with-python-implementation-244e561ab1c3/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIn this article, an advanced method called the FP Growth algorithm will be revealed. We will walk through the whole process of the FP...\n[Chonyy](https://towardsdatascience.com/author/chonyy/)\nOctober 30, 20208 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/08/1vilI3Q4nlwqsAQLq3TOzSA.jpg)](https://towardsdatascience.com/optimizing-marketing-campaigns-with-budgeted-multi-armed-bandits-a65fccd61878/)\n## [Optimizing Marketing Campaigns with Budgeted Multi-Armed Bandits](https://towardsdatascience.com/optimizing-marketing-campaigns-with-budgeted-multi-armed-bandits-a65fccd61878/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nWith demos, our new solution, and a video\n[Vadim Arzamasov](https://towardsdatascience.com/author/vadim.arzamasov/)\nAugust 16, 20249 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/08/0KH1aRR6tWzfELw7o-scaled.jpg)](https://towardsdatascience.com/top-5-statistical-concepts-every-data-scientist-must-know-d4bc8740a55d/)\n## [Top 5 Statistical Concepts Every Data Scientist Must Know](https://towardsdatascience.com/top-5-statistical-concepts-every-data-scientist-must-know-d4bc8740a55d/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nEssential pillars of statistics and data science\n[Dario Radečić](https://towardsdatascience.com/author/radecicdario/)\nAugust 29, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/06/02q66CfIhUb0Eh1NW-scaled.jpg)](https://towardsdatascience.com/geoparsing-with-python-and-natural-language-processing-4762a7c92f08/)\n## [Geoparsing with Python and Natural Language Processing](https://towardsdatascience.com/geoparsing-with-python-and-natural-language-processing-4762a7c92f08/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nExtracting place names and assigning coordinates - Tutorial\n[Abdishakur](https://towardsdatascience.com/author/shakasom/)\nJune 11, 20204 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/0gkdB-X_kmE-I7k2q-scaled.jpg)](https://towardsdatascience.com/enhancing-e-commerce-with-generative-ai-part-1-9e402fb30e7b/)\n## [Enhancing E-Commerce with Generative AI - Part 1](https://towardsdatascience.com/enhancing-e-commerce-with-generative-ai-part-1-9e402fb30e7b/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nFrom Data to Product Recommendations\n[Mina Ghashami](https://towardsdatascience.com/author/mina.ghashami/)\nJuly 31, 202417 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/0dyZeVSb0C_-QgAtM.jpg)](https://towardsdatascience.com/you-need-this-to-thrive-as-a-data-scientist-in-a-business-environment-4be7de4f7afd/)\n## [You Need This to Thrive as a Data Scientist - In a Business Environment](https://towardsdatascience.com/you-need-this-to-thrive-as-a-data-scientist-in-a-business-environment-4be7de4f7afd/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nDrastically Increment Your Value Contribution and Business Understanding with this Must-Read Book\n[Victor Roman](https://towardsdatascience.com/author/rromanss23/)\nDecember 14, 20206 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/12/1IhtPC6k9k-emQrlDjoMZrA.png)](https://towardsdatascience.com/deep-dive-into-llamaindex-workflow-event-driven-llm-architecture-8011f41f851a/)\n## [Deep Dive into LlamaIndex Workflow: Event-Driven LLM Architecture](https://towardsdatascience.com/deep-dive-into-llamaindex-workflow-event-driven-llm-architecture-8011f41f851a/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nWhat I think about the progress and shortcomings after practice\n[Peng Qian](https://towardsdatascience.com/author/qtalen/)\nDecember 17, 202415 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/1wCaAO7AC_Leq0PdqV9XaiA.png)](https://towardsdatascience.com/reinforcement-learning-part-5-temporal-difference-learning-cacf7854fe0c/)\n## [Reinforcement Learning, Part 5: Temporal-Difference Learning](https://towardsdatascience.com/reinforcement-learning-part-5-temporal-difference-learning-cacf7854fe0c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIntelligently synergizing dynamic programming and Monte Carlo algorithms\n[Slava Efimov](https://towardsdatascience.com/author/slavahead/)\nJuly 13, 202416 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/607631/image?etag=1781543525510&width=500&height=500) Critical Mistakes Companies Make When Integrating AI/ML into Their Processes ](https://towardsdatascience.com/critical-mistakes-companies-make-when-integrating-ai-ml-into-their-processes/ \"Critical Mistakes Companies Make When Integrating AI/ML into Their Processes\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n\n\n",
  "body_base_path": "attachments/387867f19833/pages/",
  "body_markdown_path": "attachments/387867f19833/pages/archived-body.md",
  "local_html": "attachments/387867f19833/pages/archived-body.html",
  "body_source": "prior_capture"
}