首页
/ 流体工作流(Fluere)开源项目教程

流体工作流(Fluere)开源项目教程

2025-04-20 10:15:55作者:管翌锬

1. 项目介绍

流体工作流(Fluere)是一个简单、轻量级的工作流引擎,使用TypeScript开发。它具有以下特性:

  • 最小核心API(小于2KB)
  • 100% 类型安全
  • 事件驱动,流式编程
  • 支持多种JavaScript运行时/框架

流体工作流旨在提供一种简单的方式,通过事件驱动的流来管理复杂的工作流。

2. 项目快速启动

首先,确保您的系统中已安装Node.js。

安装流体工作流核心包

使用npm:

npm i @llama-flow/core

或者使用yarn:

yarn add @llama-flow/core

或者使用pnpm:

pnpm add @llama-flow/core

创建工作流

以下是创建一个简单工作流的步骤:

  1. 定义事件:
import { workflowEvent } from "@llama-flow/core";

const startEvent = workflowEvent<string>();
const stopEvent = workflowEvent<1 | -1>();
  1. 连接事件到工作流:
import { createWorkflow } from "@llama-flow/core";

const convertEvent = workflowEvent();

const workflow = createWorkflow();

workflow.handle([startEvent], (start) => {
  return convertEvent.with(Number.parseInt(start.data, 10));
});

workflow.handle([convertEvent], (convert) => {
  return stopEvent.with(convert.data > 0 ? 1 : -1);
});
  1. 触发工作流:
import { pipeline } from "node:stream/promises";

const { stream, sendEvent } = workflow.createContext();

sendEvent(startEvent.with(""));

const result = await pipeline(
  stream,
  async function (source) {
    for await (const event of source) {
      if (stopEvent.include(event)) {
        return "stop received!";
      }
    }
  }
);

console.log(result); // 输出 "stop received!"

3. 应用案例和最佳实践

并行处理

流体工作流支持简单的扇出(fan-out)工具,以并行运行多个工作流。以下是一个示例:

import { until } from "@llama-flow/core/stream/until";
import { collect } from "@llama-flow/core/stream/consumer";

let condition = false;

workflow.handle([startEvent], async (start) => {
  const { sendEvent, stream } = getContext();
  for (let i = 0; i < 10; i++) {
    sendEvent(convertEvent.with(i));
  }
  // 定义停止工作流的条件
  const results = await collect(filter(until(stream, () => condition), (ev) => convertStopEvent.includes(ev)));
  console.log(results.length); // 输出 10
  return stopEvent.with();
});

workflow.handle([convertEvent], (convert) => {
  if (convert.data === 9) {
    condition = true;
  }
  return convertStopEvent.with(/* ... */);
});

集成到服务器端

流体工作流可以作为中间件集成到任何服务器框架中,如express、hono、fastify等。以下是一个使用Hono框架的示例:

import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { createHonoHandler } from "@llama-flow/core/interrupter/hono";
import { agentWorkflow, startEvent, stopEvent } from "../workflows/tool-call-agent.js";

const app = new Hono();

app.post("/workflow", createHonoHandler(agentWorkflow, async (ctx) => {
  startEvent(await ctx.req.text());
}, stopEvent));

serve(app, (port) => {
  console.log(`Server started at http://localhost:${port}`);
});

4. 典型生态项目

目前,流体工作流(Fluere)的生态项目还比较有限,但是开发者可以根据自己的需求,结合流体工作流的特点,开发出更多符合实际应用场景的项目。社区也在持续增长中,期待更多开发者的加入和贡献。

登录后查看全文
热门项目推荐