代码

cookbook/agent_concepts/user_control_flows/external_tool_execution_stream.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,
)

for run_response in agent.run(
    "我当前目录下有什么文件?", stream=True
):
    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(run_response=run_response, stream=True)
        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_stream.py

主要特性

  • 使用 agent.run(stream=True) 进行响应流式传输
  • 通过 agent.continue_run(stream=True) 实现流式续接
  • 通过外部工具执行保持实时交互
  • 演示了如何处理带有外部工具的流式响应

用例

  • 实时外部工具执行
  • 带有外部服务调用的流式应用程序
  • 带有外部工具执行的交互式界面
  • 通过外部工具进行渐进式响应生成