Skip to content

6.4 Assistants - 详细解读

一、概述

1.1 本节简介

在前面的课程中,我们学习了如何部署、连接和管理 LangGraph 应用。现在在 6.4 节中,我们将学习 Assistants(助手),这是一个强大的功能,允许你为同一个图创建多个"人格"或行为变体。

核心问题

  • 如何为不同场景定制相同的应用?
  • 如何管理应用的多个版本?
  • 如何让用户选择不同的助手?

1.2 什么是 Assistant?

Assistant = 图 + 配置

Assistant
├── Graph(图的实现)
│   └── task_maistro

└── Config(配置)
    ├── user_id: "lance"
    ├── todo_category: "work"
    └── task_maistro_role: "专业助手..."

类比

  • Graph(图) = 汽车的基本结构和引擎
  • Assistant(助手) = 不同的驾驶模式(运动模式、节能模式、舒适模式)

1.3 为什么需要 Assistants?

没有 Assistants 的痛点

python
# 每次都要传递配置
config = {
    "configurable": {
        "user_id": "lance",
        "todo_category": "work",
        "task_maistro_role": "你是一个专业的工作助手..."
    }
}

run = await client.runs.create(thread_id, "task_maistro", input, config=config)

有了 Assistants

python
# 创建一次,多次使用
work_assistant = await client.assistants.create(
    "task_maistro",
    config={"configurable": {...}}
)

# 以后直接使用 assistant_id
run = await client.runs.create(thread_id, work_assistant_id, input)

1.4 Assistants 的应用场景

实际场景示例

同一个任务管理图

┌──────────────────────────────────────────┐
│  Personal Assistant                      │
│  - todo_category: "personal"             │
│  - 风格:友好、鼓励                      │
│  - 用途:个人生活任务                    │
└──────────────────────────────────────────┘
┌──────────────────────────────────────────┐
│  Work Assistant                          │
│  - todo_category: "work"                 │
│  - 风格:专业、高效                      │
│  - 用途:工作任务                        │
└──────────────────────────────────────────┘
┌──────────────────────────────────────────┐
│  Family Assistant                        │
│  - todo_category: "family"               │
│  - 风格:温馨、协调                      │
│  - 用途:家庭事务                        │
└──────────────────────────────────────────┘

1.5 学习目标

通过本节学习,你将掌握:

  1. 理解 Assistants 概念

    • 什么是 assistant
    • 如何配置 assistant
    • Assistant vs 直接使用图
  2. 创建和管理 Assistants

    • 创建 assistant
    • 更新 assistant(版本控制)
    • 删除 assistant
    • 搜索 assistants
  3. 使用 Assistants

    • 使用不同的 assistants
    • 观察不同行为
    • 实际应用场景

二、准备工作

2.1 配置化的图

要使用 assistants,你的图必须支持配置化。task_maistro 已经做好了准备。

配置文件deployment/configuration.py

python
from langgraph.graph import StateGraph
from langgraph.config import Configuration

# 定义可配置的字段
class Configurable(Configuration):
    user_id: str = Field(default="default_user")
    todo_category: str = Field(default="general")
    task_maistro_role: str = Field(
        default="You are a helpful task assistant..."
    )

# 在图的节点中使用配置
def some_node(state, config):
    user_id = config["configurable"]["user_id"]
    todo_category = config["configurable"]["todo_category"]
    role = config["configurable"]["task_maistro_role"]

    # 使用这些配置...

可配置字段

  • user_id:用户标识
  • todo_category:待办类别(personal, work, family, etc.)
  • task_maistro_role:助手的系统提示词(定义行为风格)

2.2 连接到部署

python
%%capture --no-stderr
%pip install -U langgraph_sdk
python
from langgraph_sdk import get_client

url_for_cli_deployment = "http://localhost:8123"
client = get_client(url=url_for_cli_deployment)

三、创建 Assistants

3.1 创建 Personal Assistant

目标:创建一个管理个人任务的助手。

