ClawSkills logoClawSkills

Create a Botpress AI agent with the ADK using OpenClaw

使用 Botpress Agent 开发套件 (ADK) 构建 AI 机器人的指南

介绍

# Botpress ADK Development Guide

使用 Botpress Agent Development Kit (ADK) 构建 AI 机器人的综合指南。

## 使用场景

- 用户要求构建 Botpress 机器人或聊天机器人 - 用户提及 ADK、Agent Development Kit 或 Botpress - 用户希望创建动作、工具、工作流、对话、表、触发器或知识库 - 用户需要有关 `adk` CLI 命令(init、dev、deploy、link)的帮助 - 用户遇到与 ADK 相关的错误或需要故障排除 - 用户询问有关机器人配置、状态管理或集成的问题

## 快速参考

ADK 是一个**基于约定的 TypeScript 框架**,其中**文件结构直接映射到机器人行为**。

**您的角色:** 指导用户完成整个机器人开发生命周期——从项目设置到部署。使用此技能中的模式和代码示例来编写正确、可用的 ADK 代码。

**核心原则:** 在 ADK 中,**文件放置位置至关重要**。每种组件类型都有特定的 `src/` 子目录,并且文件会根据位置自动被发现。

## 如何使用此技能

**此技能是您构建 Botpress 机器人的主要参考。** 当用户要求您使用 ADK 构建某些内容时:

1. **确定他们需要什么** - 是新机器人、功能(动作、工具、工作流)、数据存储(表)还是事件处理(触发器)? 2. **检查正确的目录** - 每种组件类型都位于特定的 `src/` 子目录中 3. **使用以下模式** - 严格遵循代码示例,它们代表了正确的 ADK 约定 4. **运行 `adk --help`** - 用于此处未涵盖的 CLI 命令,或运行 `adk <command> --help` 以获取特定帮助

**决策指南 - 创建什么组件:**

| 用户想要... | 创建此组件 | 位置 | |------------------|-------------|----------| | 处理用户消息 | Conversation | `src/conversations/` | | 添加 AI 可以调用的函数 | Tool | `src/tools/` | | 添加可复用的业务逻辑 | Action | `src/actions/` | | 运行后台/计划任务 | Workflow | `src/workflows/` | | 存储结构化数据 | Table | `src/tables/` | | 对事件(用户创建等)做出反应 | Trigger | `src/triggers/` | | 让 AI 访问文档/数据 | Knowledge Base | `src/knowledge/` | | 连接外部服务(Slack 等) | Integration | `adk add <name>` |

**如果此技能中的信息不够**,请获取相应的 GitHub 参考文件(每个部分均提供了链接)以获取更详细的规范。

## 重要提示:ADK 是 AI 原生的

ADK **不**使用传统的聊天机器人模式。不要创建意图、实体或对话流。

**取而代之的是:** - `execute()` - AI 会根据指令自然地理解用户意图 - Tools - AI 自主决定何时调用您的函数 - `zai.extract()` - 基于模式的结构化数据提取 - 知识库 - 用于将回答建立在您文档基础上的 RAG

**文档:** https://www.botpress.com/docs/adk/ **GitHub:** https://github.com/botpress/skills/tree/master/skills/adk

---

## 前置条件与安装

在使用 ADK 之前,确保用户具备:

- **Botpress 账户** - 在 https://app.botpress.cloud 创建 - **Node.js v22.0.0+** - 使用 `node --version` 检查 - **包管理器** - bun(推荐)、pnpm、yarn 或 npm

**安装 ADK CLI:**

macOS & Linux: ```bash curl -fsSL https://github.com/botpress/adk/releases/latest/download/install.sh | bash ```

Windows (PowerShell): ```powershell powershell -c "irm https://github.com/botpress/adk/releases/latest/download/install.ps1 | iex" ```

**验证安装:** ```bash adk --version ```

如果安装失败,请访问 https://github.com/botpress/adk/releases 查看手动下载选项。

**文档:** https://www.botpress.com/docs/adk/quickstart **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/cli.md

---

## 快速开始

安装 ADK CLI 后,创建一个新机器人:

```bash adk init my-bot # Create project (choose "Hello World" template for beginners) cd my-bot npm install # Or bun/pnpm/yarn adk login # Authenticate with Botpress Cloud adk add chat # Add the chat integration for testing adk dev # Start dev server with hot reload adk chat # Test in CLI (run in separate terminal) adk deploy # Deploy to production when ready ```

位于 **http://localhost:3001/** 的可视化控制台允许您配置集成并测试机器人。

**文档:** https://www.botpress.com/docs/adk/quickstart **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/cli.md

---

## 链接和部署您的机器人

**重要提示:** 您的机器人必须链接到 Botpress Cloud 并部署才能正常工作。ADK 在开发期间在本地运行,但机器人本身驻留在 Botpress Cloud 中。

### 正确的顺序:Link → Dev → Deploy

按照此顺序使您的机器人正常工作:

```bash # 1. LINK - Connect your project to Botpress Cloud (creates agent.json) adk link

# 2. DEV - Start the development server (hot reload, testing) adk dev

# 3. DEPLOY - Push to production when ready adk deploy ```

**分步说明:**

1. **`adk link`** - 将您的本地项目链接到 Botpress Cloud 中的机器人。这会创建包含您的工作区和机器人 ID 的 `agent.json`。在进行任何其他操作之前请先运行此命令。

2. **`adk dev`** - 启动具有热重载功能的本地开发服务器。在 http://localhost:3001 打开开发控制台,您可以在其中配置集成并测试您的机器人。在单独的终端中使用 `adk chat` 进行测试。

3. **`adk deploy`** - 将您的机器人部署到生产环境。当您准备好让机器人上线并通过生产渠道(Slack、WhatsApp、网页聊天等)访问时,运行此命令。

### 故障排除错误

**如果在运行 `adk dev` 或 `adk deploy` 时遇到错误:**

1. **检查日志** - 查看终端输出或位于 http://localhost:3001 的开发控制台中的日志面板 2. **复制错误消息** - 从日志中选择并复制完整的错误消息 3. **寻求帮助** - 将错误粘贴回 AI 助手并要求其帮助修复问题

常见的错误场景: - **集成配置错误:** 通常意味着需要在 localhost:3001 的 UI 中配置集成 - **类型错误:** 通常由不正确的导入或模式不匹配引起 - **部署失败:** 可能表明缺少环境变量或配置无效

