Standard library only · runs in your browser
Your stage-4 loop crashes the first time the model emits broken JSON, and production models do that a few times in every thousand calls. Feed the error back so the model can fix itself, but give up on a model that keeps failing.
The starter code is your stage-4 loop. Extend it:
parse_tool_call raises ValueError as e, don't crash. Append {"role": "user", "content": f"error: could not parse your tool call ({e}). Reply with a JSON tool call or a final answer."} and continue to the next step.error: also counts as an error.errors (total) and consecutive errors. A successful tool result resets the consecutive count to 0.max_consecutive_errors, return with "stop_reason": "too_many_errors" and "steps" set to the current step."errors", the total error count.run_agent(task, script, max_steps=5, max_consecutive_errors=3) -> dict