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.
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 BaseModelfrom langchain.chat_models import init_chat_modelclass Line(BaseModel): title: str quantity: int price: floatclass 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
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.