代码

cookbook/agent_concepts/user_control_flows/external_tool_execution.py
import subprocess

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools import tool
from agno.utils import pprint

@tool(external_execution=True)
def execute_shell_command(command: str) -> str:
    """执行一个 shell 命令。

    Args:
        command (str): 要执行的 shell 命令

    Returns:
        str: shell 命令的输出
    """
    if command.startswith("ls"):
        return subprocess.check_output(command, shell=True).decode("utf-8")
    else:
        raise Exception(f"不支持的命令: {command}")

agent = Agent(
    model=OpenAIChat(id="gpt-4o-mini"),
    tools=[execute_shell_command],
    markdown=True,
)

run_response = agent.run("What files do I have in my current directory?")
if run_response.is_paused:
    for tool in run_response.tools_awaiting_external_execution:
        if tool.tool_name == execute_shell_command.name:
            print(f"外部执行 {tool.tool_name} 参数为 {tool.tool_args}")
            # 我们自己执行该工具。您也可以在此处执行完全外部的内容。
            result = execute_shell_command.entrypoint(**tool.tool_args)
            # 我们必须将结果设置在工具执行对象上,以便代理可以继续执行
            tool.result = result

    run_response = agent.continue_run()
    pprint.pprint_run_response(run_response)

使用方法

1

创建虚拟环境

打开 Terminal 并创建一个 python 虚拟环境。

python3 -m venv .venv
source .venv/bin/activate
2

设置您的 API 密钥

export OPENAI_API_KEY=xxx
3

安装库

pip install -U agno openai
4

运行示例

python cookbook/agent_concepts/user_control_flows/external_tool_execution.py

主要特点

  • 使用 @tool(external_execution=True) 标记需要外部执行的工具
  • 演示了如何处理工具执行结果

使用场景

  • 在代理控制之外执行敏感操作
  • 在代理控制之外执行长时间运行的操作