python
# 创建 personal assistant
personal_assistant = await client.assistants.create(
    "task_maistro",  # 图的名称
    config={"configurable": {"todo_category": "personal"}}
)

print(personal_assistant)

输出

python
{
    'assistant_id': 'e6ab9c39-4b56-4db9-bb39-a71484c5d408',
    'graph_id': 'task_maistro',
    'created_at': '2025-07-31T18:33:39.897312+00:00',
    'updated_at': '2025-07-31T18:33:39.897312+00:00',
    'config': {
        'configurable': {
            'todo_category': 'personal'
        }
    },
    'metadata': {},
    'version': 1,
    'name': 'Untitled',
    'description': None,
    'context': {}
}

字段说明

字段说明示例值
assistant_id助手唯一标识UUID
graph_id关联的图task_maistro
created_at创建时间ISO 8601 格式
updated_at更新时间ISO 8601 格式
config配置可配置字段
metadata元数据自定义数据
version版本号1, 2, 3, ...
name名称可选
description描述可选

3.2 更新 Assistant(版本控制)

现在让我们更新 personal assistant,添加更多配置:

python
# 定义助手的角色和风格
task_maistro_role = """You are a friendly and organized personal task assistant.
Your main focus is helping users stay on top of their personal tasks and commitments.

Specifically:
- Help track and organize personal tasks
- When providing a 'todo summary':
  1. List all current tasks grouped by deadline (overdue, today, this week, future)
  2. Highlight any tasks missing deadlines and gently encourage adding them
  3. Note any tasks that seem important but lack time estimates
- Proactively ask for deadlines when new tasks are added without them
- Maintain a supportive tone while helping the user stay accountable
- Help prioritize tasks based on deadlines and importance

Your communication style should be encouraging and helpful, never judgmental.

When tasks are missing deadlines, respond with something like "I notice [task] doesn't
have a deadline yet. Would you like to add one to help us track it better?"
"""

# 完整的配置
configurations = {
    "todo_category": "personal",
    "user_id": "lance",
    "task_maistro_role": task_maistro_role
}

# 更新 assistant
personal_assistant = await client.assistants.update(
    personal_assistant["assistant_id"],
    config={"configurable": configurations}
)

print(personal_assistant)

输出

python
{
    'assistant_id': 'e6ab9c39-4b56-4db9-bb39-a71484c5d408',  # ID 不变
    'graph_id': 'task_maistro',
    'created_at': '2025-07-31T18:33:39.908742+00:00',
    'updated_at': '2025-07-31T18:33:39.908742+00:00',  # 更新时间变了
    'config': {
        'configurable': {
            'user_id': 'lance',
            'todo_category': 'personal',
            'task_maistro_role': '...'  # 完整的角色定义
        }
    },
    'metadata': {},
    'version': 2,  # 版本号从 1 变为 2
    'name': 'Untitled',
    'description': None,
    'context': {}
}

关键点

  • assistant_id 保持不变
  • version 从 1 增加到 2
  • updated_at 更新
  • 配置被完全替换

版本控制的作用

  • 追踪 assistant 的变化
  • 可以回滚到旧版本
  • 方便 A/B 测试

3.3 创建 Work Assistant

现在创建一个完全不同的 work assistant:

python
# Work assistant 的角色定义
task_maistro_role = """You are a focused and efficient work task assistant.

Your main focus is helping users manage their work commitments with realistic timeframes.

Specifically:
- Help track and organize work tasks
- When providing a 'todo summary':
  1. List all current tasks grouped by deadline (overdue, today, this week, future)
  2. Highlight any tasks missing deadlines and gently encourage adding them
  3. Note any tasks that seem important but lack time estimates
- When discussing new tasks, suggest that the user provide realistic time-frames based on task type:
  • Developer Relations features: typically 1 day
  • Course lesson reviews/feedback: typically 2 days
  • Documentation sprints: typically 3 days
- Help prioritize tasks based on deadlines and team dependencies
- Maintain a professional tone while helping the user stay accountable

Your communication style should be supportive but practical.

When tasks are missing deadlines, respond with something like "I notice [task] doesn't
have a deadline yet. Based on similar tasks, this might take [suggested timeframe].
Would you like to set a deadline with this in mind?"
"""

