In my previous role I built the AI layer of an enterprise HRMS platform. At its core was a LangGraph pipeline with five steps:
- Generate a job description for a role.
- Work out the skills that role needs.
- Extract the skills an employee actually has from their resume and certifications.
- Compare the two and find the gaps.
- Suggest a personalised upskilling plan for each gap.
The first outputs looked great. They were fluent, well structured and confident. Too many of them were also wrong: skills the resume never mentioned, requirements nobody asked for, certifications that didn’t exist.
Over the following months we brought hallucination down by around 90%. Token spend fell by about 30% and generation time by about 50%. The model stayed the same. Almost none of the gain came from clever prompt wording. It came from four pieces of engineering around the model, in this order:
- Measure every run.
- Ground generation in the organisation’s own data.
- Put guardrails inside the graph, not after it.
- Audit tokens like you audit cloud spend.
Here’s what each one looked like and what I’d tell anyone starting the same journey.
1. Measure every run, not a sample
The most important change was also the least exciting: we started scoring every single run.
Before that, our feedback loop was someone reading a few outputs and saying “this one looks better”. That doesn’t scale, and it hides the failures that matter. A job description that reads beautifully but invents a requirement is worse than a clumsy one that’s accurate.
We used two open-source evaluation libraries, RAGAS and DeepEval, and tracked a small set of metrics on every run:
- Faithfulness: are the claims in the output supported by the context we gave the model?
- Groundedness: does the answer stay inside the provided sources, or does it drift into the model’s general knowledge?
- Context recall: did retrieval bring back everything needed to answer?
- Context precision: how much of what we retrieved was actually relevant?
- Bias: does the output treat candidates differently for reasons unrelated to their skills?
Splitting the context metrics from the answer metrics is what made the numbers useful. If faithfulness drops but context recall is fine, the generation step is the problem. If context recall drops, no prompt fix will help, because the model never saw the right information.
A minimal faithfulness check with DeepEval looks like this. It’s a simplified sketch, not our production code:
from deepeval.metrics import FaithfulnessMetric
from deepeval.test_case import LLMTestCase
def score_run(question: str, answer: str, retrieved_chunks: list[str]) -> float:
test_case = LLMTestCase(
input=question,
actual_output=answer,
retrieval_context=retrieved_chunks,
)
metric = FaithfulnessMetric(threshold=0.8)
metric.measure(test_case)
return metric.score # 0.0 to 1.0, stored alongside the runStore the score with the run, chart it over time, and treat a drop like a failing test. Once you can see the number move, every later change becomes an experiment you can judge rather than an opinion.
What I’d do differently: start measuring on day one, before the first demo. It’s much easier to keep a metric green than to explain why it was never measured.
2. Ground generation in your own data
This made the biggest single difference.
When the model is asked “what skills does a Senior Data Engineer need?”, it answers from its training data: a generic, internet-average answer. When it’s asked to extract skills from a resume, it fills any gap with what such a person probably knows. Both are reasonable guesses, and both are hallucinations in an HR system.
We switched from asking the model what it knows to giving it what we know. With RAG (retrieval-augmented generation) we pulled in the organisation’s own role definitions, skill frameworks and the employee’s actual documents, and asked the model to work only from those.
A few things mattered more than the choice of vector database:
- Chunk by meaning, not by character count. A skills section split in half retrieves badly.
- Tell the model what to do when the context is missing. “If the documents don’t mention it, say it isn’t mentioned” sounds obvious, but without it the model will fill the gap every time.
- Watch context precision. Retrieving twenty loosely related chunks “just in case” gives the model more material to hallucinate from, and costs more tokens.
What I’d do differently: treat retrieval as its own component with its own tests. Most of the “the model is making things up” bugs we chased were actually “retrieval didn’t find the right document” bugs.
3. Put guardrails inside the graph
Our first guardrails were a filter on the final output. By then it’s too late: you can block a bad answer, but you can’t tell which step caused it.
Because the pipeline was already a LangGraph graph, the natural fix was to make checks into nodes. After each generation step a check node scores the output. If it fails, the graph routes back for another attempt (with a limit) or flags the run for a human, instead of passing the error downstream.
A stripped-down version of the pattern:
from typing import TypedDict
from langgraph.graph import StateGraph, END
# call_llm_to_extract_skills, is_supported, flag_for_review and gap_analysis
# are your own functions; they're left out to keep the pattern readable.
class PipelineState(TypedDict):
resume_text: str
skills: list[str]
check_passed: bool
attempts: int
def extract_skills(state: PipelineState) -> dict:
skills = call_llm_to_extract_skills(state["resume_text"])
return {"skills": skills, "attempts": state["attempts"] + 1}
def check_skills(state: PipelineState) -> dict:
# e.g. every extracted skill must actually appear in the resume,
# and a bias/safety check must pass
passed = all(is_supported(s, state["resume_text"]) for s in state["skills"])
return {"check_passed": passed}
def route_after_check(state: PipelineState) -> str:
if state["check_passed"]:
return "continue"
return "retry" if state["attempts"] < 3 else "flag_for_review"
graph = StateGraph(PipelineState)
graph.add_node("extract_skills", extract_skills)
graph.add_node("check_skills", check_skills)
graph.add_node("flag_for_review", flag_for_review)
graph.add_node("gap_analysis", gap_analysis)
graph.set_entry_point("extract_skills")
graph.add_edge("extract_skills", "check_skills")
graph.add_conditional_edges(
"check_skills",
route_after_check,
{"continue": "gap_analysis", "retry": "extract_skills", "flag_for_review": "flag_for_review"},
)
graph.add_edge("gap_analysis", END)
graph.add_edge("flag_for_review", END)
app = graph.compile()We used the same idea for bias and safety checks on generated job descriptions and plans.
Masking PII before the model sees it. Resumes are full of personal data: names, phone numbers, emails, addresses. None of it helps the model judge someone’s skills, and all of it is a liability once it’s in a prompt or a log. We masked PII as the first step of the pipeline, before any resume text reached the model. A toy version:
import re
PATTERNS = {
"EMAIL": re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"),
"PHONE": re.compile(r"\+?\d[\d\s-]{8,}\d"),
}
def mask_pii(text: str) -> str:
for label, pattern in PATTERNS.items():
text = pattern.sub(f"[{label}]", text)
return textRegexes are only a starting point. For names and addresses you’ll want a dedicated PII detection library, but the principle is the same: mask on the way in, not on the way out.
What I’d do differently: give every check node a clear owner and threshold from the start. A check that nobody tunes either blocks everything or nothing.
4. Audit tokens like cloud spend
We logged token usage for every LLM call on every run: which node made the call, how many input and output tokens it used, and how long it took. Most LLM SDKs and gateways return usage with each response, so it’s cheap to collect:
import litellm
response = litellm.completion(model=MODEL, messages=messages)
usage = response.usage
log_tokens(
node="extract_skills",
prompt_tokens=usage.prompt_tokens,
completion_tokens=usage.completion_tokens,
)Once we could see it per node, the waste was obvious: long instructions repeated on every call, context passed to steps that never used it, and outputs far longer than the next step needed. Tightening prompts and restructuring the pipeline cut token spend by about 30% and generation time by about 50%.
There was a quality win too. Smaller, focused prompts gave the model less room to wander, so this work helped the hallucination numbers as well as the bill.
The takeaway
If your LLM feature works in a demo but not in production, the fix is rarely a better prompt. In our case the order that worked was:
- Measure: score every run, so you know where you stand.
- Ground: give the model your data instead of trusting its memory.
- Guard: check inside the pipeline and mask sensitive data on the way in.
- Audit: track tokens per step; the waste you find usually hurts quality too.
None of this is glamorous, and that’s the point. Hallucination is mostly an engineering problem, and engineering problems respond to measurement.
I’m curious how others handle this. Do you score every run in production, or just a sample? I’d love to hear what’s worked for you.



