Skip to content

拒绝

本指南假设您已经了解什么是双发短信,您可以在双发短信概念指南中了解相关内容。

本指南涵盖了双发短信的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);
}
# 将此内容放入名为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>)
# 使用名为"agent"的部署图
assistant_id = "agent"
thread = await client.threads.create()
import { Client } from "@langchain/langgraph-sdk";

const client = new Client({ apiUrl: <DEPLOYMENT_URL> });
// 使用名为"agent"的部署图
const assistantId = "agent";
const thread = await client.threads.create();
curl --request POST \
  --url <DEPLOYMENT_URL>/threads \
  --header 'Content-Type: application/json' \
  --data '{}'

创建运行

现在我们可以运行一个线程,并尝试使用“拒绝”选项运行第二个线程,这应该会失败,因为我们已经启动了一个运行:

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

查看运行结果

我们可以验证原始线程是否已执行完毕:

# 等待原始运行完成
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

输出:

================================ 人类消息 =================================

旧金山的天气怎么样?
================================== AI 消息 ==================================

[{'id': 'toolu_01CyewEifV2Kmi7EFKHbMDr1', 'input': {'query': 'weather in san francisco'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]
工具调用:
  tavily_search_results_json (toolu_01CyewEifV2Kmi7EFKHbMDr1)
 调用ID:toolu_01CyewEifV2Kmi7EFKHbMDr1
  参数:
    query: 旧金山的天气
================================= 工具消息 =================================
名称:tavily_search_results_json

[{"url": "https://www.accuweather.com/en/us/san-francisco/94103/june-weather/347629", "content": "获取旧金山每月天气预报,包括每日最高/最低温度、历史平均值,帮助您提前规划。"}]
================================== AI 消息 ==================================

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

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

关于六月旧金山天气的一些要点:

- 温和的温度,最高温度在 60 多华氏度,最低温度在 50 多华氏度
- 早晨多雾,通常在下午消散为晴天
- 几乎没有降雨,因为六月属于干旱季节
- 有风的条件,来自太平洋的风
- 推荐穿着多层衣物以应对天气变化

总结来说,您可以期待温和的早晨多雾天气,逐渐转变为晴朗但凉爽的下午天气。海洋层使得六月的温度相比加利福尼亚其他地区更为温和。

Comments