**系列**: AI Agent 实战笔记 **日期**: 2026-05-22 **标签**: OpenCode, 提示词工程, Prompt, 最佳实践 **难度**: ⭐⭐⭐

提示词工程 — OpenCode 高效指令编写指南

系列: AI Agent 实战笔记 日期: 2026-05-22 标签: OpenCode, 提示词工程, Prompt, 最佳实践 难度: ⭐⭐⭐

简介

与 AI Agent 交互的质量,很大程度上取决于你发出的指令(Prompt)的质量。同样的模型,用不同的提示词,可能得到天差地别的结果。OpenCode 提供了一套完整的提示词工程体系——从结构化指令模板到上下文注入,从文件引用到管道输入——让你能够精确控制 AI 的行为和输出。

提示词工程不是一门玄学,而是一门可以系统化学习和实践的工程学科。今天我们就来深入 OpenCode 的提示词工程,掌握让 AI Agent 高效工作的核心技能。

一、结构化指令

1.1 为什么需要结构化

非结构化的指令容易产生歧义和遗漏:

bash
# ❌ 不好的指令
$ opencode run --prompt "帮我改一下代码,让它更快一点"

# ✅ 结构化的指令
$ opencode run --prompt-file ./prompts/optimize-auth.yaml

结构化指令的核心优势:

  1. 明确性:每个部分都有清晰的定义,减少歧义
  2. 可复用性:模板可以在不同场景下重复使用
  3. 可版本控制:提示词可以作为代码一样被管理
  4. 可组合性:多个结构化指令可以组合使用

1.2 结构化指令格式

OpenCode 使用 YAML 格式的结构化指令:

yaml
# prompts/refactor-module.yaml
prompt:
  role: "你是一位资深的后端开发工程师,专注于代码质量和系统架构"

  task: "重构认证模块,将现有的 Session-based 认证迁移到 JWT-based 认证"

  context:
    project: "E-commerce Platform"
    current_auth: "Express Session + Passport.js"
    target_auth: "JWT (jsonwebtoken) + refresh token rotation"

  constraints:
    - "保持向后兼容,不改变公开 API 的接口签名"
    - "所有新代码必须通过 TypeScript 类型检查"
    - "单测覆盖率不低于 85%"
    - "不能使用 eval() 或动态 require()"

  requirements:
    input_files:
      - path: "src/auth/session.js"
        role: "现有认证逻辑"
      - path: "src/auth/middleware.js"
        role: "认证中间件"
      - path: "src/auth/config.js"
        role: "认证配置"

    output_files:
      - path: "src/auth/jwt.js"
        description: "新的 JWT 认证核心逻辑"
      - path: "src/auth/token-rotation.js"
        description: "Refresh token 轮换机制"
      - path: "src/auth/middleware.js"
        description: "更新后的认证中间件"

    dependencies:
      - "jsonwebtoken@^9.0"
      - "crypto"

  steps:
    - "分析现有 session 认证流程,列出需要保留的行为"
    - "设计 JWT token 结构(header, payload, signature)"
    - "实现 access token 生成和验证逻辑"
    - "实现 refresh token 轮换机制"
    - "更新认证中间件以支持 JWT"
    - "编写单元测试"
    - "更新相关文档"

  validation:
    - "运行 npm test -- --grep auth"
    - "运行 npm run lint:auth"
    - "检查类型: npx tsc --noEmit src/auth/"

  output_format:
    type: "code_with_comments"
    include_tests: true
    include_docs: true
    language: "typescript"

1.3 使用结构化指令

bash
# 方式 1: 直接使用提示词文件
opencode run --prompt-file ./prompts/refactor-module.yaml

# 方式 2: 从命令行参数构建
opencode run \
    --role "资深后端工程师" \
    --task "重构认证模块到 JWT" \
    --constraint "保持 API 兼容" \
    --constraint "单测覆盖率 >= 85%"

# 方式 3: 交互式构建
opencode prompt create --interactive

交互式模式会引导你逐步构建提示词:

bash
$ opencode prompt create --interactive

📝 提示词创建向导

1. 角色设定 (Role)
   请输入 AI 的角色描述:
   > 你是一位资深的后端开发工程师...
   ✅ Role set

