> ## 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_async.py theme={null}
import asyncio
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 = asyncio.run(agent.arun("我当前目录下有什么文件?"))
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 = asyncio.run(agent.acontinue_run(run_response=run_response))
    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_async.py
      ```

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

## 主要特性

* 使用 `agent.arun()` 进行异步代理执行
* 实现 `agent.acontinue_run()` 进行异步继续执行
* 保持与同步版本相同的外部工具执行流程
* 演示了如何处理外部工具的异步执行

## 用例

* 非阻塞式外部工具执行
* 需要异步执行的高性能应用程序
* 带有外部服务调用的 Web 应用程序
* 带有外部工具的长时间运行操作