**修复错误的示例工作流:** ``` 1. Run `adk dev` or `adk deploy` 2. See error in terminal/logs 3. Copy the error message 4. Tell the AI: "I got this error when running adk dev: [paste error]" 5. The AI will help diagnose and fix the issue ```

**文档:** https://www.botpress.com/docs/adk/quickstart **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/cli.md

---

## 项目结构

**关键规则:** 文件位置决定行为。将组件放置在正确的 `src/` 子目录中,否则它们将无法被发现。

``` my-bot/ ├── agent.config.ts # Bot configuration: name, models, state schemas, integrations ├── agent.json # Workspace/bot IDs (auto-generated by adk link/dev, add to .gitignore) ├── package.json # Node.js dependencies and scripts (dev, build, deploy) ├── tsconfig.json # TypeScript configuration ├── .env # API keys and secrets (never commit!) ├── .gitignore # Should include: agent.json, .env, node_modules/, .botpress/ ├── src/ │ ├── conversations/ # Handle incoming messages → use execute() for AI responses │ ├── workflows/ # Background processes → use step() for resumable operations │ ├── actions/ # Reusable functions → call from anywhere with actions.name() │ ├── tools/ # AI-callable functions → AI decides when to invoke these │ ├── tables/ # Data storage → auto-synced to cloud, supports semantic search │ ├── triggers/ # Event handlers → react to user.created, integration events, etc. │ └── knowledge/ # RAG sources → index docs, websites, or tables for AI context └── .botpress/ # Auto-generated types (never edit manually) ```

**关键配置文件:**

- **agent.config.ts** - 主配置,定义机器人元数据、AI 模型、状态模式和集成(由您编辑) - **agent.json** - 将代理链接到工作区/机器人 ID。由 `adk link` 或 `adk dev` 自动生成。**添加到 .gitignore** - 包含因开发者而异的环境特定 ID - **package.json** - Node.js 配置,包含 `@botpress/runtime` 依赖项以及用于 `dev`、`build`、`deploy` 的脚本 - **tsconfig.json** - 项目的 TypeScript 配置 - **.env** - 用于 API 密钥和机密的环境变量(切勿提交!) - **.gitignore** - 应包括:`agent.json`、`.env`、`node_modules/`、`.botpress/`

**文档:** https://www.botpress.com/docs/adk/project-structure **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/agent-config.md

---

## 代理配置

`agent.config.ts` 文件定义了机器人的身份、AI 模型、状态模式和集成。在设置新机器人时,请始终从这里开始。

```typescript import { defineConfig, z } from "@botpress/runtime";

export default defineConfig({ name: "my-support-bot", description: "AI customer support assistant",

// AI models for different operations defaultModels: { autonomous: "openai:gpt-4o", // Used by execute() for conversations zai: "openai:gpt-4o-mini" // Used by zai operations (cheaper, faster) },

// Global bot state - shared across all conversations and users bot: { state: z.object({ maintenanceMode: z.boolean().default(false), totalConversations: z.number().default(0) }) },

// Per-user state - persists across all conversations for each user user: { state: z.object({ name: z.string().optional(), tier: z.enum(["free", "pro"]).default("free"), preferredLanguage: z.enum(["en", "es", "fr"]).default("en") }), tags: { source: z.string(), region: z.string().optional() } },

// Per-conversation state conversation: { state: z.object({ context: z.string().optional() }), tags: { category: z.enum(["support", "sales", "general"]), priority: z.enum(["low", "medium", "high"]).optional() } },

// Integrations your bot uses (ADK 1.9+ format) dependencies: { integrations: { chat: { version: "[email protected]", enabled: true }, slack: { version: "[email protected]", enabled: true } } } }); ```

**可用模型:** - OpenAI: `openai:gpt-4o`、`openai:gpt-4o-mini`、`openai:gpt-4-turbo` - Anthropic: `anthropic:claude-3-5-sonnet`、`anthropic:claude-3-opus` - Google: `google:gemini-1.5-pro`、`google:gemini-1.5-flash`

**文档:** https://www.botpress.com/docs/adk/project-structure **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/agent-config.md

---

## 核心概念

### 1. Actions - 可复用的业务逻辑

**何时创建 Action:** - 您需要将从多个位置(工作流、对话、触发器)调用的可复用逻辑 - 您正在封装外部 API 或数据库操作 - 您需要可测试、可组合的业务逻辑 - 您需要使用自定义逻辑调用集成 API(Slack、Linear 等)

**何时不使用 Action(改用 Tool):** - 您希望 AI 自主决定何时调用它 - 该函数应该在 `execute()` 期间可用

Actions **不能**由 AI 直接调用——如果 AI 需要使用它们,请使用 `.asTool()` 将它们转换为工具。

**位置:** `src/actions/*.ts`

```typescript import { Action, z } from "@botpress/runtime";

export const fetchUser = new Action({ name: "fetchUser", description: "Retrieves user details from the database",

// Define input/output with Zod schemas for type safety input: z.object({ userId: z.string() }), output: z.object({ name: z.string(), email: z.string() }),

// IMPORTANT: Handler receives { input, client } - destructure input INSIDE the handler async handler({ input, client }) { const { user } = await client.getUser({ id: input.userId }); return { name: user.name, email: user.tags.email }; } }); ```

**调用 actions:** ```typescript import { actions } from "@botpress/runtime"; const userData = await actions.fetchUser({ userId: "123" });

// To make an action callable by the AI, convert it to a tool: tools: [actions.fetchUser.asTool()] ```

**关键规则:** - Handler 接收 `{ input, client }` - 必须在 handler 内部解构 `input` - 无法直接在参数中解构输入字段 - 可以调用其他 actions、集成 actions、访问状态 - 可以使用 `.asTool()` 转换为工具

**文档:** https://www.botpress.com/docs/adk/concepts/actions **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/actions.md

---

### 2. Tools - AI 可调用函数

**何时创建 Tool:** - 您希望 AI 自主决定何时使用此函数 - 该函数检索 AI 所需的信息(搜索、查找、获取) - 该函数代表用户执行操作(创建工单、发送消息) - 您正在构建 AI 在对话中应具备的能力

