structured() requests a JSON object or array from the model, parses it, and (optionally) validates it against a custom predicate. On parse or validation failure, it sends a repair prompt that includes the previous response and the error, then retries — up to max_retries times.
importasyncioimportosfromexecutionkitimportProvider,structureddefis_valid_user(value:object)->str|None:"""Return None for valid, error string for invalid."""ifnotisinstance(value,dict):return"Top-level value must be a JSON object."missing={"name","email","age"}-value.keys()ifmissing:returnf"Missing required fields: {sorted(missing)}"ifnotisinstance(value["age"],int)orvalue["age"]<0:return"'age' must be a non-negative integer."returnNone# ✓asyncdefmain()->None:asyncwithProvider(base_url=os.environ["LLM_BASE_URL"],api_key=os.environ.get("LLM_API_KEY",""),model=os.environ["LLM_MODEL"],)asprovider:result=awaitstructured(provider,"Extract the user record from: 'Alice, alice@example.com, 32 years old'.",validator=is_valid_user,max_retries=2,)print(result.value)# {'name': 'Alice', 'email': '...', 'age': 32}print(result.metadata["parse_attempts"])# 1 = parsed cleanly first tryprint(result.metadata["repair_attempts"])# 0 = no repair neededprint(result.metadata["validated"])# Trueasyncio.run(main())
Keep repair counts bounded. Repeated failures can indicate an unclear prompt,
an unsupported schema, or a model that does not follow the requested format.