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.
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, Optionalfrom pydantic import BaseModel, Fieldfrom langchain.chat_models import init_chat_modelclass 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."))
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.
Extraction turns messy text into clean fields. Optional fields stop the model from inventing missing facts. Next, extracting from many documents at once.