Guest User

Gpt 5.5 test output - how to make LLMs not hallucinate

a guest
Nov 4th, 2025
652
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.30 KB | None | 0 0
  1. Short answer: LangChain can strongly reduce hallucinations, but it cannot make them go to zero. Forcing the model to ground every claim in retrieved sources and to output citations helps a lot, but you also have to: control what context the model sees, control how it is allowed to answer, verify its claims after generation, and sometimes reject answers entirely.
  2.  
  3. I'll break down how to do this in LangChain.
  4.  
  5.  
  6. ---
  7.  
  8. 1. Core idea
  9.  
  10. Hallucination means: the model produces text that sounds plausible but is not supported by the available data.
  11.  
  12. LangChain is an orchestration framework. It lets you build multi-step call graphs ("chains") where you can force the model to:
  13.  
  14. 1. Read only retrieved context.
  15.  
  16.  
  17. 2. Answer only using that context.
  18.  
  19.  
  20. 3. Show where each statement came from.
  21.  
  22.  
  23. 4. Abstain if data is missing.
  24.  
  25.  
  26.  
  27. This pattern is usually called RAG (Retrieval-Augmented Generation). RAG means: instead of just prompting the model from scratch, you first retrieve relevant documents from your own data store (vector DB, SQL, etc.), then provide those documents to the model and say "answer using only this".
  28.  
  29. That solves two problems:
  30.  
  31. The model doesn't have to guess.
  32.  
  33. You can audit its claims because you know the source chunks.
  34.  
  35.  
  36. But RAG alone is not enough. You have to enforce discipline.
  37.  
  38.  
  39. ---
  40.  
  41. 2. High leverage controls
  42.  
  43. 2.1 Retrieval quality gate
  44.  
  45. If retrieval gives trash, the answer will hallucinate. This is the single highest-leverage point.
  46.  
  47. In LangChain terms:
  48.  
  49. Retriever = component that pulls documents relevant to a query from a store like FAISS, Chroma, Milvus, etc. These are vector stores, which are databases that store document embeddings (numerical representations of text meaning).
  50.  
  51. You wrap the retriever in logic: if it returns nothing or low-score results, you do not ask the LLM to answer. You instead return "No data found".
  52.  
  53.  
  54. Pseudocode sketch:
  55.  
  56. docs = retriever.get_relevant_documents(user_query)
  57.  
  58. if relevance_score_too_low(docs):
  59. return "I don't have sources for that."
  60. else:
  61. answer = llm(prompt_with(docs, user_query))
  62.  
  63. LangChain lets you do this with a RunnableLambda before the LLM call. You explicitly check metadata like similarity score.
  64.  
  65. If you don't gate like this, the model will make stuff up to be "helpful".
  66.  
  67. Conclusion: Hallucination is often retrieval failure, not generation failure.
  68.  
  69.  
  70. ---
  71.  
  72. 2.2 Grounded answering prompt
  73.  
  74. You use a strict prompt template. A prompt template is a structured string with instructions and slots like {context} and {question}.
  75.  
  76. Example pattern that actually works in production:
  77.  
  78. Rule 1. Only answer using the "Context" section.
  79.  
  80. Rule 2. For every factual claim include a citation like [1], [2], etc.
  81.  
  82. Rule 3. If the answer is not in context say "Not in sources".
  83.  
  84.  
  85. Example template body:
  86.  
  87. "You are a factual QA system. Use ONLY the Context. Do not use prior knowledge.
  88. If the Context does not contain the answer say 'Not in sources'.
  89. After each sentence add citation tags like [1] [2] that map to the sources below.
  90. Context:
  91. {context}
  92. Question: {question}
  93. Answer:"
  94.  
  95. In LangChain you pass this as a PromptTemplate to the LLM.
  96.  
  97. Why this works:
  98.  
  99. You are removing "be helpful" behavior and replacing it with "be literal".
  100.  
  101. You are training the model (in-context) to fear answering without proof.
  102.  
  103.  
  104. This does not eliminate hallucination, but it drives it down.
  105.  
  106.  
  107. ---
  108.  
  109. 2.3 Forced citation schema
  110.  
  111. You mentioned "forcing factual citations of data from a RAG". Yes. This is mandatory.
  112.  
  113. In LangChain you also add an OutputParser. An output parser is a post-processor that checks whether the LLM output matches a required format.
  114.  
  115. For example you can demand structured JSON like:
  116.  
  117. {
  118. "answer": "text",
  119. "citations": [
  120. {
  121. "claim": "string",
  122. "source_ids": ["doc_3", "doc_5"]
  123. }
  124. ],
  125. "can_answer": true
  126. }
  127.  
  128. Then:
  129.  
  130. If parsing fails (LLM didn't give citations) you reject the answer.
  131.  
  132. If citations[*].source_ids includes an ID that wasn't actually retrieved you reject the answer.
  133.  
  134. Optionally you re-prompt with "Your previous answer was invalid. Fix format."
  135.  
  136.  
  137. This is a deterministic filter you control, not model magic.
  138.  
  139. LangChain supports this using StructuredOutputParser or custom PydanticOutputParser. You define the schema with Pydantic and force the model to fill it.
  140.  
  141. This step is underused. It cuts hallucination because you are not trusting free-form prose.
  142.  
  143.  
  144. ---
  145.  
  146. 2.4 Post-verification / grading chain
  147.  
  148. After the model answers, you run a second model call that acts as a verifier. The verifier gets:
  149.  
  150. The retrieved docs.
  151.  
  152. The proposed answer with its citations.
  153.  
  154.  
  155. The verifier is prompted like: "For each claim in the answer, confirm that the claim is directly and unambiguously supported by at least one cited source span. Mark any unsupported claim."
  156.  
  157. LangChain sometimes calls this pattern "retrieval QA with answer validation" or "RAG-as-a-judge". It's just a second chain.
  158.  
  159. Behavior:
  160.  
  161. If verifier finds unsupported claims you either:
  162.  
  163. Strip them.
  164.  
  165. Replace them with "Not in sources".
  166.  
  167. Or block the answer.
  168.  
  169.  
  170.  
  171. This is similar to "constitutional checks" in safety research. It treats hallucination as a policy violation and rejects it.
  172.  
  173. This helps because the first model can still drift, but the second model is optimized only for "is this grounded". That is cognitively easier than "answer the question" and yields higher accuracy.
  174.  
  175.  
  176. ---
  177.  
  178. 2.5 Refusal / abstention
  179.  
  180. You must allow the system to say "unknown".
  181.  
  182. Hallucination mostly appears when the model thinks "I must answer anyway".
  183.  
  184. So in every step:
  185.  
  186. Retrieval gate can stop the chain.
  187.  
  188. Prompt explicitly rewards saying "Not in sources".
  189.  
  190. Output schema has a boolean can_answer.
  191.  
  192. Verifier can flip can_answer to false.
  193.  
  194.  
  195. If can_answer is false, final output is "No supported answer available from the provided sources." That is boring but safe.
  196.  
  197. In practice this is the single cleanest way to get "hallucination free" behavior at the cost of coverage.
  198.  
  199.  
  200. ---
  201.  
  202. 3. Architecture in LangChain terms
  203.  
  204. Below is a clean, high-level LangChain pipeline. I will define each block.
  205.  
  206. Terms:
  207.  
  208. Runnable in LangChain is any step that can be executed in a chain (retriever call, LLM call, lambda).
  209.  
  210. LCEL is LangChain Expression Language. It lets you compose runnables with | like Unix pipes.
  211.  
  212.  
  213. 3.1 Retrieval step
  214.  
  215. retrieve = retriever | RunnableLambda(filter_low_score_docs)
  216.  
  217. filter_low_score_docs enforces similarity score thresholds.
  218.  
  219. Similarity score is a numeric measure of how close two embeddings are. For cosine similarity, 1.0 means identical direction in vector space and 0.0 means orthogonal (unrelated).
  220.  
  221. 3.2 Answer draft step
  222.  
  223. generate = (
  224. {
  225. "context": retrieve,
  226. "question": RunnablePassthrough()
  227. }
  228. | prompt_template
  229. | llm
  230. | output_parser # forces JSON with citations
  231. )
  232.  
  233. RunnablePassthrough lets the original user question flow forward unchanged so you can use it alongside retrieved documents.
  234.  
  235. 3.3 Verification step
  236.  
  237. verify = (
  238. {
  239. "retrieved_docs": retrieve,
  240. "draft_answer": generate
  241. }
  242. | verifier_prompt
  243. | verifier_llm
  244. | verifier_parser
  245. )
  246.  
  247. The verifier LLM can be a cheaper model. It just has to check grounding.
  248.  
  249. 3.4 Final selection step
  250.  
  251. final = RunnableLambda(select_verified_or_refuse)
  252.  
  253. Where select_verified_or_refuse is a pure Python function that:
  254.  
  255. Drops any claim marked unsupported.
  256.  
  257. If too much is unsupported, returns "Not in sources".
  258.  
  259.  
  260. 3.5 Full chain
  261.  
  262. full_chain = (
  263. {"question": RunnablePassthrough()}
  264. | {
  265. "answer": generate,
  266. "verification": verify
  267. }
  268. | final
  269. )
  270.  
  271. You then expose full_chain.invoke(user_query).
  272.  
  273. Result:
  274.  
  275. Every claim is traceable.
  276.  
  277. Unsupported claims are pruned.
  278.  
  279. No "naked" statements without source IDs.
  280.  
  281. The model is not allowed to invent a source.
  282.  
  283.  
  284. This is about as close as you get to "hallucination free" with current LLMs.
  285.  
  286.  
  287. ---
  288.  
  289. 4. Important constraints
  290.  
  291. Constraint 1. You cannot actually prove truth. You only prove consistency with provided sources.
  292.  
  293. You are reducing hallucinations relative to your knowledge base. If the knowledge base is wrong or incomplete you will produce confident wrong answers that are still "grounded". The system has no external fact check against reality. It only checks against the retrieved context.
  294.  
  295. In other words you get "citation compliance", not "truth".
  296.  
  297. To improve this you can:
  298.  
  299. Add multiple retrievers: internal data + public web search + policy docs. Then merge and deduplicate results before generation.
  300.  
  301. Penalize answers that rely on a single source when multiple disagree.
  302.  
  303.  
  304. This is ensemble retrieval.
  305.  
  306. Constraint 2. Chunking and context window matter
  307.  
  308. If you chunk documents badly you get retrieval misses.
  309.  
  310. Chunking means: how you split source documents into pieces before embedding. Example: 512 tokens per chunk with overlap of 50 tokens.
  311.  
  312. If chunks are too small you lose context and the model may overfit fragments. If chunks are too big you blow the prompt window and the model can't see all relevant evidence at once. That reintroduces hallucination because it tries to fill gaps between partial chunks.
  313.  
  314. Optimal chunking is empirical per domain. Regulatory text prefers larger chunks because definitions cross-reference heavily. FAQs prefer smaller chunks.
  315.  
  316. LangChain exposes text splitters like RecursiveCharacterTextSplitter. You tune this as part of quality control.
  317.  
  318. Constraint 3. Model will try to "smooth" language between sources
  319.  
  320. Even if every sentence has [1] [2], the model will often generate connecting glue text. Sometimes that glue text encodes inferences not actually in the docs.
  321.  
  322. Your verifier chain must explicitly catch "synthesis that goes beyond sources". The verifier prompt should say:
  323.  
  324. "Mark a claim unsupported if it is inferred from multiple sources but never explicitly stated."
  325.  
  326. This prevents creative synthesis that lawyers/regulators will call hallucination.
  327.  
  328.  
  329. ---
  330.  
  331. 5. Direct answers to the implied questions
  332.  
  333. Q: Can LangChain make an LLM hallucination free just by forcing factual citations of data from RAG?
  334.  
  335. A: No. Mandatory citations reduce hallucination. They do not eliminate it. The model can still:
  336.  
  337. Cite a source number that does not really support the claim.
  338.  
  339. Fabricate relationships across sources.
  340.  
  341. Answer when retrieval failed.
  342.  
  343.  
  344. To get close to zero hallucination in practice you must add:
  345.  
  346. 1. Retrieval gating.
  347.  
  348.  
  349. 2. Strict grounded-answer prompt.
  350.  
  351.  
  352. 3. Structured output with per-claim citations and can_answer.
  353.  
  354.  
  355. 4. Automatic verification / grading against the retrieved sources.
  356.  
  357.  
  358. 5. A hard refusal path.
  359.  
  360.  
  361.  
  362. When you add all five you approach "LLM cannot assert anything that is not in your data". That is the real target for most regulated use cases (compliance, finance, medical triage, internal policy, etc.).
  363.  
  364.  
  365. ---
  366.  
  367. 6. Summary
  368.  
  369. LangChain is useful because it lets you build multi-step guarded pipelines, not because it magically fixes hallucination.
  370.  
  371. Forcing citations is necessary but not sufficient.
  372.  
  373. The winning pattern is: retrieve → generate with rules → parse → verify → refuse or answer.
  374.  
  375. You must be willing to return "Not in sources" often. If the business side refuses that outcome, you will get hallucinations. This is not a model problem. It is a product owner problem.
Add Comment
Please, Sign In to add comment