APIs, text classification, and checking the labels
March 22, 2027
Draws on talks by Scott Cunningham
Course Home Page
ellmerOn 3/17:
Today we put the model to work on a task economists actually do: turning text into a variable.
We start with single calls, not agents, because single calls can be checked one by one.
Economists already turn text into variables:
Each of these is a classification: read a document, assign one label from a fixed list.
Card et al. (PNAS 2022) measured the tone of 140 years of U.S. Congressional speeches about immigration.
Example from Scott Cunningham’s talks at Texas A&M and Baylor (October 2026).
Net tone (% pro minus % anti) by year. Original: Card et al. (2022), PNAS. LLM: zero-shot gpt-4o-mini labels. Figure by Scott Cunningham.
Agreement is evidence. It is not proof. You learn the most from where they disagree.
No checker is the truth. You compare two processes whose mistakes differ.
| Checker 1 | Checker 2 | What disagreement reveals |
|---|---|---|
| LLM | human labels | where the model’s blind spots are |
| LLM | the same LLM, new prompt | errors that come from the prompt |
| LLM | a different model | errors that come from one model’s training |
| LLM | a dictionary | where context matters |
If both make the same mistakes, agreement tells you nothing.
Adapted from Scott Cunningham’s talks (October 2026).
Sentences from FOMC post-meeting statements:
Small on purpose: you can read every sentence and check every label.
You used API keys on 2/22 for FRED and the Census. LLM keys work the same way, with one difference:
Phrase from Scott Cunningham’s talks (October 2026).
The same three steps at every provider:
Then, before anything else:
Treat the key like a card number.
Exactly as with FRED:
.env is in .gitignore. Never commit a key.You do not need a paid key to follow along.
GEMINI_API_KEY). Rate-limited, and Google may use free-tier inputs to improve its models. The code today is the same for all three. Only the line that creates the chat changes.
ellmer: One Interface, Many Providersellmer (from Posit, the RStudio company) gives every provider the same interface.
Each returns a chat object: it holds the settings and the conversation so far.
claude-haiku-4-5 or “the latest” can point to a new model next month.Closed models are retired after a year or two. If your labels must be rebuilt in five years, see the local models later today.
system_prompt: standing instructions sent with every request.params(temperature = 0): always take the most likely token. Less noise, but not a guarantee of identical answers.codebook <- "You label sentences from FOMC statements.
hawkish: points toward tighter monetary policy (rate increases,
concern about high inflation, a strong economy).
dovish: points toward easier monetary policy (rate cuts,
concern about weak activity, low inflation).
neutral: procedural, describes the mandate, or balanced.
Label the sentence on its own, without outside knowledge."Example output (illustrative, not from a real run)
A good answer, and useless as data:
Tell ellmer the exact shape of the answer, using its type_*() functions:
type_enum(): the answer must be one of these values, nothing else.ellmer turns the JSON reply into R objects.Example output (illustrative, not from a real run)
type_number() for the model’s confidence, or a short type_string() reason you can read later.# A tibble: 4 × 3
id statement_date text
<dbl> <date> <chr>
1 1 2020-03-15 The coronavirus outbreak has harmed communities and disr…
2 2 2020-03-15 Global financial conditions have also been significantly…
3 3 2020-03-15 Available economic data show that the U.S. economy came …
4 4 2020-03-15 Information received since the Federal Open Market Commi…
dovish hawkish neutral
2020-03-15 13 2 4
2022-06-15 0 8 6
2023-07-26 1 7 5
2024-09-18 4 2 4
label_draft is a first draft. [TBD: instructor reviews every label and fills label_reviewed before class.]
One call at a time is slow. parallel_chat_structured() sends many at once:
max_active and rpm keep you under the provider’s rate limits.Example output (illustrative, not from a real run)
fomc by position and save it to disk right away.path file records the job. Rerun the script and it picks up the saved results instead of paying again.This is what Scott used for 305,000 speeches.
A rough rule: one token is about four characters of English.
input output
8632 672
ellmer can count exactly after the fact (token_usage()), but you want the estimate before you spend.
[1] 0.012
[1] 64.24
Scott’s $11 came from an even cheaper model at batch prices.
Labeling is cheap. A mistake you repeat 300,000 times is not: run 50 first and check them.
The model does the production. The validation set is the checking leg, done on purpose.
Some sentences are genuinely hard:
The invasion and related events are creating additional upward pressure on inflation and are weighing on global economic activity. (June 2022)
Inflation has made further progress toward the Committee’s 2 percent objective but remains somewhat elevated. (September 2024)
To keep the code runnable here, we use a made-up label vector. In practice this column comes from your saved model output.
The made-up errors are systematic: they follow a word. Real model errors often are too.
hand
llm dovish hawkish neutral
dovish 17 0 0
hawkish 0 19 7
neutral 1 0 12
Accuracy hides which classes the errors fall in. In research, that is usually what matters: a measure that turns neutral sentences hawkish will bias a hawkishness index upward.
For one class, say hawkish:
In econometric terms: precision is about false positives (type I), recall about false negatives (type II).
dovish hawkish neutral
precision 1.00 0.73 0.92
recall 0.94 1.00 0.63
Two labelers who guess at random still agree some of the time.
Cohen’s kappa compares observed agreement to the agreement you would expect by chance:
\[\kappa = \frac{p_o - p_e}{1 - p_e}\]
\(\kappa = 1\) is perfect agreement; \(\kappa = 0\) is no better than chance.
p_o p_e kappa
0.857 0.334 0.786
Six lines, no package. When the formula is this short, write it yourself and know what it does.
# A tibble: 8 × 4
id hand llm text
<dbl> <chr> <chr> <chr>
1 16 neutral hawkish In determining the timing and size of future ad...
2 17 neutral hawkish This assessment will take into account a wide r...
3 27 neutral hawkish The Committee seeks to achieve maximum employme...
4 33 neutral hawkish The Committee's assessments will take into acco...
5 41 neutral hawkish The Committee seeks to achieve maximum employme...
6 49 dovish neutral Inflation has made further progress toward the ...
7 50 neutral hawkish The Committee seeks to achieve maximum employme...
8 56 neutral hawkish The Committee is strongly committed to supporti...
The numbers say how many errors. Reading them says why. Always do both.
Example output (illustrative, not from a real run)
Asking once is a sample of size one. On a hard sentence, the label you got is a draw.
Rerunning the script should read the saved labels, not make new ones.
-v2), and keep the old one.Six months from now, a referee asks which prompt produced Table 2. This file answers.
Same sentences, same model. Only the system prompt changes.
codebook_b <- "You are an economist at a bank that profits when
interest rates rise. Label each FOMC sentence as hawkish,
dovish, or neutral."
chat_b <- chat_anthropic(model = model, system_prompt = codebook_b,
params = params(temperature = 0))
llm_b <- parallel_chat_structured(chat_b, as.list(fomc$text),
type = label_type)Nothing in this prompt says “call things hawkish.” Does it matter?
Example output (illustrative, not from a real run)
On 4/21 we will see the same problem with agents: cues you did not know you were sending steer the results.
With an API, every sentence you label is sent to the provider’s servers.
That is fine for FOMC statements. It is not fine for:
Read the agreement. “Send it to a chatbot” is usually not on the approved list.
Ollama runs open-weight models on your own machine. Nothing leaves it.
Same code as before. Only the line that creates the chat changes. Setup is in the Ollama guide.
| API (closed model) | Local (open weights) | |
|---|---|---|
| Where the text goes | the provider’s servers | stays on your machine |
| Quality | the strongest models | a step behind, and limited by your hardware |
| Cost | per token | free after the hardware |
| Speed at scale | fast, parallel, batch | slow on a laptop |
| Reproducibility | until the model is retired | pin the weights forever: save the file |
On pinning open weights: Scott Cunningham’s talks (October 2026).
Before LLMs: count words from a list.
hand
dict dovish hawkish neutral
dovish 12 0 1
hawkish 0 12 1
neutral 6 7 17
[1] 0.7321429
In pairs. Data: lecture-slides/data/fomc-sentences.csv.
label_draft.No key or no Ollama? Do steps 1–2, then pair with a group that has one.
An optional problem set extends today’s activity:
[TBD: link to the optional LLM labeling problem set]
.env, set a low cap.ellmer: a chat object, a codebook as the system prompt, type_enum() for a fixed set of labels, parallel or batch calls, and a cost estimate first.3/24, from chatbots to agents.
The checking we did today gets harder when the output is a whole project instead of a label.
ellmer: Chat with Large Language Models. https://ellmer.tidyverse.org