# Work assistant 配置
configurations = {
    "todo_category": "work",
    "user_id": "lance",
    "task_maistro_role": task_maistro_role
}

# 创建 work assistant
work_assistant = await client.assistants.create(
    "task_maistro",
    config={"configurable": configurations}
)

print(work_assistant)

输出

python
{
    'assistant_id': '4b9de9bd-95ff-477f-8cd0-dee4575f4eed',  # 新的 ID
    'graph_id': 'task_maistro',
    'created_at': '2025-07-31T18:33:39.914775+00:00',
    'updated_at': '2025-07-31T18:33:39.914775+00:00',
    'config': {
        'configurable': {
            'user_id': 'lance',
            'todo_category': 'work',  # 不同的类别
            'task_maistro_role': '...'  # 不同的角色
        }
    },
    'metadata': {},
    'version': 1,  # 新 assistant,版本从 1 开始
    'name': 'Untitled',
    'description': None,
    'context': {}
}

Personal vs Work Assistant 对比

特性Personal AssistantWork Assistant
todo_categorypersonalwork
风格友好、鼓励性专业、高效
重点个人承诺、灵活性工作任务、时间管理
建议鼓励添加截止日期基于任务类型建议时间
语气永不评判支持但实际

四、管理 Assistants

4.1 搜索 Assistants

所有 assistants 都存储在 PostgreSQL 中,可以轻松搜索:

python
# 搜索所有 assistants
assistants = await client.assistants.search()

for assistant in assistants:
    print({
        'assistant_id': assistant['assistant_id'],
        'version': assistant['version'],
        'config': assistant['config']
    })

输出示例

python
{
    'assistant_id': '4b9de9bd-95ff-477f-8cd0-dee4575f4eed',
    'version': 1,
    'config': {
        'configurable': {
            'user_id': 'lance',
            'todo_category': 'work',
            'task_maistro_role': '...'
        }
    }
}
{
    'assistant_id': 'e6ab9c39-4b56-4db9-bb39-a71484c5d408',
    'version': 2,
    'config': {
        'configurable': {
            'user_id': 'lance',
            'todo_category': 'personal',
            'task_maistro_role': '...'
        }
    }
}

搜索参数

python
# 搜索特定图的 assistants
assistants = await client.assistants.search(
    graph_id="task_maistro"
)

# 限制返回数量
assistants = await client.assistants.search(
    limit=10,
    offset=0
)

4.2 删除 Assistants

可以删除不再使用的 assistants:

python
# 创建临时 assistant
temp_assistant = await client.assistants.create(
    "task_maistro",
    config={"configurable": configurations}
)

# 查看所有 assistants
assistants = await client.assistants.search()
for assistant in assistants:
    print(f"before delete: {{'assistant_id': {assistant['assistant_id']}}}")

# 删除临时 assistant
await client.assistants.delete(assistants[-1]["assistant_id"])

# 再次查看
assistants = await client.assistants.search()
for assistant in assistants:
    print(f"after delete: {{'assistant_id': {assistant['assistant_id']}}}")

输出

before delete: {'assistant_id': f79e12f9-67f2-46c2-9b5b-e7fa6ad31355}
before delete: {'assistant_id': 4b9de9bd-95ff-477f-8cd0-dee4575f4eed}
before delete: {'assistant_id': e6ab9c39-4b56-4db9-bb39-a71484c5d408}
before delete: {'assistant_id': 4a2980c5-2812-4d8e-ae62-3fb72f9ef98f}
before delete: {'assistant_id': 4955437e-b617-4a25-8470-11f49f71f388}

after delete: {'assistant_id': f79e12f9-67f2-46c2-9b5b-e7fa6ad31355}
after delete: {'assistant_id': 4b9de9bd-95ff-477f-8cd0-dee4575f4eed}
after delete: {'assistant_id': e6ab9c39-4b56-4db9-bb39-a71484c5d408}
after delete: {'assistant_id': 4a2980c5-2812-4d8e-ae62-3fb72f9ef98f}

