Generating Structured Output from LLMs with AWS Lambda durable functions

Get JSON output from an LLM and validate it against a schema using AWS Lambda durable functions

This pattern demonstrates structured output extraction with AWS Lambda durable functions. The LLM response is validated against a schema with automatic retry on validation errors.
The example uses an LLM to extract contact information from unstructured text and validates it using Pydantic (Python) or Zod (TypeScript).
Benefits: Automatic retry on validation failures without manual error handling. Schema enforcement ensures data quality. Checkpointing prevents re-extraction on transient failures.

Select language:

Usage Example with Python:

Structured output with Lambda durable functions using Python and Pydantic.

import json
import re

import boto3
from aws_durable_execution_sdk_python import DurableContext, durable_execution
from pydantic import BaseModel

MODEL_ID = "us.amazon.nova-lite-v1:0"
bedrock = boto3.client("bedrock-runtime")


def converse(model_id: str, prompt: str) -> str:
    response = bedrock.converse(
        modelId=model_id,
        messages=[{"role": "user", "content": [{"text": prompt}]}],
    )
    return response["output"]["message"]["content"][0]["text"]


class ExtractedContact(BaseModel):
    name: str
    email: str
    company: str


def extract_contact(text: str) -> dict:
    raw = converse(
        MODEL_ID,
        f'Extract contact info as JSON with keys "name", "email", "company": {text}',
    )
    match = re.search(r"\{[^}]+\}", raw)
    if not match:
        raise ValueError("No JSON found in response")
    data = json.loads(match.group())
    return ExtractedContact(**data).model_dump()


@durable_execution
def handler(event: dict, context: DurableContext):
    text = event.get("text", "John Smith from Acme Corp, email: john@acme.com")
    return context.step(lambda _: extract_contact(text), "extract")

                                                      



Created by:

Connor Kirkpatrick

Connor Kirkpatrick

Solution Engineer at AWS

Follow on LinkedIn