cleandataengineering.aiDrug-Safety Agent on Databricks, drawn simply
You are here: Core loop › The repair turn

Drug-Safety Agent on Databricks · Core loop · The repair turn

When the draft is malformed: one repair turn

Models sometimes reply with almost-right JSON: a missing field, a number written as text. Rather than fail at once or accept it, the agent tells the model exactly what was wrong and asks again, one time. A second failure becomes a hand-off to a person, with the reason.

Goes inA reply that broke the output contract
What happensSend the list of problems back as a message; ask for only the corrected JSON
Comes outA valid draft, or a hand-off naming what broke

One, not many. Repeated repairs hide a model that cannot do the job and burn the budget. One repair turn recovers the common slip; after that a person should look.

The real code

Cut from the repository each time this site is built, so it always matches what runs. Each header names the file and the line it was cut from.

src/drugsafety/hagent.py:120Parse; on problems, one repair turn; on a second failure, needs_human
    body, problems = _parse(result.reply)
    if problems:  # one repair turn (P-OUTPUT-CONTRACT)
        history = (Message(role="user", content=goal), Message(role="assistant", content=result.reply))
        again = await turn("Invalid reply: " + "; ".join(problems) + ". Reply with only the corrected JSON object.", history)
        if not isinstance(again, Completed):
            return done("needs_human", None, "the repair turn ended without an answer", again)
        body, problems = _parse(again.reply)
        if problems:
            return done("needs_human", None, "final reply broke the output contract: " + "; ".join(problems), again)
        result = again
    return done("draft", body, "", result)


def _parse(reply: str) -> tuple[dict | None, list[str]]: