Sub topic 2
Extracting with zero-shot and few-shot prompts
This chapter assumes basic Python, familiarity with JSON, a working idea of what a language model does with a prompt, and introductory precision, recall and F1.
Zero-shot and few-shot prompts
A zero-shot prompt describes the task and the output schema with no examples. A few-shot prompt adds a few worked input and output pairs before the new input. Examples often improve consistency on unusual cases, such as dates in unfamiliar formats, but they add input tokens to every call.
PROMPT = """Extract the invoice fields. Return only a JSON object with keys
"vendor" (string or null), "total" (number or null), "currency" (string or null).
Use null when a field is not stated. Do not guess.
Text: Invoice from Acme GmbH, total 120.50 EUR.
JSON: {"vendor": "Acme GmbH", "total": 120.5, "currency": "EUR"}
Text: {text}
JSON:"""
def build_prompt(text):
return PROMPT.replace("{text}", text)Use replace rather than str.format, because the JSON example contains braces.
Getting reliable structured output
Treat every model response as untrusted until it passes a check. The parser below rejects output that is not JSON, has missing or extra keys, or has a value of the wrong type.
import json
def parse_extraction(raw):
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None
if not isinstance(data, dict) or set(data) != {"vendor", "total", "currency"}:
return None
if data["total"] is not None and not isinstance(data["total"], (int, float)):
return None
return data
print(parse_extraction('{"vendor": "Acme", "total": 120.5, "currency": "EUR"}'))
print(parse_extraction('Sure! {"vendor": "Acme"}'))The first call prints the dictionary. The second prints None.
> Note: A None result should trigger a retry or a fallback, not a silent write to your database.
How prompted extraction fails
| Failure | Symptom | Check |
|---|---|---|
| Invented value | A field is filled although the text does not state it | Confirm the value appears in the source text |
| Format drift | Prose or markdown fences surround the JSON | Strict parser rejects the output |
| Wrong occurrence | The right string comes from the wrong place | Compare character offsets with gold data |
| Unstable answers | Identical input gives different results | Lower the temperature and measure variance |
Fine-tuned token classifiers and BIO tags
A token classifier labels each token, which is a word or word fragment, in a sentence. BIO tagging uses three kinds of tags: B- marks the beginning of an entity, I- marks a token inside an entity, and O marks a token outside any entity. Fine-tuning trains a pretrained encoder on your labeled examples so it learns your label set. The output is a set of spans that you can score exactly.
def bio_to_spans(tags):
spans = []
start = None
label = None
for i, tag in enumerate(tags + ["O"]):
if start is not None and not (tag.startswith("I-") and tag[2:] == label):
spans.append((start, i, label))
start = None
label = None
if tag != "O" and start is None:
start = i
label = tag[2:]
return spans
print(bio_to_spans(["B-PER", "I-PER", "O", "B-LOC"]))This prints [(0, 2, 'PER'), (3, 4, 'LOC')].
Exercise
Why does parse_extraction return None for 'Sure! {"vendor": "Acme"}'?
Show answer
json.loads fails on the leading prose, so the response is rejected instead of trusted.