跳到内容

复制线程

您可能希望复制(即“fork”)现有线程,以便保留现有线程的历史记录,并创建不影响原始线程的独立运行。本指南将展示如何做到这一点。

设置

此代码假定您已经有一个要复制的线程。您可以在此处阅读有关线程是什么的内容,并在这些操作指南中学习如何在线程上流式传输运行。

SDK 初始化

首先,我们需要设置我们的客户端,以便我们可以与托管的 graph 进行通信

from langgraph_sdk import get_client
client = get_client(url="<DEPLOYMENT_URL>")
assistant_id = "agent"
thread = await client.threads.create()
import { Client } from "@langchain/langgraph-sdk";

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

复制线程

以下代码假定您要复制的线程已存在。

复制线程将创建一个新线程,该线程具有与现有线程相同的历史记录,然后允许您继续执行运行。

创建副本

copied_thread = await client.threads.copy(<THREAD_ID>)
let copiedThread = await client.threads.copy(<THREAD_ID>);
curl --request POST --url <DEPLOYMENT_URL>/threads/<THREAD_ID>/copy \
--header 'Content-Type: application/json'

验证副本

我们可以验证先前线程的历史记录是否确实正确复制过来

def remove_thread_id(d):
  if 'metadata' in d and 'thread_id' in d['metadata']:
      del d
  return d

original_thread_history = list(map(remove_thread_id,await client.threads.get_history(<THREAD_ID>)))
copied_thread_history = list(map(remove_thread_id,await client.threads.get_history(copied_thread['thread_id'])))

# Compare the two histories
assert original_thread_history == copied_thread_history
# if we made it here the assertion passed!
print("The histories are the same.")
function removeThreadId(d) {
  if (d.metadata && d.metadata.thread_id) {
    delete d.metadata.thread_id;
  }
  return d;
}

// Assuming `client.threads.getHistory(threadId)` is an async function that returns a list of dicts
async function compareThreadHistories(threadId, copiedThreadId) {
  const originalThreadHistory = (await client.threads.getHistory(threadId)).map(removeThreadId);
  const copiedThreadHistory = (await client.threads.getHistory(copiedThreadId)).map(removeThreadId);

  // Compare the two histories
  console.assert(JSON.stringify(originalThreadHistory) === JSON.stringify(copiedThreadHistory));
  // if we made it here the assertion passed!
  console.log("The histories are the same.");
}

// Example usage
compareThreadHistories(<THREAD_ID>, copiedThread.thread_id);
if diff <(
    curl --request GET --url <DEPLOYMENT_URL>/threads/<THREAD_ID>/history | jq -S 'map(del(.metadata.thread_id))'
) <(
    curl --request GET --url <DEPLOYMENT_URL>/threads/<COPIED_THREAD_ID>/history | jq -S 'map(del(.metadata.thread_id))'
) >/dev/null; then
    echo "The histories are the same."
else
    echo "The histories are different."
fi

输出

The histories are the same.