主题
管理助手
本页介绍如何创建、配置和管理助手。助手允许你通过配置——例如模型选择、提示词和工具可用性——来自定义已部署图的行为,而无需修改底层的图代码。
你可以使用 SDK 操作,也可以在 LangSmith UI 中操作。
了解助手配置
助手存储在运行时自定义图行为的 context 值。你在图代码中定义 context 模式,然后在创建助手时通过 context 参数提供具体的 context 值。
请看下面这个从 context 中读取 model_name 的 call_model 节点示例:
python
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]}javascript
import { Annotation } from "@langchain/langgraph";
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 中配置的更多信息,请参阅运行时 context 文档。
为你的工作流选择 SDK 或 UI:
创建助手
使用 assistants.create 方法创建新助手。该方法需要:
- Graph ID:该助手将要使用的已部署图的名称(例如
"agent")。 - Context:与你的图的 context 模式相匹配的配置值。
- Name:助手的描述性名称。
以下示例创建了一个 model_name 设置为 openai 的助手:
python
from langgraph_sdk import get_client
# Initialize the client with your deployment URL
client = get_client(url=<DEPLOYMENT_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 assistantjavascript
import { Client } from "@langchain/langgraph-sdk";
// Initialize the client with your deployment URL
const client = new Client({ apiUrl: <DEPLOYMENT_URL> });
// 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 assistantbash
curl --request POST \
--url <DEPLOYMENT_URL>/assistants \
--header 'Content-Type: application/json' \
--data '{"graph_id":"agent", "context":{"model_name":"openai"}, "name": "Open AI Assistant"}'响应:
API 返回一个 assistant 对象,其中包含:
assistant_id:唯一标识该助手的 UUIDgraph_id:该助手所配置的图context:你提供的配置值name、metadata、时间戳及其他字段
json
{
"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(形如 "62e209ca-9154-432a-b9e9-2d75c7a9219b" 的 UUID)唯一标识该助手配置。运行图时,你将使用这个 ID 来指定应用哪个配置。
NOTE
Graph ID 与 Assistant ID
创建助手时,你需要指定 graph ID(图名称,如 "agent")。创建后会返回一个 assistant ID(UUID,如 "62e209ca...")。运行图时,两者都可以使用:
- Graph ID(例如
"agent"):使用该图的默认助手 - Assistant ID(UUID):使用特定的助手配置
相关示例请参阅使用助手。
使用助手
要使用助手,请在创建运行时传入其 assistant_id。下面的示例使用的是我们上面创建的助手:
python
# 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")javascript
// 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");
}bash
# First, create a thread
thread_id=$(curl --request POST \
--url <DEPLOYMENT_URL>/threads \
--header 'Content-Type: application/json' \
--data '{}' | jq -r '.thread_id')
# Run the graph with the assistant ID (UUID)
curl --request POST \
--url "<DEPLOYMENT_URL>/threads/${thread_id}/runs/stream" \
--header 'Content-Type: application/json' \
--data '{
"assistant_id": "<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"
}
}
'响应:
流式输出会在图按你的助手配置执行时返回事件:
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...', ...}]}}NOTE
使用图 ID 还是助手 ID
运行图时,你既可以传入图 ID,也可以传入助手 ID:
python
# Option 1: Use graph ID to get the default assistant
client.runs.stream(thread_id, "agent", input=input)
# Option 2: Use assistant ID (UUID) for a specific configuration
client.runs.stream(thread_id, "62e209ca-9154-432a-b9e9-2d75c7a9219b", input=input)为助手创建新版本
使用 assistants.update 方法可以为助手创建一个新版本。
WARNING
更新需要提供完整配置
更新时必须提供完整的配置。更新接口会从零开始创建新版本,不会与之前的版本合并。请包含你希望保留的所有配置字段。
例如,为助手添加系统提示词:
python
# 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 2javascript
// 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 2bash
curl --request PATCH \
--url <DEPLOYMENT_URL>/assistants/<ASSISTANT_ID> \
--header 'Content-Type: application/json' \
--data '{
"context": {"model_name": "openai", "system_prompt": "You are a mindful assistant!"}
}'该更新会创建一个新版本,并自动将其设为活动版本。此后所有使用该助手 ID 的运行都将采用新的配置。
使用之前的助手版本
使用 setLatest 方法可以更改哪个版本处于活动状态:
python
# 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 1javascript
// 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 1bash
curl --request POST \
--url <DEPLOYMENT_URL>/assistants/<ASSISTANT_ID>/latest \
--header 'Content-Type: application/json' \
--data '{
"version": 1
}'更改活动版本后,所有使用该助手 ID 的运行都将使用指定版本的配置。