workflow
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCRITICAL: Always Use Correct workflow
Documentation
workflow重要提示: 始终使用正确的workflow
文档
workflowYour knowledge of is outdated.
workflowThe documentation outlined below matches the installed version of the Workflow DevKit.
Follow these instructions before starting on any -related tasks:
workflowworkflowSearch the bundled documentation in :
node_modules/workflow/docs/- Find docs:
glob "node_modules/workflow/docs/**/*.mdx" - Search content:
grep "your query" node_modules/workflow/docs/
Documentation structure in :
node_modules/workflow/docs/- - Framework setup (next.mdx, express.mdx, hono.mdx, etc.)
getting-started/ - - Core concepts (workflows-and-steps.mdx, hooks.mdx, streaming.mdx, etc.)
foundations/ - - API docs (sleep.mdx, create-hook.mdx, fatal-error.mdx, etc.)
api-reference/workflow/ - - Client API (start.mdx, get-run.mdx, resume-hook.mdx, etc.)
api-reference/workflow-api/ - - AI SDK integration docs
ai/ - - Error code documentation
errors/
Related packages also include bundled docs:
- :
@workflow/ai- DurableAgent and AI integrationnode_modules/@workflow/ai/docs/ - :
@workflow/core- Core runtime (foundations, how-it-works)node_modules/@workflow/core/docs/ - :
@workflow/next- Next.js integrationnode_modules/@workflow/next/docs/
When in doubt, update to the latest version of the Workflow DevKit.
你所掌握的知识已过时。
workflow以下列出的文档与已安装的Workflow DevKit版本匹配。在开始任何与相关的任务前,请遵循以下说明:
workflowworkflow在中搜索捆绑的文档:
node_modules/workflow/docs/- 查找文档:
glob "node_modules/workflow/docs/**/*.mdx" - 搜索内容:
grep "your query" node_modules/workflow/docs/
node_modules/workflow/docs/- - 框架设置(next.mdx、express.mdx、hono.mdx等)
getting-started/ - - 核心概念(workflows-and-steps.mdx、hooks.mdx、streaming.mdx等)
foundations/ - - API文档(sleep.mdx、create-hook.mdx、fatal-error.mdx等)
api-reference/workflow/ - - 客户端API(start.mdx、get-run.mdx、resume-hook.mdx等)
api-reference/workflow-api/ - - AI SDK集成文档
ai/ - - 错误码文档
errors/
相关包也包含捆绑文档:
- :
@workflow/ai- DurableAgent与AI集成node_modules/@workflow/ai/docs/ - :
@workflow/core- 核心运行时(基础原理、工作机制)node_modules/@workflow/core/docs/ - :
@workflow/next- Next.js集成node_modules/@workflow/next/docs/
如有疑问,请更新到Workflow DevKit的最新版本。
Official Resources
官方资源
- Website: https://useworkflow.dev
- GitHub: https://github.com/vercel/workflow
Quick Reference
快速参考
Directives:
typescript
"use workflow"; // First line - makes async function durable
"use step"; // First line - makes function a cached, retryable unitEssential imports:
typescript
// Workflow primitives
import { sleep, fetch, createHook, createWebhook, getWritable } from "workflow";
import { FatalError, RetryableError } from "workflow";
import { getWorkflowMetadata, getStepMetadata } from "workflow";
// API operations
import { start, getRun, resumeHook, resumeWebhook } from "workflow/api";
// Framework integrations
import { withWorkflow } from "workflow/next";
import { workflow } from "workflow/vite";
import { workflow } from "workflow/astro";
// Or use modules: ["workflow/nitro"] for Nitro/Nuxt指令:
typescript
"use workflow"; // 第一行 - 使异步函数具备持久化能力
"use step"; // 第一行 - 使函数成为可缓存、可重试的单元必要导入:
typescript
// Workflow原语
import { sleep, fetch, createHook, createWebhook, getWritable } from "workflow";
import { FatalError, RetryableError } from "workflow";
import { getWorkflowMetadata, getStepMetadata } from "workflow";
// API操作
import { start, getRun, resumeHook, resumeWebhook } from "workflow/api";
// 框架集成
import { withWorkflow } from "workflow/next";
import { workflow } from "workflow/vite";
import { workflow } from "workflow/astro";
// 或使用模块:["workflow/nitro"] 用于Nitro/NuxtPrefer Step Functions to Avoid Sandbox Errors
优先使用Step函数以避免沙箱错误
"use workflow""use step"typescript
// Steps have full Node.js and npm access
async function fetchUserData(userId: string) {
"use step";
const response = await fetch(`https://api.example.com/users/${userId}`);
return response.json();
}
async function processWithAI(data: any) {
"use step";
// AI SDK works in steps without workarounds
return await generateText({
model: openai("gpt-4"),
prompt: `Process: ${JSON.stringify(data)}`,
});
}
// Workflow orchestrates steps - no sandbox issues
export async function dataProcessingWorkflow(userId: string) {
"use workflow";
const data = await fetchUserData(userId);
const processed = await processWithAI(data);
return { success: true, processed };
}Benefits: Steps have automatic retry, results are persisted for replay, and no sandbox restrictions.
"use workflow""use step"typescript
// Step拥有完整的Node.js和npm访问权限
async function fetchUserData(userId: string) {
"use step";
const response = await fetch(`https://api.example.com/users/${userId}`);
return response.json();
}
async function processWithAI(data: any) {
"use step";
// AI SDK在step中无需变通即可工作
return await generateText({
model: openai("gpt-4"),
prompt: `Process: ${JSON.stringify(data)}`,
});
}
// Workflow编排step - 无沙箱问题
export async function dataProcessingWorkflow(userId: string) {
"use workflow";
const data = await fetchUserData(userId);
const processed = await processWithAI(data);
return { success: true, processed };
}优势: Step具备自动重试功能,结果会被持久化以便重放,且无沙箱限制。
Workflow Sandbox Limitations
Workflow沙箱限制
When you need logic directly in a workflow function (not in a step), these restrictions apply:
| Limitation | Workaround |
|---|---|
No | |
No | Use |
| No Node.js modules (fs, crypto, etc.) | Move to a step function |
Example - Using fetch in workflow context:
typescript
import { fetch } from "workflow";
export async function myWorkflow() {
"use workflow";
globalThis.fetch = fetch; // Required for AI SDK and HTTP libraries
// Now generateText() and other libraries work
}Note: from handles the fetch assignment automatically.
DurableAgent@workflow/ai当你需要在workflow函数中直接编写逻辑(而非step中)时,以下限制适用:
| 限制 | 解决方法 |
|---|---|
无 | 从 |
无 | 使用 |
| 无Node.js模块(fs、crypto等) | 移至step函数中 |
示例 - 在workflow上下文中使用fetch:
typescript
import { fetch } from "workflow";
export async function myWorkflow() {
"use workflow";
globalThis.fetch = fetch; // AI SDK和HTTP库需要此设置
// 现在generateText()和其他库可以正常工作
}注意: 中的会自动处理fetch的赋值。
@workflow/aiDurableAgentError Handling
错误处理
Use for permanent failures (no retry), for transient failures:
FatalErrorRetryableErrortypescript
import { FatalError, RetryableError } from "workflow";
if (res.status >= 400 && res.status < 500) {
throw new FatalError(`Client error: ${res.status}`);
}
if (res.status === 429) {
throw new RetryableError("Rate limited", { retryAfter: "5m" });
}对于永久性失败(不重试)使用,对于暂时性失败使用:
FatalErrorRetryableErrortypescript
import { FatalError, RetryableError } from "workflow";
if (res.status >= 400 && res.status < 500) {
throw new FatalError(`客户端错误:${res.status}`);
}
if (res.status === 429) {
throw new RetryableError("请求受限", { retryAfter: "5m" });
}Serialization
序列化
All data passed to/from workflows and steps must be serializable.
Supported types: string, number, boolean, null, undefined, bigint, plain objects, arrays, Date, RegExp, URL, URLSearchParams, Map, Set, Headers, ArrayBuffer, typed arrays, Request, Response, ReadableStream, WritableStream.
Not supported: Functions, class instances, Symbols, WeakMap/WeakSet. Pass data, not callbacks.
所有在workflow与step之间传递的数据必须可序列化。
支持的类型: 字符串、数字、布尔值、null、undefined、bigint、普通对象、数组、Date、RegExp、URL、URLSearchParams、Map、Set、Headers、ArrayBuffer、类型化数组、Request、Response、ReadableStream、WritableStream。
不支持的类型: 函数、类实例、Symbol、WeakMap/WeakSet。传递数据,而非回调函数。
Streaming
流式处理
Use in step functions to stream data:
getWritable()typescript
async function streamData() {
"use step"; // Required - streaming only works in steps
const writer = getWritable();
await writer.write(data);
writer.releaseLock(); // Always release the lock
}
// Close when done
await getWritable().close();在step函数中使用进行流式数据传输:
getWritable()typescript
async function streamData() {
"use step"; // 必须设置 - 流式处理仅在step中生效
const writer = getWritable();
await writer.write(data);
writer.releaseLock(); // 务必释放锁
}
// 完成后关闭
await getWritable().close();Debugging
调试
bash
undefinedbash
undefinedCheck workflow endpoints are reachable
检查工作流端点是否可达
npx workflow health
npx workflow health --port 3001 # Non-default port
npx workflow health
npx workflow health --port 3001 # 非默认端口
Visual dashboard for runs
运行实例的可视化仪表板
npx workflow web
npx workflow web --app-url http://localhost:3001
npx workflow web
npx workflow web --app-url http://localhost:3001
CLI inspection (for agents)
CLI检查(适用于代理)
npx workflow inspect runs
npx workflow inspect run <run_id>
**Tip:** Only import workflow APIs you actually use. Unused imports can cause 500 errors.npx workflow inspect runs
npx workflow inspect run <run_id>
**提示:** 仅导入实际使用的workflow API。未使用的导入可能导致500错误。",