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

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

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

    类型参数

    • ArgsT extends unknown[]

      任务函数接受的参数类型

    • OutputT

      任务函数返回的值的类型

    参数

    • optionsOrName: string | TaskOptions

      TaskOptions 对象,或任务名称的字符串

    • func: TaskFunc<ArgsT, 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;
    });