• 使用 task 函数定义 LangGraph 任务。

    任务只能从 entrypoint 内部或 StateGraph 内部调用。任务可以像常规函数一样调用,但有以下区别:

    • 当启用检查点时,函数输入和输出必须可序列化。
    • 包装的函数只能从 entrypoint 或 StateGraph 内部调用。
    • 调用函数会产生一个 Promise。这使得并行化任务变得容易。

    类型参数

    • ArgsT extends unknown[]

      任务函数接受的参数类型

    • OutputT

      任务函数返回值的类型

    参数

    返回 ((...args) => Promise<OutputT>)

    一个代理函数,它接受与原始函数相同的参数,并始终以 Promise 形式返回结果

    示例:基本示例

    const addOne = task("add", async (a: number) => a + 1);

    const workflow = entrypoint("example", async (numbers: number[]) => {
    const promises = numbers.map(n => addOne(n));
    const results = await Promise.all(promises);
    return results;
    });

    // Call the entrypoint
    await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]

    示例:使用重试策略

    const addOne = task({
    name: "add",
    retry: { maxAttempts: 3 }
    },
    async (a: number) => a + 1
    );

    const workflow = entrypoint("example", async (numbers: number[]) => {
    const promises = numbers.map(n => addOne(n));
    const results = await Promise.all(promises);
    return results;
    });