以编程方式使用文档

在很多情况下,按计划运行助手是非常有用的。

例如,假设你正在构建一个每天运行并发送电子邮件摘要 的每日新闻助手。你可以使用定时任务每天晚上8:00运行该助手。

LangSmith Deployment 支持定时任务,这些任务按用户定义的计划运行。用户指定一个计划、一个助手和一些输入。之后,服务器将按指定的计划:

  • * 使用指定的助手创建一个新线程
  • * 将指定的输入发送到该线程

请注意,这每次都会将相同的输入发送到线程。

LangSmith Deployment API 提供了多个用于创建和管理定时任务的端点。请参阅 API 参考文档 了解更多详情。

有时候你不想基于用户交互来运行图表,而是希望按计划安排图表运行——例如,如果你希望图表为团队撰写并发送每周待办事项的电子邮件。LangSmith Deployment 允许你通过使用 Crons 客户端来做到这一点,而无需编写自己的脚本。要安排图表任务,你需要传递一个 cron 表达式 来告知客户端你希望何时运行图表。 Cron 任务在后台运行,不会干扰图表的正常调用。

设置

首先,让我们设置 SDK 客户端、助手和线程:

Python

    from langgraph_sdk import get_client

    client = get_client(url=)
    # Using the graph deployed with the name "agent"
    assistant_id = "agent"
    # create thread
    thread = await client.threads.create()
    print(thread)
    

Javascript

    const client = new Client({ apiUrl:  });
    // Using the graph deployed with the name "agent"
    const assistantId = "agent";
    // create thread
    const thread = await client.threads.create();
    console.log(thread);
    

CURL

    curl --request POST \
        --url /assistants/search \
        --header 'Content-Type: application/json' \
        --data '{
            "limit": 10,
            "offset": 0
        }' | jq -c 'map(select(.config == null or .config == {})) | .[0].graph_id' && \
    curl --request POST \
        --url /threads \
        --header 'Content-Type: application/json' \
        --data '{}'
    

Output:

{
'thread_id': '9dde5490-2b67-47c8-aa14-4bfec88af217',
'created_at': '2024-08-30T23:07:38.242730+00:00',
'updated_at': '2024-08-30T23:07:38.242730+00:00',
'metadata': {},
'status': 'idle',
'config': {},
'values': None
}

线程上的定时任务

要创建与特定线程关联的定时任务,你可以编写:

Python

    # This schedules a job to run at 15:27 (3:27PM) UTC every day
    cron_job = await client.crons.create_for_thread(
        thread["thread_id"],
        assistant_id,
        schedule="27 15 * * *",
        input={"messages": [{"role": "user", "content": "What time is it?"}]},
    )
    

Javascript

    // This schedules a job to run at 15:27 (3:27PM) UTC every day
    const cronJob = await client.crons.create_for_thread(
      thread["thread_id"],
      assistantId,
      {
        schedule: "27 15 * * *",
        input: { messages: [{ role: "user", content: "What time is it?" }] }
      }
    );
    

CURL

    curl --request POST \
        --url /threads//runs/crons \
        --header 'Content-Type: application/json' \
        --data '{
            "assistant_id": ,
        }'
    

请注意,删除 **非常** 不再有用的任务是 Cron 重要的。否则你可能会产生不必要的 LLM API 费用!你可以使用以下代码删除 Cron 任务:

Python

    await client.crons.delete(cron_job["cron_id"])
    

Javascript

    await client.crons.delete(cronJob["cron_id"]);
    

CURL

    curl --request DELETE \
        --url /runs/crons/
    

无状态定时任务

你也可以使用以下代码创建无状态定时任务。无状态定时任务每次执行时都会创建一个新线程:

Python

    # This schedules a job to run at 15:27 (3:27PM) UTC every day
    cron_job_stateless = await client.crons.create(
        assistant_id,
        schedule="27 15 * * *",
        input={"messages": [{"role": "user", "content": "What time is it?"}]},
    )
    

Javascript

    // This schedules a job to run at 15:27 (3:27PM) UTC every day
    const cronJobStateless = await client.crons.create(
      assistantId,
      {
        schedule: "27 15 * * *",
        input: { messages: [{ role: "user", content: "What time is it?" }] }
      }
    );
    

CURL

    curl --request POST \
        --url /runs/crons \
        --header 'Content-Type: application/json' \
        --data '{
            "assistant_id": ,
        }'
    

同样,使用完毕后请记得删除你的任务!

Python

    await client.crons.delete(cron_job_stateless["cron_id"])
    

Javascript

    await client.crons.delete(cronJobStateless["cron_id"]);
    

CURL

    curl --request DELETE \
        --url /runs/crons/
    

无状态定时任务的线程清理

每次触发无状态定时任务时,都会创建一个新线程。使用 on_run_completed parameter:

  • - **"delete"** (默认):运行完成后自动删除线程。
  • - **"keep"**:保留线程以供以后检索。你需要负责清理这些线程。请参阅 如何为应用程序添加 TTL 了解推荐的方法。

示例:保留线程以供以后检索

Python

    # Create a stateless cron that keeps threads after execution.
    # Configure checkpointer.ttl in langgraph.json to auto-delete old threads.
    # See: https://docs.langchain.com/langsmith/configure-ttl
    cron_job = await client.crons.create(
        assistant_id,
        schedule="27 15 * * *",
        input={"messages": [{"role": "user", "content": "Daily report"}]},
        on_run_completed="keep"
    )

    # You can later retrieve the runs and their results
    runs = await client.runs.search(
        metadata={"cron_id": cron_job["cron_id"]}
    )
    

Javascript

    // Create a stateless cron that keeps threads after execution.
    // Configure checkpointer.ttl in langgraph.json to auto-delete old threads.
    // See: https://docs.langchain.com/langsmith/configure-ttl
    const cronJob = await client.crons.create(
      assistantId,
      {
        schedule: "27 15 * * *",
        input: { messages: [{ role: "user", content: "Daily report" }] },
        onRunCompleted: "keep"
      }
    );

    // You can later retrieve the runs and their results
    const runs = await client.runs.search({
      metadata: { cron_id: cronJob["cron_id"] }
    });
    

CURL

    # Create a stateless cron that keeps threads after execution.
    # Configure checkpointer.ttl in langgraph.json to auto-delete old threads.
    # See: https://docs.langchain.com/langsmith/configure-ttl
    curl --request POST \
        --url /runs/crons \
        --header 'Content-Type: application/json' \
        --data '{
            "assistant_id": "",
            "schedule": "27 15 * * *",
            "input": {"messages": [{"role": "user", "content": "Daily report"}]},
            "on_run_completed": "keep"
        }'