**AI 根据以下因素决定何时使用工具:** 1. 工具的 `description` - 使其清晰且具体,说明何时使用它 2. 输入模式的 `.describe()` 字段 - 帮助 AI 理解参数的含义 3. 对话上下文和用户意图

**与 Actions 的主要区别:** 工具可以直接解构输入;Actions 则不能。

**位置:** `src/tools/*.ts`

```typescript import { Autonomous, z } from "@botpress/runtime";

export const searchProducts = new Autonomous.Tool({ name: "searchProducts", // This description is critical - it tells the AI when to use this tool description: "Search the product catalog. Use when user asks about products, availability, pricing, or wants to browse items.",

input: z.object({ query: z.string().describe("Search keywords"), category: z.string().optional().describe("Filter by category") }), output: z.object({ products: z.array(z.object({ id: z.string(), name: z.string(), price: z.number() })) }),

// Unlike actions, tools CAN destructure input directly in the handler handler: async ({ query, category }) => { // Your search logic here return { products: [] }; } }); ```

**使用 ThinkSignal:** 当工具无法完成但您想给 AI 提供上下文时: ```typescript import { Autonomous } from "@botpress/runtime";

// Inside handler - AI will see this message and can respond appropriately throw new Autonomous.ThinkSignal( "No results found", "No products found matching that query. Ask user to try different search terms." ); ```

**高级工具属性:** ```typescript export const myTool = new Autonomous.Tool({ name: "myTool", description: "Tool description", input: z.object({...}), output: z.object({...}), aliases: ["searchDocs", "findDocs"], // Alternative names handler: async (input, ctx) => { console.log(`Call ID: ${ctx.callId}`); // Unique call identifier // ... }, retry: async ({ attempt, error }) => { if (attempt < 3 && error?.code === 'RATE_LIMIT') { await new Promise(r => setTimeout(r, 1000 * attempt)); return true; // Retry } return false; // Don't retry } }); ```

**文档:** https://www.botpress.com/docs/adk/concepts/tools **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/tools.md

---

### 3. Conversations - 消息处理器

**何时创建对话:** - 每个机器人至少需要一个对话处理器来响应用户 - 如果不同渠道需要不同的行为,请创建单独的处理器 - 使用 `channel: "*"` 通过一个处理器处理所有渠道

**构建对话时的关键决策:** 1. **哪些渠道?** - 指定 `"*"` 表示所有渠道,或指定特定渠道如 `"slack.dm"` 2. **AI 需要哪些工具?** - 将它们传递给 `execute({ tools: [...] })` 3. **什么知识应作为回复的基础?** - 将其传递给 `execute({ knowledge: [...] })` 4. **什么指令指导 AI?** - 定义个性、规则和上下文

**`execute()` 函数是 ADK 的核心** - 它使用你的工具和知识运行自主 AI 逻辑。大多数对话处理器都会调用 `execute()`。

**位置:** `src/conversations/*.ts`

```typescript import { Conversation, z } from "@botpress/runtime";

export const Chat = new Conversation({ // Which channels this handler responds to channel: "chat.channel", // Or "*" for all, or ["slack.dm", "webchat.channel"]

// Per-conversation state (optional) state: z.object({ messageCount: z.number().default(0) }),

async handler({ message, state, conversation, execute, user }) { state.messageCount += 1;

// Handle commands if (message?.payload?.text?.startsWith("/help")) { await conversation.send({ type: "text", payload: { text: "Available commands: /help, /status" } }); return; }

// Let the AI handle the response with your tools and knowledge await execute({ // Instructions guide the AI's behavior and personality instructions: `You are a helpful customer support agent for Acme Corp. User's name: ${user.state.name || "there"} User's tier: ${user.state.tier} Be friendly, concise, and always offer to help further.`,

// Tools the AI can use during this conversation tools: [searchProducts, actions.createTicket.asTool()],

// Knowledge bases for RAG - AI will search these to ground responses knowledge: [DocsKnowledgeBase],

model: "openai:gpt-4o", temperature: 0.7, iterations: 10 // Max tool call iterations }); } }); ```

**处理器上下文:** - `message` - 用户的消息数据 - `execute` - 运行自主 AI 逻辑 - `conversation` - 对话实例方法 - `state` - 可变状态 - `client` - Botpress API 客户端 - `type` - 事件分类

**Execute 函数选项:** ```typescript await execute({ instructions: string | async function, // Required tools: Tool[], // AI-callable tools knowledge: Knowledge[], // Knowledge bases for RAG exits: Exit[], // Structured exit handlers model: string, // AI model to use temperature: number, // 0-1, default 0.7 iterations: number, // Max tool calls, default 10 hooks: { onBeforeTool: async ({ tool, input }) => { ... }, onAfterTool: async ({ tool, output }) => { ... }, onTrace: async (trace) => { ... } } }); ```

**常用渠道:** `chat.channel`, `webchat.channel`, `slack.dm`, `slack.channel`, `discord.channel`, `whatsapp.channel`, `"*"` (全部)

**文档:** https://www.botpress.com/docs/adk/concepts/conversations **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/conversations.md

---

### 4. 工作流 - 后台与多步骤流程

**何时创建工作流:** - 耗时超过 2 分钟(默认超时时间)的操作 - 需要在崩溃/重启后继续运行的多步骤流程 - 计划/周期性任务(每日报告、定期同步) - 后台处理(订单履行、数据迁移) - 需要等待外部事件或用户输入的操作

**何时不使用工作流(改为在对话中处理):** - 立即完成的快速操作 - 简单的请求-响应模式 - 不需要持久化的操作

**关键工作流概念:** - **步骤是检查点** - 如果工作流崩溃,它将从上次完成的步骤恢复 - **状态持久化** - 将进度存储在 `state` 中以跟踪跨步骤的进度 - **始终传递 conversationId** - 如果工作流需要向用户回发消息

**位置:** `src/workflows/*.ts`

