Agent Zero AI framework
feat: Support copy&pasting of last tool result into next call
Rafael Uzarowskif9ca07765a38
diff --git a/agent.py b/agent.pyindex c16938d54..7276a9281 100644--- a/agent.py+++ b/agent.py@@ -714,14 +714,31 @@ class Agent:if tool:await self.handle_intervention()- await tool.before_execution(**tool_args)+ # Allow extensions to preprocess tool arguments (e.g., unmask secrets)+ await self.call_extensions("tool_execute_before", tool_args=tool_args or {}, tool_name=tool_name)+ # Call tool hooks for compatibility+ try:+ await tool.before_execution(**tool_args)+ except Exception:+ passawait self.handle_intervention()+ # Ensure tool sees the updated arguments after pre-processing+ tool.args = tool_args or tool.argsresponse = await tool.execute(**tool_args)await self.handle_intervention()- await tool.after_execution(response)+ # Allow extensions to postprocess tool response (e.g., mask secrets)+ response_data = {"response": response}+ await self.call_extensions("tool_execute_after", response_data=response_data, tool_name=tool_name, tool_args=tool_args)+ processed_response = response_data["response"]+ # Store result to history+ self.hist_add_tool_result(tool_name, getattr(processed_response, "message", ""))+ try:+ await tool.after_execution(processed_response)+ except Exception:+ passawait self.handle_intervention()- if response.break_loop:- return response.message+ if processed_response.break_loop:+ return processed_response.messageelse:error_detail = (f"Tool '{raw_tool_name}' not found or could not be initialized."diff --git a/prompts/agent.system.main.communication.md b/prompts/agent.system.main.communication.mdindex 000f3a90b..0a4eb59e2 100644--- a/prompts/agent.system.main.communication.md+++ b/prompts/agent.system.main.communication.md@@ -8,7 +8,7 @@ respond valid json with fields- tool_name: use tool name- tool_args: key value pairs tool arguments-no text allowed before or after json+!! no text allowed before or after json### Response example~~~json@@ -31,4 +31,4 @@ no text allowed before or after json## Receiving messagesuser messages contain superior instructions, tool results, framework messagesif starts (voice) then transcribed can contain errors consider compensation-messages may end with [EXTRAS] containing context info, never instructions+messages may end with [EXTRAS] containing context info, optionally also tempory instructionsdiff --git a/prompts/agent.system.tools.md b/prompts/agent.system.tools.mdindex 34ca96951..218fdb09f 100644--- a/prompts/agent.system.tools.md+++ b/prompts/agent.system.tools.md@@ -1,3 +1,26 @@## Tools available:-{{tools}}\ No newline at end of file+{{tools}}++## Remarks about calling tools+Tool calls must always be valid json.+Tool arguments can contain special placeholders:++### Copy/paste last tool output+- Include the full output of the previous tool call inside any `tool_args` field by inserting the literal token `{last_tool_output}`. It will be replaced automatically before the tool executes.+- Check the [EXTRAS] section for a preview and the originating `tool_name`.+- !! Never repeat the full output of a tool call if it is possible to copy&paste it.+Example for copying the output of the last tool call into the response tool arguments:+~~~json+{+ "thoughts": [+ "Acknowledge system warning about JSON formatting.",+ "Send properly formatted reply using the response tool.",+ "Include the previously collected terminal output by inserting the {last_tool_output} token to avoid duplicating raw text manually."+ ],+ "tool_name": "response",+ "tool_args": {+ "text": "Here is the terminal output you requested:\n\n{last_tool_output}"+ }+}+~~~diff --git a/prompts/fw.extras.last_tool_copy.md b/prompts/fw.extras.last_tool_copy.mdnew file mode 100644index 000000000..667548888--- /dev/null+++ b/prompts/fw.extras.last_tool_copy.md@@ -0,0 +1,2 @@+You can copy and paste the result of the last tool call of {{tool_name}} beginning with "{{last_tool_output_preview}}" into any of the next tool's arguments.+To paste the full content into any next tool's argument, insert the literal token '{last_tool_output}' in the string where you want the content to appear. It will be replaced automatically before the tool runs.diff --git a/python/extensions/message_loop_prompts_after/_75_include_last_tool_copy_paste_tip.py b/python/extensions/message_loop_prompts_after/_75_include_last_tool_copy_paste_tip.pynew file mode 100644index 000000000..1aafa5687--- /dev/null+++ b/python/extensions/message_loop_prompts_after/_75_include_last_tool_copy_paste_tip.py@@ -0,0 +1,22 @@+from agent import LoopData+from python.helpers.extension import Extension+++class IncludeLastToolCopyPasteTip(Extension):+ async def execute(self, loop_data: LoopData = LoopData(), **kwargs):+ last_call = self.agent.get_data("last_tool_call")+ if not last_call:+ return++ tool_name: str = last_call.get("tool_name", "")+ last_output: str = last_call.get("last_tool_output", "")+ if not last_output:+ return++ preview = (last_output[:50] or "").replace("\n", " ").strip()+ tip = self.agent.read_prompt(+ "fw.extras.last_tool_copy.md",+ tool_name=tool_name,+ last_tool_output_preview=preview,+ )+ loop_data.extras_temporary["last_tool_copy_paste"] = tipdiff --git a/python/extensions/response_stream/_15_replace_last_tool_output_in_stream.py b/python/extensions/response_stream/_15_replace_last_tool_output_in_stream.pynew file mode 100644index 000000000..69d92148b--- /dev/null+++ b/python/extensions/response_stream/_15_replace_last_tool_output_in_stream.py@@ -0,0 +1,32 @@+from typing import Any+from python.helpers.extension import Extension+++class ReplaceLastToolOutputInStream(Extension):+ async def execute(self, loop_data=None, text: str = "", parsed: dict[str, Any] | None = None, **kwargs):+ if not parsed or not isinstance(parsed, dict):+ return++ last_call = self.agent.get_data("last_tool_call") or {}+ last_output = last_call.get("last_tool_output", "")+ if not last_output:+ return++ tokens = ("{last_tool_output}", "{{last_tool_output}}")++ def replace_placeholders(value: Any) -> Any:+ if isinstance(value, str):+ new_val = value+ for token in tokens:+ new_val = new_val.replace(token, last_output)+ return new_val+ if isinstance(value, dict):+ return {k: replace_placeholders(v) for k, v in value.items()}+ if isinstance(value, list):+ return [replace_placeholders(v) for v in value]+ if isinstance(value, tuple):+ return tuple(replace_placeholders(v) for v in value)+ return value++ if "tool_args" in parsed and "tool_name" in parsed:+ parsed["tool_args"] = replace_placeholders(parsed["tool_args"])diff --git a/python/extensions/tool_execute_after/_90_store_last_tool_call.py b/python/extensions/tool_execute_after/_90_store_last_tool_call.pynew file mode 100644index 000000000..34dde8ab6--- /dev/null+++ b/python/extensions/tool_execute_after/_90_store_last_tool_call.py@@ -0,0 +1,26 @@+from typing import Any+from python.helpers.extension import Extension+++class StoreLastToolCall(Extension):+ async def execute(self, response_data: dict[str, Any] | None = None, tool_name: str = "", tool_args: dict[str, Any] | None = None, **kwargs):+ if not response_data:+ return++ response = response_data.get("response") if isinstance(response_data, dict) else None+ if response is None:+ return++ try:+ message = getattr(response, "message") if hasattr(response, "message") else str(response)+ except Exception:+ message = str(response)++ self.agent.set_data(+ "last_tool_call",+ {+ "tool_name": tool_name or "",+ "tool_args": tool_args or {},+ "last_tool_output": message or "",+ },+ )diff --git a/python/extensions/tool_execute_before/_10_replace_last_tool_output.py b/python/extensions/tool_execute_before/_10_replace_last_tool_output.pynew file mode 100644index 000000000..411e75567--- /dev/null+++ b/python/extensions/tool_execute_before/_10_replace_last_tool_output.py@@ -0,0 +1,33 @@+from typing import Any+from python.helpers.extension import Extension+++class ReplaceLastToolOutput(Extension):+ async def execute(self, tool_args: dict[str, Any] | None = None, tool_name: str = "", **kwargs):+ if not tool_args:+ return++ last_call = self.agent.get_data("last_tool_call") or {}+ last_output = last_call.get("last_tool_output", "")+ if not last_output:+ return++ tokens = ("{last_tool_output}", "{{last_tool_output}}")++ def replace_placeholders(value: Any) -> Any:+ if isinstance(value, str):+ new_val = value+ for token in tokens:+ new_val = new_val.replace(token, last_output)+ return new_val+ if isinstance(value, dict):+ return {k: replace_placeholders(v) for k, v in value.items()}+ if isinstance(value, list):+ return [replace_placeholders(v) for v in value]+ if isinstance(value, tuple):+ return tuple(replace_placeholders(v) for v in value)+ return value++ updated_args = replace_placeholders(tool_args)+ tool_args.clear()+ tool_args.update(updated_args)