4.3 获取特定 Assistant

python
# 通过 ID 获取 assistant
assistant = await client.assistants.get(assistant_id)

# 获取特定版本
assistant = await client.assistants.get(assistant_id, version=1)

五、使用 Assistants

5.1 设置 Assistant IDs

python
# 获取 assistants 列表
assistants = await client.assistants.search()

# 设置要使用的 assistant IDs
work_assistant_id = assistants[0]['assistant_id']
personal_assistant_id = assistants[1]['assistant_id']

5.2 使用 Work Assistant

python
from langchain_core.messages import HumanMessage
from langchain_core.messages import convert_to_messages

# 用户输入
user_input = "Create or update few ToDos: 1) Re-film Module 6, lesson 5 by end of day today. 2) Update audioUX by next Monday."

# 创建线程
thread = await client.threads.create()

# 使用 work assistant 运行
async for chunk in client.runs.stream(
    thread["thread_id"],
    work_assistant_id,  # 使用 work assistant
    input={"messages": [HumanMessage(content=user_input)]},
    stream_mode="values"
):
    if chunk.event == 'values':
        state = chunk.data
        convert_to_messages(state["messages"])[-1].pretty_print()

输出

================================ Human Message =================================
Create or update few ToDos: 1) Re-film Module 6, lesson 5 by end of day today.
2) Update audioUX by next Monday.

================================== Ai Message ==================================
I've updated your ToDo list with the tasks and deadlines you provided. Here's a
summary of your current tasks:

### Overdue
- None

### Today
- **Re-film Module 6, lesson 5**: Deadline is today by the end of the day.

### This Week
- **Update audioUX**: Deadline is next Monday, August 4th.

### Future
- **Finalize set of report generation tutorials**: Deadline is August 5th.

I noticed that the task "Update audioUX" doesn't have a time estimate yet. Based
on similar tasks, this might take about 1 day. Would you like to set a time estimate
with this in mind?

观察 Work Assistant 的行为

  • ✅ 按截止日期分组(Overdue, Today, This Week, Future)
  • ✅ 提醒缺少时间估计
  • 建议基于相似任务的时间("might take about 1 day")
  • ✅ 专业、高效的语气

5.3 Work Assistant 的"推回"行为

python
# 尝试创建已存在的任务
user_input = "Create another ToDo: Finalize set of report generation tutorials."
thread = await client.threads.create()

async for chunk in client.runs.stream(
    thread["thread_id"],
    work_assistant_id,
    input={"messages": [HumanMessage(content=user_input)]},
    stream_mode="values"
):
    if chunk.event == 'values':
        state = chunk.data
        convert_to_messages(state["messages"])[-1].pretty_print()

输出

================================ Human Message =================================
Create another ToDo: Finalize set of report generation tutorials.

================================== Ai Message ==================================
It looks like the task "Finalize set of report generation tutorials" is already
on your ToDo list with a deadline of August 5, 2025. If there's anything specific
you'd like to update or change about this task, please let me know!

行为分析

  • Work assistant 检测到任务已存在
  • 主动提醒用户,而不是创建重复任务
  • 询问是否需要更新
  • 这是因为 task_maistro_role 中定义的专业行为

5.4 添加截止日期

python
user_input = "OK, for this task let's get it done by next Tuesday."

async for chunk in client.runs.stream(
    thread["thread_id"],
    work_assistant_id,
    input={"messages": [HumanMessage(content=user_input)]},
    stream_mode="values"
):
    if chunk.event == 'values':
        state = chunk.data
        convert_to_messages(state["messages"])[-1].pretty_print()

输出

================================ Human Message =================================
OK, for this task let's get it done by next Tuesday.

================================== Ai Message ==================================
I've updated the deadline for "Finalize set of report generation tutorials" to
next Tuesday, which is August 5, 2025. If there's anything else you'd like to
adjust, feel free to let me know!

