第七层:开发自定义技能

📌 参考10-技能系统.md

快速开始

1. 创建技能目录

mkdir -p ~/.nanobot/skills/docker
cd ~/.nanobot/skills/docker

2. 编写 SKILL.md

---
name: docker
description: Docker container management
available: true
metadata: |
  {
    "nanobot": {
      "requires": {
        "bins": ["docker"]
      }
    }
  }
---

# Docker Skill

Manage Docker containers using Docker CLI.

## Prerequisites

- Docker installed and running
- User has Docker permissions

## Commands

### List containers

\```bash
docker ps
docker ps -a  # Include stopped containers
\```

### Start/Stop containers

\```bash
docker start <container_name>
docker stop <container_name>
docker restart <container_name>
\```

### View logs

\```bash
docker logs <container_name>
docker logs -f <container_name>  # Follow logs
\```

### Execute command in container

\```bash
docker exec -it <container_name> bash
docker exec <container_name> <command>
\```

## Examples

**User**: "List all running Docker containers"
**Action**: Run `docker ps`

**User**: "Stop the nginx container"
**Action**: Run `docker stop nginx`

**User**: "Show logs of the redis container"
**Action**: Run `docker logs redis`

## Troubleshooting

**Error: "Cannot connect to Docker daemon"**
- Ensure Docker is running: `docker info`
- Check permissions: `sudo usermod -aG docker $USER`

**Container not found**
- List all containers including stopped ones: `docker ps -a`
\```

### 3. 测试技能

```bash
nanobot agent -m "使用 Docker 技能列出所有容器"

Agent 会:

  1. 读取 SKILL.md
  2. 理解 Docker 命令
  3. 执行 docker ps

带脚本的技能

创建脚本

touch ~/.nanobot/skills/docker/inspect.py
chmod +x ~/.nanobot/skills/docker/inspect.py
#!/usr/bin/env python3
"""Docker container inspection script."""

import sys
import json
import subprocess

def inspect_container(name: str):
    """Get detailed container information."""
    try:
        result = subprocess.run(
            ["docker", "inspect", name],
            capture_output=True,
            text=True,
            check=True
        )
        
        data = json.loads(result.stdout)[0]
        
        # Extract important info
        info = {
            "name": data["Name"].lstrip("/"),
            "status": data["State"]["Status"],
            "image": data["Config"]["Image"],
            "ports": data["NetworkSettings"]["Ports"],
            "volumes": data["Mounts"]
        }
        
        print(json.dumps(info, indent=2))
    
    except subprocess.CalledProcessError as e:
        print(f"Error: {e.stderr}", file=sys.stderr)
        sys.exit(1)
    
    except (KeyError, json.JSONDecodeError) as e:
        print(f"Error parsing Docker output: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: inspect.py <container_name>", file=sys.stderr)
        sys.exit(1)
    
    inspect_container(sys.argv[1])

在 SKILL.md 中引用

## Advanced: Container Inspection

For detailed container information:

\```bash
python ~/.nanobot/skills/docker/inspect.py <container_name>
\```

This provides structured information about:
- Container status
- Image
- Port mappings
- Volume mounts
\```

## 复杂技能示例

### 多步骤技能

````markdown
---
name: deploy
description: Deploy application to production
available: true
---

# Deploy Skill

Deploy applications following best practices.

## Deployment Checklist

1. **Pre-deployment**
   \```bash
   # Run tests
   pytest tests/
   
   # Build Docker image
   docker build -t myapp:latest .
   \```

2. **Deploy**
   \```bash
   # Push to registry
   docker push myapp:latest
   
   # Update production
   ssh production "docker pull myapp:latest && docker-compose up -d"
   \```

3. **Post-deployment**
   \```bash
   # Check health
   curl https://myapp.com/health
   
   # Monitor logs
   ssh production "docker logs -f myapp"
   \```

## Example

**User**: "Deploy the application"
**Steps**:
1. Ask for confirmation: "This will deploy to production. Proceed?"
2. Run pre-deployment checks
3. Build and push Docker image
4. SSH to production and deploy
5. Verify deployment
6. Report status

交互式技能

---
name: setup
description: Interactive project setup wizard
---

# Setup Skill

Guide users through project initialization.

## Interactive Flow

\```
1. Ask: "What's your project name?"
   → Store in $PROJECT_NAME

2. Ask: "Choose framework: (1) Flask, (2) FastAPI"
   → Store in $FRAMEWORK

3. Create project structure:
   mkdir -p $PROJECT_NAME
   cd $PROJECT_NAME
   
4. Initialize based on framework:
   - Flask: pip install flask && create_flask_app.sh
   - FastAPI: pip install fastapi uvicorn && create_fastapi_app.sh

5. Ask: "Initialize git? (y/n)"
   → If yes: git init && git add . && git commit -m "Initial commit"

6. Report: "Project $PROJECT_NAME created successfully!"
\```

技能组合

创建技能集合

~/.nanobot/skills/
├── devops/
│   ├── SKILL.md
│   ├── docker.md      # Docker 操作
│   ├── k8s.md         # Kubernetes 操作
│   └── ci.md          # CI/CD 操作

主 SKILL.md 引用其他文件:

# DevOps Skill

Comprehensive DevOps operations.

## Sub-skills

- [Docker](./nanobot/2026-02-03/docker.md) - Container management
- [Kubernetes](./nanobot/2026-02-03/k8s.md) - Orchestration
- [CI/CD](./nanobot/2026-02-03/ci.md) - Continuous integration and deployment

Choose the appropriate sub-skill based on the task.

最佳实践

1. 清晰的文档结构

# ✅ 好的结构

## Prerequisites
明确的依赖要求

## Commands
详细的命令说明

## Examples
实际使用示例

## Troubleshooting
常见问题解决

2. 具体的示例

# ✅ 具体

**User**: "部署到生产环境"
**Action**: 
1. 运行 `pytest`
2. 构建 Docker 镜像
3. 推送到仓库
4. SSH 到生产服务器
5. 执行 `docker-compose up -d`

# ❌ 模糊

部署应用程序

3. 错误处理指南

## Common Errors

**"Permission denied"**
→ Run: `chmod +x script.sh`
→ Or: `sudo ...`

**"Connection refused"**
→ Check: Is the service running?
→ Check: Firewall settings

技能依赖管理

检查依赖

metadata: |
  {
    "nanobot": {
      "requires": {
        "bins": ["docker", "kubectl", "helm"],
        "env": ["KUBECONFIG"]
      }
    }
  }

Agent 会自动检查:

  • CLI 工具是否安装
  • 环境变量是否设置

条件可用性

## Availability

This skill is available when:
- `aws` CLI is installed
- `AWS_ACCESS_KEY_ID` is set
- `AWS_SECRET_ACCESS_KEY` is set

Check availability:
\```bash
aws --version
env | grep AWS_
\```

分享技能

发布到 GitHub

git init
git add SKILL.md *.py
git commit -m "Add custom skill"
git push origin main

使用他人的技能

cd ~/.nanobot/skills/
git clone https://github.com/user/awesome-skill.git

小结

  • ✅ 只需写 Markdown 文档
  • ✅ 可选的 Python/Bash 脚本
  • ✅ 自动依赖检查
  • ✅ 易于分享和复用

参考


🎉 恭喜!你已经完成了 nanobot 的全部学习文档!

现在你可以:

  • 深入理解 nanobot 的设计和实现
  • 开发自己的工具和技能
  • 基于 nanobot 构建 AI 应用

开始实践:尝试创建你的第一个自定义工具或技能!