```typescript import { Workflow, z } from "@botpress/runtime";

export const ProcessOrderWorkflow = new Workflow({ name: "processOrder", description: "Processes customer orders", timeout: "6h", // Max duration schedule: "0 9 * * *", // Optional: run daily at 9am (cron syntax)

input: z.object({ orderId: z.string(), conversationId: z.string() // Include this to message the user back! }),

state: z.object({ currentStep: z.number().default(0), processedItems: z.array(z.string()).default([]) }),

output: z.object({ success: z.boolean(), itemsProcessed: z.number() }),

async handler({ input, state, step, client, execute }) { // State is passed as parameter, auto-tracked state.currentStep = 1;

// IMPORTANT: Each step needs a unique, stable name (no dynamic names!) const orderData = await step("fetch-order", async () => { return await fetchOrderData(input.orderId); });

// Steps can have retry logic await step("process-payment", async () => { return await processPayment(orderData); }, { maxAttempts: 3 });

// To message the user from a workflow, use client.createMessage (NOT conversation.send) await step("notify-user", async () => { await client.createMessage({ conversationId: input.conversationId, type: "text", payload: { text: "Your order has been processed!" } }); });

return { success: true, itemsProcessed: state.processedItems.length }; } });

// Start a workflow from a conversation or trigger await ProcessOrderWorkflow.start({ orderId: "123", conversationId: conversation.id // Always pass this if you need to message back });

// Get or create with deduplication const instance = await ProcessOrderWorkflow.getOrCreate({ key: `order-${orderId}`, // Prevents duplicate workflows input: { orderId, conversationId } }); ```

**步骤方法:**

| 方法 | 目的 | |--------|---------| | `step(name, fn)` | 带缓存的基本执行 | | `step.sleep(name, ms)` | 暂停毫秒数 | | `step.sleepUntil(name, date)` | 暂停直到特定日期 | | `step.listen()` | 等待外部事件 | | `step.progress(msg)` | 更新进度消息 | | `step.request(name, prompt)` | 请求用户输入(阻塞) | | `step.executeWorkflow()` | 启动并等待另一个工作流 | | `step.waitForWorkflow(id)` | 等待现有工作流 | | `step.map(items, fn)` | 并发处理数组 | | `step.forEach(items, fn)` | 对项目执行而不返回结果 | | `step.batch(items, fn)` | 分组处理 | | `step.fail(reason)` | 将工作流标记为失败 | | `step.abort()` | 立即停止而不失败 |

**关键规则:** - 步骤名称必须**唯一**且**稳定**(避免在循环中使用动态命名) - State 作为参数传递,而不是通过 `this.state` 访问 - 对于需要向用户发送消息的工作流,始终传递 `conversationId` - 默认超时时间为 2 分钟 - 对于较长的流程请使用步骤

**文档:** https://www.botpress.com/docs/adk/concepts/workflows/overview **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/workflows.md

---

### 5. 表格 - 数据存储

**何时创建表格:** - 你需要持久化结构化数据(用户、订单、工单、日志) - 你想要按字段查询/筛选数据 - 你需要对文本内容进行语义搜索(设置 `searchable: true`) - 你正在存储应该在机器人重启后保留的数据

**何时不使用表格(改用状态):** - 每个用户/对话的简单键值数据 → 使用 `user.state` 或 `conversation.state` - 不需要持久化的临时数据 - 适合存储在状态中的少量数据

**表格 vs 知识库:** - **表格** = 你进行 CRUD(创建、读取、更新、删除)的结构化数据 - **知识库** = 供 AI 搜索和参考的文档/内容

**位置:** `src/tables/*.ts`

**关键规则(违反将导致错误):** - 不要定义 `id` 列 - 它将作为数字自动创建 - 表名必须以 "Table" 结尾(例如 `OrdersTable`,而不是 `Orders`)

```typescript import { Table, z } from "@botpress/runtime";

export const OrdersTable = new Table({ name: "OrdersTable", // Must end with "Table" description: "Stores order information", columns: { // NO id column - it's automatic! orderId: z.string(), userId: z.string(), status: z.enum(["pending", "completed", "cancelled"]), total: z.number(), createdAt: z.date(), // Enable semantic search on a column: notes: { schema: z.string(), searchable: true } } }); ```

**CRUD 操作:** ```typescript // Create - id is auto-assigned await OrdersTable.createRows({ rows: [{ orderId: "ord-123", userId: "user-456", status: "pending", total: 99.99, createdAt: new Date() }] });

// Read with filters const { rows } = await OrdersTable.findRows({ filter: { userId: "user-456", status: "pending" }, orderBy: "createdAt", orderDirection: "desc", limit: 10 });

// Get single row by id const row = await OrdersTable.getRow({ id: 123 });

// Semantic search (on searchable columns) const { rows } = await OrdersTable.findRows({ search: "delivery issue", limit: 5 });

// Update - must include the id await OrdersTable.updateRows({ rows: [{ id: 1, status: "completed" }] });

// Upsert - insert or update based on key column await OrdersTable.upsertRows({ rows: [{ orderId: "ord-123", status: "shipped" }], keyColumn: "orderId" });

// Delete by filter await OrdersTable.deleteRows({ status: "cancelled" });

// Delete by IDs await OrdersTable.deleteRowIds([123, 456]); ```

**高级:计算列:** ```typescript columns: { basePrice: z.number(), taxRate: z.number(), fullPrice: { computed: true, schema: z.number(), dependencies: ["basePrice", "taxRate"], value: async (row) => row.basePrice * (1 + row.taxRate) } } ```

**文档:** https://www.botpress.com/docs/adk/concepts/tables **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/tables.md

---

### 6. 知识库 - AI 上下文的 RAG

**何时创建知识库:** - 你希望 AI 根据你的文档回答问题 - 你有 AI 应该参考的 FAQ、政策或产品信息 - 你希望 AI 回复基于特定内容(而非幻觉) - 你正在构建需要访问帮助文章的支持机器人

**RAG 在 ADK 中如何工作:** 1. 你定义知识源(网站、文件、表格) 2. 内容被索引并嵌入以进行语义搜索 3. 在 `execute()` 期间,AI 会自动搜索相关知识 4. AI 使用检索到的内容生成基于事实的回复

**选择 DataSource 类型:** - **网站** - 索引公共文档、帮助站点、博客 - **目录** - 索引本地 markdown/text 文件(仅限开发!) - **表格** - 从你的表格索引结构化数据

**位置:** `src/knowledge/*.ts`

