AI Hints
Home›LangChain Tutorial›Shapes, Labels, Extraction
LangChain · Lesson 33 of 120

Extraction

Fields from text.

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

Customers write messy, friendly emails. Hidden inside are the facts we need. The order number, the book title, and what they want. Extraction pulls those facts out into fields.

Extraction
From the video: Extraction
  • Messy emails
  • Facts hidden inside
  • Pull them out

Extracting from an email

Our order request model has an order number, a book title, and an action. The order number is optional, because customers sometimes forget it. Run it. From a chatty email, we get clean fields. Where the email doesn't say something, the field is empty, rather than invented.

extract.pypython
from typing import Literal, Optional
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model

class OrderRequest(BaseModel):
    order_number: Optional[str] = Field(None, description="like RB-1234, if given")
    book_title: Optional[str] = None
    action: Literal["track", "cancel", "return", "other"]

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

email = """Hi there! Hope you're well. I ordered Circe last week (order RB-5521)
but I've changed my mind, could you cancel it please? Thanks, Jo"""
print(extract.invoke(email))
print(extract.invoke("Where is my book? I can't find my order number."))
Output
order_number='RB-5521' book_title='Circe' action='cancel'
order_number=None book_title=None action='track'

Extraction tips

A few tips for good extraction. Make fields optional when the text might not contain them, so the model isn't pushed to guess. Describe formats, like RB dash and four digits. Add a system message saying, never invent values. And spot check results, especially early on.

keyvalue
Optionaldon't force guesses
Formatsdescribe them
System messagenever invent
Spot checkearly and often

Summary

Extraction turns messy text into clean fields. Optional fields stop the model from inventing missing facts. Next, extracting from many documents at once.

Key takeaways
  • Optional fields
  • Describe formats
  • No invented values
Next up: Batch Extraction — many documents