以编程方式使用文档

本页面介绍如何创建、配置和管理 助手。助手允许您通过配置来自定义 已部署 图的运行行为——如模型选择、提示词和工具可用性——而无需更改底层图代码。

您可以通过 SDKLangSmith UI.

了解助手配置

助手存储 _上下文_ 值,用于在运行时自定义图的行为。您需要在图代码中定义一个上下文模式,然后在通过 context 参数 创建助手时提供特定的上下文值。

考虑这个 call_model 节点的示例,它从 model_name 中读取上下文:

class ContextSchema(TypedDict):
    model_name: str

builder = StateGraph(AgentState, context_schema=ContextSchema)

def call_model(state, runtime: Runtime[ContextSchema]):
    messages = state["messages"]
    model = _get_model(runtime.context.get("model_name", "anthropic"))
    response = model.invoke(messages)
    return {"messages": [response]}
const ContextSchema = Annotation.Root({
    model_name: Annotation<string>,
    system_prompt: Annotation<string>,
});

const builder = new StateGraph(AgentState, ContextSchema)

function callModel(state: State, runtime: Runtime[ContextSchema]) {
  const messages = state.messages;
  const model = _getModel(runtime.context.model_name ?? "anthropic");
  const response = model.invoke(messages);
  return { messages: [response] };
}

当您创建助手时,需要为这些配置字段提供特定的值。助手会存储此配置,并在图运行时应用它。

有关 LangGraph中配置的更多信息,请参阅 运行时上下文文档.

选择 SDK 或 UI 作为您的工作流程:

SDK

创建助手

使用 AssistantsClient.create 方法创建新助手。此方法需要: - **图 ID**:此助手将使用的已部署图的名称(例如, "agent"). - **上下文**:与图的上下文模式匹配的配置值。 - **名称**:助手的描述性名称。

以下示例创建一个助手, model_name 设置为 openai:

from langgraph_sdk import get_client

# Initialize the client with your deployment URL
client = get_client(url=)

# Create an assistant for the "agent" graph
# The first parameter is the graph ID (also called graph name)
openai_assistant = await client.assistants.create(
    "agent",  # Graph ID of the deployed graph
    context={"model_name": "openai"},
    name="Open AI Assistant"
)

print(openai_assistant)
# Output includes the assistant_id (UUID) that uniquely identifies this assistant
// Initialize the client with your deployment URL
const client = new Client({ apiUrl:  });

// Create an assistant for the "agent" graph
const openAIAssistant = await client.assistants.create({
    graphId: 'agent',  // Graph ID of the deployed graph
    name: "Open AI Assistant",
    context: { "model_name": "openai" },
});

console.log(openAIAssistant);
// Output includes the assistant_id (UUID) that uniquely identifies this assistant
curl --request POST \
    --url /assistants \
    --header 'Content-Type: application/json' \
    --data '{"graph_id":"agent", "context":{"model_name":"openai"}, "name": "Open AI Assistant"}'

Response:

API 返回一个包含以下内容的助手对象: - assistant_id:唯一标识此助手的 UUID - graph_id:此助手配置的图 - context:您提供的配置值 - name, metadata、时间戳和其他字段

{
  "assistant_id": "62e209ca-9154-432a-b9e9-2d75c7a9219b",
  "graph_id": "agent",
  "name": "Open AI Assistant",
  "context": {
    "model_name": "openai"
  },
  "metadata": {},
  "created_at": "2024-08-31T03:09:10.230718+00:00",
  "updated_at": "2024-08-31T03:09:10.230718+00:00"
}

assistant_id (UUID 如 "62e209ca-9154-432a-b9e9-2d75c7a9219b")唯一标识此助手配置。运行图时,您将使用此 ID 来指定要应用哪个配置。

使用助手

要使用助手,请传递其 assistant_id 在创建运行时。以下示例使用我们上面创建的助手:

# Create a thread for the conversation
thread = await client.threads.create()

# Prepare the input
input = {"messages": [{"role": "user", "content": "who made you?"}]}

# Run the graph using the assistant's configuration
# Pass the assistant_id (UUID) as the second parameter
async for event in client.runs.stream(
    thread["thread_id"],
    openai_assistant["assistant_id"],  # Assistant ID (UUID)
    input=input,
    stream_mode="updates",
):
    print(f"Receiving event of type: {event.event}")
    print(event.data)
    print("\n\n")
// Create a thread for the conversation
const thread = await client.threads.create();

// Prepare the input
const input = { "messages": [{ "role": "user", "content": "who made you?" }] };

// Run the graph using the assistant's configuration
// Pass the assistant_id (UUID) as the second parameter
const streamResponse = client.runs.stream(
  thread["thread_id"],
  openAIAssistant["assistant_id"],  // Assistant ID (UUID)
  {
    input,
    streamMode: "updates"
  }
);

