第 6 天 14 分钟阅读

高级配置与定制

掌握自定义工具开发、Prompt 工程技巧、资源限制、插件扩展和环境变量的高级配置。

自定义工具

工具(Tools)是 Agent 与外部世界交互的桥梁。ThePopeBot 允许你创建自定义工具来扩展 Agent 的能力。

工具定义结构

每个工具需要定义名称、描述、参数和执行逻辑:

import { defineTool } from '@thepopebot/core';

export const databaseQuery = defineTool({
  name: 'database-query',
  description: '执行数据库查询并返回结果。支持 SELECT 查询,禁止修改操作。',
  parameters: {
    type: 'object',
    properties: {
      query: {
        type: 'string',
        description: '要执行的 SQL 查询语句(仅支持 SELECT)',
      },
      database: {
        type: 'string',
        enum: ['main', 'analytics', 'logs'],
        description: '目标数据库',
      },
      limit: {
        type: 'number',
        default: 100,
        description: '返回结果数量限制',
      },
    },
    required: ['query', 'database'],
  },

  // 安全验证
  validate: (params) => {
    const forbidden = ['INSERT', 'UPDATE', 'DELETE', 'DROP', 'ALTER'];
    const upperQuery = params.query.toUpperCase();
    for (const keyword of forbidden) {
      if (upperQuery.includes(keyword)) {
        throw new Error(`禁止执行 ${keyword} 操作`);
      }
    }
    return true;
  },

  // 执行逻辑
  execute: async (params) => {
    const db = getDatabase(params.database);
    const results = await db.query(params.query, { limit: params.limit });
    return {
      rowCount: results.length,
      data: results,
      executionTime: results.meta.duration,
    };
  },
});

注册自定义工具

import { registerTools } from '@thepopebot/core';
import { databaseQuery } from './tools/database-query';
import { slackNotify } from './tools/slack-notify';

registerTools([databaseQuery, slackNotify]);

工具分类最佳实践

类别示例安全等级
只读工具数据库查询、文件读取低风险
写入工具文件创建、消息发送中风险
系统工具Shell 执行、进程管理高风险
外部工具API 调用、第三方集成需审查

Prompt 工程技巧

高质量的系统提示是 Agent 表现优秀的关键。以下是一些经过验证的 Prompt 工程技巧。

结构化提示模板

const advancedPrompt = `
# 角色定义
你是 [角色名称],专注于 [专业领域]。

# 核心能力
1. [能力 1]:[详细说明]
2. [能力 2]:[详细说明]

# 决策框架
当面对任务时,遵循以下流程:
1. 理解:确认你完全理解了任务需求
2. 规划:列出需要执行的步骤
3. 执行:按计划逐步执行
4. 验证:检查结果是否符合预期
5. 报告:提供清晰的执行报告

# 工具使用规范
- 优先使用最精确的工具
- 每次工具调用前说明原因
- 工具失败时提供替代方案

# 输出格式
- 使用 Markdown 格式
- 代码块标注语言类型
- 重要信息使用粗体标记

# 安全边界
- 不执行未经授权的操作
- 敏感操作前请求确认
- 不泄露系统内部信息
`;

上下文注入

动态地将项目上下文注入到系统提示中:

function buildContextualPrompt(project: ProjectInfo): string {
  return `
${basePrompt}

# 项目上下文
- 项目名称:${project.name}
- 技术栈:${project.techStack.join(', ')}
- 代码规范:${project.codeStyle}
- 分支策略:${project.branchStrategy}

# 项目特定规则
${project.customRules.map(rule => `- ${rule}`).join('\n')}
`;
}

少样本学习(Few-Shot)

通过提供示例来引导 Agent 的输出格式:

const fewShotPrompt = `
当用户请求代码审查时,按以下格式输出:

## 示例输入
"请审查这个函数的性能"

## 示例输出
### 性能分析报告
**文件**: src/utils/process.ts
**函数**: processData()

| 问题 | 严重程度 | 建议 |
|------|---------|------|
| 循环内创建对象 | 中 | 移到循环外部 |
| 未使用缓存 | 高 | 添加 Map 缓存 |

**预期改善**: 处理时间减少约 40%
`;

资源限制

合理的资源限制能防止 Agent 过度消耗系统资源。

