跳转至

拒绝

本指南假定你了解什么是双重文本,你可以在双重文本概念指南中了解相关内容。

本指南介绍双重文本的 reject 选项,它通过抛出错误拒绝图的新运行,并继续原始运行直到完成。下面是使用 reject 选项的快速示例。

设置

首先,我们将定义一个用于打印 JS 和 CURL 模型输出的快速辅助函数(如果使用 Python,可以跳过此步骤):

function prettyPrint(m) {
  const padded = " " + m['type'] + " ";
  const sepLen = Math.floor((80 - padded.length) / 2);
  const sep = "=".repeat(sepLen);
  const secondSep = sep + (padded.length % 2 ? "=" : "");

  console.log(`${sep}${padded}${secondSep}`);
  console.log("\n\n");
  console.log(m.content);
}
# PLACE THIS IN A FILE CALLED pretty_print.sh
pretty_print() {
  local type="$1"
  local content="$2"
  local padded=" $type "
  local total_width=80
  local sep_len=$(( (total_width - ${#padded}) / 2 ))
  local sep=$(printf '=%.0s' $(eval "echo {1.."${sep_len}"}"))
  local second_sep=$sep
  if (( (total_width - ${#padded}) % 2 )); then
    second_sep="${second_sep}="
  fi

  echo "${sep}${padded}${second_sep}"
  echo
  echo "$content"
}

现在,让我们导入所需的包并实例化客户端、助手和线程。

import httpx
from langchain_core.messages import convert_to_messages
from langgraph_sdk import get_client

client = get_client(url=<DEPLOYMENT_URL>)
# Using the graph deployed with the name "agent"
assistant_id = "agent"
thread = await client.threads.create()
import { Client } from "@langchain/langgraph-sdk";

const client = new Client({ apiUrl: <DEPLOYMENT_URL> });
// Using the graph deployed with the name "agent"
const assistantId = "agent";
const thread = await client.threads.create();
curl --request POST \
  --url <DEPLOYMENT_URL>/threads \
  --header 'Content-Type: application/json' \
  --data '{}'

创建运行

现在我们可以运行一个线程并尝试使用"reject"选项运行第二个,由于我们已经启动了一个运行,这应该会失败:

run = await client.runs.create(
    thread["thread_id"],
    assistant_id,
    input={"messages": [{"role": "user", "content": "what's the weather in sf?"}]},
)
try:
    await client.runs.create(
        thread["thread_id"],
        assistant_id,
        input={
            "messages": [{"role": "user", "content": "what's the weather in nyc?"}]
        },
        multitask_strategy="reject",
    )
except httpx.HTTPStatusError as e:
    print("Failed to start concurrent run", e)
const run = await client.runs.create(
  thread["thread_id"],
  assistantId,
  input={"messages": [{"role": "user", "content": "what's the weather in sf?"}]},
);

try {
  await client.runs.create(
    thread["thread_id"],
    assistantId,
    {
      input: {"messages": [{"role": "user", "content": "what's the weather in nyc?"}]},
      multitask_strategy:"reject"
    },
  );
} catch (e) {
  console.error("Failed to start concurrent run", e);
}
curl --request POST \
--url <DEPLOY<ENT_URL>>/threads/<THREAD_ID>/runs \
--header 'Content-Type: application/json' \
--data "{
  \"assistant_id\": \"agent\",
  \"input\": {\"messages\": [{\"role\": \"human\", \"content\": \"what\'s the weather in sf?\"}]},
}" && curl --request POST \
--url <DEPLOY<ENT_URL>>/threads/<THREAD_ID>/runs \
--header 'Content-Type: application/json' \
--data "{
  \"assistant_id\": \"agent\",
  \"input\": {\"messages\": [{\"role\": \"human\", \"content\": \"what\'s the weather in nyc?\"}]},
  \"multitask_strategy\": \"reject\"
}" || { echo "Failed to start concurrent run"; echo "Error: $?" >&2; }

输出:

Failed to start concurrent run Client error '409 Conflict' for url 'http://localhost:8123/threads/f9e7088b-8028-4e5c-88d2-9cc9a2870e50/runs'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409

查看运行结果

我们可以验证原始线程已完成执行:

# wait until the original run completes
await client.runs.join(thread["thread_id"], run["run_id"])

state = await client.threads.get_state(thread["thread_id"])

for m in convert_to_messages(state["values"]["messages"]):
    m.pretty_print()
await client.runs.join(thread["thread_id"], run["run_id"]);

const state = await client.threads.getState(thread["thread_id"]);

for (const m of state["values"]["messages"]) {
  prettyPrint(m);
}
source pretty_print.sh && curl --request GET \
--url <DEPLOYMENT_URL>/threads/<THREAD_ID>/runs/<RUN_ID>/join && \
curl --request GET --url <DEPLOYMENT_URL>/threads/<THREAD_ID>/state | \
jq -c '.values.messages[]' | while read -r element; do
    type=$(echo "$element" | jq -r '.type')
    content=$(echo "$element" | jq -r '.content | if type == "array" then tostring else . end')
    pretty_print "$type" "$content"
done

输出:

================================ Human Message =================================

旧金山的天气怎么样?
================================== Ai Message ==================================

[{'id': 'toolu_01CyewEifV2Kmi7EFKHbMDr1', 'input': {'query': 'weather in san francisco'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]
Tool Calls:
  tavily_search_results_json (toolu_01CyewEifV2Kmi7EFKHbMDr1)
 Call ID: toolu_01CyewEifV2Kmi7EFKHbMDr1
  Args:
    query: weather in san francisco
================================= Tool Message =================================
Name: tavily_search_results_json

[{"url": "https://www.accuweather.com/en/us/san-francisco/94103/june-weather/347629", "content": "获取旧金山加利福尼亚州的每月天气预报,包括每日高温/低温、历史平均值,帮助你提前规划。"}]
================================== Ai Message ==================================

根据 Tavily 的搜索结果,旧金山目前的天气为:

旧金山 6 月的平均高温约为 65°F(18°C),平均低温约为 54°F(12°C)。由于夏季经常笼罩城市的海洋雾层,6 月往往是旧金山较凉爽和多雾的月份之一。

关于旧金山典型 6 月天气的一些关键点:

- 温和的温度,最高温度在华氏 60 度,最低温度在华氏 50 度
- 多雾的早晨通常会消散为晴朗的下午
- 几乎没有降雨,因为 6 月处于旱季
- 微风条件,太平洋吹来的风
- 建议穿多层衣服以应对变化的天气条件

总之,你可以预期旧金山这个时节会有温和、多雾的早晨,之后是晴朗但凉爽的下午。与加利福尼亚其他地区相比,海洋层使 6 月的温度保持温和。