2.0 KiB
2.0 KiB
以编程方式运行工作流
学习如何从代码执行您的工作流,这对于将它们集成到应用程序中至关重要。
创建工作流运行器
创建一个新文件来测试程序化执行:
// src/run-workflow.ts
import { mastra } from "./mastra";
async function runContentWorkflow() {
console.log("🚀 Running workflow programmatically...\n");
try {
// Get the workflow instance
const workflow = mastra.getWorkflow("contentWorkflow");
if (!workflow) {
throw new Error("Workflow not found");
}
// Create a run instance
const run = await workflow.createRun();
// Execute with test data
const result = await run.start({
inputData: {
content:
"Climate change is one of the most pressing challenges of our time, requiring immediate action from governments, businesses, and individuals worldwide.",
type: "blog",
},
});
if (result.status === "success") {
console.log("✅ Success!");
console.log(
"📊 Reading time:",
result.result.metadata.readingTime,
"minutes",
);
console.log("🎯 Difficulty:", result.result.metadata.difficulty);
console.log("📅 Processed at:", result.result.metadata.processedAt);
}
} catch (error) {
console.error("❌ Error:", (error as Error).message);
}
}
// Run the workflow
runContentWorkflow();
运行代码
执行您的工作流运行器:
npx tsx src/run-workflow.ts
关键方法
mastra.getWorkflow(id):按ID获取注册的工作流workflow.createRun():创建新的执行实例run.start(inputData):使用提供的数据执行工作流
返回值
start() 方法返回:
success:表示工作流是否成功完成的布尔值result:工作流的最终输出executionTime:工作流运行所需的时间
您的工作流现在可以从应用程序中的任何位置运行!接下来,您将了解错误处理。