export const resourceLimits = {
  // Token 限制
  tokens: {
    maxInputTokens: 8192,
    maxOutputTokens: 4096,
    maxTotalPerSession: 100000,
    warningThreshold: 0.8,
  },

  // 工具调用限制
  toolCalls: {
    maxPerMessage: 10,
    maxPerSession: 100,
    timeoutMs: 30000,
    retries: 2,
  },

  // 文件操作限制
  fileOperations: {
    maxFileSize: '10MB',
    maxFilesPerOperation: 20,
    allowedPaths: ['src/', 'tests/', 'docs/'],
    blockedPaths: ['node_modules/', '.env', '.git/'],
  },

  // 并发限制
  concurrency: {
    maxParallelTools: 3,
    maxParallelAgents: 5,
    queueSize: 50,
  },

  // 费用控制
  cost: {
    maxDailyCost: 10.00,    // 美元
    maxMonthlyCost: 200.00,
    alertThreshold: 0.7,
  },
};

限制监控

import { ResourceMonitor } from '@thepopebot/core';

const monitor = new ResourceMonitor(resourceLimits);

monitor.on('warning', (metric, current, limit) => {
  console.warn(`资源警告: ${metric} 已达 ${(current/limit*100).toFixed(0)}%`);
});

monitor.on('limit-reached', (metric) => {
  console.error(`资源限制: ${metric} 已达上限,暂停操作`);
});

插件扩展

ThePopeBot 的插件系统允许你以模块化的方式扩展功能。

插件结构

import { definePlugin } from '@thepopebot/core';

export const analyticsPlugin = definePlugin({
  name: 'analytics',
  version: '1.0.0',
  description: '为 Agent 添加使用分析和报告功能',

  // 插件初始化
  setup: async (app) => {
    // 注册新工具
    app.registerTool(analyticsQueryTool);
    app.registerTool(reportGeneratorTool);

    // 添加中间件
    app.use(trackingMiddleware);

    // 注册事件监听
    app.on('message', async (msg) => {
      await trackUsage(msg);
    });

    app.on('tool-call', async (call) => {
      await trackToolUsage(call);
    });
  },

  // 插件销毁
  teardown: async () => {
    await flushAnalytics();
  },
});

安装和使用插件

import { createApp } from '@thepopebot/core';
import { analyticsPlugin } from './plugins/analytics';
import { notificationPlugin } from './plugins/notification';

const app = createApp({
  agents: [codeAssistant, securityAgent],
  plugins: [
    analyticsPlugin,
    notificationPlugin.configure({
      channels: ['slack', 'email'],
      onError: true,
      onComplete: true,
    }),
  ],
});

环境变量配置

ThePopeBot 使用分层的环境变量配置系统,支持不同环境的灵活切换。

环境变量层级

# .env.defaults    - 默认值(提交到仓库)
# .env             - 本地覆盖(不提交)
# .env.production  - 生产环境
# .env.staging     - 预发布环境
# .env.test        - 测试环境

完整的环境变量参考

# === LLM 配置 ===
LLM_PROVIDER=openai           # openai | anthropic | azure
OPENAI_API_KEY=sk-xxx
ANTHROPIC_API_KEY=sk-ant-xxx
LLM_MODEL=gpt-4
LLM_TEMPERATURE=0.7
LLM_MAX_TOKENS=4096

# === Agent 配置 ===
AGENT_NAME=my-agent
AGENT_AUTONOMY=semi           # full | semi | supervised
AGENT_MAX_ITERATIONS=10

# === 渠道配置 ===
WEB_PORT=3000
WEB_AUTH_TYPE=jwt
TELEGRAM_BOT_TOKEN=xxx
WEBHOOK_SECRET=xxx

# === 存储配置 ===
DATABASE_URL=postgresql://localhost:5432/thepopebot
REDIS_URL=redis://localhost:6379
STORAGE_TYPE=local             # local | s3 | gcs

# === 安全配置 ===
JWT_SECRET=your-jwt-secret
ENCRYPTION_KEY=your-encryption-key
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW=60000

# === 监控配置 ===
LOG_LEVEL=info                 # debug | info | warn | error
SENTRY_DSN=https://[email protected]/xxx
METRICS_ENABLED=true
METRICS_PORT=9090

配置验证

import { validateConfig } from '@thepopebot/core';

// 启动时自动验证必要的环境变量
const config = validateConfig({
  required: ['LLM_PROVIDER', 'OPENAI_API_KEY'],
  optional: ['LOG_LEVEL', 'METRICS_ENABLED'],
  validate: {
    LLM_TEMPERATURE: (v) => parseFloat(v) >= 0 && parseFloat(v) <= 2,
    WEB_PORT: (v) => parseInt(v) > 0 && parseInt(v) < 65536,
  },
});

小结

今天你学习了 ThePopeBot 的高级配置和定制技巧,包括自定义工具开发、Prompt 工程、资源限制、插件系统和环境变量管理。明天是最后一天,我们将学习如何将 Agent 部署到生产环境。