Skip to main content

Calling an LLM and Getting Structured Data Back

Why This Matters

The LLM step is what makes this automation possible: no rule-based parser could read every supplier’s email style. It is also the least predictable step. The trick is to ask the LLM for something you can check: structured data in a fixed shape, with “I don’t know” allowed.

The prompt

From intake/extract.py:

PROMPT = """Extract the purchase order from the message below.
Answer with JSON only, no other text, in exactly this shape:
{{"supplier": str, "order_number": str, "delivery_date": "YYYY-MM-DD",
  "lines": [{{"sku": str, "quantity": int, "unit_price": number}}]}}
If a field is missing in the message, use null. Do not guess.

Message:
{message}"""

Three choices make this prompt testable:

  1. A fixed JSON shape. Your code can parse it; free text it cannot.
  2. null for missing fields. The model is allowed to say “not in the message”.
  3. “Do not guess.” A guessed delivery date is worse than a missing one, because it looks right.

(The double braces {{ }} are Python’s way to write a literal { inside a text that is filled in with .format().)

From answer to order

def extract_order(message: str, llm: LLM) -> Order:
    answer = llm.complete(PROMPT.format(message=message))
    try:
        data = json.loads(answer)
        lines = tuple(
            OrderLine(sku=str(line["sku"]), quantity=int(line["quantity"]), unit_price=float(line["unit_price"]))
            for line in data["lines"]
        )
        return Order(
            supplier=str(data["supplier"]),
            order_number=str(data.get("order_number") or ""),
            delivery_date=date.fromisoformat(data["delivery_date"]),
            lines=lines,
        )
    except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
        raise ExtractionError(f"Could not read the LLM answer as an order: {error}") from error

Anything that does not fit the shape (not JSON, a missing field, a date that is null) becomes an ExtractionError, and the pipeline turns that into the status failed. A missing order number becomes an empty text, so the rules can flag it and a human can fill it in.

The LLM is a parameter

extract_order does not know which LLM it talks to. It receives anything with a complete(prompt) method (see intake/llm.py):

ClassUsed for
RecordedLLMTests and demos: replays a recorded answer from samples/*.llm.json, so results are the same every time and need no API key
AnthropicLLMA real model through the Anthropic Messages API, with ANTHROPIC_API_KEY set

Look at a recorded answer, samples/order-2.llm.json, next to the email it came from, samples/order-2.eml. Then at samples/order-3: the email says “same price as last time” and “asap”, and the recorded answer correctly uses null for the price and the date.

Exercise

  1. Compare each sample email with its recorded answer. Is every value really in the email?
  2. Optional, with an API key: run python -m intake samples/order-2.eml --llm anthropic --today 2026-12-01 (with the fake ERP running, see lesson 6, Running the Bot End to End). Does the real model give the same answer as the recording?
  3. Write a fourth sample email that is tricky: two order numbers, or prices including VAT. Predict what a good answer would be before you try a model.

Key Takeaways

  • Ask the LLM for structured data in a fixed shape, with null for “not in the message”.
  • “Do not guess” protects you from values that look right but are invented.
  • Anything that does not fit the shape becomes a clear error, never a booked order.
  • Make the LLM a parameter, so tests can use recorded answers.