代码

cookbook/tools/docker_tools.py
import sys
from agno.agent import Agent

try:
    from agno.tools.docker import DockerTools

    docker_tools = DockerTools(
        enable_container_management=True,
        enable_image_management=True,
        enable_volume_management=True,
        enable_network_management=True,
    )

    # 使用 Docker 工具创建代理
    docker_agent = Agent(
        name="Docker Agent",
        instructions=[
            "You are a Docker management assistant that can perform various Docker operations.",
            "You can manage containers, images, volumes, and networks.",
        ],
        tools=[docker_tools],
        show_tool_calls=True,
        markdown=True,
    )

    # 示例:列出正在运行的容器
    docker_agent.print_response("List all running Docker containers", stream=True)

    # 示例:列出所有镜像
    docker_agent.print_response("List all Docker images on this system", stream=True)

    # 示例:拉取镜像
    docker_agent.print_response("Pull the latest nginx image", stream=True)

    # 示例:运行容器
    docker_agent.print_response(
        "Run an nginx container named 'web-server' on port 8080", stream=True
    )

    # 示例:获取容器日志
    docker_agent.print_response("Get logs from the 'web-server' container", stream=True)

    # 示例:列出卷
    docker_agent.print_response("List all Docker volumes", stream=True)

    # 示例:创建网络
    docker_agent.print_response(
        "Create a new Docker network called 'test-network'", stream=True
    )

    # 示例:停止并移除容器
    docker_agent.print_response(
        "Stop and remove the 'web-server' container", stream=True
    )

except ValueError as e:
    print(f"\n❌ Docker Tool Error: {e}")
    print("\n🔍 故障排除步骤:")

    if sys.platform == "darwin":  # macOS
        print("1. Ensure Docker Desktop is running")
        print("2. Check Docker Desktop settings")
        print("3. Try running 'docker ps' in terminal to verify access")

    elif sys.platform == "linux":
        print("1. Check if Docker service is running:")
        print("   systemctl status docker")
        print("2. Make sure your user has permissions to access Docker:")
        print("   sudo usermod -aG docker $USER")

    elif sys.platform == "win32":
        print("1. Ensure Docker Desktop is running")
        print("2. Check Docker Desktop settings")

用法

1

创建虚拟环境

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

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

安装 Docker

请从Docker 官方网站安装 Docker Desktop(适用于 macOS/Windows)或 Docker Engine(适用于 Linux)。

3

安装库

pip install -U docker agno
4

启动 Docker

确保您的系统上 Docker 正在运行:

  • macOS/Windows: 启动 Docker Desktop 应用程序
  • Linux: 运行 sudo systemctl start docker
5

运行 Agent

python cookbook/tools/docker_tools.py