skills 使用py脚本,如果涉及到第三方包怎么办

TwoAdmin 2025-10-22 6 10/22

Skill 本身不解决依赖问题,依赖需要在执行环境中提前准备好

SKILL.md 只是一个指令文件,它告诉 Agent "请运行 scripts/pdf_parser.py",但不会自动安装这个脚本所需的第三方包。Python 脚本运行时的 ImportError 需要由环境来保障。

几种解决方案

方案一:在 Skill 文档中明确声明依赖(推荐)

SKILL.md 中添加一个 ## Dependencies 章节,让 Agent 在执行前检查和提示:

markdown
## Dependencies

This skill requires the following Python packages:

```bash
pip install pypdf2 pdfplumber pymupdf

If you encounter ImportError, install the missing package and retry.

text
然后在执行流程中要求 Agent 先验证:

```markdown
## Execution Flow

1. **Check dependencies**: Run `python -c "import pypdf2"` to verify. If fails, instruct user to install dependencies.
2. Run `scripts/pdf_parser.py <file>`

方案二:在脚本内部做优雅降级

pdf_parser.py 自己处理导入失败的情况:

python
#!/usr/bin/env python3
"""PDF parser with fallback strategies"""

def parse_pdf(filepath):
    # Try multiple backends
    try:
        import pypdf2
        # use pypdf2
    except ImportError:
        try:
            import pdfplumber
            # use pdfplumber
        except ImportError:
            print("ERROR: No PDF library found. Please run: pip install pypdf2")
            sys.exit(1)

方案三:使用环境隔离(适合生产环境)

在 Agent 的执行环境中预先配置好依赖:

dockerfile
# Dockerfile for Agent runtime
FROM python:3.11-slim

RUN pip install pypdf2 pdfplumber pymupdf pandas openpyxl

# 所有 skills 的脚本共享这个环境
COPY skills/ /skills/

或者使用虚拟环境 + requirements.txt:

text
project/
├── skills/
│   └── pdf-skill/
│       ├── SKILL.md
│       ├── scripts/
│       │   └── pdf_parser.py
│       ├── requirements.txt
│       └── .venv/              # 虚拟环境放这里
│           ├── bin/
│           └── lib/

虚拟环境需要提前装好,但有两种策略:

一、完全提前装好(打包分发)

.venv 文件夹直接打包进 Skill,别人下载下来就能直接用。

text
pdf-skill/
├── SKILL.md
├── scripts/
├── requirements.txt
└── .venv/              # 已装好依赖,直接可用
    ├── bin/
    └── lib/python3.11/site-packages/  # 已安装的包

优点

  • 零配置,开箱即用

  • 不依赖网络(如果打包时已装好)

缺点

  • 体积大(一个 .venv 可能几十到几百 MB)

  • 跨平台问题(Linux 的 .venv 不能在 Windows 用)

  • Python 版本兼容性(Python 3.11 的 venv 不能在 3.12 用)

二、只保留配置,首次运行时自动装(推荐)

Skill 文件夹不包含 .venv,只保留 requirements.txt,Agent 或用户在第一次使用时自动安装。

text
pdf-skill/
├── SKILL.md
├── scripts/
│   └── pdf_parser.py
├── requirements.txt    # 只有依赖列表
└── setup.sh            # 可选:一键安装脚本

在 SKILL.md 中描述自动安装逻辑

markdown
## First-time Setup

The virtual environment will be created automatically on first use.

**Detection logic for Agent:**

```bash
SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_PYTHON="$SKILL_DIR/.venv/bin/python"

if [ ! -f "$VENV_PYTHON" ]; then
    echo "📦 First use: Creating virtual environment..."
    cd "$SKILL_DIR"
    python3 -m venv .venv
    .venv/bin/pip install -r requirements.txt
    echo "✅ Setup complete"
fi

# Now run the script
$VENV_PYTHON scripts/pdf_parser.py "$@"
text
### Agent 执行时的实际流程

当用户说"帮我解析这个 PDF":

1. Agent 加载 `pdf-skill` 的 `SKILL.md`
2. 读取到上面的检测逻辑
3. 检查 `.venv/bin/python` 是否存在
4. **首次运行**:
   ```bash
   cd /path/to/skills/pdf-skill
   python3 -m venv .venv              # 创建虚拟环境
   .venv/bin/pip install -r requirements.txt  # 安装依赖(需要网络)
   .venv/bin/python scripts/pdf_parser.py document.pdf
text
### 方案四:Skill 打包成容器(最隔离)

把整个 skill 打包成容器镜像,Agent 通过 Docker 运行:

```markdown
## Execution

Run the PDF parser in an isolated container:

```bash
docker run --rm -v $(pwd):/data pdf-skill:latest python /scripts/pdf_parser.py /data/document.pdf
text
这样依赖完全封装在镜像里,不污染主机环境。

## 现实中的两种主流做法

### 1. 轻量级(Claude/Cursor 风格)

- **假设环境已配置好**,Skill 文档只写"需要装什么"
- Agent 运行脚本时如果报错,把错误信息返回给用户
- 用户手动装依赖后重试

**优点**:简单直接  
**缺点**:体验断档,用户需要懂技术

### 2. 重量级(企业 Agent 平台风格)

- Agent 运行在一个**预装了常见库的沙箱**中
- 每个 Skill 可以声明 `requirements.txt`,平台自动安装
- 或者用 Nix/Guix 做声明式环境

**优点**:用户无感知  
**缺点**:实现复杂

## 针对你的 Himalaya 示例

看回你给的 `himalaya` skill,它其实用了类似的思路:

```markdown
prerequisites:
  commands: [himalaya]   # 声明需要 himalaya 命令

但没有处理 himalaya 未安装的情况。更完善的写法应该是:

markdown
prerequisites:
  commands: [himalaya]
  install_hint: |
    curl -sSL https://raw.githubusercontent.com/pimalaya/himalaya/master/install.sh | sh

总结

层级 谁负责 做法
Skill 定义 文档作者 SKILL.md 中声明依赖清单
Agent 执行 Agent 逻辑 执行前检查,缺失时报错或提示安装
运行环境 平台/用户 预先安装好所有可能用到的库

核心原则SKILL.md声明式的("我需要什么"),实际依赖管理是命令式的(需要环境提前满足或 Agent 动态处理)。

对于你的场景,最简单的做法是:SKILL.md 的开头加一个 ## Requirements 章节,列出 pip install xxx 命令,并在执行流程的第一步要求 Agent 检查。这样既清晰又实用。

- THE END -

TwoAdmin

5月15日16:32

最后修改:2026年5月15日
0

非特殊说明,本博所有文章均为博主原创。