Learning objectives
After reading this article you will be able to:
- Understand why an LLM states false things with confidence
- Recognize the signs of a made-up answer
- Apply the techniques that reduce hallucination and know the limits of each
A customer asks the store's chatbot whether orders ship to Canada. The bot says yes, in three business days, with total confidence. The store has never shipped outside the US. Nobody programmed that answer: the model put together a plausible sentence for a question the documentation did not cover.
This behavior has a name, hallucination, and a known cause. You cannot bring it to zero, but you can cut it down a lot and, more importantly, catch it before the answer reaches the user.
What is an LLM hallucination?#
OpenAI defines hallucinations as plausible but false statements generated by language models. NIST, in its generative AI profile (AI 600-1), uses the term confabulation: the production of confidently stated but erroneous or false content.
In practice it shows up in two ways:
- Against facts about the world: a library function that does not exist, a wrong date, a made-up paper with real authors.
- Against the context you gave: the document says one thing and the answer says another, or goes beyond what the document supports. Anthropic describes both as text that is factually incorrect or inconsistent with the given context.
The second kind matters most in a business chatbot, because it is the one your code can control.
Why does the model make things up?#
An LLM generates text by predicting the next token, as what is an LLM explains. NIST sums up the consequence: confabulations are a natural result of how generative models are designed, producing outputs that approximate the statistical distribution of their training data. The model learned what sounds right, not what is right.
OpenAI points to two more specific causes in a paper on the subject:
- Rare facts follow no pattern. Spelling and parentheses follow consistent rules, so errors there disappear with scale. An arbitrary, low-frequency fact, like a pet's birthday, cannot be inferred from patterns.
- Evaluations reward guessing. On a multiple-choice test, a guess might be right and a blank guarantees zero. Models graded only on accuracy learn to answer instead of saying "I don't know".
In your app, more causes add up:
- The information is not in the context. If the shipping policy was not sent in the prompt, the model answers from memory, and its memory does not include your store.
- Knowledge has a cutoff date. Questions about recent versions, prices or events fall outside training.
- The question assumes something false. "Which parameter of function X turns on mode Y?" invites the model to invent a parameter.
- The context is too long. Anthropic warns that accuracy and recall degrade as context grows. See how to keep it in check in context_length_exceeded.
- The prompt forbids doubt. Instructions like "always answer" or "never say you don't know" push the model toward guessing.
How do you recognize a made-up answer?#
Be suspicious when an answer has very specific details with no source: numbers, dates, parameter names, URLs, quotes. Be suspicious of confident answers on niche topics, and of answers that go beyond the document you sent.
Three practical tests:
- Ask again. Anthropic suggests running the same prompt several times and comparing: answers that change between runs point to hallucination.
- Check the citations. Does each link exist? Is each quoted passage in the document, word for word?
- Build a test set. Collect 20 to 50 real questions with known answers, including a few that the documentation does not answer. The hit rate shows quality; the unanswerable questions show whether the bot can say "I don't know".
What actually reduces hallucination?#
In order of impact, for a chatbot over your own data:
| Technique | How to apply it | Limit |
|---|---|---|
| Put the source in the context | Retrieve the relevant passages of your documents, send them with the question (RAG) and say to use only those documents, not general knowledge | The model can still misread a passage or go beyond it |
| Allow "I don't know" | Explicitly permit the model to admit uncertainty and define the exact phrase ("I couldn't find that in the documentation") so your code can detect it and hand off to a person | A prompt that demands an answer every time undoes it |
| Ask for citations | For long documents, ask for the relevant word-for-word quotes first and the answer second; remove any claim without a supporting quote | A quote can exist and still not support the claim |
| Use tools | Price, stock and order status come from a function calling lookup that returns the real data from your system | Only covers what your system exposes |
| Test against manipulation | Try to push the bot into stating something false on purpose, the way a malicious user would (prompt injection) | Does not catch honest mistakes |
The first three come from Anthropic's guide, which says permission to admit uncertainty can drastically reduce false information. A full RAG setup with vector search is in how to build a RAG chatbot; the difference between tools and MCP servers, in MCP vs function calling.
How do you validate the answer in code?#
Instructions in the prompt reduce the problem; validation in code catches what slips through. Ask for the answer in a structured format and check it with rules.
Structured output (Structured Outputs, on OpenAI) makes the model follow a JSON Schema. It guarantees the format, not the truth: the documentation itself says your application still has to validate the business rules the schema does not express. The example below requires a word-for-word quote for every answer and checks that it exists in the document. Set the environment variables first (the model ID comes from the provider's models page):
# .env
OPENAI_API_KEY=your-key
OPENAI_MODEL=model-idimport json
import os
from openai import OpenAI
client = OpenAI()
MODEL = os.environ["OPENAI_MODEL"]
DOCS = {
"plans": "The Basic plan includes 2 users and 10 GB of storage.",
"support": "Support answers by email on business days, from 9 a.m. to 6 p.m.",
}
SCHEMA = {
"type": "object",
"properties": {
"found": {"type": "boolean"},
"answer": {"type": "string"},
"citations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"source": {"type": "string", "enum": list(DOCS)},
"quote": {"type": "string"},
},
"required": ["source", "quote"],
"additionalProperties": False,
},
},
},
"required": ["found", "answer", "citations"],
"additionalProperties": False,
}
DONT_KNOW = "I couldn't find that in the documentation. Let me get a person to help."
def answer(question: str) -> str:
context = "\n".join(f'<doc id="{k}">{v}</doc>' for k, v in DOCS.items())
r = client.chat.completions.create(
model=MODEL,
messages=[
{
"role": "system",
"content": "Answer only from the documents, never from general knowledge. "
"For each claim, copy into 'quote' the exact sentence from the document that supports it. "
"If the documents do not have the answer, set found=false.",
},
{"role": "user", "content": f"{context}\n\nQuestion: {question}"},
],
response_format={
"type": "json_schema",
"json_schema": {"name": "answer", "strict": True, "schema": SCHEMA},
},
)
msg = r.choices[0].message
if msg.refusal or not msg.content:
return DONT_KNOW
data = json.loads(msg.content)
# Rule: every quote must exist, word for word, in the source it names
cited = bool(data["citations"]) and all(
c["quote"] in DOCS[c["source"]] for c in data["citations"]
)
if not data["found"] or not cited:
return DONT_KNOW
return data["answer"]
print(answer("How many users does the Basic plan include?"))
print(answer("Do you have a mobile app?"))The second question has no answer in the documents. If the model invents an app, the quote will not exist in the text, and the code returns the fallback phrase. The same idea applies to other fields: a product ID is checked against the database, a URL against an allowlist, a number against the price table.
Do temperature and a second check help?#
Temperature controls how the next token is sampled. In OpenAI's API it ranges from 0 to 2, and the documentation says lower values make the output more focused and deterministic. That helps with extraction and classification, because the answer becomes repeatable. But a low temperature does not fix a wrong fact: the model just repeats the same mistake. Not every model accepts the parameter, so check the documentation of the one you use.
A second check catches part of what got through. After the answer, a new call receives the answer and the documents and verifies that each claim is supported by the text, removing what is not. Anthropic recommends both variations: having the model find a quote for every claim, and feeding the output into a follow-up verification call. It costs one more call, so save it for answers that matter, like price, deadlines and contract terms.
None of these techniques brings the problem to zero. Anthropic itself warns that they reduce hallucinations significantly but do not eliminate them, and asks you to validate all critical information. For costly decisions, keep a person reviewing.
How to do this on Square Cloud#
On Square Cloud, from the Standard plan (R$44.99 a month), the AI Gateway is an OpenAI-compatible API for using the cubic model in your own products. You point the OpenAI SDK at https://api.squarecloud.app/v2/ai with an account API key that has the ai:chat scope. The techniques that rely only on the prompt and your own code (source in the context, "I don't know", citations checked by rule) work as with any model; before taking the response_format example there, check the documentation to see whether the gateway accepts JSON Schema.
Three gateway features help reduce hallucination, without eliminating it:
- Built-in web search. When a question needs current information, the model decides to search and cites the source URLs. That gives it real text to lean on, but it can still summarize what it read wrongly: show the links to the user and check them in code before displaying them.
- Function calling in the OpenAI format, with up to 32 tools, to fetch price, stock or status from your system instead of letting the model guess.
cubic-decision, atPOST /v2/ai/decisions, which answers typed decisions: yes or no, a choice between options or a score on a scale. When the task is to classify or approve, a closed answer leaves less room to invent than free text does.
For RAG, the gateway only handles generation and does not create embeddings, so those come from another provider. The index can live in PostgreSQL hosting, which comes with the pgvector extension and also starts on Standard. See the details on the AI Gateway page.
AI
Host AI apps in always-on containers
FAQs
Can you eliminate LLM hallucinations?
No. The right techniques cut how often they happen, but Anthropic's documentation, for one, warns that none of them removes the problem. For critical information, validate the output with rules or human review.
Does temperature 0 prevent hallucinations?
No. A low temperature makes answers more predictable, but the model can repeat the same mistake with full confidence. It helps with extraction and classification and is no substitute for providing the source.
Does RAG fix hallucinations?
It reduces them, because the model answers from passages of your documents instead of what it memorized in training. It can still misread a passage or go beyond it, so ask for citations and validate.
Why does the chatbot invent links and references?
URLs, function names and citations are plausible strings of text to the model. Without a real source in the context or a search tool, it builds one that looks right. Check that every link exists before showing it.
More in AI
See all 31 articles- How much does an AI chatbot cost to build and run?Running an AI chatbot costs model tokens, hosting, a database and, with RAG, extra context per message. See how to estimate the cost per conversation.
- How much does a RAG system cost? Embeddings, database and LLMA RAG system has three costs: embeddings, a vector database and the LLM. See the math for 1,000 questions a day, with hypothetical prices, and where the bill grows.
- RAG vs fine-tuning: which to useRAG puts your data in the prompt at question time; fine-tuning changes the model's weights with examples. Compare cost, updates, latency and when to use each.
- pgvector vs a dedicated vector database: which to usepgvector stores vectors in PostgreSQL, next to your data; a dedicated vector database focuses on scale and filtering. Compare indexes, operations and migration.