2. 任务描述 (Task)
   请描述需要完成的任务:
   > 重构认证模块,将 Session-based 迁移到 JWT...
   ✅ Task set

3. 约束条件 (Constraints)
   请输入约束条件(输入空行结束):
   > 保持向后兼容
   > 所有新代码通过 TypeScript 类型检查
   > 单测覆盖率不低于 85%
   >
   ✅ 3 constraints added

4. 输入文件 (Input Files)
   请输入相关文件(输入空行结束):
   > src/auth/session.js: 现有认证逻辑
   > src/auth/middleware.js: 认证中间件
   >
   ✅ 2 input files added

5. 输出格式 (Output Format)
   请选择输出格式 [code/markdown/json]:
   > code
   ✅ Output format set

📋 提示词预览:
---
role: 你是一位资深的后端开发工程师...
task: 重构认证模块...
constraints: [保持向后兼容, ...]
input_files: [src/auth/session.js, ...]
output_format: code
---

保存到文件? [Y/n]: y
文件路径: ./prompts/refactor-auth.yaml
✅ Prompt saved to ./prompts/refactor-auth.yaml

1.4 提示词模板系统

OpenCode 支持提示词模板,可以在模板中使用变量:

yaml
# prompts/templates/refactor.yaml
prompt:
  role: "{{role}}"
  task: "重构 {{module}} 模块,从 {{from}} 迁移到 {{to}}"

  constraints:
    - "{{constraints}}"

  requirements:
    input_files: "{{input_files}}"
    output_format: "code_with_comments"

使用模板:

bash
opencode run --template ./prompts/templates/refactor.yaml \
    --var role="资深前端工程师" \
    --var module="状态管理" \
    --var from="Redux" \
    --var to="Zustand" \
    --var constraints="保持现有组件接口不变" \
    --var input_files="src/store/index.js,src/store/slices/*.js"

二、上下文注入

2.1 上下文层级

OpenCode 支持多层级的上下文注入,从项目级到任务级:

