-
Notifications
You must be signed in to change notification settings - Fork 1
Day 5: self-healing, interruption, and model-API retry #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c328f11
Add loop detector and interruption to the agent loop
folathecoder 03dc6ec
Test loop detector, self-heal recovery, and interrupt then resume
folathecoder 3ae2801
Broaden model-API retry to transient errors; fail fast on permanent
folathecoder 1e29285
Test transient-error retry vs fail-fast on permanent errors
folathecoder bc5e804
Clean up memory.py module docstring (plain prose, no em dashes)
folathecoder File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,17 @@ | ||
| """The agent loop. | ||
|
|
||
| Agent assembles the framework's primitives — a Model, a set of Tools, and a | ||
| Memory of typed steps — into an async ReAct loop. A single async generator | ||
| (``_run_stream``) drives everything and yields Events; ``run()`` is a thin | ||
| dispatcher that either hands back that stream (``stream=True``) or drains it and | ||
| returns the final answer (``stream=False``). | ||
| Agent ties the framework's primitives (a Model, some Tools, and a Memory of | ||
| typed steps) into an async ReAct loop. One async generator, _run_stream, does | ||
| the real work and yields Events. run() is a thin dispatcher: it hands back that | ||
| stream when stream is True, or drains it and returns the final answer otherwise. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import time | ||
| import json | ||
| from dataclasses import replace | ||
| from collections.abc import AsyncIterator, Callable, Sequence | ||
| from typing import Any | ||
|
|
||
|
|
@@ -25,6 +26,11 @@ | |
| "final_answer tool (or simply reply with plain text)." | ||
| ) | ||
|
|
||
| _LOOP_NUDGE = ( | ||
| " Note: you already made this exact tool call and got the same result. " | ||
| "Try a different approach." | ||
| ) | ||
|
|
||
|
|
||
| class Agent: | ||
| """An async tool-calling agent. | ||
|
|
@@ -48,11 +54,11 @@ def __init__( | |
| self.max_steps = max_steps | ||
| self.step_callbacks = list(step_callbacks) | ||
| self.parallel_tools = parallel_tools | ||
| self.skills = list(skills) # wired in Day 6 | ||
| self.skills = list(skills) # accepted but not consumed yet | ||
|
|
||
| self.memory = Memory() | ||
| self._interrupt = asyncio.Event() | ||
|
|
||
| # final_answer is always available so the model has an explicit way to stop. | ||
| all_tools = [*tools, FinalAnswerTool()] | ||
| self.tools: dict[str, Tool] = {tool.name: tool for tool in all_tools} | ||
| self._tool_schemas = [tool.to_schema() for tool in all_tools] | ||
|
|
@@ -67,10 +73,15 @@ def run( | |
| ) -> Any: | ||
| """Run the agent on a task. | ||
|
|
||
| With stream=False (default) returns a coroutine resolving to the final | ||
| answer string: ``answer = await agent.run(task)``. | ||
| With stream=True returns an async iterator of Events: | ||
| ``async for event in agent.run(task, stream=True): ...``. | ||
| With stream=False (the default) this returns a coroutine that resolves | ||
| to the final answer string: | ||
|
|
||
| answer = await agent.run(task) | ||
|
|
||
| With stream=True it returns an async iterator of Events instead: | ||
|
|
||
| async for event in agent.run(task, stream=True): | ||
| ... | ||
| """ | ||
| events = self._run_stream(task, reset=reset, max_steps=max_steps) | ||
| if stream: | ||
|
|
@@ -95,17 +106,34 @@ async def _run_stream( | |
| self.memory.add(TaskStep(task=task)) | ||
|
|
||
| limit = max_steps or self.max_steps | ||
|
|
||
| # Remember the previous step's calls so we can spot an exact repeat. | ||
| previous_signature: tuple[tuple[str, str], ...] | None = None | ||
|
|
||
| for _ in range(limit): | ||
| if self._interrupt.is_set(): | ||
| self._interrupt.clear() | ||
| yield FinalEvent(answer="Run interrupted.") | ||
| return | ||
|
|
||
| started = time.monotonic() | ||
| messages = self.memory.to_messages(self.instructions) | ||
| response = await self.model.generate(messages, tools=self._tool_schemas) | ||
|
|
||
| # Forgiving termination: a turn with no tool calls IS the final answer. | ||
| # Forgiving termination: no tool calls means the content is the answer. | ||
| if not response.tool_calls: | ||
| self.memory.add(FinalStep(answer=response.content)) | ||
| yield FinalEvent(answer=response.content, usage=response.usage) | ||
| return | ||
|
|
||
| # Fingerprint this step's calls: (name, canonical JSON args) each. | ||
| signature = tuple( | ||
| (tc.name, json.dumps(tc.arguments, sort_keys=True)) | ||
| for tc in response.tool_calls | ||
| ) | ||
| looping = signature == previous_signature | ||
| previous_signature = signature | ||
|
|
||
| # Announce every call, then run them (concurrently or in order). | ||
| for tool_call in response.tool_calls: | ||
| yield ToolCallEvent(tool_call=tool_call) | ||
|
Comment on lines
+129
to
139
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1. Loop nudge overclaims result Agent._run_stream() appends a note saying the repeated tool call “got the same result,” but the loop detector only compares the (tool name, args) signature and never checks whether the tool output actually matched the previous step. This can mislead the model (and anyone inspecting observations) when tools are non-deterministic or when repeating a call is intentional. Agent Prompt
|
||
|
|
@@ -117,6 +145,10 @@ async def _run_stream( | |
| else: | ||
| results = [await self._execute_tool(tc) for tc in response.tool_calls] | ||
|
|
||
| # Same calls as the last step: nudge the model to change approach. | ||
| if looping: | ||
| results = [replace(r, content=r.content + _LOOP_NUDGE) for r in results] | ||
|
|
||
| for result in results: | ||
| yield ToolResultEvent(result=result) | ||
|
|
||
|
|
@@ -169,8 +201,8 @@ async def _execute_tool(self, tool_call: ToolCall) -> ToolResult: | |
| try: | ||
| output = await tool.call(tool_call.arguments) | ||
| except Exception as exc: | ||
| # Deliberate broad catch: a failing tool becomes an observation the | ||
| # model can recover from, never a crash. (Day 5 refines the layers.) | ||
| # A failing tool becomes an observation the model can recover from | ||
| # rather than a crash, so catching broadly here is intentional. | ||
| return ToolResult( | ||
| tool_call_id=tool_call.id, | ||
| name=tool_call.name, | ||
|
|
@@ -183,3 +215,11 @@ async def _execute_tool(self, tool_call: ToolCall) -> ToolResult: | |
| content=str(output), | ||
| is_error=False, | ||
| ) | ||
|
|
||
| def interrupt(self) -> None: | ||
| """Request a graceful stop before the next step. | ||
|
|
||
| The current run pauses rather than crashing; resume it later with | ||
| run(..., reset=False), which continues from the steps already in memory. | ||
| """ | ||
| self._interrupt.set() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
2. Interrupt bypasses forced-final
🐞 Bug☼ ReliabilityAgent Prompt
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools