MAX_RETRIES = 2 def extract_with_retry(document: str) -> Transaction: history = [ {"role": "system", "content": "Extract the transaction details."}, {"role": "user", "content": document}, ] for attempt in range(MAX_RETRIES + 1): completion = client.beta.chat.completions.parse( model="gpt-4o", messages=history, response_format=Transaction ) raw = completion.choices[0].message.content try: return Transaction.model_validate_json(raw) except ValidationError as e: if attempt == MAX_RETRIES: raise # give up, let the caller route this to a human logger.warning("validation failed on attempt %d: %s", attempt, e) history += [ {"role": "assistant", "content": raw}, {"role": "user", "content": f"That failed validation: {e}. Fix only the bad field."}, ]