Structured output with JSON, validated with Pydantic - Chat Orders
Day Topic Example Status 1 Talking to an LLM from code Classifying emails by category and urgency โ Code 2 Roles, examples and delimiters in prompts Translating technical language into plain language โ Code 3 Structured output with JSON, validated with Pydantic Turning a chat order into a table ๐ You're here 4 Images with vision models Scanning a receipt and returning a JSON with the productsโฆ
Day 3 of the structured output tutorial focuses on using JSON output validated with Pydantic to turn chat orders into a CSV file. The goal is to extract the relevant information from the chat order, such as products, address, payment method, and order status, and format it into a CSV file with one product per row.
Pydantic plays a dual role in this process. Firstly, it defines the structure of the expected output, ensuring the model returns the correct fields. Secondly, it validates the output, confirming that every field exists and has the appropriate data type.
The schema for the Product and Orders classes is provided. The Product class describes a single product with fields for the product name and quantity. The Orders class contains the entire order information, including an address, payment method, and a list of Product objects.
Several key points about the schema are worth noting. The description field serves as an instruction for the model, preventing confusion between the customer and product names. The None type allows for optional fields when the message doesn't mention them. Literal restricts the possible values for the payment method, rejecting any inputs that don't match the allowed options. The order field is a boolean indicating whether the message represents an actual order.
The tutorial emphasizes the importance of setting the temperature to 0 for consistent results, as the same input should always produce the same output. Writing the CSV file is a straightforward Python task using the with open() context manager. The nested models make it easy to flatten the data, looping through the list of Product objects within each order to write one product per row.
Rewritten by urgent.news; may contain errors โ check the original.
Source: dev.to