Sub topic 12
Using an LLM as a labeling source
This chapter assumes you know the labeling functions, label matrix and label model from the earlier chapters, and that you can call a text-generation model from Python. It treats a large language model (LLM) as one more noisy labeling function. You will learn how to prompt it, parse its answers, let it abstain, and judge it before trusting it.
Why an LLM fits the weak supervision model
A regex labeling function is cheap and narrow. It fires on a few surface patterns and abstains on everything else. An LLM sits at the other end. It covers almost every input and understands context, so it can label "Thank you, but it is terrible" as negative where a thanks-keyword rule votes positive. It is also slower and costs money per call. Its errors are harder to predict, because they come from the prompt wording, the model version and the input style, not from a visible pattern.
In weak supervision terms, an LLM is a high-coverage source with unknown, input-dependent accuracy. That is how you should handle it:
- Give it the same interface as any other labeling function: text in, a class or
ABSTAINout. - Put its votes in a column of the label matrix.
- Measure its coverage, conflicts and accuracy before combining it with other sources.
Designing the prompt as a labeling function
Every choice in the prompt is part of the labeling function's definition. If you change the wording, you have changed the function, and you should re-measure it.
A good labeling prompt has four parts:
- The task and the label set. Name the classes exactly as your code will parse them, such as
positiveandnegative. - An escape option. Add a sentence such as "If you cannot tell, answer unsure." Without it, the model must pick a class, so it guesses, and a guess counts as a confident vote.
- An output format. Ask for one word. Long free-text answers are harder to parse and invite explanations that contain several class names.
- Optional examples. A few labeled examples in the prompt often help with domain-specific labels. Take them from your development data and keep them out of the gold set, or the evaluation will be inflated.
Set the temperature to 0 when you want a single reproducible vote. Use a higher temperature only when you deliberately sample several answers to measure agreement, as the next chapter does.
Parsing answers and abstaining
Models rarely return exactly the string you asked for. You will see Positive., **negative**, Negative, because... and refusals. The parser decides what counts as a vote, and anything it cannot read must become ABSTAIN. It must not default to a class.
The code below wraps an LLM as a labeling function with caching and puts it next to a regex function. The fake_ask function stands in for a real model call so that the example runs without an API key. Replace it with a function that sends the prompt to your provider and returns the reply text.
import re
ABSTAIN, NEG, POS = -1, 0, 1
LABEL_IDS = {'negative': NEG, 'positive': POS}
PROMPT = (
'Classify the sentiment of the review. '
'Answer with exactly one word: positive, negative, or unsure.\n\n'
'Review: {review}'
)
def parse_label(raw):
"""Map a raw model reply to a class id; anything unreadable is ABSTAIN."""
words = re.findall(r'[a-z]+', raw.lower())
if words and words[0] in LABEL_IDS:
return LABEL_IDS[words[0]]
return ABSTAIN
def make_llm_lf(ask, name):
cache = {} # one call per distinct text, so reruns are free and stable
def lf(text):
if text not in cache:
cache[text] = parse_label(ask(PROMPT.format(review=text)))
return cache[text]
lf.__name__ = name
return lf
def fake_ask(prompt):
review = prompt.split('Review: ', 1)[1].lower()
if 'love' in review or 'great' in review:
return 'Positive.'
if 'broken' in review or 'terrible' in review:
return 'negative'
return 'I am not sure'
def lf_thanks(text):
return POS if 'thank' in text.lower() else ABSTAIN
texts = [
'I love this phone, great battery',
'Arrived broken, I want a refund',
'Thank you, but it is terrible',
'It is a phone',
]
gold = [POS, NEG, NEG, NEG] # hand labels; the last one is a judgment call
lfs = [lf_thanks, make_llm_lf(fake_ask, 'lf_llm')]
L = [[lf(t) for lf in lfs] for t in texts]
print(L) # [[-1, 1], [-1, 0], [1, 0], [-1, -1]]
llm_col = [row[1] for row in L]
covered = [(p, g) for p, g in zip(llm_col, gold) if p != ABSTAIN]
coverage = len(covered) / len(texts)
accuracy = sum(p == g for p, g in covered) / len(covered)
print('coverage', coverage, 'accuracy on covered', accuracy)
# coverage 0.75 accuracy on covered 1.0The matrix shows the pattern you want from an LLM source. On the third text the thanks rule and the LLM disagree, which is exactly the kind of conflict a label model uses to estimate accuracies. The fourth text has no information, so the LLM abstains.
Report accuracy only on the examples where the source voted, and report coverage next to it. An LLM that answers 40% of examples at 95% accuracy is a different source from one that answers 100% at 80%.
Judging the LLM column
Run the LLM labeling function on your gold set and compute the same diagnostics as for any other function:
- Coverage: the share of examples where it does not abstain.
- Accuracy on covered examples: compare to gold labels, and also per class.
- Conflict rate: how often it disagrees with the other columns, and who is right when it does.
Per-class numbers matter because LLM errors are often lopsided. Models tend to over-assign some classes, for example calling mixed or neutral reviews "positive", or treating any text that mentions a complaint as "negative". A single overall accuracy hides this.
Then compare configurations. Different prompts, different model versions and different example sets each give a different labeling function. Keep a record of the prompt text and model identifier alongside the labels. A silent model update can change the labels you get on the next run.
Using LLM votes downstream
You have two ways to use the votes.
As a column in the label matrix. Treat it like any other function and let the label model weight it. This is the default choice when you have other sources, because the label model can learn that the LLM is more accurate than a keyword rule, and it can downweight the LLM where it conflicts with everything else.
As the main labeler, with filtering. When the LLM is your only source, there is no matrix to combine. You can sample several answers per example and keep only the examples where the answers agree. The next chapter covers that agreement filtering in detail.
Both routes end with the same step: train the end model on the resulting labels and evaluate on the gold set.
Common errors
| Problem | What happens | Fix |
|---|---|---|
| No escape option in the prompt | The model guesses on unclear text, and the guess enters the matrix as a vote | Add an `unsure` answer and parse it as `ABSTAIN` |
| Parser defaults to a class | Refusals and rambling answers get a label | Return `ABSTAIN` for anything not matching the label set |
| Prompt examples reused in the gold set | Measured accuracy is too high | Draw examples from a separate development split |
| Prompt edited without re-measuring | The labeling function changed, but old diagnostics are still reported | Version prompt and model name, and re-run diagnostics after every edit |
| Uncached calls at temperature above 0 | The same text gets different labels on different runs | Cache by text, or set temperature to 0 |
| LLM and end model share a pretrained base | The end model learns the LLM's biases and looks better than it is | Judge on gold labels, not on agreement with the LLM |
Cost deserves a plan too. Calls scale with the number of examples times the number of samples. Develop the prompt on a few hundred examples, check the diagnostics, and only then label the full pool.
Exercise
Your LLM labeling function covers 95% of a sentiment dataset and scores 88% accuracy on the covered gold examples. A teammate suggests removing the unsure option from the prompt so coverage reaches 100%. What is likely to happen to the quality of the labels, and how would you check?
Show answer
Coverage will rise, but the added votes come from examples the model found unclear, so their accuracy is probably lower than 88%, and overall label noise goes up. The label model also loses the signal that these examples were hard. To check, run both prompt versions on the gold set. Compare accuracy on the examples that only the no-escape prompt labels, and compare the end model's gold-set F1 when trained on each set of labels.
Exercise
A reply from the model is "Negative, although parts of the review are positive." Using the first-word parser in this chapter, what label does it produce, and what is one risk of that rule?
Show answer
It produces NEG, because the first word is "negative". The risk is that the first word may not reflect the model's real answer, for example in a reply like "Positive in tone, but negative overall", and the parser would count it as POS. Asking for exactly one word, and abstaining on any reply that is not a single label, avoids this.