```typescript import { Knowledge, DataSource } from "@botpress/runtime";

// Website source - index via sitemap const websiteSource = DataSource.Website.fromSitemap( "https://docs.example.com/sitemap.xml", { id: "website-docs", maxPages: 500, maxDepth: 10, filter: (ctx) => ctx.url.includes("/docs/") // Only index /docs/ pages } );

// Local files (development only - won't work in production) const localSource = DataSource.Directory.fromPath("src/knowledge/docs", { id: "local-docs", filter: (path) => path.endsWith(".md") });

// Table-based knowledge const tableSource = DataSource.Table.fromTable(FAQTable, { id: "faq-table", transform: ({ row }) => `Question: ${row.question}\nAnswer: ${row.answer}`, filter: ({ row }) => row.published === true });

export const DocsKB = new Knowledge({ name: "docsKB", description: "Product documentation and help articles", sources: [websiteSource, localSource, tableSource] });

// Use in conversations - AI will search this knowledge base await execute({ instructions: "Answer based on the documentation", knowledge: [DocsKB] });

// Manually refresh knowledge base await DocsKB.refresh(); // Smart refresh (only changed content) await DocsKB.refresh({ force: true }); // Force full re-index await DocsKB.refreshSource("website-docs", { force: true }); // Refresh specific source ```

**网站源方法:** - `fromSitemap(url, options)` - 解析 XML 站点地图 - `fromWebsite(baseUrl, options)` - 从基础 URL 爬取(需要浏览器集成) - `fromLlmsTxt(url, options)` - 解析 llms.txt 文件 - `fromUrls(urls, options)` - 索引特定 URL

**文档:** https://www.botpress.com/docs/adk/concepts/knowledge **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/knowledge-bases.md

---

### 7. 触发器 - 事件驱动的自动化

**何时创建触发器:** - 你需要自动对事件做出反应(用户注册、创建问题等) - 你想在特定事件发生时启动工作流 - 你需要在外部系统更改时同步数据 - 你想基于事件发送通知

**常见触发器模式:** - **用户入职** - 在 `user.created` 上触发 → 启动入职工作流 - **集成同步** - 在 `linear:issueCreated` 上触发 → 在表格中创建记录 - **通知** - 在 `workflow.completed` 上触发 → 发送 Slack 消息

**查找可用事件:** - 机器人事件:`user.created`, `conversation.started`, `workflow.completed` 等 - 集成事件:运行 `adk info <integration> --events` 查看可用事件

**位置:** `src/triggers/*.ts`

```typescript import { Trigger } from "@botpress/runtime";

export default new Trigger({ name: "onNewUser", description: "Start onboarding when user created", events: ["user.created"], // Can listen to multiple events

handler: async ({ event, client, actions }) => { const { userId, email } = event.payload;

// Start an onboarding workflow await OnboardingWorkflow.start({ userId, email }); } });

// Integration events use format: integration:eventName export const LinearTrigger = new Trigger({ name: "onLinearIssue", description: "Handle Linear issue events", events: ["linear:issueCreated", "linear:issueUpdated"],

handler: async ({ event, actions }) => { if (event.type === "linear:issueCreated") { await actions.slack.sendMessage({ channel: "#notifications", text: `New issue: ${event.payload.title}` }); } } }); ```

**常见机器人事件:** - `user.created`, `user.updated`, `user.deleted` - `conversation.started`, `conversation.ended`, `message.created` - `workflow.started`, `workflow.completed`, `workflow.failed` - `bot.started`, `bot.stopped`

**常见集成事件:** - Slack: `slack:reactionAdded`, `slack:memberJoinedChannel` - Linear: `linear:issueCreated`, `linear:issueUpdated` - GitHub: `github:issueOpened`, `github:pullRequestOpened` - Intercom: `intercom:conversationEvent`, `intercom:contactEvent`

**查找集成事件:** 运行 `adk info <integration> --events`

**文档:** https://www.botpress.com/docs/adk/concepts/triggers **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/triggers.md

---

## 发送消息

**关键:该方法取决于你从何处发送:**

| 上下文 | 方法 | 原因 | |---------|--------|-----| | 在对话中 | `conversation.send()` | 具有对话上下文 | | 在工作流/操作中 | `client.createMessage()` | 需要显式 `conversationId` |

**常见错误:** 在对话中使用 `client.createMessage()`。请始终改用 `conversation.send()`。

该方法取决于你从何处发送:

**在对话中** - 使用 `conversation.send()`: ```typescript await conversation.send({ type: "text", payload: { text: "Hello!" } }); await conversation.send({ type: "image", payload: { imageUrl: "https://..." } }); await conversation.send({ type: "choice", payload: { text: "Pick one:", choices: [ { title: "Option A", value: "a" }, { title: "Option B", value: "b" } ] } }); ```

**在工作流或操作中** - 使用带有 `conversationId` 的 `client.createMessage()`: ```typescript await client.createMessage({ conversationId: input.conversationId, // Must have this! type: "text", payload: { text: "Workflow complete!" } }); ```

**所有消息类型:** ```typescript // Text { type: "text", payload: { text: "Hello!" } }

// Markdown { type: "markdown", payload: { text: "# Heading\n**Bold**" } }

// Image { type: "image", payload: { imageUrl: "https://..." } }

// Audio { type: "audio", payload: { audioUrl: "https://..." } }

// Video { type: "video", payload: { videoUrl: "https://..." } }

// File { type: "file", payload: { fileUrl: "https://...", title: "Document.pdf" } }

// Location { type: "location", payload: { latitude: 40.7128, longitude: -74.0060, address: "New York, NY" } }

// Card { type: "card", payload: { title: "Product Name", subtitle: "Description", imageUrl: "https://...", actions: [ { action: "url", label: "View", value: "https://..." }, { action: "postback", label: "Buy", value: "buy_123" } ] }}

// Carousel { type: "carousel", payload: { items: [ { title: "Item 1", subtitle: "...", imageUrl: "...", actions: [...] }, { title: "Item 2", subtitle: "...", imageUrl: "...", actions: [...] } ] }}

// Choice (Quick Replies) { type: "choice", payload: { text: "Select an option:", choices: [ { title: "Option 1", value: "opt1" }, { title: "Option 2", value: "opt2" } ] }}

// Dropdown { type: "dropdown", payload: { text: "Select country:", options: [ { label: "United States", value: "us" }, { label: "Canada", value: "ca" } ] }} ```

**GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/messages.md

---

## Zai - LLM 实用操作

**何时使用 Zai vs execute():** - **使用 `zai`** 进行特定的、结构化的 AI 操作(提取数据、分类、总结) - **使用 `execute()`** 进行具有工具的自主、多轮 AI 对话