5.5 使用 Personal Assistant

现在使用 personal assistant,观察不同的行为:

python
user_input = "Create ToDos: 1) Check on swim lessons for the baby this weekend. 2) For winter travel, check AmEx points."

thread = await client.threads.create()

async for chunk in client.runs.stream(
    thread["thread_id"],
    personal_assistant_id,  # 使用 personal assistant
    input={"messages": [HumanMessage(content=user_input)]},
    stream_mode="values"
):
    if chunk.event == 'values':
        state = chunk.data
        convert_to_messages(state["messages"])[-1].pretty_print()

输出

================================ Human Message =================================
Create ToDos: 1) Check on swim lessons for the baby this weekend. 2) For winter
travel, check AmEx points.

================================== Ai Message ==================================
I've added the tasks to your ToDo list:

1. Check on swim lessons for the baby this weekend (estimated time: 30 minutes)
2. For winter travel, check AmEx points (estimated time: 45 minutes)

I notice these tasks don't have deadlines yet. Would you like to set a deadline for them?

观察 Personal Assistant 的行为

  • ✅ 友好、鼓励的语气
  • ✅ 自动估计时间
  • ✅ 温和地询问是否添加截止日期("Would you like to...")
  • ✅ 不会像 work assistant 那样建议具体时间

5.6 Personal Assistant 的 ToDo 总结

python
user_input = "Give me a todo summary."

thread = await client.threads.create()

async for chunk in client.runs.stream(
    thread["thread_id"],
    personal_assistant_id,
    input={"messages": [HumanMessage(content=user_input)]},
    stream_mode="values"
):
    if chunk.event == 'values':
        state = chunk.data
        convert_to_messages(state["messages"])[-1].pretty_print()

输出

================================ Human Message =================================
Give me a todo summary.

================================== Ai Message ==================================
Here's your current ToDo summary:

**Overdue:**
- Re-film Module 6, lesson 5 (Deadline: 2025-07-30)

**Due This Week:**
- Update audioUX (Deadline: 2025-08-04)
- Finalize set of report generation tutorials (Deadline: 2025-08-05)

**No Deadline:**
- For winter travel, check AmEx points
- Check on swim lessons for the baby this weekend

**Notes:**
- The task "Update audioUX" doesn't have a time estimate. It might be important
  to add one to better manage your time.
- I notice "For winter travel, check AmEx points" and "Check on swim lessons for
  the baby this weekend" don't have deadlines yet. Would you like to set deadlines
  for these tasks?

关键观察

  • Personal assistant 访问了 所有类别 的待办(包括 work 类别的)
  • 这是因为它使用的是 相同的 user_id("lance")
  • Store 中的数据按 (todo_category, user_id) 组织
  • Personal assistant 的 todo_category 是 "personal",但它能看到其他类别

实际应用中的解决方案

  • 方案 1:在 Store 查询时只返回特定 category 的待办
  • 方案 2:在系统提示中告诉 assistant 只关注特定类别
  • 方案 3:使用不同的 user_id 来完全隔离

六、Assistants 的高级应用

6.1 团队协作场景

python
# 创建团队的不同助手
team_manager = await client.assistants.create(
    "task_maistro",
    config={
        "configurable": {
            "user_id": "team",
            "todo_category": "team",
            "task_maistro_role": "你是团队经理助手,帮助协调团队任务..."
        }
    }
)

developer_assistant = await client.assistants.create(
    "task_maistro",
    config={
        "configurable": {
            "user_id": "developer",
            "todo_category": "development",
            "task_maistro_role": "你是开发助手,关注技术任务..."
        }
    }
)

6.2 多语言支持

python
# 中文助手
chinese_assistant = await client.assistants.create(
    "task_maistro",
    config={
        "configurable": {
            "user_id": "user_cn",
            "todo_category": "general",
            "task_maistro_role": "你是一个友好的中文任务助手..."
        }
    }
)

