AI Hints
Home›LangChain Tutorial›Structured Output in Practice
LangChain · Lesson 34 of 120

Batch Extraction

Many documents.

⏱ 2 min read▶ Video at 36:40🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

One email is easy. But Riverside Books has a backlog of a hundred reviews to tag. Structured output works perfectly with batch, so we can process many documents in parallel.

Batch Extraction
From the video: Batch Extraction
  • A backlog of reviews
  • Structured output + batch
  • In parallel

Tagging reviews in a batch

Each review becomes a review tag, with a star rating from one to five, and whether it mentions delivery. We batch all the reviews, with at most five calls running at once. Run it. Every review gets a rating and a flag, and the program then counts them up, like a tiny report.

batch_tags.pypython
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model

class ReviewTag(BaseModel):
    stars: int = Field(ge=1, le=5)
    mentions_delivery: bool

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
tagger = model.with_structured_output(ReviewTag)

reviews = ["Arrived fast, wonderful story!", "Dull plot.", "Box was crushed in the post.",
           "A masterpiece, read it twice.", "Late delivery but a lovely book."]
tags = tagger.batch(reviews, config={"max_concurrency": 5})
for r, t in zip(reviews, tags):
    print(t.stars, "★", "📦" if t.mentions_delivery else "  ", r)
print("delivery mentions:", sum(t.mentions_delivery for t in tags))
Output
5 ★ 📦 Arrived fast, wonderful story!
2 ★    Dull plot.
1 ★ 📦 Box was crushed in the post.
5 ★    A masterpiece, read it twice.
4 ★ 📦 Late delivery but a lovely book.
delivery mentions: 3

Scaling up

For bigger jobs, keep max concurrency below your provider's rate limit. Use return exceptions, so one bad document doesn't stop the batch. Save results as you go. And track the token usage, because a thousand documents can add up.

keyvalue
max_concurrencybelow the rate limit
return_exceptionsskip bad items
Save as you godon't lose work
Track tokenscosts add up

Summary

Structured output plus batch processes many documents in parallel, giving typed results you can count and store. Next, what to do when output goes wrong.

Key takeaways
  • with_structured_output
  • + batch
  • max_concurrency
Next up: When Output Goes Wrong — validation