**Zai 非常适用于:** - 从用户消息中提取结构化数据 (`zai.extract`) - 对内容进行分类/标记 (`zai.check`, `zai.label`) - 总结长内容 (`zai.summarize`) - 根据文档回答问题 (`zai.answer`) - 智能排序/筛选/分组数据 (`zai.sort`, `zai.filter`, `zai.group`)

**Zai 操作针对速度和成本进行了优化** - 它们使用在 `agent.config.ts` 中配置的 `zai` 模型(通常是更快/更便宜的模型)。

```typescript import { adk, z } from "@botpress/runtime";

// Extract structured data from text const contact = await adk.zai.extract( "Contact John at [email protected], phone 555-0100", z.object({ name: z.string(), email: z.string(), phone: z.string() }) ); // Returns: { name: "John", email: "[email protected]", phone: "555-0100" }

// Check if text matches a condition (returns boolean) const isSpam = await adk.zai.check(messageText, "is spam or promotional");

// Label text with multiple criteria const labels = await adk.zai.label(customerEmail, { spam: "is spam", urgent: "needs immediate response", complaint: "expresses dissatisfaction" }); // Returns: { spam: false, urgent: true, complaint: true }

// Summarize content const summary = await adk.zai.summarize(longDocument, { length: 200, bulletPoints: true });

// Answer questions from documents (with citations) const result = await adk.zai.answer(docs, "What is the refund policy?"); if (result.type === "answer") { console.log(result.answer); console.log(result.citations); } // Response types: "answer", "ambiguous", "out_of_topic", "invalid_question", "missing_knowledge"

// Rate items on 1-5 scale const scores = await adk.zai.rate(products, "quality score");

// Sort by criteria const sorted = await adk.zai.sort(tickets, "by urgency, most urgent first");

// Group items semantically const groups = await adk.zai.group(emails, { instructions: "categorize by topic" });

// Rewrite text const professional = await adk.zai.rewrite("hey wassup", "make it professional and friendly");

// Filter arrays const activeUsers = await adk.zai.filter(users, "have been active this month");

// Generate text const blogPost = await adk.zai.text("Write about AI in healthcare", { length: 1000, temperature: 0.7 });

// Patch code files const patched = await adk.zai.patch(files, "add JSDoc comments to all functions"); ```

**Zai 配置:** ```typescript // Create configured instance const preciseZai = adk.zai.with({ modelId: "best", // "best" | "fast" | custom model ID temperature: 0.1 });

// Enable active learning const learningZai = adk.zai.learn("sentiment-analysis"); ```

**文档:** https://www.botpress.com/docs/adk/zai/overview **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/zai-complete-guide.md

---

## 集成

**何时添加集成:** - 你需要连接到外部服务(Slack、Linear、GitHub 等) - 你想从渠道接收消息(webchat、WhatsApp、Discord) - 你需要使用预构建的操作调用外部 API - 你想对外部系统的事件做出反应

**集成工作流:** 1. **搜索** - 使用 `adk search <name>` 查找集成 2. **添加** - 使用 `adk add <name>@<version>` 安装 3. **配置** - 在 UI `http://localhost:3001/` 中设置凭据 4. **使用** - 通过 `actions.<integration>.<action>()` 调用操作

**使集成操作可供 AI 使用:** ```typescript // Convert any integration action to an AI-callable tool tools: [actions.slack.sendMessage.asTool()] ```

**CLI 命令:** ```bash adk search slack # Find integrations adk add slack@latest # Add to project adk add slack --alias my-slack # Add with custom alias adk info slack --events # See available events adk list # List installed integrations adk upgrade slack # Update to latest adk remove slack # Remove integration ```

**使用集成操作:** ```typescript import { actions } from "@botpress/runtime";

// Slack await actions.slack.sendMessage({ channel: "#general", text: "Hello!" }); await actions.slack.addReaction({ channel: "C123", timestamp: "123", name: "thumbsup" });

// Linear await actions.linear.issueCreate({ teamId: "123", title: "Bug report", description: "Details" }); const { items } = await actions.linear.issueList({ first: 10, filter: { state: { name: { eq: "In Progress" } } } });

// GitHub await actions.github.createIssue({ owner: "org", repo: "repo", title: "Issue" });

// Browser (web scraping) const results = await actions.browser.webSearch({ query: "Botpress docs", maxResults: 5 });

// Make integration actions available to AI as tools await execute({ tools: [actions.slack.sendMessage.asTool()] }); ```

**文档:** https://www.botpress.com/docs/adk/managing-integrations **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/integration-actions.md

---

## 状态管理

**理解状态层级 - 选择正确的级别:**

| 状态级别 | 作用域 | 用于 | |-------------|-------|---------| | `bot.state` | 全局,所有用户 | 功能开关、计数器、维护模式 | | `user.state` | 每个用户,其所有对话 | 用户首选项、个人资料、层级 | | `conversation.state` | 每个对话 | 上下文、消息计数、活动工作流 | | `workflow.state` | 每个工作流实例 | 进度跟踪、中间结果 |

**状态会自动持久化** - 只需修改它,它就会保存。

在机器人的任何位置访问和修改状态:

```typescript import { bot, user, conversation } from "@botpress/runtime";

// Bot state - global, shared across all users bot.state.maintenanceMode = true; bot.state.totalConversations += 1;

// User state - per user, persists across conversations user.state.name = "Alice"; user.state.tier = "pro"; user.state.preferredLanguage = "es";

// In handlers, state is passed as a parameter async handler({ state }) { state.messageCount += 1; // Auto-persisted }

// Tags - simple string key-value pairs for categorization user.tags.source = "website"; user.tags.region = "north-america"; conversation.tags.category = "support"; conversation.tags.priority = "high"; ```

**状态类型:** - **机器人状态** - 全局,在所有用户和对话之间共享 - **用户状态** - 每个用户,在其所有对话中持久化 - **对话状态** - 每个对话,在对话之间隔离 - **工作流状态** - 每个工作流实例,在步骤之间持久化

**标签与状态:** - 使用 **标签** 用于:分类、简单字符串、筛选/查询 - 使用 **状态** 用于:复杂对象、数组、嵌套数据、业务逻辑

**GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/tags.md

---

## 上下文 API

在任何处理程序中访问运行时服务:

```typescript import { context } from "@botpress/runtime";

// Always available const client = context.get("client"); // Botpress API client const citations = context.get("citations"); // Citation manager const cognitive = context.get("cognitive"); // LLM client const logger = context.get("logger"); // Structured logger const botId = context.get("botId"); // Current bot ID const configuration = context.get("configuration"); // Bot config

// Conditionally available (use { optional: true }) const user = context.get("user", { optional: true }); const conversation = context.get("conversation", { optional: true }); const message = context.get("message", { optional: true }); const workflow = context.get("workflow", { optional: true }); const chat = context.get("chat", { optional: true }); // Conversation transcript

if (user) { console.log(`User: ${user.id}`); } ```

**GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/context-api.md

---

## CLI 快速参考

```bash # Project Lifecycle adk init <name> # Create new project adk login # Authenticate with Botpress adk dev # Start dev server (hot reload) adk dev --port 3000 # Custom port adk chat # Test in CLI adk build # Build for production adk deploy # Deploy to Botpress Cloud adk deploy --env production # Deploy to specific environment

# Integration Management adk add <integration> # Add integration adk add [email protected] # Add specific version adk add slack --alias my-slack # Add with alias adk remove <integration> # Remove integration adk search <query> # Search integrations adk list # List installed integrations adk list --available # List all available adk info <name> # Integration details adk info <name> --events # Show available events adk upgrade <name> # Update integration adk upgrade # Interactive upgrade all

# Knowledge & Assets adk kb sync --dev # Sync knowledge bases adk kb sync --prod --force # Force re-sync production adk assets sync # Sync static files

# Advanced adk run <script.ts> # Run TypeScript script adk mcp # Start MCP server adk link --workspace ws_123 --bot bot_456 # Link to existing bot

# Utilities adk self-upgrade # Update CLI adk telemetry --disable # Disable telemetry adk --help # Full CLI help adk <command> --help # Help for specific command ```

**文档:** https://www.botpress.com/docs/adk/cli-reference **GitHub:** https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/cli.md

---

## 使用 `execute()` 进行自主执行

**`execute()` 函数是 ADK AI 功能的核心。** 它运行一个自主 AI 代理,可以: - 从自然语言理解用户意图 - 决定调用哪些工具以及何时调用 - 搜索知识库以获取相关信息 - 生成上下文响应 - 循环执行多个工具调用,直到任务完成

**何时使用 execute():** - 在对话处理程序中生成 AI 响应 - 在需要 AI 决策的工作流中 - 任何你想要自主、多步骤 AI 行为的地方

**需配置的关键参数:** - `instructions` - 告诉 AI 它是谁以及如何表现 - `tools` - 赋予 AI 能力(搜索、创建、更新等) - `knowledge` - 基于 AI 的文档 - `exits` - 为特定结果定义结构化输出架构

`execute()` 函数启用了自主 AI 代理行为:

```typescript import { Autonomous, z } from "@botpress/runtime";

// Define custom tool const searchTool = new Autonomous.Tool({ name: "search", description: "Search documentation", input: z.object({ query: z.string() }), output: z.string(), handler: async ({ query }) => { // Search implementation return "results..."; } });

// Define exit (structured response) const AnswerExit = new Autonomous.Exit({ name: "Answer", description: "Provide final answer to the user", schema: z.object({ answer: z.string(), confidence: z.number(), sources: z.array(z.string()) }) });

// Execute AI with tools, knowledge, and exits const result = await execute({ instructions: "Help the user with their request. Be helpful and concise.",

// Add tools tools: [ searchTool, actions.linear.issueCreate.asTool() ],

// Add knowledge bases knowledge: [DocsKnowledgeBase, FAQKnowledgeBase],

// Define exits for structured outputs exits: [AnswerExit],

// Model configuration model: "openai:gpt-4o", temperature: 0.7, iterations: 10, // Max tool call iterations

// Hooks for monitoring hooks: { onBeforeTool: async ({ tool, input }) => { console.log(`Calling ${tool.name}`, input); return { input: { ...input, enhanced: true } }; // Modify input }, onAfterTool: async ({ tool, output }) => { console.log(`Result:`, output); } } });

// Handle structured exit if (result.is(AnswerExit)) { console.log(result.output.answer); console.log(result.output.sources); } ```

---

## 故障排除

| 错误 | 原因 | 解决方案 | |-------|-------|----------| | 操作中出现 "Cannot destructure property" | 直接在处理程序参数中解构输入 | 使用 `async handler({ input, client })` 然后在内部使用 `const { field } = input` | | 表创建失败 | 表名无效或定义了 `id` | 删除 `id` 列,确保名称以 "Table" 结尾 | | 找不到集成操作 | 集成未安装或配置 | 运行 `adk list`,使用 `adk add` 添加,在 localhost:3001 的 UI 中配置 | | 知识库未更新 | KB 未同步 | 运行 `adk kb sync --dev` 或 `adk kb sync --force` | | 工作流未恢复 | 动态步骤名称 | 使用稳定、唯一的步骤名称(不要使用 `step(\`item-${i}\`)`) | | 类型已过时 | 生成的类型陈旧 | 运行 `adk dev` 或 `adk build` 以重新生成 | | 无法从工作流向用户发送消息 | 缺少 conversationId | 启动工作流时传递 `conversationId`,使用 `client.createMessage()` | | "user is not defined" | 在对话外访问对话上下文 | 使用 `context.get("user", { optional: true })` | | 状态更改未持久化 | 创建新对象而不是修改 | 直接修改状态:`state.user.name = "Alice"` | | AI 未使用工具 | 描述不佳 | 改进工具描述,为输入添加详细的 `.describe()` |

**获取更多帮助:** 运行 `adk --help` 或查看: - **文档:** https://www.botpress.com/docs/adk/ - **GitHub:** https://github.com/botpress/skills/tree/master/skills/adk/references

---

## 常见模式与最佳实践

### 1. 始终为工作流传递 conversationId ```typescript // In conversation - starting a workflow that needs to message back await MyWorkflow.start({ conversationId: conversation.id, // Always include this! data: "..." });

// In workflow - messaging back to user await client.createMessage({ conversationId: input.conversationId, type: "text", payload: { text: "Processing complete!" } }); ```

### 2. 使用环境变量管理密钥 ```typescript // In .env (never commit!) API_KEY=sk-... SLACK_TOKEN=xoxb-...

// In code config: { apiKey: process.env.API_KEY } ```