# 英文助手
english_assistant = await client.assistants.create(
    "task_maistro",
    config={
        "configurable": {
            "user_id": "user_en",
            "todo_category": "general",
            "task_maistro_role": "You are a friendly English task assistant..."
        }
    }
)

6.3 实验和 A/B 测试

python
# 版本 A:简短响应
assistant_v1 = await client.assistants.create(
    "task_maistro",
    config={
        "configurable": {
            "task_maistro_role": "保持回复简短,不超过 3 句话..."
        }
    }
)

# 版本 B:详细响应
assistant_v2 = await client.assistants.create(
    "task_maistro",
    config={
        "configurable": {
            "task_maistro_role": "提供详细的解释和建议..."
        }
    }
)

# 分配给不同用户测试
if user_group == "A":
    assistant_id = assistant_v1["assistant_id"]
else:
    assistant_id = assistant_v2["assistant_id"]

6.4 动态助手选择

python
async def select_assistant(user_request, client):
    """根据用户请求动态选择助手"""

    # 分析用户请求
    if "work" in user_request.lower() or "project" in user_request.lower():
        # 工作相关,使用 work assistant
        assistants = await client.assistants.search()
        work_assistants = [
            a for a in assistants
            if a['config']['configurable'].get('todo_category') == 'work'
        ]
        return work_assistants[0]['assistant_id']

    elif "family" in user_request.lower() or "home" in user_request.lower():
        # 家庭相关,使用 personal assistant
        assistants = await client.assistants.search()
        personal_assistants = [
            a for a in assistants
            if a['config']['configurable'].get('todo_category') == 'personal'
        ]
        return personal_assistants[0]['assistant_id']

    else:
        # 默认使用通用 assistant
        return "default_assistant_id"

# 使用
user_request = "Add a work task to review the quarterly report"
assistant_id = await select_assistant(user_request, client)

run = await client.runs.create(
    thread_id,
    assistant_id,
    input={"messages": [HumanMessage(content=user_request)]}
)

七、最佳实践

7.1 命名和描述

python
# 好的实践:清晰的命名和描述
personal_assistant = await client.assistants.create(
    "task_maistro",
    config={"configurable": {...}},
    metadata={
        "name": "Lance's Personal Assistant",
        "description": "Manages personal tasks with a friendly, encouraging tone",
        "category": "personal",
        "owner": "lance"
    }
)

7.2 版本管理策略

python
# 创建新 assistant 而不是更新现有的
# 这样可以保留所有历史版本

# 不好的做法:
await client.assistants.update(assistant_id, config=new_config)

# 好的做法:
new_assistant = await client.assistants.create("task_maistro", config=new_config)
# 旧 assistant 仍然可用,如果需要可以回滚

7.3 配置管理

python
# 集中管理配置
ASSISTANT_CONFIGS = {
    "personal": {
        "todo_category": "personal",
        "user_id": "lance",
        "task_maistro_role": "..."
    },
    "work": {
        "todo_category": "work",
        "user_id": "lance",
        "task_maistro_role": "..."
    },
    "family": {
        "todo_category": "family",
        "user_id": "family",
        "task_maistro_role": "..."
    }
}

# 批量创建
async def create_all_assistants(client):
    assistants = {}
    for name, config in ASSISTANT_CONFIGS.items():
        assistant = await client.assistants.create(
            "task_maistro",
            config={"configurable": config}
        )
        assistants[name] = assistant["assistant_id"]
    return assistants

7.4 错误处理

python
async def safe_create_assistant(client, graph_id, config):
    """安全创建 assistant"""
    try:
        return await client.assistants.create(graph_id, config=config)
    except Exception as e:
        logger.error(f"Failed to create assistant: {e}")
        # 返回默认 assistant 或重试
        return None

async def safe_use_assistant(client, thread_id, assistant_id, input):
    """安全使用 assistant"""
    try:
        return await client.runs.create(thread_id, assistant_id, input=input)
    except Exception as e:
        logger.error(f"Failed to use assistant {assistant_id}: {e}")
        # 回退到默认图
        return await client.runs.create(thread_id, "task_maistro", input=input)