for await (const event of streamResponse) {
  console.log(`Receiving event of type: ${event.event}`);
  console.log(event.data);
  console.log("\n\n");
}
# First, create a thread
thread_id=$(curl --request POST \
    --url /threads \
    --header 'Content-Type: application/json' \
    --data '{}' | jq -r '.thread_id')

# Run the graph with the assistant ID (UUID)
curl --request POST \
    --url "/threads/${thread_id}/runs/stream" \
    --header 'Content-Type: application/json' \
    --data '{
        "assistant_id": "",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": "who made you?"
                }
            ]
        },
        "stream_mode": ["updates"]
    }' | \
    sed 's/\r$//' | \
    awk '
    /^event:/ {
        if (data_content != "") {
            print data_content "\n"
        }
        sub(/^event: /, "Receiving event of type: ", $0)
        printf "%s...\n", $0
        data_content = ""
    }
    /^data:/ {
        sub(/^data: /, "", $0)
        data_content = $0
    }
    END {
        if (data_content != "") {
            print data_content "\n\n"
        }
    }
'

Response:

流在图执行时返回事件,使用您的助手配置:

Receiving event of type: metadata
{'run_id': '1ef6746e-5893-67b1-978a-0f1cd4060e16'}

Receiving event of type: updates
{'agent': {'messages': [{'content': 'I was created by OpenAI...', ...}]}}

为您的助手创建新版本

使用 AssistantsClient.update 方法创建助手的新版本。

例如,要向助手添加系统提示:

# Update the assistant with a new configuration
# IMPORTANT: Include ALL configuration fields, not just the ones you're changing
openai_assistant_v2 = await client.assistants.update(
    openai_assistant["assistant_id"],  # Assistant ID (UUID)
    context={
          "model_name": "openai",  # Must include existing fields
          "system_prompt": "You are a mindful assistant!",  # New field
    },
)

# This creates version 2 and sets it as the active version
# Future runs using this assistant_id will use version 2
// Update the assistant with a new configuration
// IMPORTANT: Include ALL configuration fields, not just the ones you're changing
const openaiAssistantV2 = await client.assistants.update(
    openAIAssistant["assistant_id"],  // Assistant ID (UUID)
    {
        context: {
            model_name: 'openai',  // Must include existing fields
            system_prompt: 'You are a mindful assistant!',  // New field
        },
    },
);

// This creates version 2 and sets it as the active version
// Future runs using this assistant_id will use version 2
curl --request PATCH \
--url /assistants/ \
--header 'Content-Type: application/json' \
--data '{
"context": {"model_name": "openai", "system_prompt": "You are a mindful assistant!"}
}'

更新会创建一个新版本并自动将其设为活跃版本。所有未来使用此助手 ID 的运行都将使用新配置。

使用之前的助手版本

使用 setLatest 方法更改活跃版本:

# Roll back to version 1 of the assistant
await client.assistants.set_latest(
    openai_assistant['assistant_id'],  # Assistant ID (UUID)
    1  # Version number
)

# All future runs using this assistant_id will now use version 1
// Roll back to version 1 of the assistant
await client.assistants.setLatest(
    openaiAssistant['assistant_id'],  // Assistant ID (UUID)
    1  // Version number
);

// All future runs using this assistant_id will now use version 1
curl --request POST \
--url /assistants//latest \
--header 'Content-Type: application/json' \
--data '{
"version": 1
}'

更改活跃版本后,所有使用此助手 ID 的运行都将使用指定版本的配置。

UI

创建助手

您可以从 LangSmith UI:

1. 导航到您的部署并选择 **助手** tab. 1. 点击 **+ 新建助手**. 1. 在打开的表单中: - 选择此助手对应的图。 - 提供名称和描述。 - 使用该图的配置架构配置助手。 1. 点击 **创建助手**.

这将带您进入 Studio 您可以在此处测试助手。返回 **助手** 标签页查看表格中新创建的助手。

使用助手

在 LangSmith UI 中使用助手:

  1. 导航到您的部署并选择 **助手** tab.
  2. 找到您想使用的助手。
  3. 点击 **Studio** 用于该助手。

这将打开 Studio 并使用选定的助手。当您提交输入时(在 **Graph** or **Chat** 模式下),助手的配置将被应用到运行中。

为您的助手创建新版本

要从 UI 更新助手并创建新版本,您可以使用助手标签页或 Studio。两种方法都会创建新版本并将其设为活动版本:

1. 导航到您的部署并选择 **Assistants** tab. 1. 找到您要编辑的助手。 1. 点击 **编辑**. 1. 修改助手的名称、描述或配置。 1. 保存您的更改。

Studio

1. 为助手打开 Studio。 1. 点击 **管理助手**. 1. 编辑助手的配置。 1. 保存您的更改。

使用之前的助手版本

要从 Studio 将之前的版本设为活动版本:

  1. 为助手打开 Studio。
  2. 点击 **管理助手**.
  3. 找到助手并选择您要使用的版本。
  4. 切换该版本的 **活动** 开关。

这将更新助手以在所有未来的运行中使用选定的版本。