### 3. 在工作流中保持步骤名称稳定 ```typescript // GOOD - Single step for batch await step("process-all-items", async () => { for (const item of items) { await processItem(item); } });

// BAD - Dynamic names break resume for (let i = 0; i < items.length; i++) { await step(`process-${i}`, async () => { ... }); // Don't do this! } ```

### 4. 操作/工具中的错误处理 ```typescript export default new Action({ handler: async ({ input }) => { try { // Action logic return { success: true }; } catch (error) { console.error("Action failed:", error); throw new Error(`Failed to process: ${error.message}`); } } }); ```

### 5. 使用 ThinkSignal 处理工具边缘情况 ```typescript handler: async ({ query }) => { const results = await search(query);

if (!results.length) { throw new Autonomous.ThinkSignal( "No results", "No results found. Ask the user to try different search terms." ); }

return results; } ```

### 6. 多渠道处理 ```typescript export default new Conversation({ channels: ["slack.channel", "webchat.channel"], handler: async ({ conversation }) => { const channel = conversation.channel;

if (channel === "slack.channel") { // Slack-specific handling (threading, mentions, etc.) } else if (channel === "webchat.channel") { // Webchat-specific handling } } }); ```

---

## 完整参考文档

### 官方 Botpress ADK 文档 **基础 URL:** https://www.botpress.com/docs/adk/

| 主题 | URL | |-------|-----| | 介绍 | https://www.botpress.com/docs/adk/introduction | | 快速入门 | https://www.botpress.com/docs/adk/quickstart | | 项目结构 | https://www.botpress.com/docs/adk/project-structure | | 操作 | https://www.botpress.com/docs/adk/concepts/actions | | 工具 | https://www.botpress.com/docs/adk/concepts/tools | | 对话 | https://www.botpress.com/docs/adk/concepts/conversations | | 工作流概述 | https://www.botpress.com/docs/adk/concepts/workflows/overview | | 工作流步骤 | https://www.botpress.com/docs/adk/concepts/workflows/steps | | 表 | https://www.botpress.com/docs/adk/concepts/tables | | 触发器 | https://www.botpress.com/docs/adk/concepts/triggers | | 知识库 | https://www.botpress.com/docs/adk/concepts/knowledge | | 管理集成 | https://www.botpress.com/docs/adk/managing-integrations | | Zai 概述 | https://www.botpress.com/docs/adk/zai/overview | | Zai 参考 | https://www.botpress.com/docs/adk/zai/reference | | CLI 参考 | https://www.botpress.com/docs/adk/cli-reference |

### GitHub 仓库参考(AI 优化版) **基础 URL:** https://github.com/botpress/skills/tree/master/skills/adk/references

有关本指南之外的详细规范,请获取相应的参考文件:

| 主题 | 参考文件 | |-------|----------------| | 操作 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/actions.md | | 工具 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/tools.md | | 工作流 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/workflows.md | | 对话 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/conversations.md | | 表 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/tables.md | | 触发器 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/triggers.md | | 知识库 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/knowledge-bases.md | | 消息 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/messages.md | | 代理配置 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/agent-config.md | | CLI | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/cli.md | | 集成操作 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/integration-actions.md | | 模型配置 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/model-configuration.md | | 上下文 API | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/context-api.md | | 标签 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/tags.md | | 文件 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/files.md | | Zai 完整指南 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/zai-complete-guide.md | | Zai 代理参考 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/zai-agent-reference.md | | MCP 服务器 | https://raw.githubusercontent.com/botpress/skills/master/skills/adk/references/mcp-server.md |

---

## 常见场景 - 构建内容

**"我想构建一个根据我们的文档回答问题的支持机器人"** 1. 创建一个知识库,并将你的文档作为来源 2. 创建一个使用 `execute()` 和该知识的对话处理程序 3. 添加 `chat` 集成以进行测试

**"我希望机器人在用户报告问题时在 Linear 中创建工单"** 1. 添加 Linear 集成:`adk add linear` 2. 创建一个调用 `actions.linear.issueCreate()` 的工具 3. 将该工具传递给你的对话中的 `execute()`

**"我需要运行每日同步任务"** 1. 创建一个工作流,并设置 `schedule: "0 9 * * *"`(cron 语法) 2. 在步骤中实现同步逻辑 3. 该工作流将在预定时间自动运行

**"我想存储用户首选项"** 1. 在 `agent.config.ts` 中的 `user.state` 下定义架构 2. 通过 `user.state.preferenceField = value` 访问/修改 3. 状态会自动持久化

**"我需要在新用户注册时做出反应"** 1. 创建一个监听 `user.created` 事件的触发器 2. 在处理程序中,启动一个入职工作流或发送欢迎消息

**"我想存储订单数据并对其进行搜索"** 1. 使用你的架构创建一个表(记住:没有 `id` 字段,名称以 "Table" 结尾) 2. 在要搜索的文本列上使用 `searchable: true` 3. 使用 CRUD 方法:`createRows`、`findRows`、`updateRows`、`deleteRows`

---

## 总结

本技能提供了使用 ADK 构建 Botpress 机器人的全面指导:

- **设置与初始化** - ADK 安装和项目创建 - **项目结构** - 约定、文件和组织 - **核心概念** - 动作、工具、工作流、对话、表格、知识、触发器 - **状态管理** - 机器人、用户、对话和工作流状态 - **集成管理** - 添加和配置集成 - **Zai (AI Operations)** - 提取、检查、标签、摘要、回答、排序、分组、重写、过滤 - **CLI 参考** - 完整命令指南 - **测试与部署** - 本地测试和云端部署 - **常见模式** - 最佳实践和故障排除

**核心原则:** ADK 是一个基于约定的框架,文件位置决定行为。将组件放在正确的 `src/` 子目录中,它们就会自动成为机器人的功能。

**何时使用此技能:** - 用户想要创建一个新的 Botpress 机器人 - 用户询问如何添加动作、工具、工作流、对话、表格、知识库或触发器 - 用户需要集成方面的帮助(Slack、Linear、GitHub 等) - 用户想要了解 ADK 模式和最佳实践 - 用户遇到错误或需要故障排除 - 用户询问 CLI 命令、配置或部署

**官方文档:** https://www.botpress.com/docs/adk/ **GitHub 仓库:** https://github.com/botpress/adk **技能仓库:** https://github.com/botpress/skills

更多产品