AI Hints
Home›LangChain Tutorial›Rewriting and Extraction
LangChain · Lesson 113 of 120

Data from Tables

Text to rows.

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

Customers write orders in emails, in their own words. Two copies of this, one of that. To process them, we need neat rows. Title, quantity, and price. Structured output turns messy text into data.

Data from Tables
From the video: Data from Tables
  • Orders in plain words
  • We need rows
  • Structured output

Extracting order lines

An order line has a title, a quantity, and a price. An order is a list of lines. With structured output, the model fills in that list, from the email. Then normal Python takes over, and prints a table with totals. Run it. The messy email becomes three neat rows, and an order total.

extract_rows.pypython
from pydantic import BaseModel
from langchain.chat_models import init_chat_model

class Line(BaseModel):
    title: str
    quantity: int
    price: float

class Order(BaseModel):
    lines: list[Line]

email = ("Hi! Please send me two copies of Dune at £9.99 each, The Hobbit (£8.99), "
         "and three of Circe, which I think are £10.99.")
model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
order = model.with_structured_output(Order).invoke(f"Extract the order lines:\n{email}")

for l in order.lines:
    print(f"{l.title:<12} x{l.quantity}  £{l.price:.2f}  = £{l.quantity * l.price:.2f}")
print("order total: £%.2f" % sum(l.quantity * l.price for l in order.lines))
Output
Dune         x2  £9.99  = £19.98
The Hobbit   x1  £8.99  = £8.99
Circe        x3  £10.99  = £32.97
order total: £61.94

Extraction tips

Describe each field clearly, and use the right types, like integers for quantities. Let fields be optional when the text might not mention them. Always check the numbers with code, because models can misread. And for big batches, use batch, or async.

keyvalue
Typesint, float, str
Optionalfor missing data
Validatecheck with code
Volumebatch or async

Summary

Structured output with a list of Pydantic rows turns messy text into clean data. Then ordinary code takes over. Next, a quiz on applied techniques.

Key takeaways
  • Pydantic rows
  • list[Line]
  • Code checks the maths
Next up: Applied Quiz — test yourself