> ## Documentation Index
> Fetch the complete documentation index at: https://ikun.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 流式外部工具执行

> 此示例演示了如何实现流式外部工具执行，从而在执行代理控制之外的工具时实现实时交互和响应流。

## 代码

```python cookbook/agent_concepts/user_control_flows/external_tool_execution_stream.py theme={null}
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)
```

## 用法

<Steps>
  <Snippet file="create-venv-step.mdx" />

  <Step title="设置你的 API 密钥">
    ```bash theme={null}
    export OPENAI_API_KEY=xxx
    ```
  </Step>

  <Step title="安装库">
    ```bash theme={null}
    pip install -U agno openai
    ```
  </Step>

  <Step title="运行示例">
    <CodeGroup>
      ```bash Mac theme={null}
      python cookbook/agent_concepts/user_control_flows/external_tool_execution_stream.py
      ```

      ```bash Windows theme={null}
      python cookbook/agent_concepts/user_control_flows/external_tool_execution_stream.py
      ```
    </CodeGroup>
  </Step>
</Steps>

## 主要特性

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

## 用例

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