@botpress/adk 1.19.0-beta.7 → 2.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-init/agent-project-generator.d.ts +5 -1
- package/dist/agent-init/agent-project-generator.d.ts.map +1 -1
- package/dist/agent-project/agent-project.d.ts +3 -3
- package/dist/agent-project/agent-project.d.ts.map +1 -1
- package/dist/agent-project/agent-resolver.d.ts.map +1 -1
- package/dist/agent-project/config-writer.d.ts +1 -1
- package/dist/agent-project/config-writer.d.ts.map +1 -1
- package/dist/agent-project/dependencies-parser.d.ts.map +1 -1
- package/dist/agent-project/dependency-state-to-dependencies.d.ts +11 -0
- package/dist/agent-project/dependency-state-to-dependencies.d.ts.map +1 -0
- package/dist/agent-project/file-watcher.d.ts.map +1 -1
- package/dist/agent-project/types.d.ts +9 -4
- package/dist/agent-project/types.d.ts.map +1 -1
- package/dist/agent0/capabilities/commands/adk-build.md +6 -5
- package/dist/agent0/capabilities/commands/adk-debug.md +1 -1
- package/dist/agent0/capabilities/commands/adk-dev-console.md +1 -1
- package/dist/agent0/capabilities/commands/adk-document.md +10 -2
- package/dist/agent0/capabilities/commands/adk-eval.md +1 -1
- package/dist/agent0/capabilities/commands/adk-explain.md +2 -2
- package/dist/agent0/capabilities/commands/adk-init.md +2 -2
- package/dist/agent0/capabilities/commands/adk-ship.md +1 -1
- package/dist/agent0/capabilities/commands/adk-test.md +3 -3
- package/dist/agent0/capabilities/commands/adk-validate.md +3 -3
- package/dist/agent0/capabilities/skills/adk/SKILL.md +21 -21
- package/dist/agent0/capabilities/skills/adk/references/actions.md +245 -239
- package/dist/agent0/capabilities/skills/adk/references/advanced-patterns.md +185 -218
- package/dist/agent0/capabilities/skills/adk/references/agent-config.md +74 -71
- package/dist/agent0/capabilities/skills/adk/references/assets.md +45 -48
- package/dist/agent0/capabilities/skills/adk/references/autonomous-execution.md +40 -46
- package/dist/agent0/capabilities/skills/adk/references/cli.md +17 -7
- package/dist/agent0/capabilities/skills/adk/references/context-api.md +98 -94
- package/dist/agent0/capabilities/skills/adk/references/conversation-lifecycle.md +65 -62
- package/dist/agent0/capabilities/skills/adk/references/conversations.md +395 -385
- package/dist/agent0/capabilities/skills/adk/references/custom-components.md +1 -1
- package/dist/agent0/capabilities/skills/adk/references/desk.md +236 -234
- package/dist/agent0/capabilities/skills/adk/references/explain-config.md +54 -37
- package/dist/agent0/capabilities/skills/adk/references/files.md +301 -306
- package/dist/agent0/capabilities/skills/adk/references/integration-actions.md +211 -214
- package/dist/agent0/capabilities/skills/adk/references/integrations.md +33 -31
- package/dist/agent0/capabilities/skills/adk/references/interfaces.md +13 -12
- package/dist/agent0/capabilities/skills/adk/references/knowledge-bases.md +98 -111
- package/dist/agent0/capabilities/skills/adk/references/mcp-server.md +6 -0
- package/dist/agent0/capabilities/skills/adk/references/messages.md +280 -256
- package/dist/agent0/capabilities/skills/adk/references/model-configuration.md +52 -49
- package/dist/agent0/capabilities/skills/adk/references/patterns-mistakes.md +102 -101
- package/dist/agent0/capabilities/skills/adk/references/plugins.md +15 -15
- package/dist/agent0/capabilities/skills/adk/references/tables.md +204 -210
- package/dist/agent0/capabilities/skills/adk/references/tags.md +141 -143
- package/dist/agent0/capabilities/skills/adk/references/tools.md +191 -199
- package/dist/agent0/capabilities/skills/adk/references/triggers.md +331 -336
- package/dist/agent0/capabilities/skills/adk/references/workflow-steps.md +132 -96
- package/dist/agent0/capabilities/skills/adk/references/workflows.md +479 -464
- package/dist/agent0/capabilities/skills/adk/references/zai-agent-reference.md +127 -129
- package/dist/agent0/capabilities/skills/adk/references/zai-complete-guide.md +255 -276
- package/dist/agent0/capabilities/skills/adk-debugger/SKILL.md +21 -17
- package/dist/agent0/capabilities/skills/adk-debugger/references/common-failures.md +25 -25
- package/dist/agent0/capabilities/skills/adk-debugger/references/conversation-analysis.md +49 -41
- package/dist/agent0/capabilities/skills/adk-debugger/references/debug-workflow.md +20 -14
- package/dist/agent0/capabilities/skills/adk-debugger/references/llm-debugging.md +13 -13
- package/dist/agent0/capabilities/skills/adk-debugger/references/trace-summarization.md +18 -18
- package/dist/agent0/capabilities/skills/adk-debugger/references/traces-and-logs.md +67 -67
- package/dist/agent0/capabilities/skills/adk-dev-console/SKILL.md +36 -36
- package/dist/agent0/capabilities/skills/adk-dev-console/references/agent-steps.md +14 -6
- package/dist/agent0/capabilities/skills/adk-dev-console/references/multi-agent-dashboard.md +13 -13
- package/dist/agent0/capabilities/skills/adk-dev-console/references/pages.md +18 -0
- package/dist/agent0/capabilities/skills/adk-docs/SKILL.md +13 -13
- package/dist/agent0/capabilities/skills/adk-docs/references/doc-standards.md +15 -0
- package/dist/agent0/capabilities/skills/adk-evals/SKILL.md +29 -23
- package/dist/agent0/capabilities/skills/adk-evals/references/eval-format.md +31 -23
- package/dist/agent0/capabilities/skills/adk-evals/references/test-patterns.md +25 -36
- package/dist/agent0/capabilities/skills/adk-evals/references/testing-workflow.md +6 -4
- package/dist/agent0/config/schema.d.ts.map +1 -1
- package/dist/agent0/config/store.d.ts +8 -3
- package/dist/agent0/config/store.d.ts.map +1 -1
- package/dist/agent0/index.js +214 -59
- package/dist/agent0/index.js.map +17 -15
- package/dist/agent0/providers/catalog.d.ts.map +1 -1
- package/dist/agent0/providers/registry.d.ts.map +1 -1
- package/dist/agent0/providers/source.d.ts +8 -3
- package/dist/agent0/providers/source.d.ts.map +1 -1
- package/dist/agent0/runtime/client.d.ts +4 -3
- package/dist/agent0/runtime/client.d.ts.map +1 -1
- package/dist/agent0/runtime/engine.d.ts +7 -1
- package/dist/agent0/runtime/engine.d.ts.map +1 -1
- package/dist/agent0/runtime/manager.d.ts +2 -3
- package/dist/agent0/runtime/manager.d.ts.map +1 -1
- package/dist/agent0/runtime/process.d.ts +10 -0
- package/dist/agent0/runtime/process.d.ts.map +1 -1
- package/dist/assets/manager.d.ts +3 -0
- package/dist/assets/manager.d.ts.map +1 -1
- package/dist/auth/credentials.d.ts +1 -1
- package/dist/auth/credentials.d.ts.map +1 -1
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/service.d.ts.map +1 -1
- package/dist/bot-generator/generator.d.ts +22 -0
- package/dist/bot-generator/generator.d.ts.map +1 -1
- package/dist/bot-generator/integration-sync.d.ts +2 -0
- package/dist/bot-generator/integration-sync.d.ts.map +1 -1
- package/dist/bot-generator/interface-sync.d.ts +2 -0
- package/dist/bot-generator/interface-sync.d.ts.map +1 -1
- package/dist/bot-generator/plugin-sync.d.ts +2 -0
- package/dist/bot-generator/plugin-sync.d.ts.map +1 -1
- package/dist/cognitive/models.d.ts.map +1 -1
- package/dist/commands/base-command.d.ts +1 -0
- package/dist/commands/base-command.d.ts.map +1 -1
- package/dist/commands/bp-cli.d.ts.map +1 -1
- package/dist/commands/bp-cli.js +147 -0
- package/dist/commands/bp-cli.js.map +12 -0
- package/dist/commands/bp-dev-command.d.ts +3 -1
- package/dist/commands/bp-dev-command.d.ts.map +1 -1
- package/dist/commands/bp-dev-stderr.d.ts +9 -0
- package/dist/commands/bp-dev-stderr.d.ts.map +1 -1
- package/dist/commands/bp-dev-worker-env.d.ts +7 -0
- package/dist/commands/bp-dev-worker-env.d.ts.map +1 -0
- package/dist/commands/index.d.ts +1 -0
- package/dist/commands/index.d.ts.map +1 -1
- package/dist/config/manager.d.ts.map +1 -1
- package/dist/dependencies/catalog/catalog-service.d.ts +53 -0
- package/dist/dependencies/catalog/catalog-service.d.ts.map +1 -0
- package/dist/dependencies/catalog/client-factory.d.ts +33 -0
- package/dist/dependencies/catalog/client-factory.d.ts.map +1 -0
- package/dist/dependencies/catalog/integration-source.d.ts +34 -0
- package/dist/dependencies/catalog/integration-source.d.ts.map +1 -0
- package/dist/dependencies/catalog/interface-source.d.ts +23 -0
- package/dist/dependencies/catalog/interface-source.d.ts.map +1 -0
- package/dist/dependencies/catalog/plugin-source.d.ts +49 -0
- package/dist/dependencies/catalog/plugin-source.d.ts.map +1 -0
- package/dist/dependencies/catalog/resolution-cache.d.ts +76 -0
- package/dist/dependencies/catalog/resolution-cache.d.ts.map +1 -0
- package/dist/dependencies/dependency-manager.d.ts +31 -16
- package/dist/dependencies/dependency-manager.d.ts.map +1 -1
- package/dist/dependencies/errors.d.ts +9 -6
- package/dist/dependencies/errors.d.ts.map +1 -1
- package/dist/dependencies/index.d.ts +5 -4
- package/dist/dependencies/index.d.ts.map +1 -1
- package/dist/dependencies/index.js +2309 -1697
- package/dist/dependencies/index.js.map +41 -32
- package/dist/dependencies/legacy-lock-file.d.ts +15 -0
- package/dist/dependencies/legacy-lock-file.d.ts.map +1 -0
- package/dist/dependencies/migration.d.ts +19 -0
- package/dist/dependencies/migration.d.ts.map +1 -1
- package/dist/dependencies/resolvers/integration-resolver.d.ts +4 -3
- package/dist/dependencies/resolvers/integration-resolver.d.ts.map +1 -1
- package/dist/dependencies/resolvers/plugin-resolver.d.ts +4 -4
- package/dist/dependencies/resolvers/plugin-resolver.d.ts.map +1 -1
- package/dist/dependencies/snapshot-store.d.ts +59 -0
- package/dist/dependencies/snapshot-store.d.ts.map +1 -0
- package/dist/dependencies/status-resolver.d.ts +36 -0
- package/dist/dependencies/status-resolver.d.ts.map +1 -0
- package/dist/dependencies/status.d.ts +214 -0
- package/dist/dependencies/status.d.ts.map +1 -0
- package/dist/dependencies/types.d.ts +388 -37
- package/dist/dependencies/types.d.ts.map +1 -1
- package/dist/file-watcher/watcher.d.ts +21 -5
- package/dist/file-watcher/watcher.d.ts.map +1 -1
- package/dist/generators/action-types.d.ts.map +1 -1
- package/dist/generators/client-wrapper.d.ts.map +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3643 -2345
- package/dist/index.js.map +68 -58
- package/dist/integrations/config-utils.d.ts +11 -7
- package/dist/integrations/config-utils.d.ts.map +1 -1
- package/dist/integrations/hub-cache.d.ts +0 -58
- package/dist/integrations/hub-cache.d.ts.map +1 -1
- package/dist/integrations/index.d.ts +1 -3
- package/dist/integrations/index.d.ts.map +1 -1
- package/dist/integrations/manager.d.ts +19 -53
- package/dist/integrations/manager.d.ts.map +1 -1
- package/dist/interfaces/enhanced-cache.d.ts +7 -7
- package/dist/interfaces/enhanced-cache.d.ts.map +1 -1
- package/dist/interfaces/manager.d.ts +11 -17
- package/dist/interfaces/manager.d.ts.map +1 -1
- package/dist/interfaces/parser.d.ts.map +1 -1
- package/dist/knowledge/manager.d.ts +3 -0
- package/dist/knowledge/manager.d.ts.map +1 -1
- package/dist/plugins/index.d.ts +0 -1
- package/dist/plugins/index.d.ts.map +1 -1
- package/dist/plugins/manager.d.ts +16 -48
- package/dist/plugins/manager.d.ts.map +1 -1
- package/dist/preflight/checker.d.ts +6 -1
- package/dist/preflight/checker.d.ts.map +1 -1
- package/dist/preflight/dependency-gate.d.ts +37 -0
- package/dist/preflight/dependency-gate.d.ts.map +1 -0
- package/dist/preflight/index.d.ts +2 -1
- package/dist/preflight/index.d.ts.map +1 -1
- package/dist/preflight/types.d.ts +18 -0
- package/dist/preflight/types.d.ts.map +1 -1
- package/dist/runner/script-runner.d.ts.map +1 -1
- package/dist/secrets/manager.d.ts.map +1 -1
- package/dist/tables/table-manager.d.ts +3 -0
- package/dist/tables/table-manager.d.ts.map +1 -1
- package/dist/templates/README.md +23 -13
- package/dist/templates/blank/agent.config.ts +3 -3
- package/dist/templates/blank/src/triggers/index.ts +1 -1
- package/dist/templates/botpress-desk/evals/index.eval.ts +1 -1
- package/dist/templates/botpress-desk/src/triggers/index.ts +1 -1
- package/dist/templates/crm-enrichment/README.md +3 -3
- package/dist/templates/crm-enrichment/agent.config.ts +2 -2
- package/dist/templates/crm-enrichment/src/conversations/index.ts +1 -1
- package/dist/templates/hello-world/agent.config.ts +3 -3
- package/dist/templates/hello-world/src/triggers/index.ts +1 -1
- package/dist/templates/knowledge-assistant/src/triggers/index.ts +1 -1
- package/dist/templates/template.config.json +3 -3
- package/dist/test-utils/mock-module.d.ts +29 -0
- package/dist/test-utils/mock-module.d.ts.map +1 -0
- package/dist/utils/ids.d.ts +10 -0
- package/dist/utils/ids.d.ts.map +1 -1
- package/dist/utils/require-chat.d.ts.map +1 -1
- package/dist/utils/source-map-optimizer.d.ts +10 -11
- package/dist/utils/source-map-optimizer.d.ts.map +1 -1
- package/dist/workspace/workspace-cache.d.ts +2 -1
- package/dist/workspace/workspace-cache.d.ts.map +1 -1
- package/package.json +8 -4
- package/dist/agent-project/lock-to-dependencies.d.ts +0 -11
- package/dist/agent-project/lock-to-dependencies.d.ts.map +0 -1
- package/dist/dependencies/lock-file.d.ts +0 -15
- package/dist/dependencies/lock-file.d.ts.map +0 -1
- package/dist/integrations/enhanced-cache.d.ts +0 -53
- package/dist/integrations/enhanced-cache.d.ts.map +0 -1
- package/dist/plugins/enhanced-cache.d.ts +0 -53
- package/dist/plugins/enhanced-cache.d.ts.map +0 -1
- package/dist/templates/blank/package.json +0 -17
- package/dist/templates/blank/tsconfig.json +0 -25
- package/dist/templates/botpress-desk/package.json +0 -17
- package/dist/templates/crm-enrichment/package.json +0 -18
- package/dist/templates/crm-enrichment/tsconfig.json +0 -25
- package/dist/templates/hello-world/package.json +0 -18
- package/dist/templates/hello-world/tsconfig.json +0 -25
- package/dist/templates/knowledge-assistant/package.json +0 -18
- package/dist/templates/knowledge-assistant/tsconfig.json +0 -25
- package/dist/templates/slack-triage/package.json +0 -18
- package/dist/templates/slack-triage/tsconfig.json +0 -25
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
Workflows are multi-step, resumable processes that maintain state across executions. They're perfect for complex operations, scheduled tasks, and long-running processes that may need to pause for user input or external events.
|
|
4
4
|
|
|
5
5
|
## Table of Contents
|
|
6
|
+
|
|
6
7
|
- [Basic Concepts](#basic-concepts)
|
|
7
8
|
- [Creating Workflows](#creating-workflows)
|
|
8
9
|
- [Managing Instances](#managing-instances)
|
|
@@ -17,12 +18,14 @@ Workflows are multi-step, resumable processes that maintain state across executi
|
|
|
17
18
|
## Basic Concepts
|
|
18
19
|
|
|
19
20
|
### What are Workflows?
|
|
21
|
+
|
|
20
22
|
- **Resumable**: Can pause and resume from where they left off
|
|
21
23
|
- **Stateful**: Maintain state across steps and restarts
|
|
22
24
|
- **Scheduled**: Can run on cron schedules
|
|
23
25
|
- **Interactive**: Can request data from conversations
|
|
24
26
|
|
|
25
27
|
### File Location
|
|
28
|
+
|
|
26
29
|
- **Location**: `src/workflows/*.ts`
|
|
27
30
|
- **Auto-registration**: Files automatically become available as workflows
|
|
28
31
|
|
|
@@ -36,55 +39,55 @@ Workflows are multi-step, resumable processes that maintain state across executi
|
|
|
36
39
|
> The handler receives `{ input, state, step, client, execute }` where `state` is a mutable parameter that's automatically tracked and persisted.
|
|
37
40
|
|
|
38
41
|
```typescript
|
|
39
|
-
import { Workflow, z } from
|
|
42
|
+
import { Workflow, z } from '@botpress/runtime'
|
|
40
43
|
|
|
41
44
|
export const MyWorkflow = new Workflow({
|
|
42
|
-
name:
|
|
43
|
-
description:
|
|
45
|
+
name: 'myWorkflow',
|
|
46
|
+
description: 'Description of what this workflow does',
|
|
44
47
|
|
|
45
48
|
// Optional: Set workflow timeout (default: 5 minutes)
|
|
46
|
-
timeout:
|
|
49
|
+
timeout: '6h', // Can be: "30m", "2h", "1d", etc.
|
|
47
50
|
|
|
48
51
|
// Optional: Schedule for automatic execution
|
|
49
|
-
schedule:
|
|
52
|
+
schedule: '0 9 * * *', // Cron format (daily at 9 AM)
|
|
50
53
|
|
|
51
54
|
// Input schema - data required to start the workflow
|
|
52
55
|
input: z.object({
|
|
53
56
|
userId: z.string(),
|
|
54
|
-
data: z.string()
|
|
57
|
+
data: z.string(),
|
|
55
58
|
}),
|
|
56
59
|
|
|
57
60
|
// State schema - mutable data that persists across steps
|
|
58
61
|
state: z.object({
|
|
59
62
|
currentStep: z.number().default(0),
|
|
60
|
-
processedItems: z.array(z.string()).default([])
|
|
63
|
+
processedItems: z.array(z.string()).default([]),
|
|
61
64
|
}),
|
|
62
65
|
|
|
63
66
|
// Output schema - what the workflow returns when complete
|
|
64
67
|
output: z.object({
|
|
65
68
|
result: z.boolean(),
|
|
66
|
-
itemsProcessed: z.number()
|
|
69
|
+
itemsProcessed: z.number(),
|
|
67
70
|
}),
|
|
68
71
|
|
|
69
72
|
// Handler receives state as a parameter
|
|
70
73
|
async handler({ input, state, step, client, execute }) {
|
|
71
74
|
// Access and modify state directly (it's automatically tracked)
|
|
72
|
-
state.currentStep = 1
|
|
75
|
+
state.currentStep = 1
|
|
73
76
|
|
|
74
77
|
// Execute steps
|
|
75
|
-
const data = await step(
|
|
76
|
-
return await fetchSomething(input.userId)
|
|
77
|
-
})
|
|
78
|
+
const data = await step('fetch-data', async () => {
|
|
79
|
+
return await fetchSomething(input.userId)
|
|
80
|
+
})
|
|
78
81
|
|
|
79
|
-
state.processedItems.push(data)
|
|
82
|
+
state.processedItems.push(data)
|
|
80
83
|
|
|
81
84
|
// Return output
|
|
82
85
|
return {
|
|
83
86
|
result: true,
|
|
84
|
-
itemsProcessed: state.processedItems.length
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
})
|
|
87
|
+
itemsProcessed: state.processedItems.length,
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
})
|
|
88
91
|
```
|
|
89
92
|
|
|
90
93
|
### Handler Parameters
|
|
@@ -107,20 +110,20 @@ The `execute` function enables AI operations within workflows:
|
|
|
107
110
|
|
|
108
111
|
```typescript
|
|
109
112
|
export const AnalyzeWorkflow = new Workflow({
|
|
110
|
-
name:
|
|
113
|
+
name: 'analyze',
|
|
111
114
|
async handler({ input, step, execute }) {
|
|
112
|
-
const result = await step(
|
|
115
|
+
const result = await step('ai-analysis', async () => {
|
|
113
116
|
return await execute({
|
|
114
|
-
instructions:
|
|
115
|
-
model:
|
|
117
|
+
instructions: 'Analyze the provided data',
|
|
118
|
+
model: 'openai:gpt-4o',
|
|
116
119
|
temperature: 0,
|
|
117
|
-
input: { data: input.data }
|
|
118
|
-
})
|
|
119
|
-
})
|
|
120
|
+
input: { data: input.data },
|
|
121
|
+
})
|
|
122
|
+
})
|
|
120
123
|
|
|
121
|
-
return { analysis: result }
|
|
122
|
-
}
|
|
123
|
-
})
|
|
124
|
+
return { analysis: result }
|
|
125
|
+
},
|
|
126
|
+
})
|
|
124
127
|
```
|
|
125
128
|
|
|
126
129
|
## Managing Instances
|
|
@@ -131,25 +134,26 @@ export const AnalyzeWorkflow = new Workflow({
|
|
|
131
134
|
// 1. Start a new workflow (always creates new instance)
|
|
132
135
|
const instance = await MyWorkflow.start({
|
|
133
136
|
userId: user.id,
|
|
134
|
-
data:
|
|
135
|
-
})
|
|
136
|
-
console.log(instance.id)
|
|
137
|
+
data: 'some data',
|
|
138
|
+
})
|
|
139
|
+
console.log(instance.id) // "wflw_abc123"
|
|
137
140
|
|
|
138
141
|
// 2. Get or create (idempotent - uses key for deduplication)
|
|
139
142
|
const instance = await MyWorkflow.getOrCreate({
|
|
140
143
|
key: user.id, // Unique key prevents duplicates
|
|
141
|
-
input: { userId: user.id, data:
|
|
142
|
-
})
|
|
144
|
+
input: { userId: user.id, data: 'x' },
|
|
145
|
+
})
|
|
143
146
|
|
|
144
147
|
// 3. Check status via getOrCreate (no standalone get/list methods)
|
|
145
148
|
const instance = await MyWorkflow.getOrCreate({
|
|
146
149
|
key: user.id,
|
|
147
|
-
input: { userId: user.id, data:
|
|
148
|
-
})
|
|
149
|
-
console.log(instance.status)
|
|
150
|
+
input: { userId: user.id, data: 'x' },
|
|
151
|
+
})
|
|
152
|
+
console.log(instance.status) // "in_progress" | "completed" | "failed"
|
|
150
153
|
```
|
|
151
154
|
|
|
152
155
|
### Important Notes
|
|
156
|
+
|
|
153
157
|
- There is NO `create()`, `get()`, or `list()` method - use `start()` or `getOrCreate()`
|
|
154
158
|
- `start()`: Always creates a new instance
|
|
155
159
|
- `getOrCreate()`: Creates only if no instance exists with the given key
|
|
@@ -157,14 +161,19 @@ console.log(instance.status); // "in_progress" | "completed" | "failed"
|
|
|
157
161
|
### Instance Properties
|
|
158
162
|
|
|
159
163
|
```typescript
|
|
160
|
-
const instance = await MyWorkflow.getOrCreate({
|
|
164
|
+
const instance = await MyWorkflow.getOrCreate({
|
|
165
|
+
key: userId,
|
|
166
|
+
input: {
|
|
167
|
+
/* ... */
|
|
168
|
+
},
|
|
169
|
+
})
|
|
161
170
|
|
|
162
171
|
// Available properties
|
|
163
|
-
console.log(instance.id)
|
|
164
|
-
console.log(instance.status)
|
|
165
|
-
console.log(instance.input)
|
|
166
|
-
console.log(instance.state)
|
|
167
|
-
console.log(instance.output)
|
|
172
|
+
console.log(instance.id) // "wflw_abc123"
|
|
173
|
+
console.log(instance.status) // "in_progress" | "completed" | "failed" | "cancelled"
|
|
174
|
+
console.log(instance.input) // Input data
|
|
175
|
+
console.log(instance.state) // Current state
|
|
176
|
+
console.log(instance.output) // Output (undefined if not complete)
|
|
168
177
|
```
|
|
169
178
|
|
|
170
179
|
### Workflow Control Methods
|
|
@@ -174,11 +183,16 @@ console.log(instance.output); // Output (undefined if not complete)
|
|
|
174
183
|
Cancel a running workflow from outside:
|
|
175
184
|
|
|
176
185
|
```typescript
|
|
177
|
-
const instance = await MyWorkflow.getOrCreate({
|
|
186
|
+
const instance = await MyWorkflow.getOrCreate({
|
|
187
|
+
key: userId,
|
|
188
|
+
input: {
|
|
189
|
+
/* ... */
|
|
190
|
+
},
|
|
191
|
+
})
|
|
178
192
|
|
|
179
|
-
if (instance && instance.status ===
|
|
180
|
-
await instance.cancel()
|
|
181
|
-
console.log(instance.status)
|
|
193
|
+
if (instance && instance.status === 'in_progress') {
|
|
194
|
+
await instance.cancel()
|
|
195
|
+
console.log(instance.status) // "cancelled"
|
|
182
196
|
}
|
|
183
197
|
```
|
|
184
198
|
|
|
@@ -190,30 +204,30 @@ Complete a workflow immediately with output (from within the handler):
|
|
|
190
204
|
|
|
191
205
|
```typescript
|
|
192
206
|
export const MyWorkflow = new Workflow({
|
|
193
|
-
name:
|
|
207
|
+
name: 'myWorkflow',
|
|
194
208
|
output: z.object({
|
|
195
209
|
result: z.string(),
|
|
196
|
-
skipped: z.boolean()
|
|
210
|
+
skipped: z.boolean(),
|
|
197
211
|
}),
|
|
198
212
|
|
|
199
213
|
async handler({ input, workflow, step }) {
|
|
200
214
|
// Check condition and complete early
|
|
201
215
|
if (input.skipProcessing) {
|
|
202
216
|
workflow.complete({
|
|
203
|
-
result:
|
|
204
|
-
skipped: true
|
|
205
|
-
})
|
|
217
|
+
result: 'Skipped',
|
|
218
|
+
skipped: true,
|
|
219
|
+
})
|
|
206
220
|
// Code after complete() is never reached
|
|
207
221
|
}
|
|
208
222
|
|
|
209
223
|
// Normal processing continues if not completed early
|
|
210
|
-
const data = await step(
|
|
211
|
-
return await processData(input)
|
|
212
|
-
})
|
|
224
|
+
const data = await step('process', async () => {
|
|
225
|
+
return await processData(input)
|
|
226
|
+
})
|
|
213
227
|
|
|
214
|
-
return { result: data, skipped: false }
|
|
215
|
-
}
|
|
216
|
-
})
|
|
228
|
+
return { result: data, skipped: false }
|
|
229
|
+
},
|
|
230
|
+
})
|
|
217
231
|
```
|
|
218
232
|
|
|
219
233
|
**Note:** `workflow.complete()` can only be called from within the workflow handler. It immediately interrupts execution.
|
|
@@ -224,28 +238,28 @@ Fail a workflow with an error reason (from within the handler):
|
|
|
224
238
|
|
|
225
239
|
```typescript
|
|
226
240
|
export const MyWorkflow = new Workflow({
|
|
227
|
-
name:
|
|
241
|
+
name: 'myWorkflow',
|
|
228
242
|
|
|
229
243
|
async handler({ input, workflow, step }) {
|
|
230
244
|
// Validate input
|
|
231
245
|
if (!input.data || input.data.length === 0) {
|
|
232
|
-
workflow.fail(
|
|
246
|
+
workflow.fail('Invalid input: data cannot be empty')
|
|
233
247
|
// Code after fail() is never reached
|
|
234
248
|
}
|
|
235
249
|
|
|
236
250
|
// Check external conditions
|
|
237
|
-
const isAvailable = await step(
|
|
238
|
-
return await checkServiceAvailability()
|
|
239
|
-
})
|
|
251
|
+
const isAvailable = await step('check-service', async () => {
|
|
252
|
+
return await checkServiceAvailability()
|
|
253
|
+
})
|
|
240
254
|
|
|
241
255
|
if (!isAvailable) {
|
|
242
|
-
workflow.fail(
|
|
256
|
+
workflow.fail('External service unavailable')
|
|
243
257
|
}
|
|
244
258
|
|
|
245
259
|
// Continue normal processing
|
|
246
|
-
return { success: true }
|
|
247
|
-
}
|
|
248
|
-
})
|
|
260
|
+
return { success: true }
|
|
261
|
+
},
|
|
262
|
+
})
|
|
249
263
|
```
|
|
250
264
|
|
|
251
265
|
**Note:** `workflow.fail()` can only be called from within the workflow handler. It immediately interrupts execution and marks the workflow as failed.
|
|
@@ -256,41 +270,41 @@ Extend or set a new timeout for long-running workflows:
|
|
|
256
270
|
|
|
257
271
|
```typescript
|
|
258
272
|
export const LongRunningWorkflow = new Workflow({
|
|
259
|
-
name:
|
|
260
|
-
timeout:
|
|
273
|
+
name: 'longRunning',
|
|
274
|
+
timeout: '1h', // Initial timeout
|
|
261
275
|
|
|
262
276
|
async handler({ input, workflow, step }) {
|
|
263
277
|
// Extend timeout before a long operation
|
|
264
|
-
workflow.setTimeout({ in:
|
|
278
|
+
workflow.setTimeout({ in: '6h' }) // Relative: 6 hours from now
|
|
265
279
|
|
|
266
280
|
// Or set an absolute deadline
|
|
267
|
-
workflow.setTimeout({ at:
|
|
281
|
+
workflow.setTimeout({ at: '2025-12-31T23:59:59Z' })
|
|
268
282
|
|
|
269
283
|
// Long-running operation
|
|
270
284
|
for (const batch of batches) {
|
|
271
285
|
await step(`process-batch-${batch.id}`, async () => {
|
|
272
286
|
// Extend timeout for each batch if needed
|
|
273
|
-
workflow.setTimeout({ in:
|
|
274
|
-
return await processBatch(batch)
|
|
275
|
-
})
|
|
287
|
+
workflow.setTimeout({ in: '30m' })
|
|
288
|
+
return await processBatch(batch)
|
|
289
|
+
})
|
|
276
290
|
}
|
|
277
291
|
|
|
278
|
-
return { completed: true }
|
|
279
|
-
}
|
|
280
|
-
})
|
|
292
|
+
return { completed: true }
|
|
293
|
+
},
|
|
294
|
+
})
|
|
281
295
|
```
|
|
282
296
|
|
|
283
297
|
**Duration formats:** `"30m"`, `"1h"`, `"6 hours"`, `"1d"`, etc.
|
|
284
298
|
|
|
285
299
|
#### Control Methods Summary
|
|
286
300
|
|
|
287
|
-
| Method
|
|
288
|
-
|
|
289
|
-
| `instance.cancel()`
|
|
290
|
-
| `workflow.complete(output)`
|
|
291
|
-
| `workflow.fail(reason)`
|
|
292
|
-
| `workflow.setTimeout({ in })` | Inside handler
|
|
293
|
-
| `workflow.setTimeout({ at })` | Inside handler
|
|
301
|
+
| Method | Location | Purpose |
|
|
302
|
+
| ----------------------------- | --------------- | ---------------------------- |
|
|
303
|
+
| `instance.cancel()` | Outside handler | Cancel a workflow externally |
|
|
304
|
+
| `workflow.complete(output)` | Inside handler | Complete early with output |
|
|
305
|
+
| `workflow.fail(reason)` | Inside handler | Fail with error message |
|
|
306
|
+
| `workflow.setTimeout({ in })` | Inside handler | Extend timeout (relative) |
|
|
307
|
+
| `workflow.setTimeout({ at })` | Inside handler | Set absolute deadline |
|
|
294
308
|
|
|
295
309
|
## State, Input, and Output
|
|
296
310
|
|
|
@@ -298,48 +312,48 @@ export const LongRunningWorkflow = new Workflow({
|
|
|
298
312
|
|
|
299
313
|
```typescript
|
|
300
314
|
export const DataWorkflow = new Workflow({
|
|
301
|
-
name:
|
|
315
|
+
name: 'dataWorkflow',
|
|
302
316
|
|
|
303
317
|
// INPUT: Read-only data passed at creation
|
|
304
318
|
input: z.object({
|
|
305
319
|
userId: z.string(),
|
|
306
|
-
config: z.object({ mode: z.string() })
|
|
320
|
+
config: z.object({ mode: z.string() }),
|
|
307
321
|
}),
|
|
308
322
|
|
|
309
323
|
// STATE: Mutable data persisted across steps
|
|
310
324
|
state: z.object({
|
|
311
325
|
currentStep: z.number().default(0),
|
|
312
326
|
items: z.array(z.string()).default([]),
|
|
313
|
-
error: z.string().optional()
|
|
327
|
+
error: z.string().optional(),
|
|
314
328
|
}),
|
|
315
329
|
|
|
316
330
|
// OUTPUT: Final result returned on completion
|
|
317
331
|
output: z.object({
|
|
318
332
|
success: z.boolean(),
|
|
319
|
-
totalProcessed: z.number()
|
|
333
|
+
totalProcessed: z.number(),
|
|
320
334
|
}),
|
|
321
335
|
|
|
322
336
|
async handler({ input, state, step }) {
|
|
323
337
|
// INPUT is read-only
|
|
324
|
-
console.log(input.userId)
|
|
338
|
+
console.log(input.userId) // ✅ Read
|
|
325
339
|
// input.userId = "new"; // ❌ TypeScript error
|
|
326
340
|
|
|
327
341
|
// STATE is mutable via the state parameter
|
|
328
|
-
state.currentStep = 1
|
|
329
|
-
state.items.push(
|
|
342
|
+
state.currentStep = 1 // ✅ Automatically persisted
|
|
343
|
+
state.items.push('item1')
|
|
330
344
|
|
|
331
345
|
// Steps automatically persist state
|
|
332
|
-
await step(
|
|
333
|
-
state.currentStep = 2
|
|
334
|
-
})
|
|
346
|
+
await step('process', async () => {
|
|
347
|
+
state.currentStep = 2 // Saved even if workflow crashes
|
|
348
|
+
})
|
|
335
349
|
|
|
336
350
|
// OUTPUT is returned at the end
|
|
337
351
|
return {
|
|
338
352
|
success: true,
|
|
339
|
-
totalProcessed: state.items.length
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
})
|
|
353
|
+
totalProcessed: state.items.length,
|
|
354
|
+
}
|
|
355
|
+
},
|
|
356
|
+
})
|
|
343
357
|
```
|
|
344
358
|
|
|
345
359
|
## Step Mechanics
|
|
@@ -406,61 +420,64 @@ async handler({ input, state, step }) {
|
|
|
406
420
|
|
|
407
421
|
```typescript
|
|
408
422
|
// Sleep for specified milliseconds
|
|
409
|
-
await step.sleep(
|
|
423
|
+
await step.sleep('wait-5s', 5000)
|
|
410
424
|
|
|
411
425
|
// Sleep until specific time
|
|
412
|
-
await step.sleepUntil(
|
|
426
|
+
await step.sleepUntil('wait-until', new Date('2025-12-31'))
|
|
413
427
|
|
|
414
428
|
// Update progress message
|
|
415
|
-
await step.progress(
|
|
429
|
+
await step.progress('Processing items...')
|
|
416
430
|
|
|
417
431
|
// Execute child workflow
|
|
418
|
-
const result = await step.executeWorkflow(
|
|
419
|
-
"child",
|
|
420
|
-
ChildWorkflow,
|
|
421
|
-
{ input: data }
|
|
422
|
-
);
|
|
432
|
+
const result = await step.executeWorkflow('child', ChildWorkflow, { input: data })
|
|
423
433
|
|
|
424
434
|
// Wait for workflow completion
|
|
425
|
-
await step.waitForWorkflow(
|
|
435
|
+
await step.waitForWorkflow('wait-child', childWorkflowId)
|
|
426
436
|
|
|
427
437
|
// Request data from conversation (pauses workflow)
|
|
428
|
-
const answer = await step.request(
|
|
429
|
-
"confirmation",
|
|
430
|
-
"Do you want to proceed?"
|
|
431
|
-
);
|
|
438
|
+
const answer = await step.request('confirmation', 'Do you want to proceed?')
|
|
432
439
|
|
|
433
440
|
// Process array in batches
|
|
434
|
-
await step.batch(
|
|
435
|
-
|
|
436
|
-
|
|
441
|
+
await step.batch(
|
|
442
|
+
'batch-urls',
|
|
443
|
+
urls,
|
|
444
|
+
async (batch) => {
|
|
445
|
+
// Process batch
|
|
446
|
+
},
|
|
447
|
+
{ batchSize: 20 }
|
|
448
|
+
)
|
|
437
449
|
|
|
438
450
|
// Map over array with parallel processing and retry logic
|
|
439
451
|
const results = await step.map(
|
|
440
|
-
|
|
452
|
+
'map-items',
|
|
441
453
|
items,
|
|
442
454
|
async (item) => {
|
|
443
|
-
return processItem(item)
|
|
455
|
+
return processItem(item)
|
|
444
456
|
},
|
|
445
457
|
{
|
|
446
|
-
concurrency: 10,
|
|
447
|
-
maxAttempts: 3
|
|
458
|
+
concurrency: 10, // Process 10 items at a time
|
|
459
|
+
maxAttempts: 3, // Retry failed items up to 3 times
|
|
448
460
|
}
|
|
449
|
-
)
|
|
461
|
+
)
|
|
450
462
|
|
|
451
463
|
// ForEach with concurrency
|
|
452
|
-
await step.forEach(
|
|
453
|
-
|
|
454
|
-
|
|
464
|
+
await step.forEach(
|
|
465
|
+
'foreach-items',
|
|
466
|
+
items,
|
|
467
|
+
async (item) => {
|
|
468
|
+
await processItem(item)
|
|
469
|
+
},
|
|
470
|
+
{ concurrency: 5 }
|
|
471
|
+
)
|
|
455
472
|
|
|
456
473
|
// Listen for events (pauses until event)
|
|
457
|
-
await step.listen(
|
|
474
|
+
await step.listen('wait-for-event')
|
|
458
475
|
|
|
459
476
|
// Fail workflow with message
|
|
460
|
-
await step.fail(
|
|
477
|
+
await step.fail('Workflow failed due to X')
|
|
461
478
|
|
|
462
479
|
// Abort workflow (no args, synchronous, does not mark as failed)
|
|
463
|
-
step.abort()
|
|
480
|
+
step.abort()
|
|
464
481
|
```
|
|
465
482
|
|
|
466
483
|
### Step Rules
|
|
@@ -474,15 +491,17 @@ step.abort();
|
|
|
474
491
|
```typescript
|
|
475
492
|
// ❌ BAD: Dynamic step names break resume
|
|
476
493
|
for (let i = 0; i < items.length; i++) {
|
|
477
|
-
await step(`process-${i}`, async () => {
|
|
494
|
+
await step(`process-${i}`, async () => {
|
|
495
|
+
/* ... */
|
|
496
|
+
})
|
|
478
497
|
}
|
|
479
498
|
|
|
480
499
|
// ✅ GOOD: Single step for batch operations
|
|
481
|
-
await step(
|
|
500
|
+
await step('process-all-items', async () => {
|
|
482
501
|
for (const item of items) {
|
|
483
|
-
await processItem(item)
|
|
502
|
+
await processItem(item)
|
|
484
503
|
}
|
|
485
|
-
})
|
|
504
|
+
})
|
|
486
505
|
```
|
|
487
506
|
|
|
488
507
|
## Communication Patterns
|
|
@@ -494,52 +513,46 @@ Workflows can pause and request data from conversations:
|
|
|
494
513
|
```typescript
|
|
495
514
|
// In Workflow
|
|
496
515
|
export const InteractiveWorkflow = new Workflow({
|
|
497
|
-
name:
|
|
516
|
+
name: 'interactive',
|
|
498
517
|
|
|
499
518
|
// Define expected request types
|
|
500
519
|
requests: {
|
|
501
520
|
email: z.object({ email: z.string().email() }),
|
|
502
|
-
confirmation: z.object({ confirmed: z.boolean() })
|
|
521
|
+
confirmation: z.object({ confirmed: z.boolean() }),
|
|
503
522
|
},
|
|
504
523
|
|
|
505
524
|
async handler({ state, step }) {
|
|
506
525
|
// Request email (workflow pauses here)
|
|
507
|
-
const { email } = await step.request(
|
|
508
|
-
"email",
|
|
509
|
-
"Please enter your email address:"
|
|
510
|
-
);
|
|
526
|
+
const { email } = await step.request('email', 'Please enter your email address:')
|
|
511
527
|
|
|
512
528
|
// Request confirmation
|
|
513
|
-
const { confirmed } = await step.request(
|
|
514
|
-
"confirmation",
|
|
515
|
-
"Do you want to proceed?"
|
|
516
|
-
);
|
|
529
|
+
const { confirmed } = await step.request('confirmation', 'Do you want to proceed?')
|
|
517
530
|
|
|
518
531
|
if (confirmed) {
|
|
519
532
|
// Continue processing
|
|
520
533
|
}
|
|
521
|
-
}
|
|
522
|
-
})
|
|
534
|
+
},
|
|
535
|
+
})
|
|
523
536
|
|
|
524
537
|
// In Conversation - handle the request
|
|
525
538
|
export const Chat = new Conversation({
|
|
526
|
-
channel:
|
|
539
|
+
channel: 'chat.channel',
|
|
527
540
|
|
|
528
541
|
async handler({ type, request, conversation }) {
|
|
529
|
-
if (type ===
|
|
542
|
+
if (type === 'workflow_request') {
|
|
530
543
|
// Send prompt to user
|
|
531
544
|
await conversation.send({
|
|
532
|
-
type:
|
|
533
|
-
payload: { text: request.workflow.prompt }
|
|
534
|
-
})
|
|
545
|
+
type: 'text',
|
|
546
|
+
payload: { text: request.workflow.prompt },
|
|
547
|
+
})
|
|
535
548
|
|
|
536
549
|
// Later, provide data back
|
|
537
|
-
await request.workflow.provide(
|
|
538
|
-
email: userInput
|
|
539
|
-
})
|
|
550
|
+
await request.workflow.provide('email', {
|
|
551
|
+
email: userInput,
|
|
552
|
+
})
|
|
540
553
|
}
|
|
541
|
-
}
|
|
542
|
-
})
|
|
554
|
+
},
|
|
555
|
+
})
|
|
543
556
|
```
|
|
544
557
|
|
|
545
558
|
### 2. Sending Progress Updates (Non-blocking)
|
|
@@ -548,37 +561,37 @@ Send messages without pausing execution:
|
|
|
548
561
|
|
|
549
562
|
```typescript
|
|
550
563
|
export const NotificationWorkflow = new Workflow({
|
|
551
|
-
name:
|
|
564
|
+
name: 'notification',
|
|
552
565
|
input: z.object({
|
|
553
566
|
conversationId: z.string(), // CRITICAL: Required for messaging
|
|
554
|
-
userId: z.string()
|
|
567
|
+
userId: z.string(),
|
|
555
568
|
}),
|
|
556
569
|
|
|
557
570
|
async handler({ input, state, client, step }) {
|
|
558
571
|
// Send progress update
|
|
559
|
-
await step(
|
|
572
|
+
await step('notify-start', async () => {
|
|
560
573
|
await client.createMessage({
|
|
561
574
|
conversationId: input.conversationId,
|
|
562
|
-
type:
|
|
563
|
-
payload: { text:
|
|
564
|
-
})
|
|
565
|
-
})
|
|
575
|
+
type: 'text',
|
|
576
|
+
payload: { text: '🚀 Processing started...' },
|
|
577
|
+
})
|
|
578
|
+
})
|
|
566
579
|
|
|
567
580
|
// Do work
|
|
568
|
-
const result = await step(
|
|
569
|
-
return await processData()
|
|
570
|
-
})
|
|
581
|
+
const result = await step('process', async () => {
|
|
582
|
+
return await processData()
|
|
583
|
+
})
|
|
571
584
|
|
|
572
585
|
// Send completion
|
|
573
|
-
await step(
|
|
586
|
+
await step('notify-complete', async () => {
|
|
574
587
|
await client.createMessage({
|
|
575
588
|
conversationId: input.conversationId,
|
|
576
|
-
type:
|
|
577
|
-
payload: { text: `✅ Complete: ${result}` }
|
|
578
|
-
})
|
|
579
|
-
})
|
|
580
|
-
}
|
|
581
|
-
})
|
|
589
|
+
type: 'text',
|
|
590
|
+
payload: { text: `✅ Complete: ${result}` },
|
|
591
|
+
})
|
|
592
|
+
})
|
|
593
|
+
},
|
|
594
|
+
})
|
|
582
595
|
```
|
|
583
596
|
|
|
584
597
|
### 3. Starting Workflows from Conversations
|
|
@@ -606,32 +619,32 @@ When a workflow completes, fails, is canceled, or times out, the associated conv
|
|
|
606
619
|
```typescript
|
|
607
620
|
// In Conversation - handle workflow completion
|
|
608
621
|
export const Chat = new Conversation({
|
|
609
|
-
channel:
|
|
622
|
+
channel: 'chat.channel',
|
|
610
623
|
|
|
611
624
|
async handler({ type, completion, conversation }) {
|
|
612
|
-
if (type ===
|
|
625
|
+
if (type === 'workflow_callback') {
|
|
613
626
|
// completion.type — workflow name (e.g., "processOrder")
|
|
614
627
|
// completion.workflow — workflow instance
|
|
615
628
|
// completion.status — "completed" | "failed" | "canceled" | "timed_out"
|
|
616
629
|
// completion.output — workflow output (when completed)
|
|
617
630
|
// completion.error — error message (when failed)
|
|
618
631
|
|
|
619
|
-
if (completion.status ===
|
|
632
|
+
if (completion.status === 'completed') {
|
|
620
633
|
await conversation.send({
|
|
621
|
-
type:
|
|
634
|
+
type: 'text',
|
|
622
635
|
payload: {
|
|
623
|
-
text: `Processing finished! Result: ${JSON.stringify(completion.output)}
|
|
624
|
-
}
|
|
625
|
-
})
|
|
626
|
-
} else if (completion.status ===
|
|
636
|
+
text: `Processing finished! Result: ${JSON.stringify(completion.output)}`,
|
|
637
|
+
},
|
|
638
|
+
})
|
|
639
|
+
} else if (completion.status === 'failed') {
|
|
627
640
|
await conversation.send({
|
|
628
|
-
type:
|
|
629
|
-
payload: { text: `Processing failed: ${completion.error}` }
|
|
630
|
-
})
|
|
641
|
+
type: 'text',
|
|
642
|
+
payload: { text: `Processing failed: ${completion.error}` },
|
|
643
|
+
})
|
|
631
644
|
}
|
|
632
645
|
}
|
|
633
|
-
}
|
|
634
|
-
})
|
|
646
|
+
},
|
|
647
|
+
})
|
|
635
648
|
```
|
|
636
649
|
|
|
637
650
|
This replaces the need to poll workflow status or use raw event type guards. See **[Conversations — Handling Workflow Callbacks](./conversations.md#handling-workflow-callbacks-completion-events)** for full examples.
|
|
@@ -653,39 +666,36 @@ This replaces the need to poll workflow status or use raw event type guards. See
|
|
|
653
666
|
Workflows can start and wait for other workflows to complete:
|
|
654
667
|
|
|
655
668
|
```typescript
|
|
656
|
-
import { Workflow, WorkflowDefinitions } from
|
|
669
|
+
import { Workflow, WorkflowDefinitions } from '@botpress/runtime'
|
|
657
670
|
|
|
658
671
|
export const ParentWorkflow = new Workflow({
|
|
659
|
-
name:
|
|
672
|
+
name: 'parent',
|
|
660
673
|
input: z.object({
|
|
661
674
|
conversationId: z.string(),
|
|
662
|
-
uniqueKey: z.string()
|
|
675
|
+
uniqueKey: z.string(),
|
|
663
676
|
}),
|
|
664
677
|
output: z.object({
|
|
665
|
-
childResult: z.any()
|
|
678
|
+
childResult: z.any(),
|
|
666
679
|
}),
|
|
667
680
|
|
|
668
681
|
async handler({ step, input }) {
|
|
669
682
|
// Start another workflow and wait for it
|
|
670
|
-
const { output } = await step(
|
|
683
|
+
const { output } = await step('call-child', async () => {
|
|
671
684
|
const { id } = await ChildWorkflow.getOrCreate({
|
|
672
|
-
input: { data:
|
|
673
|
-
statuses: [
|
|
674
|
-
key: `child_${input.uniqueKey}
|
|
675
|
-
})
|
|
685
|
+
input: { data: 'some data' },
|
|
686
|
+
statuses: ['pending', 'in_progress', 'completed'],
|
|
687
|
+
key: `child_${input.uniqueKey}`,
|
|
688
|
+
})
|
|
676
689
|
|
|
677
690
|
// Wait for the workflow to complete
|
|
678
|
-
const result = await step.waitForWorkflow(
|
|
679
|
-
"ChildWorkflow",
|
|
680
|
-
id
|
|
681
|
-
);
|
|
691
|
+
const result = await step.waitForWorkflow('ChildWorkflow', id)
|
|
682
692
|
|
|
683
|
-
return result.output as WorkflowDefinitions[
|
|
684
|
-
})
|
|
693
|
+
return result.output as WorkflowDefinitions['child']['output']
|
|
694
|
+
})
|
|
685
695
|
|
|
686
|
-
return { childResult: output }
|
|
687
|
-
}
|
|
688
|
-
})
|
|
696
|
+
return { childResult: output }
|
|
697
|
+
},
|
|
698
|
+
})
|
|
689
699
|
```
|
|
690
700
|
|
|
691
701
|
### Workflow Coordination Pattern
|
|
@@ -694,28 +704,25 @@ Use getOrCreate with unique keys to prevent duplicate workflows:
|
|
|
694
704
|
|
|
695
705
|
```typescript
|
|
696
706
|
export const ExtractTopicsWorkflow = new Workflow({
|
|
697
|
-
name:
|
|
707
|
+
name: 'topics',
|
|
698
708
|
input: z.object({
|
|
699
|
-
conversationId: z.string()
|
|
709
|
+
conversationId: z.string(),
|
|
700
710
|
}),
|
|
701
711
|
|
|
702
712
|
async handler({ step, input }) {
|
|
703
713
|
// Get or create ensures only one workflow per conversation
|
|
704
714
|
const { id } = await InsightsWorkflow.getOrCreate({
|
|
705
715
|
input: { conversationId: input.conversationId },
|
|
706
|
-
statuses: [
|
|
707
|
-
key: `insights_conversation_${input.conversationId}
|
|
708
|
-
})
|
|
716
|
+
statuses: ['pending', 'in_progress', 'completed'],
|
|
717
|
+
key: `insights_conversation_${input.conversationId}`, // Unique key
|
|
718
|
+
})
|
|
709
719
|
|
|
710
720
|
// If workflow already exists with key, returns existing instance
|
|
711
|
-
const { output } = await step.waitForWorkflow(
|
|
712
|
-
"InsightsWorkflow",
|
|
713
|
-
id
|
|
714
|
-
);
|
|
721
|
+
const { output } = await step.waitForWorkflow('InsightsWorkflow', id)
|
|
715
722
|
|
|
716
|
-
return output
|
|
717
|
-
}
|
|
718
|
-
})
|
|
723
|
+
return output
|
|
724
|
+
},
|
|
725
|
+
})
|
|
719
726
|
```
|
|
720
727
|
|
|
721
728
|
### Workflow Synchronization Pattern
|
|
@@ -724,34 +731,31 @@ When you need to ensure certain operations complete before others:
|
|
|
724
731
|
|
|
725
732
|
```typescript
|
|
726
733
|
export const SyncWorkflow = new Workflow({
|
|
727
|
-
name:
|
|
734
|
+
name: 'sync',
|
|
728
735
|
|
|
729
736
|
async handler({ step, input }) {
|
|
730
737
|
// Step 1: Get or create dependent workflow
|
|
731
|
-
const topics = await step(
|
|
738
|
+
const topics = await step('find topics', async () => {
|
|
732
739
|
const { id } = await InsightsTopicsWorkflow.getOrCreate({
|
|
733
740
|
input: { conversationId: input.conversationId },
|
|
734
|
-
statuses: [
|
|
741
|
+
statuses: ['pending', 'in_progress', 'completed'],
|
|
735
742
|
key: `topics_conversation_${input.conversationId}`,
|
|
736
|
-
})
|
|
743
|
+
})
|
|
737
744
|
|
|
738
|
-
const { output } = await step.waitForWorkflow(
|
|
739
|
-
"InsightsTopicsWorkflow",
|
|
740
|
-
id
|
|
741
|
-
);
|
|
745
|
+
const { output } = await step.waitForWorkflow('InsightsTopicsWorkflow', id)
|
|
742
746
|
|
|
743
|
-
return output as WorkflowDefinitions[
|
|
744
|
-
})
|
|
747
|
+
return output as WorkflowDefinitions['insights_topics']['output']
|
|
748
|
+
})
|
|
745
749
|
|
|
746
750
|
// Step 2: Use the topics in the main processing
|
|
747
|
-
const insights = await step(
|
|
751
|
+
const insights = await step('process insights', async () => {
|
|
748
752
|
// Use topics data from the dependent workflow
|
|
749
|
-
return processWithTopics(topics)
|
|
750
|
-
})
|
|
753
|
+
return processWithTopics(topics)
|
|
754
|
+
})
|
|
751
755
|
|
|
752
|
-
return { insights }
|
|
753
|
-
}
|
|
754
|
-
})
|
|
756
|
+
return { insights }
|
|
757
|
+
},
|
|
758
|
+
})
|
|
755
759
|
```
|
|
756
760
|
|
|
757
761
|
## AI/LLM Integration
|
|
@@ -761,53 +765,53 @@ Workflows have full access to AI capabilities through multiple approaches:
|
|
|
761
765
|
### 1. Using execute() Function (Autonomous Agent)
|
|
762
766
|
|
|
763
767
|
```typescript
|
|
764
|
-
import { Workflow, z, Autonomous } from
|
|
765
|
-
import { actions } from
|
|
768
|
+
import { Workflow, z, Autonomous } from '@botpress/runtime'
|
|
769
|
+
import { actions } from '@botpress/runtime'
|
|
766
770
|
|
|
767
771
|
export const AIWorkflow = new Workflow({
|
|
768
|
-
name:
|
|
772
|
+
name: 'aiWorkflow',
|
|
769
773
|
input: z.object({ question: z.string() }),
|
|
770
774
|
output: z.object({ answer: z.string() }),
|
|
771
775
|
|
|
772
776
|
handler: async ({ input, state, execute, step }) => {
|
|
773
777
|
// Define exits for structured responses
|
|
774
778
|
const AnswerExit = new Autonomous.Exit({
|
|
775
|
-
name:
|
|
776
|
-
description:
|
|
779
|
+
name: 'Answer',
|
|
780
|
+
description: 'Provide answer',
|
|
777
781
|
schema: z.object({
|
|
778
782
|
answer: z.string(),
|
|
779
|
-
confidence: z.number()
|
|
780
|
-
})
|
|
781
|
-
})
|
|
783
|
+
confidence: z.number(),
|
|
784
|
+
}),
|
|
785
|
+
})
|
|
782
786
|
|
|
783
787
|
// Define tools for AI
|
|
784
788
|
const SearchTool = new Autonomous.Tool({
|
|
785
|
-
name:
|
|
786
|
-
description:
|
|
789
|
+
name: 'Search',
|
|
790
|
+
description: 'Search for info',
|
|
787
791
|
input: z.object({ query: z.string() }),
|
|
788
792
|
output: z.string(),
|
|
789
793
|
handler: async ({ query }) => {
|
|
790
|
-
return await actions.browser.webSearch({ query })
|
|
791
|
-
}
|
|
792
|
-
})
|
|
794
|
+
return await actions.browser.webSearch({ query })
|
|
795
|
+
},
|
|
796
|
+
})
|
|
793
797
|
|
|
794
798
|
// Execute AI with tools
|
|
795
799
|
const result = await execute({
|
|
796
800
|
instructions: `Answer: "${input.question}"`,
|
|
797
801
|
tools: [SearchTool],
|
|
798
802
|
exits: [AnswerExit],
|
|
799
|
-
model:
|
|
803
|
+
model: 'openai:gpt-4o',
|
|
800
804
|
temperature: 0.7,
|
|
801
|
-
iterations: 10
|
|
802
|
-
})
|
|
805
|
+
iterations: 10,
|
|
806
|
+
})
|
|
803
807
|
|
|
804
808
|
if (result.is(AnswerExit)) {
|
|
805
|
-
return { answer: result.output.answer }
|
|
809
|
+
return { answer: result.output.answer }
|
|
806
810
|
}
|
|
807
811
|
|
|
808
|
-
return { answer:
|
|
809
|
-
}
|
|
810
|
-
})
|
|
812
|
+
return { answer: 'No answer found' }
|
|
813
|
+
},
|
|
814
|
+
})
|
|
811
815
|
```
|
|
812
816
|
|
|
813
817
|
### 2. Using execute() with Knowledge Bases
|
|
@@ -815,27 +819,27 @@ export const AIWorkflow = new Workflow({
|
|
|
815
819
|
Provide knowledge bases directly to the AI for RAG-powered responses:
|
|
816
820
|
|
|
817
821
|
```typescript
|
|
818
|
-
import { Workflow, z, Autonomous } from
|
|
819
|
-
import { KnowledgeDocs } from
|
|
822
|
+
import { Workflow, z, Autonomous } from '@botpress/runtime'
|
|
823
|
+
import { KnowledgeDocs } from '../knowledge/docs' // Your knowledge base
|
|
820
824
|
|
|
821
825
|
export const KnowledgeWorkflow = new Workflow({
|
|
822
|
-
name:
|
|
826
|
+
name: 'answerFromKnowledge',
|
|
823
827
|
input: z.object({ question: z.string() }),
|
|
824
828
|
|
|
825
829
|
handler: async ({ input, execute }) => {
|
|
826
830
|
const AnswerExit = new Autonomous.Exit({
|
|
827
|
-
name:
|
|
828
|
-
description:
|
|
831
|
+
name: 'Answer',
|
|
832
|
+
description: 'Found answer in knowledge base',
|
|
829
833
|
schema: z.object({
|
|
830
834
|
answer: z.string(),
|
|
831
|
-
sources: z.array(z.string())
|
|
832
|
-
})
|
|
833
|
-
})
|
|
835
|
+
sources: z.array(z.string()),
|
|
836
|
+
}),
|
|
837
|
+
})
|
|
834
838
|
|
|
835
839
|
const NoAnswerExit = new Autonomous.Exit({
|
|
836
|
-
name:
|
|
837
|
-
description:
|
|
838
|
-
})
|
|
840
|
+
name: 'NoAnswer',
|
|
841
|
+
description: 'No relevant information found',
|
|
842
|
+
})
|
|
839
843
|
|
|
840
844
|
const result = await execute({
|
|
841
845
|
instructions: `Find answer to: "${input.question}"
|
|
@@ -843,55 +847,53 @@ export const KnowledgeWorkflow = new Workflow({
|
|
|
843
847
|
If no relevant information exists, use NoAnswer exit.`,
|
|
844
848
|
knowledge: [KnowledgeDocs], // Pass knowledge bases directly
|
|
845
849
|
exits: [AnswerExit, NoAnswerExit],
|
|
846
|
-
model:
|
|
850
|
+
model: 'openai:gpt-4o',
|
|
847
851
|
temperature: 0,
|
|
848
|
-
iterations: 5
|
|
849
|
-
})
|
|
852
|
+
iterations: 5,
|
|
853
|
+
})
|
|
850
854
|
|
|
851
855
|
if (result.is(AnswerExit)) {
|
|
852
856
|
// Access citations if needed
|
|
853
|
-
const citations = context.get(
|
|
854
|
-
const [cleaned, found] = citations.removeCitationsFromObject(result.output.answer)
|
|
857
|
+
const citations = context.get('citations')
|
|
858
|
+
const [cleaned, found] = citations.removeCitationsFromObject(result.output.answer)
|
|
855
859
|
|
|
856
860
|
return {
|
|
857
861
|
answer: cleaned,
|
|
858
|
-
hasSources: found.length > 0
|
|
859
|
-
}
|
|
862
|
+
hasSources: found.length > 0,
|
|
863
|
+
}
|
|
860
864
|
}
|
|
861
865
|
|
|
862
|
-
return { answer:
|
|
863
|
-
}
|
|
864
|
-
})
|
|
866
|
+
return { answer: 'No information found', hasSources: false }
|
|
867
|
+
},
|
|
868
|
+
})
|
|
865
869
|
```
|
|
866
870
|
|
|
867
871
|
### 3. Using Cognitive Client (Raw LLM)
|
|
868
872
|
|
|
869
873
|
```typescript
|
|
870
|
-
import { Workflow, z, context } from
|
|
874
|
+
import { Workflow, z, context } from '@botpress/runtime'
|
|
871
875
|
|
|
872
876
|
export const DirectLLMWorkflow = new Workflow({
|
|
873
|
-
name:
|
|
877
|
+
name: 'directLLM',
|
|
874
878
|
|
|
875
879
|
handler: async ({ input, state, step }) => {
|
|
876
|
-
const cognitive = context.get(
|
|
880
|
+
const cognitive = context.get('cognitive')
|
|
877
881
|
|
|
878
|
-
const result = await step(
|
|
882
|
+
const result = await step('generate', async () => {
|
|
879
883
|
const response = await cognitive.generateContent({
|
|
880
|
-
model:
|
|
881
|
-
systemPrompt:
|
|
882
|
-
messages: [
|
|
883
|
-
{ role: "user", content: input.prompt }
|
|
884
|
-
],
|
|
884
|
+
model: 'openai:gpt-4o',
|
|
885
|
+
systemPrompt: 'You are helpful',
|
|
886
|
+
messages: [{ role: 'user', content: input.prompt }],
|
|
885
887
|
temperature: 0.7,
|
|
886
|
-
maxTokens: 1000
|
|
887
|
-
})
|
|
888
|
+
maxTokens: 1000,
|
|
889
|
+
})
|
|
888
890
|
|
|
889
|
-
return response.choices[0].message.content
|
|
890
|
-
})
|
|
891
|
+
return response.choices[0].message.content
|
|
892
|
+
})
|
|
891
893
|
|
|
892
|
-
return { response: result }
|
|
893
|
-
}
|
|
894
|
-
})
|
|
894
|
+
return { response: result }
|
|
895
|
+
},
|
|
896
|
+
})
|
|
895
897
|
```
|
|
896
898
|
|
|
897
899
|
### 3. Using Zai (Structured Operations)
|
|
@@ -899,34 +901,37 @@ export const DirectLLMWorkflow = new Workflow({
|
|
|
899
901
|
Use `adk.zai` for structured AI operations (extract, check, summarize, etc.) inside workflows. Always wrap Zai calls in `step()` for persistence.
|
|
900
902
|
|
|
901
903
|
```typescript
|
|
902
|
-
import { Workflow, z, adk } from
|
|
904
|
+
import { Workflow, z, adk } from '@botpress/runtime'
|
|
903
905
|
|
|
904
906
|
export const ZaiWorkflow = new Workflow({
|
|
905
|
-
name:
|
|
907
|
+
name: 'zaiWorkflow',
|
|
906
908
|
handler: async ({ input, state, step }) => {
|
|
907
|
-
const insights = await step(
|
|
908
|
-
adk.zai.extract(
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
909
|
+
const insights = await step('extract insights', async () =>
|
|
910
|
+
adk.zai.extract(
|
|
911
|
+
input.text,
|
|
912
|
+
z.array(
|
|
913
|
+
z.object({
|
|
914
|
+
type: z.enum(['bug', 'feature_request', 'question']),
|
|
915
|
+
description: z.string(),
|
|
916
|
+
priority: z.enum(['low', 'medium', 'high']),
|
|
917
|
+
})
|
|
918
|
+
)
|
|
919
|
+
)
|
|
920
|
+
)
|
|
921
|
+
const hasBugs = await step('check for bugs', async () => adk.zai.check(insights, 'Are there any bug reports?'))
|
|
922
|
+
return { insights, hasBugs }
|
|
918
923
|
},
|
|
919
|
-
})
|
|
924
|
+
})
|
|
920
925
|
```
|
|
921
926
|
|
|
922
927
|
### AI Approach Comparison
|
|
923
928
|
|
|
924
|
-
| Approach
|
|
925
|
-
|
|
926
|
-
| **execute()**
|
|
927
|
-
| **Cognitive Client**
|
|
928
|
-
| **Zai**
|
|
929
|
-
| **Integration Actions** | Provider-specific features
|
|
929
|
+
| Approach | Best For | Example Use Case |
|
|
930
|
+
| ----------------------- | ------------------------------ | ------------------------ |
|
|
931
|
+
| **execute()** | Multi-step AI tasks with tools | Research, support agents |
|
|
932
|
+
| **Cognitive Client** | Simple text generation | Content generation |
|
|
933
|
+
| **Zai** | Structured data extraction | Entity extraction |
|
|
934
|
+
| **Integration Actions** | Provider-specific features | Vision models |
|
|
930
935
|
|
|
931
936
|
### Important AI Notes
|
|
932
937
|
|
|
@@ -946,10 +951,8 @@ Workflows can be converted to tools using `.asTool()`. This is useful when you w
|
|
|
946
951
|
```typescript
|
|
947
952
|
// Starts the workflow and returns immediately
|
|
948
953
|
await execute({
|
|
949
|
-
tools: [
|
|
950
|
-
|
|
951
|
-
]
|
|
952
|
-
});
|
|
954
|
+
tools: [MyWorkflow.asTool()],
|
|
955
|
+
})
|
|
953
956
|
```
|
|
954
957
|
|
|
955
958
|
When a workflow is exposed this way, the tool starts the workflow and returns a lightweight result such as the workflow ID and current status.
|
|
@@ -960,52 +963,52 @@ An Action wrapper is still useful when you want to rename the tool, constrain in
|
|
|
960
963
|
|
|
961
964
|
```typescript
|
|
962
965
|
// File: /actions/start-processing.ts
|
|
963
|
-
import { Action, z } from
|
|
964
|
-
import { DataProcessingWorkflow } from
|
|
966
|
+
import { Action, z } from '@botpress/runtime'
|
|
967
|
+
import { DataProcessingWorkflow } from '../workflows/data-processing'
|
|
965
968
|
|
|
966
969
|
export default new Action({
|
|
967
|
-
name:
|
|
968
|
-
description:
|
|
970
|
+
name: 'startDataProcessing',
|
|
971
|
+
description: 'Start data processing workflow',
|
|
969
972
|
|
|
970
973
|
input: z.object({
|
|
971
974
|
datasetId: z.string(),
|
|
972
|
-
options: z
|
|
973
|
-
|
|
974
|
-
|
|
975
|
+
options: z
|
|
976
|
+
.object({
|
|
977
|
+
fullScan: z.boolean().default(false),
|
|
978
|
+
})
|
|
979
|
+
.optional(),
|
|
975
980
|
}),
|
|
976
981
|
|
|
977
982
|
output: z.object({
|
|
978
|
-
workflowId: z.string()
|
|
983
|
+
workflowId: z.string(),
|
|
979
984
|
}),
|
|
980
985
|
|
|
981
986
|
async handler({ input }) {
|
|
982
987
|
// Calls workflow.start() - returns immediately
|
|
983
988
|
const instance = await DataProcessingWorkflow.start({
|
|
984
989
|
datasetId: input.datasetId,
|
|
985
|
-
options: input.options || { fullScan: false }
|
|
986
|
-
})
|
|
990
|
+
options: input.options || { fullScan: false },
|
|
991
|
+
})
|
|
987
992
|
|
|
988
|
-
return { workflowId: instance.id }
|
|
989
|
-
}
|
|
990
|
-
})
|
|
993
|
+
return { workflowId: instance.id }
|
|
994
|
+
},
|
|
995
|
+
})
|
|
991
996
|
```
|
|
992
997
|
|
|
993
998
|
Use the Action wrapper as a tool:
|
|
994
999
|
|
|
995
1000
|
```typescript
|
|
996
|
-
import { Conversation, actions } from
|
|
1001
|
+
import { Conversation, actions } from '@botpress/runtime'
|
|
997
1002
|
|
|
998
1003
|
export default new Conversation({
|
|
999
|
-
channel:
|
|
1004
|
+
channel: '*',
|
|
1000
1005
|
handler: async ({ execute }) => {
|
|
1001
1006
|
await execute({
|
|
1002
|
-
instructions:
|
|
1003
|
-
tools: [
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
}
|
|
1008
|
-
});
|
|
1007
|
+
instructions: 'Help the user',
|
|
1008
|
+
tools: [actions.startDataProcessing.asTool()],
|
|
1009
|
+
})
|
|
1010
|
+
},
|
|
1011
|
+
})
|
|
1009
1012
|
```
|
|
1010
1013
|
|
|
1011
1014
|
### Tracking Workflow Status
|
|
@@ -1013,44 +1016,44 @@ export default new Conversation({
|
|
|
1013
1016
|
#### 1. Status Check Action
|
|
1014
1017
|
|
|
1015
1018
|
```typescript
|
|
1016
|
-
import { Action, z, context } from
|
|
1019
|
+
import { Action, z, context } from '@botpress/runtime'
|
|
1017
1020
|
|
|
1018
1021
|
export default new Action({
|
|
1019
|
-
name:
|
|
1020
|
-
description:
|
|
1022
|
+
name: 'checkProcessingStatus',
|
|
1023
|
+
description: 'Check workflow status',
|
|
1021
1024
|
|
|
1022
1025
|
input: z.object({
|
|
1023
|
-
workflowId: z.string()
|
|
1026
|
+
workflowId: z.string(),
|
|
1024
1027
|
}),
|
|
1025
1028
|
|
|
1026
1029
|
output: z.object({
|
|
1027
1030
|
status: z.string(),
|
|
1028
|
-
progress: z.number()
|
|
1031
|
+
progress: z.number(),
|
|
1029
1032
|
}),
|
|
1030
1033
|
|
|
1031
1034
|
async handler({ workflowId }) {
|
|
1032
|
-
const client = context.get(
|
|
1033
|
-
const { workflow } = await client.getWorkflow({ id: workflowId })
|
|
1034
|
-
|
|
1035
|
-
const { state } = await client
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
const
|
|
1044
|
-
const
|
|
1045
|
-
|
|
1046
|
-
|
|
1035
|
+
const client = context.get('client')
|
|
1036
|
+
const { workflow } = await client.getWorkflow({ id: workflowId })
|
|
1037
|
+
|
|
1038
|
+
const { state } = await client
|
|
1039
|
+
.getState({
|
|
1040
|
+
name: 'workflowSteps',
|
|
1041
|
+
id: workflowId,
|
|
1042
|
+
type: 'workflow',
|
|
1043
|
+
})
|
|
1044
|
+
.catch(() => ({ state: { payload: { steps: {} } } }))
|
|
1045
|
+
|
|
1046
|
+
const steps = state.payload.steps || {}
|
|
1047
|
+
const stepArray = Object.values(steps)
|
|
1048
|
+
const completed = stepArray.filter((s: any) => s.finishedAt).length
|
|
1049
|
+
const progress = stepArray.length > 0 ? Math.round((completed / stepArray.length) * 100) : 0
|
|
1047
1050
|
|
|
1048
1051
|
return {
|
|
1049
1052
|
status: workflow.status,
|
|
1050
|
-
progress
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
})
|
|
1053
|
+
progress,
|
|
1054
|
+
}
|
|
1055
|
+
},
|
|
1056
|
+
})
|
|
1054
1057
|
```
|
|
1055
1058
|
|
|
1056
1059
|
#### 2. Progress Events
|
|
@@ -1058,39 +1061,39 @@ export default new Action({
|
|
|
1058
1061
|
Send progress events from workflow:
|
|
1059
1062
|
|
|
1060
1063
|
```typescript
|
|
1061
|
-
import { context } from
|
|
1064
|
+
import { context } from '@botpress/runtime'
|
|
1062
1065
|
|
|
1063
1066
|
export const DataProcessingWorkflow = new Workflow({
|
|
1064
|
-
name:
|
|
1067
|
+
name: 'dataProcessing',
|
|
1065
1068
|
|
|
1066
1069
|
async handler({ input, state, step, client }) {
|
|
1067
|
-
const workflow = context.get(
|
|
1068
|
-
const conversationId = workflow.conversationId
|
|
1070
|
+
const workflow = context.get('workflow')
|
|
1071
|
+
const conversationId = workflow.conversationId
|
|
1069
1072
|
|
|
1070
1073
|
if (conversationId) {
|
|
1071
1074
|
await client.createEvent({
|
|
1072
|
-
type:
|
|
1075
|
+
type: 'workflowProgress',
|
|
1073
1076
|
conversationId,
|
|
1074
1077
|
payload: {
|
|
1075
1078
|
workflowId: workflow.id,
|
|
1076
|
-
stage:
|
|
1077
|
-
progress: 50
|
|
1078
|
-
}
|
|
1079
|
-
})
|
|
1079
|
+
stage: 'processing',
|
|
1080
|
+
progress: 50,
|
|
1081
|
+
},
|
|
1082
|
+
})
|
|
1080
1083
|
}
|
|
1081
1084
|
|
|
1082
|
-
return { itemsProcessed: 0 }
|
|
1083
|
-
}
|
|
1084
|
-
})
|
|
1085
|
+
return { itemsProcessed: 0 }
|
|
1086
|
+
},
|
|
1087
|
+
})
|
|
1085
1088
|
```
|
|
1086
1089
|
|
|
1087
1090
|
### Key Differences
|
|
1088
1091
|
|
|
1089
|
-
| Aspect
|
|
1090
|
-
|
|
1091
|
-
| **Returns**
|
|
1092
|
-
| **Execution** | Synchronous
|
|
1093
|
-
| **Example**
|
|
1092
|
+
| Aspect | Action | Workflow Wrapper |
|
|
1093
|
+
| ------------- | ------------- | ----------------- |
|
|
1094
|
+
| **Returns** | Final result | Workflow ID |
|
|
1095
|
+
| **Execution** | Synchronous | Asynchronous |
|
|
1096
|
+
| **Example** | `fetchUser()` | `startIndexing()` |
|
|
1094
1097
|
|
|
1095
1098
|
> **See Also:** [Converting Actions to Tools](./actions.md#converting-actions-to-tools) for more details on using `.asTool()` with different action patterns.
|
|
1096
1099
|
|
|
@@ -1099,51 +1102,51 @@ export const DataProcessingWorkflow = new Workflow({
|
|
|
1099
1102
|
Run workflows automatically on a schedule:
|
|
1100
1103
|
|
|
1101
1104
|
```typescript
|
|
1102
|
-
import { bot, Workflow, z } from
|
|
1105
|
+
import { bot, Workflow, z } from '@botpress/runtime'
|
|
1103
1106
|
|
|
1104
1107
|
export const DailySync = new Workflow({
|
|
1105
|
-
name:
|
|
1106
|
-
description:
|
|
1108
|
+
name: 'dailySync',
|
|
1109
|
+
description: 'Syncs data daily with incremental updates',
|
|
1107
1110
|
|
|
1108
1111
|
// Cron schedule (runs at 8 AM every day)
|
|
1109
|
-
schedule:
|
|
1112
|
+
schedule: '0 8 * * *',
|
|
1110
1113
|
|
|
1111
1114
|
// Long timeout for large sync operations
|
|
1112
|
-
timeout:
|
|
1115
|
+
timeout: '6h',
|
|
1113
1116
|
|
|
1114
1117
|
// Scheduled workflows can have optional input for manual triggering
|
|
1115
1118
|
input: z.object({
|
|
1116
|
-
fullSync: z.boolean().default(false).describe(
|
|
1119
|
+
fullSync: z.boolean().default(false).describe('Force full sync'),
|
|
1117
1120
|
}),
|
|
1118
1121
|
|
|
1119
1122
|
// Track sync progress
|
|
1120
1123
|
state: z.object({
|
|
1121
1124
|
lastSyncDate: z.string().optional(),
|
|
1122
|
-
itemsProcessed: z.number().default(0)
|
|
1125
|
+
itemsProcessed: z.number().default(0),
|
|
1123
1126
|
}),
|
|
1124
1127
|
|
|
1125
1128
|
async handler({ input, state, step }) {
|
|
1126
1129
|
// Access global bot state to check if initial sync is done
|
|
1127
|
-
bot.state.syncStatus ??= { initialized: false }
|
|
1130
|
+
bot.state.syncStatus ??= { initialized: false }
|
|
1128
1131
|
|
|
1129
|
-
const isInitialSync = input.fullSync || !bot.state.syncStatus.initialized
|
|
1132
|
+
const isInitialSync = input.fullSync || !bot.state.syncStatus.initialized
|
|
1130
1133
|
|
|
1131
|
-
const report = await step(
|
|
1132
|
-
return await generateDailyReport(isInitialSync)
|
|
1133
|
-
})
|
|
1134
|
+
const report = await step('generate', async () => {
|
|
1135
|
+
return await generateDailyReport(isInitialSync)
|
|
1136
|
+
})
|
|
1134
1137
|
|
|
1135
|
-
await step(
|
|
1136
|
-
await sendReportToTeam(report)
|
|
1137
|
-
})
|
|
1138
|
+
await step('send', async () => {
|
|
1139
|
+
await sendReportToTeam(report)
|
|
1140
|
+
})
|
|
1138
1141
|
|
|
1139
1142
|
// Mark initial sync as complete in global state
|
|
1140
1143
|
if (isInitialSync) {
|
|
1141
|
-
bot.state.syncStatus.initialized = true
|
|
1144
|
+
bot.state.syncStatus.initialized = true
|
|
1142
1145
|
}
|
|
1143
1146
|
|
|
1144
|
-
return { sent: true }
|
|
1145
|
-
}
|
|
1146
|
-
})
|
|
1147
|
+
return { sent: true }
|
|
1148
|
+
},
|
|
1149
|
+
})
|
|
1147
1150
|
```
|
|
1148
1151
|
|
|
1149
1152
|
### Cron Syntax Reference
|
|
@@ -1162,13 +1165,13 @@ export const DailySync = new Workflow({
|
|
|
1162
1165
|
|
|
1163
1166
|
```typescript
|
|
1164
1167
|
const schedulePatterns = {
|
|
1165
|
-
everyMinute:
|
|
1166
|
-
every5Minutes:
|
|
1167
|
-
everyHour:
|
|
1168
|
-
daily9AM:
|
|
1169
|
-
weekdaysMorning:
|
|
1170
|
-
firstOfMonth:
|
|
1171
|
-
}
|
|
1168
|
+
everyMinute: '* * * * *',
|
|
1169
|
+
every5Minutes: '*/5 * * * *',
|
|
1170
|
+
everyHour: '0 * * * *',
|
|
1171
|
+
daily9AM: '0 9 * * *',
|
|
1172
|
+
weekdaysMorning: '0 9 * * 1-5', // Mon-Fri at 9am
|
|
1173
|
+
firstOfMonth: '0 0 1 * *',
|
|
1174
|
+
}
|
|
1172
1175
|
```
|
|
1173
1176
|
|
|
1174
1177
|
## Accessing Global Bot State
|
|
@@ -1176,31 +1179,32 @@ const schedulePatterns = {
|
|
|
1176
1179
|
Workflows can also access and modify global bot state (not just workflow-specific state):
|
|
1177
1180
|
|
|
1178
1181
|
```typescript
|
|
1179
|
-
import { bot, Workflow, z } from
|
|
1182
|
+
import { bot, Workflow, z } from '@botpress/runtime'
|
|
1180
1183
|
|
|
1181
1184
|
export const AnalysisWorkflow = new Workflow({
|
|
1182
|
-
name:
|
|
1183
|
-
schedule:
|
|
1185
|
+
name: 'analysis',
|
|
1186
|
+
schedule: '0 8 * * *', // Daily at 8 AM
|
|
1184
1187
|
|
|
1185
1188
|
async handler({ state, step }) {
|
|
1186
1189
|
// Perform analysis
|
|
1187
|
-
const results = await step(
|
|
1188
|
-
return await performAnalysis()
|
|
1189
|
-
})
|
|
1190
|
+
const results = await step('analyze', async () => {
|
|
1191
|
+
return await performAnalysis()
|
|
1192
|
+
})
|
|
1190
1193
|
|
|
1191
1194
|
// Store results in global bot state
|
|
1192
|
-
bot.state.analysisResults = results
|
|
1193
|
-
bot.state.lastAnalysisDate = new Date().toISOString()
|
|
1195
|
+
bot.state.analysisResults = results
|
|
1196
|
+
bot.state.lastAnalysisDate = new Date().toISOString()
|
|
1194
1197
|
|
|
1195
1198
|
// Access existing bot state
|
|
1196
|
-
console.log(`Previous analysis: ${bot.state.lastAnalysisDate}`)
|
|
1199
|
+
console.log(`Previous analysis: ${bot.state.lastAnalysisDate}`)
|
|
1197
1200
|
|
|
1198
|
-
return { completed: true }
|
|
1199
|
-
}
|
|
1200
|
-
})
|
|
1201
|
+
return { completed: true }
|
|
1202
|
+
},
|
|
1203
|
+
})
|
|
1201
1204
|
```
|
|
1202
1205
|
|
|
1203
1206
|
This is useful for:
|
|
1207
|
+
|
|
1204
1208
|
- Storing cross-workflow shared data
|
|
1205
1209
|
- Maintaining global configuration
|
|
1206
1210
|
- Tracking system-wide metrics
|
|
@@ -1209,34 +1213,37 @@ This is useful for:
|
|
|
1209
1213
|
## Best Practices
|
|
1210
1214
|
|
|
1211
1215
|
### 1. Use Meaningful Keys
|
|
1216
|
+
|
|
1212
1217
|
```typescript
|
|
1213
1218
|
// Prevent duplicate workflows for same user
|
|
1214
1219
|
await MyWorkflow.getOrCreate({
|
|
1215
1220
|
key: userId, // Or composite: `${userId}-${date}`
|
|
1216
|
-
input: { userId }
|
|
1217
|
-
})
|
|
1221
|
+
input: { userId },
|
|
1222
|
+
})
|
|
1218
1223
|
```
|
|
1219
1224
|
|
|
1220
1225
|
### 2. Keep Step Names Stable
|
|
1226
|
+
|
|
1221
1227
|
```typescript
|
|
1222
1228
|
// ✅ GOOD: Stable step names
|
|
1223
|
-
await step(
|
|
1229
|
+
await step('process-batch', async () => {
|
|
1224
1230
|
for (const item of items) {
|
|
1225
|
-
await processItem(item)
|
|
1231
|
+
await processItem(item)
|
|
1226
1232
|
}
|
|
1227
|
-
})
|
|
1233
|
+
})
|
|
1228
1234
|
|
|
1229
1235
|
// ❌ BAD: Dynamic step names
|
|
1230
1236
|
for (let i = 0; i < items.length; i++) {
|
|
1231
|
-
await step(`process-${i}`, async () => {})
|
|
1237
|
+
await step(`process-${i}`, async () => {})
|
|
1232
1238
|
}
|
|
1233
1239
|
```
|
|
1234
1240
|
|
|
1235
1241
|
### 3. Store Progress in State
|
|
1242
|
+
|
|
1236
1243
|
```typescript
|
|
1237
1244
|
// Access state via the state parameter in workflow handlers
|
|
1238
|
-
state.progress =
|
|
1239
|
-
state.percentComplete = 50
|
|
1245
|
+
state.progress = 'Processing item 5 of 10'
|
|
1246
|
+
state.percentComplete = 50
|
|
1240
1247
|
// External systems can poll this state via workflow instance
|
|
1241
1248
|
```
|
|
1242
1249
|
|
|
@@ -1269,85 +1276,91 @@ async handler({ state, step }) {
|
|
|
1269
1276
|
```
|
|
1270
1277
|
|
|
1271
1278
|
### 5. Handle Errors Gracefully
|
|
1279
|
+
|
|
1272
1280
|
```typescript
|
|
1273
|
-
await step(
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
+
await step(
|
|
1282
|
+
'risky-op',
|
|
1283
|
+
async () => {
|
|
1284
|
+
try {
|
|
1285
|
+
return await riskyOperation()
|
|
1286
|
+
} catch (error) {
|
|
1287
|
+
state.lastError = error.message // Store error in state
|
|
1288
|
+
throw error // Re-throw to mark step as failed
|
|
1289
|
+
}
|
|
1290
|
+
},
|
|
1291
|
+
{ maxAttempts: 3 }
|
|
1292
|
+
)
|
|
1281
1293
|
```
|
|
1282
1294
|
|
|
1283
1295
|
### 6. Use Appropriate Timeouts
|
|
1296
|
+
|
|
1284
1297
|
```typescript
|
|
1285
1298
|
export const MyWorkflow = new Workflow({
|
|
1286
|
-
timeout:
|
|
1299
|
+
timeout: '5m', // Balance completion time and resources
|
|
1287
1300
|
// ...
|
|
1288
|
-
})
|
|
1301
|
+
})
|
|
1289
1302
|
```
|
|
1290
1303
|
|
|
1291
1304
|
## Complete Example: Research Workflow
|
|
1292
1305
|
|
|
1293
1306
|
```typescript
|
|
1294
|
-
import { Workflow, z, Autonomous } from
|
|
1295
|
-
import { actions } from
|
|
1307
|
+
import { Workflow, z, Autonomous } from '@botpress/runtime'
|
|
1308
|
+
import { actions } from '@botpress/runtime'
|
|
1296
1309
|
|
|
1297
1310
|
export const ResearchWorkflow = new Workflow({
|
|
1298
|
-
name:
|
|
1299
|
-
description:
|
|
1311
|
+
name: 'research',
|
|
1312
|
+
description: 'Research a topic using web searches',
|
|
1300
1313
|
|
|
1301
1314
|
input: z.object({
|
|
1302
1315
|
topic: z.string(),
|
|
1303
|
-
conversationId: z.string()
|
|
1316
|
+
conversationId: z.string(),
|
|
1304
1317
|
}),
|
|
1305
1318
|
|
|
1306
1319
|
state: z.object({
|
|
1307
1320
|
sources: z.array(z.string()).default([]),
|
|
1308
|
-
progress: z.string().default(
|
|
1321
|
+
progress: z.string().default('Starting...'),
|
|
1309
1322
|
}),
|
|
1310
1323
|
|
|
1311
1324
|
output: z.object({
|
|
1312
|
-
report: z.string()
|
|
1325
|
+
report: z.string(),
|
|
1313
1326
|
}),
|
|
1314
1327
|
|
|
1315
1328
|
async handler({ input, state, execute, step, client }) {
|
|
1316
1329
|
// Notify start
|
|
1317
|
-
await step(
|
|
1330
|
+
await step('notify-start', async () => {
|
|
1318
1331
|
await client.createMessage({
|
|
1319
1332
|
conversationId: input.conversationId,
|
|
1320
|
-
type:
|
|
1321
|
-
payload: { text: `🔍 Researching "${input.topic}"...` }
|
|
1322
|
-
})
|
|
1323
|
-
})
|
|
1333
|
+
type: 'text',
|
|
1334
|
+
payload: { text: `🔍 Researching "${input.topic}"...` },
|
|
1335
|
+
})
|
|
1336
|
+
})
|
|
1324
1337
|
|
|
1325
1338
|
// Define search tool
|
|
1326
1339
|
const SearchTool = new Autonomous.Tool({
|
|
1327
|
-
name:
|
|
1328
|
-
description:
|
|
1340
|
+
name: 'webSearch',
|
|
1341
|
+
description: 'Search the web',
|
|
1329
1342
|
input: z.object({ query: z.string() }),
|
|
1330
1343
|
output: z.string(),
|
|
1331
1344
|
async handler({ query }) {
|
|
1332
1345
|
const results = await actions.browser.webSearch({
|
|
1333
1346
|
query,
|
|
1334
|
-
count: 5
|
|
1335
|
-
})
|
|
1336
|
-
state.sources.push(...results.urls)
|
|
1337
|
-
throw new Autonomous.ThinkSignal(
|
|
1338
|
-
}
|
|
1339
|
-
})
|
|
1347
|
+
count: 5,
|
|
1348
|
+
})
|
|
1349
|
+
state.sources.push(...results.urls) // State accessible in closure
|
|
1350
|
+
throw new Autonomous.ThinkSignal('Found sources', results)
|
|
1351
|
+
},
|
|
1352
|
+
})
|
|
1340
1353
|
|
|
1341
1354
|
// Define report exit
|
|
1342
1355
|
const ReportExit = new Autonomous.Exit({
|
|
1343
|
-
name:
|
|
1344
|
-
description:
|
|
1345
|
-
schema: z.string()
|
|
1346
|
-
})
|
|
1356
|
+
name: 'Report',
|
|
1357
|
+
description: 'Final research report',
|
|
1358
|
+
schema: z.string(),
|
|
1359
|
+
})
|
|
1347
1360
|
|
|
1348
1361
|
// Execute research
|
|
1349
|
-
const report = await step(
|
|
1350
|
-
state.progress =
|
|
1362
|
+
const report = await step('research', async () => {
|
|
1363
|
+
state.progress = 'Researching...' // Update state
|
|
1351
1364
|
|
|
1352
1365
|
const result = await execute({
|
|
1353
1366
|
instructions: `Research "${input.topic}".
|
|
@@ -1355,32 +1368,33 @@ export const ResearchWorkflow = new Workflow({
|
|
|
1355
1368
|
Compile findings into a comprehensive report.`,
|
|
1356
1369
|
tools: [SearchTool],
|
|
1357
1370
|
exits: [ReportExit],
|
|
1358
|
-
iterations: 15
|
|
1359
|
-
})
|
|
1371
|
+
iterations: 15,
|
|
1372
|
+
})
|
|
1360
1373
|
|
|
1361
1374
|
if (result.is(ReportExit)) {
|
|
1362
|
-
return result.output
|
|
1375
|
+
return result.output
|
|
1363
1376
|
}
|
|
1364
|
-
return
|
|
1365
|
-
})
|
|
1377
|
+
return 'Research incomplete'
|
|
1378
|
+
})
|
|
1366
1379
|
|
|
1367
1380
|
// Send report
|
|
1368
|
-
await step(
|
|
1381
|
+
await step('send-report', async () => {
|
|
1369
1382
|
await client.createMessage({
|
|
1370
1383
|
conversationId: input.conversationId,
|
|
1371
|
-
type:
|
|
1372
|
-
payload: { text: `📄 Research Report:\n\n${report}` }
|
|
1373
|
-
})
|
|
1374
|
-
})
|
|
1384
|
+
type: 'text',
|
|
1385
|
+
payload: { text: `📄 Research Report:\n\n${report}` },
|
|
1386
|
+
})
|
|
1387
|
+
})
|
|
1375
1388
|
|
|
1376
|
-
return { report }
|
|
1377
|
-
}
|
|
1378
|
-
})
|
|
1389
|
+
return { report }
|
|
1390
|
+
},
|
|
1391
|
+
})
|
|
1379
1392
|
```
|
|
1380
1393
|
|
|
1381
1394
|
## Workflow Lifecycle
|
|
1382
1395
|
|
|
1383
1396
|
### Status Values
|
|
1397
|
+
|
|
1384
1398
|
- `pending`: Created but not started
|
|
1385
1399
|
- `in_progress`: Currently executing
|
|
1386
1400
|
- `completed`: Finished successfully
|
|
@@ -1391,6 +1405,7 @@ export const ResearchWorkflow = new Workflow({
|
|
|
1391
1405
|
When a workflow reaches a terminal status (`completed`, `failed`, `cancelled`, `timedout`), the associated conversation handler receives a `workflow_callback` event. Use `type === "workflow_callback"` in the conversation handler to react to these transitions — see [Handling Workflow Completion in Conversations](#4-handling-workflow-completion-in-conversations).
|
|
1392
1406
|
|
|
1393
1407
|
### Managing Lifecycle
|
|
1408
|
+
|
|
1394
1409
|
```typescript
|
|
1395
1410
|
// Check status
|
|
1396
1411
|
const instance = await MyWorkflow.getOrCreate({ key: userId, input: { /* ... */ } });
|