Using LLMs in Data Pipelines: Extraction and Tagging
Turn free text into validated rows with an LLM: Pydantic schemas, structured outputs, batch jobs, retries, prompt caching and human spot-checks.
Most “AI data processing” in practice means one job: taking text that people wrote for other people (reviews, emails, invoices, tickets, contract clauses) and turning it into rows a database can use. A large language model is good at reading that text; your pipeline still has to make sure every row is the right shape, costs what you expect and gets checked by a person now and then. This guide walks through that loop with the Claude API, Pydantic and pandas, then shows the matching OpenAI features. Every API detail comes from the vendors’ own documentation, linked in each section.
Where the model sits in the pipeline
| Stage | What happens | Tool used here |
|---|---|---|
| Load | Read raw records with a stable ID | pandas |
| Schema | Describe the fields you want out | Pydantic model |
| Extract or tag | Send each record with the schema | Claude structured outputs |
| Scale | Submit thousands of records at once | Message Batches API |
| Validate | Re-check every result locally | Pydantic, stop reasons |
| Review | A person reads a sample | Your spreadsheet or queue |
The model only handles one stage. Everything around it is ordinary data engineering, and that is where most of the reliability comes from. If your records then flow into a warehouse, a data-quality layer such as the one in our Great Expectations guide is a sensible next check.
Step 1: write the schema as a Pydantic model
Start from the columns you want, not from the prompt. For a pile of product reviews that might be the product name, a sentiment label, a list of issue tags and whether the customer asked for a refund. Restricting labels to a fixed set (a Literal type) keeps the tag column usable for grouping later.
Anthropic’s structured outputs feature constrains the response to a JSON schema. A few details matter for data work:
- The API supports a subset of JSON Schema. Numeric limits such as
minimum, string length limits and recursive schemas are not supported, and objects must setadditionalPropertiesto false. - The SDK helpers handle that for you: they strip unsupported constraints, copy them into field descriptions, and (if the helper validates) check the reply against your original model, constraints included.
- Optional fields have a cost. There is a limit of 24 optional parameters across the strict schemas in one request, and the docs suggest making fields required where you can.
- Capitalization of enum values is not guaranteed. The docs advise comparing them case-insensitively, which is why the example below lowercases the label before Pydantic checks it.
Pydantic gives you two hooks for rules the schema cannot express. “Before” validators run ahead of Pydantic’s own parsing; “after” validators run once the type checks pass. Raising ValueError inside either one makes validation fail with a ValidationError you can catch, and model_validate_json() checks a JSON string against the model in one call (Pydantic validators, models).
Step 2: run one record first
For a single call, the Python SDK’s client.messages.parse() takes the Pydantic model as output_format, sends the schema and returns the parsed object in parsed_output. Use it to iterate on the prompt and schema with ten or twenty real records before scaling up. Anthropic also recommends checking each request shape against the normal Messages API first, because a batch only reports invalid parameters after the whole batch has finished.
Two latency notes: the first request with a new schema is slower because the grammar has to compile, and compiled grammars are then cached for 24 hours after last use. Changing the schema structure resets that cache.
Step 3: tag a whole file with the Message Batches API
The Message Batches API runs requests asynchronously at half the standard price. Each batch can hold up to 100,000 requests or 256 MB, whichever comes first. Most batches finish within an hour; anything not done after 24 hours expires. Results stay downloadable for 29 days, and they can come back in any order, so every request carries a custom_id that you use to join results back to your rows.
Structured outputs work inside batches, but the parse() helper does not, so the example converts the Pydantic model with transform_schema() and passes it in output_config.format. It uses Claude Haiku 5.5, which Anthropic’s models overview lists for classification, extraction and routing.
import time
from typing import Literal
import anthropic, pandas as pd
from pydantic import BaseModel, ValidationError, field_validator
class Review(BaseModel):
product: str
sentiment: Literal["positive", "neutral", "negative"]
issues: list[Literal["delivery", "quality", "price", "support", "other"]]
refund_requested: bool
@field_validator("sentiment", mode="before")
@classmethod
def lower(cls, v):
return v.lower() if isinstance(v, str) else v
client = anthropic.Anthropic()
df = pd.read_csv("reviews.csv") # columns: id, text
schema = anthropic.transform_schema(Review)
SYSTEM = [{"type": "text", "text": "You tag product reviews. Use only the listed labels.",
"cache_control": {"type": "ephemeral"}}]
batch = client.messages.batches.create(requests=[
{"custom_id": f"r-{row.id}",
"params": {"model": "claude-haiku-5-5", "max_tokens": 512, "system": SYSTEM,
"messages": [{"role": "user", "content": row.text}],
"output_config": {"format": {"type": "json_schema", "schema": schema}}}}
for row in df.itertuples()])
while client.messages.batches.retrieve(batch.id).processing_status != "ended":
time.sleep(60)
rows, retry = [], []
for r in client.messages.batches.results(batch.id):
if r.result.type != "succeeded" or r.result.message.stop_reason != "end_turn":
retry.append(r.custom_id); continue
text = next(b.text for b in r.result.message.content if b.type == "text")
try:
rows.append({"custom_id": r.custom_id, **Review.model_validate_json(text).model_dump()})
except ValidationError:
retry.append(r.custom_id)
out = pd.DataFrame(rows)
out.to_json("tagged.jsonl", orient="records", lines=True)
print(len(out), "tagged;", len(retry), "to retry or review")
Writing JSON Lines keeps one record per line, which pandas reads back with read_json(..., lines=True) (pandas docs).
Step 4: sort failures before you retry
Not every failure deserves a second call. The batch results file gives each request one of four outcomes, and the right response differs:
| Outcome | What it means | What to do |
|---|---|---|
succeeded but stop_reason is refusal | The model declined; output may not fit the schema, and you are billed | Send to human review, not an automatic retry |
succeeded but stop_reason is max_tokens | Output was cut off | Retry with a higher max_tokens |
succeeded, Pydantic fails | A business rule or label was off | Retry once, then review |
errored, invalid_request_error | The request itself was malformed | Fix the request first |
errored, other type | Server-side problem | Safe to resend as is |
expired or canceled | Never reached the model; not billed | Resubmit in a new batch |
Collect the IDs to retry into a fresh, smaller batch. Cap the number of attempts per record so a single odd input does not loop forever.
Step 5: keep the bill predictable
- Batch anything that can wait. The batch discount applies to all usage in the batch.
- Put shared instructions first and cache them. Prompt caching stores a prefix (tools, then system, then messages) and later requests with the same prefix read it at a fraction of the input price (prompt caching docs). The caching and batch discounts stack. Two catches: a prefix under the model’s minimum (512 tokens for Claude Haiku 5.5) is silently not cached, so a short system prompt like the one above only benefits once you add longer instructions or labelled examples; and in batches, cache hits are best-effort. Anthropic suggests identical
cache_controlblocks in every request and, because batches can outlast the default 5-minute lifetime, the 1-hour cache option. - Pick the smallest model that passes your sample. Run the same 100 labelled records through two models and compare before choosing.
- Know the hidden tokens. Structured outputs add a short system prompt explaining the format, so input counts rise slightly.
Step 6: have a person check a sample
Validation proves a row has the right shape, not that it is right. A “negative” label that should have been “neutral” passes every check above. Build a habit instead:
- Before launch, hand-label a few hundred records and measure agreement with the model per field.
- On each production run, pull a random sample of rows plus every row that needed a retry, and have someone compare them with the source text.
- Keep the reviewer’s corrections. They become your test set for the next prompt or model change.
- Store the source ID, model name and run date beside each row, so you can find and redo affected rows if a problem turns up later.
If the extracted data feeds replies to customers, see our walkthrough on drafting support replies with an LLM, which covers the review step for generated text.
The same pattern with OpenAI
OpenAI’s Structured Outputs work the same way from Python: pass a Pydantic model as text_format to client.responses.parse(). OpenAI recommends Structured Outputs over the older JSON mode, since only the former enforces the schema, and points new projects to gpt-6-astra. Its Batch API also charges half price, but takes a .jsonl file uploaded through the Files API (under 200 MB) with a 24-hour completion window. Output lines may arrive out of order, failures go to a separate error file, and custom_id is again how you join results back. See the OpenAI API listing for more, or Instructor if you want one Pydantic-first library across several providers.
Limits worth knowing
An LLM step is slower and costlier per record than a regex or a lookup table, so use it only for fields that genuinely need reading comprehension. Structured outputs cannot be combined with Anthropic’s citations feature, so if you need a source span for every extracted value, that is a separate design. And schema compliance says nothing about truth: the spot-check in step 6 is what tells you the pipeline is working.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.