> ## 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.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,
)

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)
```

## 使用方法

<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.py
      ```

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

## 主要特点

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

## 使用场景

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