Sub topic 12
Combining both approaches
This chapter assumes you have read the earlier chapters in this tutorial. You should know how a gold dataset is built, how span-level precision, recall and F1 are computed, how a prompted extractor returns validated JSON, and how a token classifier produces BIO tags. The code uses only the Python standard library.
Why combine the two approaches
Prompting and fine-tuning have opposite strengths. A prompted large language model (LLM) needs no training data and adapts to a new schema in minutes, but each call is slow and costly, and its output varies. A fine-tuned token classifier is fast, cheap per document and deterministic, but it needs labeled data and cannot handle a schema it was not trained on.
A hybrid pipeline lets each approach do the part it is good at. Three patterns cover most real projects:
- LLM labeling: the LLM produces labels that humans review or that serve directly as training data.
- Distillation: a small model is trained on the LLM's labels and replaces the LLM in production.
- Fallback routing: a small model handles easy documents, and uncertain ones go to the LLM.
These patterns are often chained. The LLM bootstraps data, a small model is distilled from it, and the LLM stays in the loop for hard cases.
Pattern 1: the LLM as annotator
Annotation is the slowest step in building a gold set. An LLM can pre-label documents, and a human then corrects the labels instead of writing them from scratch. Correcting is usually faster than labeling blank text. It also fits the schema and labeling rules you already wrote, because those rules go into the prompt.
There are two quality levels of LLM-produced labels:
- Gold: a human reviewed every label. Use these for evaluation.
- Silver: no human reviewed them, or only a sample. Use these for training, never for the final evaluation.
Keep your evaluation set human-labeled. If the LLM labels both the training data and the test data, the score measures agreement with the LLM, not correctness. Any systematic LLM error, such as always including a title like "Dr." in a person span, is then counted as correct.
Pre-labeling also biases annotators. People tend to accept a suggestion that looks plausible, so some wrong labels pass review. Measure this by double-annotating a small sample without suggestions and comparing it with the reviewed pre-labeled version.
Pattern 2: distillation to a token classifier
Distillation here means training a small model on labels that a large model produced. The LLM is the teacher and the token classifier is the student. The student cannot exceed the teacher's quality on the teacher's own mistakes, but it can run at a small fraction of the cost and latency. If the teacher's errors are noisy rather than systematic, the student sometimes smooths them out.
The main technical step is converting LLM output into BIO tags. LLMs return entity strings, not token positions. The converter must find each string in the text. If it cannot find one, the LLM probably altered or invented the text, so the example should be dropped instead of trained on.
def entities_to_bio(tokens, entities):
"""tokens: list of str; entities: list of (surface_text, label).
Returns a list of BIO tags, or None if any entity cannot be located."""
tags = ["O"] * len(tokens)
for surface, label in entities:
words = surface.split()
n = len(words)
if n == 0:
return None
found = False
for i in range(len(tokens) - n + 1):
if tokens[i:i + n] == words and all(t == "O" for t in tags[i:i + n]):
tags[i] = "B-" + label
for j in range(i + 1, i + n):
tags[j] = "I-" + label
found = True
break
if not found:
return None
return tags
tokens = "Angela Merkel visited Paris .".split()
print(entities_to_bio(tokens, [("Angela Merkel", "PER"), ("Paris", "LOC")]))
print(entities_to_bio(tokens, [("Angela Merckel", "PER")]))The first call prints ['B-PER', 'I-PER', 'O', 'B-LOC', 'O']. The second prints None because the LLM misspelled the name, so that example is rejected.
This converter has a known limitation. It labels only the first occurrence of each string. If "Paris" appears twice, the second mention stays O, which teaches the student that it is not an entity. In real text, either label every occurrence or ask the LLM for character offsets and verify them against the source.
Choosing which LLM labels to trust
Filter before training. Useful filters are:
- Drop examples where the output fails schema validation.
- Drop examples where an entity string is not found in the text.
- Run the LLM twice, with different prompts or at a nonzero temperature, and keep only the entities both runs agree on. Disagreement marks hard or ambiguous spans.
- Send the disagreeing examples to human review. These are the most valuable ones to correct by hand.
Pattern 3: routing with a fallback
A router sends each document to the cheapest model that can handle it. The small model runs first. If its confidence is high, its answer is used. Otherwise the document goes to the LLM.
A minimal router looks like this:
def route(text, small_model, llm, threshold=0.85):
"""small_model returns (start, end, label, score) tuples.
llm returns (start, end, label) tuples."""
spans = small_model(text)
if all(score >= threshold for *_, score in spans):
return "small", [s[:3] for s in spans]
return "llm", llm(text)
def small_stub(text):
if "Paris" in text:
return [(0, 13, "PER", 0.97), (22, 27, "LOC", 0.62)]
return [(0, 5, "ORG", 0.95)]
def llm_stub(text):
return [(0, 13, "PER"), (22, 27, "LOC")]
print(route("Angela Merkel visited Paris.", small_stub, llm_stub))
print(route("Acme sells tools.", small_stub, llm_stub))The first document has a span scored 0.62, below the threshold, so it goes to the LLM. The second has one span scored 0.95, so the small model's answer is accepted.
Setting the threshold
The threshold trades cost against accuracy. Choose it on a held-out gold set, not by intuition:
- Run the small model on the gold set and record each document's minimum span score.
- For each candidate threshold, compute the fraction of documents routed to the LLM and the F1 of the combined output.
- Pick the lowest threshold that meets your F1 target. A lower threshold means fewer LLM calls.
Report the routed fraction alongside F1. A router that sends 80% of traffic to the LLM saves little money.
What confidence does not tell you
Token classifiers produce a score for every token that is not O, so the score reflects how sure the model is about the spans it found. It says nothing about spans it missed. A document with no predicted spans passes all(...) on an empty list and is accepted, even if it contains a missed entity. Misses are a recall problem, and confidence thresholds do not catch them.
Two mitigations help. First, route documents with no predicted spans to the LLM if your data usually contains at least one entity. Second, audit a random sample of accepted documents regularly and measure the small model's recall on that sample.
Model scores are also often miscalibrated. A score of 0.9 may be right 75% of the time. This is another reason to choose the threshold from measured F1 instead of reading the score as a probability.
Pattern 4: the LLM as a checker
The LLM does not have to extract. It can review the small model's output instead. For example, the prompt can contain the text and the candidate spans and ask "Is each span correct? Answer yes or no for each." This is a smaller task than free extraction, the output is easy to validate, and it can be applied only to low-confidence spans. It can reject false positives, but it will not find entities the small model never proposed.
Gotchas in hybrid systems
| Problem | Cause | Mitigation |
|---|---|---|
| Student model learns teacher errors | Silver labels contain systematic mistakes | Review a sample of teacher labels by category and fix the prompt before labeling at scale |
| Inflated evaluation score | The LLM also labeled the test set | Keep the test set human-labeled and never use it for training or prompt tuning |
| Inconsistent output across routes | The small model and the LLM follow different span conventions, for example titles or trailing punctuation | Write labeling rules once, use them in both the prompt and the annotation guide, and normalize spans after both routes |
| Router drift | Input distribution changes and the small model's scores shift | Log the routed fraction and recheck it weekly; a sudden rise signals drift |
| Silent recall loss | Missed entities do not lower confidence | Audit a random sample of accepted documents |
| Rising cost | The LLM handles more traffic than planned | Retrain the small model on the LLM-handled documents after human review |
The last row describes a feedback loop. Documents that the router sends to the LLM are exactly the ones the small model finds hard. After review, they become training data for the next version of the small model, so the routed fraction falls over time.
Evaluating a hybrid system
Evaluate the whole pipeline, not each model alone. Use the same gold set and the same span-level exact-match scoring as in the earlier chapters on metrics. Report:
- F1 for the final output of the full pipeline.
- F1 split by route, which shows whether the small model's easy documents are really easy.
- The fraction of documents sent to the LLM.
- Average cost and latency per document, weighted by that fraction.
Latency has a long tail in a router. Documents on the fallback path take the small model's time plus the LLM's time. If you have a latency limit, check the 95th percentile, not the average.
When a hybrid is not worth it
A hybrid adds components that need monitoring. Skip it in these cases:
- Volume is low enough that LLM cost is small. Prompting alone is simpler.
- The schema changes often. A distilled model must be retrained with each change.
- Strict latency is needed on every request. Fallback calls will break the limit, so use only the small model and accept lower recall.
A hybrid pays off when volume is high, the schema is stable, and a clear share of documents are easy. The next chapter turns these considerations into a decision procedure.
Exercise
A team distills an LLM into a BIO token classifier. They label 5,000 documents with the LLM, train on 4,000, and report F1 on the remaining 1,000 using the LLM's labels as gold. The score is 0.94. Give two reasons this number may overstate real quality, and say how to fix the evaluation.
Show answer
First, the gold labels are the LLM's own, so the score measures agreement with the LLM. Any systematic LLM mistake, such as including titles in person spans, counts as correct. Second, the test documents may come from the same source and distribution as the training data, and the LLM's labels contain errors the student has copied, so the score hides them. To fix it, have humans label a test set independently, ideally without showing them the LLM's suggestions, and compute span-level F1 against those human labels. Use a sample from the real production distribution.
Exercise
Your router sends documents to the LLM when any span score is below 0.85. After deployment, 3% of accepted small-model documents turn out to contain a missed entity. Why did the threshold not catch these, and what two actions would you take?
Show answer
Confidence scores apply only to spans the model predicted. A missed entity has no score, so the threshold cannot flag it. First, audit a random sample of accepted documents with human labels and track the small model's recall. Second, route documents with zero predicted spans to the LLM when most documents in your data contain at least one entity.