text
┌─────────────────────────────────────────┐
│           项目级上下文                    │
│  (.opencode/context/project.yaml)       │
│  - 项目概述                              │
│  - 技术栈                                │
│  - 编码规范                              │
│  - 目录结构说明                          │
├─────────────────────────────────────────┤
│           模块级上下文                    │
│  (.opencode/context/modules/*.yaml)     │
│  - 模块职责                              │
│  - 模块间依赖关系                        │
│  - 关键设计决策                          │
├─────────────────────────────────────────┤
│           任务级上下文                    │
│  (--context ./context/task.yaml)        │
│  - 当前任务描述                          │
│  - 相关文件                              │
│  - 特殊要求                              │
├─────────────────────────────────────────┤
│           运行时上下文                    │
│  (--context-inline "...")               │
│  - 即时信息                              │
│  - 错误消息                              │
│  - 用户反馈                              │
└─────────────────────────────────────────┘

2.2 项目级上下文

项目级上下文定义了整个项目的基本信息:

yaml
# .opencode/context/project.yaml
project:
  name: "E-commerce Platform"
  description: "一个基于 Node.js 的电商平台后端服务"
  version: "2.3.0"

  tech_stack:
    runtime: "Node.js 20 LTS"
    framework: "Express.js 4.x"
    language: "TypeScript 5.x"
    database: "PostgreSQL 15"
    cache: "Redis 7"
    orm: "Prisma 5"

  coding_standards:
    style_guide: "Airbnb JavaScript Style Guide"
    naming: "camelCase for variables, PascalCase for classes"
    imports: "absolute imports from src/"
    error_handling: "try-catch with custom error classes"
    testing: "Jest + Supertest, 80% coverage minimum"

  architecture:
    pattern: "Clean Architecture"
    layers:
      - "Controllers (route handlers)"
      - "Services (business logic)"
      - "Repositories (data access)"
      - "Models (data structures)"

  conventions:
    commits: "Conventional Commits"
    branches: "Git Flow"
    releases: "Semantic Versioning"

2.3 自动上下文发现

OpenCode 可以自动发现项目上下文:

bash
# 自动扫描项目结构生成上下文
opencode context discover --project ~/my-project

# 输出示例
🔍 Scanning project structure...
   Found package.json → detected tech stack
   Found tsconfig.json → detected TypeScript config
   Found .eslintrc → detected linting rules
   Found prisma/schema.prisma → detected database schema
   Found 45 source files → mapped module structure

📝 Generated context file: .opencode/context/project.yaml

# 查看生成的上下文
opencode context view

# 手动补充上下文
opencode context edit --file .opencode/context/project.yaml

2.4 选择性上下文注入

并非所有上下文信息都对每个任务有用。OpenCode 支持选择性注入:

bash
# 只注入特定模块的上下文
opencode run --task "修复登录 Bug" \
    --context .opencode/context/modules/auth.yaml

# 注入多个上下文
opencode run --task "实现购物车功能" \
    --context .opencode/context/modules/cart.yaml \
    --context .opencode/context/modules/products.yaml \
    --context .opencode/context/modules/users.yaml

# 排除某些上下文
opencode run --task "优化 API 性能" \
    --context .opencode/context/project.yaml \
    --exclude-context .opencode/context/modules/legacy.yaml

2.5 动态上下文

运行时动态注入上下文信息:

bash
# 注入 Git 状态作为上下文
opencode run --task "修复 merge 冲突" \
    --context-inline "$(git status --short)"

# 注入测试结果作为上下文
opencode run --task "修复失败的测试" \
    --context-inline "$(npm test -- --json 2>&1)"

# 注入错误日志作为上下文
opencode run --task "诊断启动失败" \
    --context-inline "$(tail -100 logs/server.log)"

三、文件引用

3.1 文件引用语法

OpenCode 支持多种方式引用文件内容:

bash
# 方式 1: 内联引用 (--file)
opencode run --task "优化这个文件" --file src/auth/session.js

# 方式 2: 批量引用 (--files)
opencode run --task "重构认证模块" --files "src/auth/**/*.js"

# 方式 3: 从列表文件读取
opencode run --task "统一代码风格" --file-list files-to-fix.txt

# 方式 4: 使用上下文标签
opencode run --task "修复以下文件" \
    --ref @src/auth/session.js \
    --ref @src/auth/middleware.js

3.2 引用粒度控制

精确控制引用的文件内容和范围:

bash
# 引用完整文件
opencode run --file src/auth/session.js

# 引用文件的部分内容(按行号)
opencode run --file "src/auth/session.js:10-50"

# 引用文件的部分内容(按函数/类名)
opencode run --file "src/auth/session.js:function validateToken"

# 引用文件的导入部分
opencode run --file "src/auth/session.js:imports"

# 引用文件的导出部分
opencode run --file "src/auth/session.js:exports"

3.3 文件内容过滤

对于大型文件,可以只引用相关内容:

bash
# 只引用包含特定关键词的行
opencode run --task "审查密码相关代码" \
    --file "src/auth/session.js" \
    --filter "password|hash|encrypt"

# 引用特定类型的内容
opencode run --task "审查类型定义" \
    --file "src/auth/*.ts" \
    --filter "type|interface"

# 引用 Git diff
opencode run --task "审查最近的变更" \
    --file "src/auth/session.js" \
    --filter "git-diff:HEAD~3..HEAD"

3.4 文件组

将相关文件组织成组,方便复用:

yaml
# .opencode/file-groups.yaml
groups:
  auth-module:
    files:
      - "src/auth/session.js"
      - "src/auth/middleware.js"
      - "src/auth/config.js"
      - "src/auth/types.ts"
    description: "认证模块核心文件"

  api-routes:
    files:
      - "src/routes/*.js"
    description: "所有 API 路由"

  test-suite:
    files:
      - "tests/**/*.test.js"
      - "tests/**/*.spec.js"
    description: "测试文件"
bash
# 使用文件组
opencode run --task "重构认证模块" \
    --file-group auth-module

# 组合多个文件组
opencode run --task "全面代码审查" \
    --file-group auth-module \
    --file-group api-routes \
    --file-group test-suite

3.5 外部文件引用

引用项目外部的文件:

bash
# 引用绝对路径文件
opencode run --task "参考设计规范" \
    --file /docs/api-design-guide.md

# 引用 URL 内容
opencode run --task "遵循最佳实践" \
    --url "https://example.com/best-practices.md"

# 引用另一个项目的文件
opencode run --task "保持风格一致" \
    --file "../reference-project/src/config.js"

四、管道输入

4.1 基本管道

OpenCode 支持从标准输入接收任务描述和上下文:

bash
# 通过管道传递任务描述
echo "重构认证模块到 JWT" | opencode run --stdin

# 通过管道传递结构化指令
cat ./prompts/refactor.yaml | opencode run --stdin --format yaml

# 通过管道传递文件列表
find src/auth -name "*.js" | opencode run --task "审查所有认证文件" --stdin-files

4.2 管道组合

管道可以与其他命令组合使用,形成强大的工作流:

bash
# 组合 git diff 和代码审查
git diff main...feature/auth | opencode review --stdin-diff

# 组合测试输出和错误修复
npm test 2>&1 | opencode fix --stdin-errors

# 组合 lint 输出和代码修复
npm run lint 2>&1 | opencode fix --stdin-lint --auto-fix

# 组合日志和错误诊断
journalctl -u myservice --since "1 hour ago" | opencode diagnose --stdin-logs

4.3 管道工作流

构建复杂的多步骤管道工作流:

bash
# 工作流 1: 完整的 PR 审查管道
$ git diff main...feature/auth | \
    opencode analyze --stdin-diff | \
    opencode review --stdin-analysis | \
    opencode format --stdin-review --output report.md

# 工作流 2: 自动化修复管道
$ npm test 2>&1 | \
    opencode identify-errors --stdin | \
    opencode generate-fix --stdin-errors | \
    opencode apply-fix --stdin-fix --dry-run | \
    opencode validate-fix --stdin-patch

# 工作流 3: 代码质量检查管道
$ find src -name "*.js" | \
    xargs opencode analyze --files | \
    opencode generate-report --stdin-analysis | \
    tee quality-report.md | \
    opencode create-issues --stdin-report --github

4.4 管道格式化

OpenCode 支持多种管道输入格式:

bash
# JSON 格式管道
echo '{"task": "fix bug", "file": "src/index.js", "line": 42}' | \
    opencode run --stdin --format json

# Markdown 格式管道
cat task-description.md | opencode run --stdin --format markdown

# 纯文本格式管道(默认)
echo "优化数据库查询性能" | opencode run --stdin --format text

4.5 管道输出

管道输出同样灵活,可以对接下游工具:

bash
# 输出为 JSON(供程序处理)
opencode run --task "分析代码" --output json | jq '.issues[]'

# 输出为 Markdown(供文档使用)
opencode run --task "生成文档" --output markdown > docs.md

# 输出为 Patch(供 Git 使用)
opencode run --task "修复 Bug" --output patch | git apply

# 输出为 SARIF(供安全工具使用)
opencode run --task "安全扫描" --output sarif > security-results.sarif

# 输出为 GitHub Review Comment
opencode run --task "代码审查" --output github-review | gh pr review --body -

五、高级技巧

5.1 Few-shot 提示

通过示例指导 AI 的输出格式和行为:

yaml
# prompts/few-shot-refactor.yaml
prompt:
  task: "按照以下模式重构代码"

  examples:
    - input: |
        function getUser(id) {
          const user = db.query("SELECT * FROM users WHERE id = " + id);
          return user;
        }
      output: |
        async function getUser(id: number): Promise<User> {
          const user = await db.query<User>(
            "SELECT * FROM users WHERE id = $1",
            [id]
          );
          if (!user) throw new NotFoundError("User not found");
          return user;
        }

    - input: |
        function createPost(data) {
          const post = db.query("INSERT INTO posts VALUES ...");
          return post;
        }
      output: |
        async function createPost(data: CreatePostDto): Promise<Post> {
          const post = await db.query<Post>(
            "INSERT INTO posts (title, content, author_id) VALUES ($1, $2, $3) RETURNING *",
            [data.title, data.content, data.authorId]
          );
          return post;
        }

  target_code: "src/services/comment.js"

5.2 Chain-of-Thought 提示

引导 AI 逐步思考:

yaml
# prompts/chain-thought.yaml
prompt:
  task: "诊断并修复以下问题"

  reasoning_steps:
    1. "分析错误信息,确定问题类型"
    2. "定位问题代码位置"
    3. "分析问题的根本原因"
    4. "列出可能的修复方案"
    5. "评估每个方案的优缺点"
    6. "选择最佳方案并实施"
    7. "验证修复是否有效"

  output_format: "逐步展示每个步骤的分析和结论"

5.3 提示词质量评估

OpenCode 内置提示词质量检查:

bash
# 检查提示词质量
opencode prompt check --file ./prompts/refactor.yaml

# 输出示例
📋 Prompt Quality Report:

✅ Role: Clear and specific
✅ Task: Well-defined with scope
✅ Context: Comprehensive
⚠️ Constraints: Missing error handling requirements
⚠️ Examples: No few-shot examples provided
✅ Output Format: Clearly specified

Score: 82/100

Suggestions:
1. Add constraints about error handling patterns
2. Include few-shot examples for better output control
3. Specify expected file structure for output

5.4 提示词版本管理

提示词作为代码一样被管理:

bash
# 创建提示词仓库
opencode prompt repo init

# 版本化提示词
opencode prompt version --file ./prompts/refactor.yaml --tag v1.0

# 查看提示词历史
opencode prompt history --file ./prompts/refactor.yaml

# 回滚到之前的版本
opencode prompt rollback --file ./prompts/refactor.yaml --version v0.9

六、实战案例

6.1 完整示例:大型重构任务

bash
# 步骤 1: 创建结构化提示词
$ cat > prompts/full-refactor.yaml << 'EOF'
prompt:
  role: "你是一位资深的全栈工程师,擅长大规模代码重构"

  task: "将整个认证模块从 Session-based 迁移到 JWT-based"

  context:
    - @.opencode/context/project.yaml
    - @.opencode/context/modules/auth.yaml

  constraints:
    - "保持所有公开 API 的接口签名不变"
    - "所有新代码必须通过 TypeScript 类型检查"
    - "单测覆盖率不低于 85%"
    - "遵循 Clean Architecture 分层原则"
    - "使用参数化查询防止 SQL 注入"

  requirements:
    input_files:
      - @src/auth/session.js
      - @src/auth/middleware.js
      - @src/auth/config.js
      - @src/auth/types.ts

    output_format:
      type: "code_with_comments"
      include_tests: true

  validation:
    - "npm test -- --grep auth"
    - "npx tsc --noEmit src/auth/"
    - "npm run lint:auth"
EOF

# 步骤 2: 执行任务
$ opencode run --prompt-file prompts/full-refactor.yaml \
    --workspace /tmp/refactor-workspace \
    --timeout 2h

# 步骤 3: 查看结果
$ opencode run --show-output --last

6.2 日常开发工作流

bash
# 早晨:自动代码审查
$ git fetch origin && \
    git diff origin/main...HEAD | \
    opencode review --stdin-diff \
    --output markdown > ~/reports/daily-review.md

# 开发中:实时错误修复
$ npm test 2>&1 | \
    opencode fix --stdin-errors \
    --auto-apply \
    --backup-before-fix

# 提交前:代码质量检查
$ find src -name "*.ts" | \
    opencode analyze --files | \
    opencode format-report --stdin \
    --output summary.md

总结

今天我们系统学习了 OpenCode 的提示词工程体系。从结构化指令的编写,到多层级上下文注入;从精确的文件引用,到灵活的管道输入——这些都是让 AI Agent 高效工作的核心技能。

核心要点:

  • 结构化指令:使用 YAML 格式定义角色、任务、约束、输入输出,减少歧义
  • 上下文注入:项目级、模块级、任务级、运行时多层级上下文,精确提供所需信息
  • 文件引用:支持完整文件、部分行号、函数级别、Git diff 等多种引用粒度
  • 管道输入:与 shell 命令组合,形成强大的自动化工作流
  • 高级技巧:Few-shot 提示、Chain-of-Thought、质量评估、版本管理

提示词工程的核心原则:越具体越好,越结构化越好,越可复用越好。花时间在提示词上,会换来 AI 输出质量的显著提升。