환각을 줄이는 퓨샷
구체적인 예시로 추출 결과를 근거에 연결합니다
환각을 줄이는 퓨샷은(는) CoddyKit의 무료 Claude Architect 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Claude Architect 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Models Hallucinate in Extraction
When you ask Claude to extract data from a messy document, the biggest risk is hallucination: the model invents a plausible value to fill a field instead of admitting the value is absent.
This happens most when your instructions are vague, when the desired output format is ambiguous, or when edge cases (missing fields, conflicting numbers) aren't addressed. A vague prompt like "extract the invoice details" leaves the model guessing.
In this lesson you'll learn to ground extraction with concrete examples so the model copies real source values instead of fabricating them.
Few-Shot: Show, Don't Just Tell
Few-shot prompting means giving Claude 2-4 targeted examples of input paired with the exact output you want. The model generalizes from these examples — it does not merely repeat them.
Few-shot is the recommended technique for four things: consistency, edge cases, output format, and reducing hallucination. Our focus today is the last one.
The key idea: a well-chosen example that shows how to behave when data is missing teaches the model far more reliably than a sentence of instruction.
Explicit Criteria Beat Vague Ones
Before adding examples, sharpen your instructions. Explicit criteria beat vague ones every time.
Vague: "be accurate" or "extract carefully." Explicit: "copy values exactly from the source; if a field does not appear, return null."
Examples then demonstrate that rule in action. Instructions tell; few-shot examples show. Together they leave the model almost no room to invent.
An Example That Demonstrates 'null'
The single most powerful anti-hallucination example is one where a field is genuinely absent in the input and the expected output shows null.
Below, the source has no email. The example output models the correct behavior: leave it null rather than guess a domain.
Two or three such examples teach the model to prefer "not present" over a fabricated value.
system = (
"Extract contact fields. Copy values exactly from the source. "
"If a field is not present, return null. Do not infer or invent."
)
examples = [
{
"role": "user",
"content": "Source: Jane Cole, Acme Ltd. Call 555-0199.",
},
{
"role": "assistant",
"content": '{"name": "Jane Cole", "company": "Acme Ltd", '
'"phone": "555-0199", "email": null}',
},
]Wire Examples Into messages
Few-shot examples live in the messages array as alternating user/assistant turns, before the real input. Remember: the model keeps no state, so you send the full message list every request.
The shots prime the pattern; the final user turn is the document to extract.
resp = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
system=system,
messages=[
*examples, # the 2-4 few-shot turns from before
{
"role": "user",
"content": "Source: Omar Diaz, Bolt Inc.", # no phone, no email
},
],
)Combine Few-Shot With Structured Output
Few-shot reduces hallucination; tool_use with a JSON Schema eliminates syntax errors and enforces required fields. Use them together.
Set tool_choice to "any" to guarantee the model returns structured output instead of prose. The examples still teach what to extract; the schema guarantees the shape.
tools = [{
"name": "record_contact",
"description": "Save extracted contact fields from a source document.",
"input_schema": {
"type": "object",
"properties": {
"name": {"type": ["string", "null"]},
"company": {"type": ["string", "null"]},
"phone": {"type": ["string", "null"]},
"email": {"type": ["string", "null"]},
},
"required": ["name"],
},
}]
# tool_choice 'any' forces SOME tool call -> structured output
resp = client.messages.create(
model="claude-sonnet-4-5", max_tokens=1024, system=system,
tools=tools, tool_choice={"type": "any"}, messages=messages,
)Never Require a Possibly-Absent Field
A critical schema rule that directly fights hallucination: mark a field required only if it is always present.
If you require a field that may be absent, the model is forced to produce something — and it will fabricate a value to satisfy the schema. That is hallucination caused by your own schema.
Above, only name is required. email and phone are optional and nullable, so the model can faithfully report their absence.
Cover Edge Cases With Targeted Shots
Pick examples that target your specific ambiguities, not random documents. Two to four shots per ambiguity is the sweet spot.
For grounding extraction, useful shots include:
- A field that is missing → output
null. - An ambiguous value (e.g. two phone numbers) → show the disambiguation rule.
- A tricky format (date written three ways) → show the normalized output.
The model generalizes the underlying rule to unseen documents.
Self-Correction: Calculated vs Stated
For numeric extraction, hallucination often hides in arithmetic. A strong pattern is to extract both the calculated_total and the stated_total, then compare them to detect discrepancies.
A few-shot example can demonstrate this dual-extraction so the model learns to surface mismatches instead of silently "fixing" the math.
tools = [{
"name": "audit_invoice",
"description": "Extract line items plus both the summed and the printed total.",
"input_schema": {
"type": "object",
"properties": {
"line_items": {"type": "array", "items": {"type": "number"}},
"calculated_total": {"type": "number"}, # sum of line_items
"stated_total": {"type": "number"}, # printed on the doc
},
"required": ["line_items", "calculated_total", "stated_total"],
},
}]When Retry Helps — and When It Doesn't
Pair few-shot with retry-with-feedback for robustness, but know its limits.
Retry fixes format, structural, and arithmetic errors: resend the original document, the wrong output, and the exact validation error, and the model self-corrects.
Retry does NOT help when the information is simply absent from the source. No number of retries conjures a missing value — that's where your nullable schema and few-shot "null" examples do the real work.
Keep Provenance to Stay Grounded
Grounding isn't only about avoiding invented values — it's about being able to trace each claim to its source.
For extraction at scale, keep claim→source mappings (the quote, doc name, or location the value came from). A few-shot example can show the model attaching a short source snippet to each field, making fabricated values obvious because they'd have no supporting quote.
This provenance habit is what separates an auditable extraction pipeline from a black box.
# Example shot: each field carries the exact source span it came from
assistant_output = {
"company": {"value": "Bolt Inc", "source": "Omar Diaz, Bolt Inc."},
"phone": {"value": None, "source": None}, # absent -> null, no source
}Quick Check: Grounding Extraction
A scenario question on reducing hallucination in structured extraction.
Recap: Few-Shot to Reduce Hallucination
Key takeaways for grounding extraction:
- Few-shot examples (2-4) teach the model to generalize, not just repeat — best for consistency, edge cases, format, and reducing hallucination.
- The strongest anti-hallucination shot shows a missing field mapped to null.
- Pair examples with explicit criteria: "copy exactly; absent → null; never infer."
- Use tool_use + JSON Schema for structure, with
tool_choice: "any"to force it. Mark a field required only if always present — never require a possibly-absent field. - Extract calculated vs stated totals to catch numeric errors; keep provenance for auditability.
- Retry-with-feedback fixes format and math errors — but never recovers data that is simply absent.
AI 튜터와 함께 Python을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 26
- 레슨
- 104
자주 묻는 질문
“환각을 줄이는 퓨샷” 강의는 무료인가요?
네 — “환각을 줄이는 퓨샷” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Claude Architect 강의 전체를 잠금 해제할 수 있습니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.
“환각을 줄이는 퓨샷”에서 뭘 배우나요?
구체적인 예시로 추출 결과를 근거에 연결합니다 브라우저에서 직접 실행하는 실습 코드로 Claude Architect을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Claude Architect을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Claude Architect은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“환각을 줄이는 퓨샷” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Claude Architect 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Claude Architect 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 예시 2~4개가 효과적인 이유
- 형식 및 예외 사례를 위한 예시
- 일반화와 반복
- 환각을 줄이는 퓨샷