八、常见问题和解决方案

8.1 问题:Assistant 配置未生效

现象:创建了 assistant,但行为没有变化

检查清单

  1. 图是否正确读取配置?
  2. 配置字段名是否正确?
  3. 是否使用了正确的 assistant_id?

解决方案

python
# 验证配置
assistant = await client.assistants.get(assistant_id)
print("Config:", assistant['config'])

# 验证运行时配置
run = await client.runs.create(thread_id, assistant_id, input=input)
run_details = await client.runs.get(thread_id, run["run_id"])
print("Run config:", run_details['kwargs']['config'])

8.2 问题:Assistant 之间数据混淆

现象:Personal assistant 看到 work 任务

原因:使用相同的 user_id

解决方案

python
# 方案 1:使用不同的 user_id
personal_config = {"user_id": "lance_personal", ...}
work_config = {"user_id": "lance_work", ...}

# 方案 2:在查询时过滤
def get_todos(store, user_id, category):
    namespace = ("todo", category, user_id)
    return store.search(namespace)

8.3 问题:版本管理混乱

现象:不知道使用哪个版本

解决方案

python
# 使用元数据标记版本
await client.assistants.update(
    assistant_id,
    config=config,
    metadata={
        "version_name": "v2.1-improved-suggestions",
        "changelog": "Added time estimation suggestions",
        "date": "2024-11-05"
    }
)

# 查询时查看元数据
assistants = await client.assistants.search()
for a in assistants:
    print(f"{a['assistant_id']}: {a['metadata'].get('version_name', 'unnamed')}")

九、总结

9.1 核心要点

  1. Assistant = Graph + Config

    • 图的实现 + 配置参数
    • 一个图可以有多个 assistants
    • 每个 assistant 有不同的行为
  2. 版本控制

    • 更新 assistant 会增加版本号
    • 可以追踪变化
    • 支持回滚
  3. 持久化

    • Assistants 存储在 PostgreSQL
    • 可以搜索、更新、删除
    • 跨会话持久化
  4. 实际应用

    • 多用户场景
    • A/B 测试
    • 多语言支持
    • 个性化体验

9.2 API 快速参考

python
# 创建
assistant = await client.assistants.create(graph_id, config=config)

# 更新(创建新版本)
assistant = await client.assistants.update(assistant_id, config=new_config)

# 获取
assistant = await client.assistants.get(assistant_id)
assistant = await client.assistants.get(assistant_id, version=2)

# 搜索
assistants = await client.assistants.search()
assistants = await client.assistants.search(graph_id="task_maistro")

# 删除
await client.assistants.delete(assistant_id)

# 使用
run = await client.runs.create(thread_id, assistant_id, input=input)

9.3 最佳实践清单

  • ✅ 使用清晰的配置和描述
  • ✅ 利用版本控制追踪变化
  • ✅ 集中管理 assistant 配置
  • ✅ 为不同场景创建专门的 assistants
  • ✅ 实现错误处理和回退机制
  • ✅ 使用元数据记录版本信息
  • ✅ 定期清理不用的 assistants

9.4 Module-6 总结

恭喜你完成了 Module-6 的所有内容!让我们回顾一下:

课程主题关键内容
6.1Creating部署到生产环境
6.2ConnectingSDK、Runs、Threads、Store API
6.3Double Texting并发请求处理策略
6.4Assistants配置化和版本控制

你现在掌握了:

  • ✅ 如何部署 LangGraph 应用
  • ✅ 如何使用 API 和 SDK
  • ✅ 如何处理生产环境的并发问题
  • ✅ 如何创建和管理多个 assistants

文档版本:1.0 最后更新:2024-11-05 作者:AI Assistant 基于:LangChain Academy Module-6 Lesson 6.4

恭喜你完成了整个 Module-6!你现在已经掌握了 LangGraph 的生产部署全流程。🎉🎊

基于 MIT 许可证发布。内容版权归作者所有。