跳转到内容
Hugging Face 智能体课程
1. 课程运作方式及问答环节
单元2. 智能体框架

构建你的第一个 LangGraph

现在我们已经理解了构建基础,接下来让我们通过构建我们的第一个功能图来实践这些知识。我们将实现Alfred的电子邮件处理系统,在这个系统中,他需要:

  1. 阅读传入的电子邮件
  2. 将它们分类为垃圾邮件或合法内容
  3. 为合法电子邮件起草初步回复
  4. 在合法情况下向韦恩先生发送信息(仅限打印)

这个示例展示了如何使用 LangGraph 构建一个涉及基于大语言模型的决策的工作流程。虽然这不能被视为一个智能体,因为没有涉及任何工具,但本节更侧重于学习 LangGraph 框架,而不是智能体。

[!TIP] 您可以按照代码进行操作。 这个笔记本 您可以使用 Google Colab来运行它。

我们的工作流程

这是我们将要构建的工作流程: 第一个 LangGraph

设置我们的环境

首先,让我们安装所需的包:

%pip install langgraph langchain_openai

接下来,让我们导入必要的模块:

import os
from typing import TypedDict, List, Dict, Any, Optional
from langgraph.graph import StateGraph, START, END
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage

步骤1:定义我们的状态

让我们定义阿尔弗雷德在电子邮件处理工作流程中需要跟踪的信息:

class EmailState(TypedDict):
    # The email being processed
    email: Dict[str, Any]  # Contains subject, sender, body, etc.

    # Category of the email (inquiry, complaint, etc.)
    email_category: Optional[str]

    # Reason why the email was marked as spam
    spam_reason: Optional[str]

    # Analysis and decisions
    is_spam: Optional[bool]
    
    # Response generation
    email_draft: Optional[str]
    
    # Processing metadata
    messages: List[Dict[str, Any]]  # Track conversation with LLM for analysis

💡 提示: 使你的状态足够全面,以记录所有重要信息,但避免用不必要的细节使状态变得臃肿。

步骤2:定义我们的节点

现在,让我们创建将构成我们节点的处理函数:

# Initialize our LLM
model = ChatOpenAI(temperature=0)

def read_email(state: EmailState):
    """Alfred reads and logs the incoming email"""
    email = state["email"]
    
    # Here we might do some initial preprocessing
    print(f"Alfred is processing an email from {email['sender']} with subject: {email['subject']}")
    
    # No state changes needed here
    return {}

def classify_email(state: EmailState):
    """Alfred uses an LLM to determine if the email is spam or legitimate"""
    email = state["email"]
    
    # Prepare our prompt for the LLM
    prompt = f"""
    As Alfred the butler, analyze this email and determine if it is spam or legitimate.
    
    Email:
    From: {email['sender']}
    Subject: {email['subject']}
    Body: {email['body']}
    
    First, determine if this email is spam. If it is spam, explain why.
    If it is legitimate, categorize it (inquiry, complaint, thank you, etc.).
    """
    
    # Call the LLM
    messages = [HumanMessage(content=prompt)]
    response = model.invoke(messages)
    
    # Simple logic to parse the response (in a real app, you'd want more robust parsing)
    response_text = response.content.lower()
    is_spam = "spam" in response_text and "not spam" not in response_text
    
    # Extract a reason if it's spam
    spam_reason = None
    if is_spam and "reason:" in response_text:
        spam_reason = response_text.split("reason:")[1].strip()
    
    # Determine category if legitimate
    email_category = None
    if not is_spam:
        categories = ["inquiry", "complaint", "thank you", "request", "information"]
        for category in categories:
            if category in response_text:
                email_category = category
                break
    
    # Update messages for tracking
    new_messages = state.get("messages", []) + [
        {"role": "user", "content": prompt},
        {"role": "assistant", "content": response.content}
    ]
    
    # Return state updates
    return {
        "is_spam": is_spam,
        "spam_reason": spam_reason,
        "email_category": email_category,
        "messages": new_messages
    }

def handle_spam(state: EmailState):
    """Alfred discards spam email with a note"""
    print(f"Alfred has marked the email as spam. Reason: {state['spam_reason']}")
    print("The email has been moved to the spam folder.")
    
    # We're done processing this email
    return {}

def draft_response(state: EmailState):
    """Alfred drafts a preliminary response for legitimate emails"""
    email = state["email"]
    category = state["email_category"] or "general"
    
    # Prepare our prompt for the LLM
    prompt = f"""
    As Alfred the butler, draft a polite preliminary response to this email.
    
    Email:
    From: {email['sender']}
    Subject: {email['subject']}
    Body: {email['body']}
    
    This email has been categorized as: {category}
    
    Draft a brief, professional response that Mr. Hugg can review and personalize before sending.
    """
    
    # Call the LLM
    messages = [HumanMessage(content=prompt)]
    response = model.invoke(messages)
    
    # Update messages for tracking
    new_messages = state.get("messages", []) + [
        {"role": "user", "content": prompt},
        {"role": "assistant", "content": response.content}
    ]
    
    # Return state updates
    return {
        "email_draft": response.content,
        "messages": new_messages
    }

def notify_mr_hugg(state: EmailState):
    """Alfred notifies Mr. Hugg about the email and presents the draft response"""
    email = state["email"]
    
    print("\n" + "="*50)
    print(f"Sir, you've received an email from {email['sender']}.")
    print(f"Subject: {email['subject']}")
    print(f"Category: {state['email_category']}")
    print("\nI've prepared a draft response for your review:")
    print("-"*50)
    print(state["email_draft"])
    print("="*50 + "\n")
    
    # We're done processing this email
    return {}

步骤3:定义我们的路由逻辑

我们需要一个函数来确定分类后的路径选择:

def route_email(state: EmailState) -> str:
    """Determine the next step based on spam classification"""
    if state["is_spam"]:
        return "spam"
    else:
        return "legitimate"

💡 注意: 这个路由功能由 LangGraph 调用,用于确定在分类节点之后应跟随哪条边。返回值必须与我们的条件边映射中的某个键相匹配。

步骤4:创建StateGraph并定义边

现在我们将所有部分连接在一起:

# Create the graph
email_graph = StateGraph(EmailState)

# Add nodes
email_graph.add_node("read_email", read_email)
email_graph.add_node("classify_email", classify_email)
email_graph.add_node("handle_spam", handle_spam)
email_graph.add_node("draft_response", draft_response)
email_graph.add_node("notify_mr_hugg", notify_mr_hugg)

# Start the edges
email_graph.add_edge(START, "read_email")
# Add edges - defining the flow
email_graph.add_edge("read_email", "classify_email")

# Add conditional branching from classify_email
email_graph.add_conditional_edges(
    "classify_email",
    route_email,
    {
        "spam": "handle_spam",
        "legitimate": "draft_response"
    }
)

# Add the final edges
email_graph.add_edge("handle_spam", END)
email_graph.add_edge("draft_response", "notify_mr_hugg")
email_graph.add_edge("notify_mr_hugg", END)

# Compile the graph
compiled_graph = email_graph.compile()

请注意我们是如何使用这个特殊方法的。 END 由 LangGraph 提供的节点。这表示工作流程完成的终端状态。

步骤5:运行应用程序

让我们用一封合法的电子邮件和一封垃圾邮件来测试我们的图模型:

# Example legitimate email
legitimate_email = {
    "sender": "john.smith@example.com",
    "subject": "Question about your services",
    "body": "Dear Mr. Hugg, I was referred to you by a colleague and I'm interested in learning more about your consulting services. Could we schedule a call next week? Best regards, John Smith"
}

# Example spam email
spam_email = {
    "sender": "winner@lottery-intl.com",
    "subject": "YOU HAVE WON $5,000,000!!!",
    "body": "CONGRATULATIONS! You have been selected as the winner of our international lottery! To claim your $5,000,000 prize, please send us your bank details and a processing fee of $100."
}

# Process the legitimate email
print("\nProcessing legitimate email...")
legitimate_result = compiled_graph.invoke({
    "email": legitimate_email,
    "is_spam": None,
    "spam_reason": None,
    "email_category": None,
    "email_draft": None,
    "messages": []
})

# Process the spam email
print("\nProcessing spam email...")
spam_result = compiled_graph.invoke({
    "email": spam_email,
    "is_spam": None,
    "spam_reason": None,
    "email_category": None,
    "email_draft": None,
    "messages": []
})

步骤6:使用Langfuse检查我们的邮件分类智能体 📡

在精细调整邮件分拣智能体时,阿尔弗雷德对调试其运行感到疲惫。智能体本质上是不可预测的,且难以进行监控。但由于他希望打造一款终极的垃圾邮件检测智能体,并将其部署到生产环境中,因此他需要强大的可追溯性,以便未来进行监控和分析。

为此,Alfred可以使用诸如可观测性工具 Langfuse 追踪和监控智能体。

首先,我们使用pip安装Langfuse:

%pip install -q langfuse

其次,我们使用 `pip` 安装 `Langchain`(使用 `LangFuse` 需要安装 `LangChain`)。

%pip install langchain

接下来,我们将 Langfuse 的 API 密钥和主机地址作为环境变量进行设置。您可以通过注册来获取自己的 Langfuse 凭据。 Langfuse Cloud 或 自托管 Langfuse.

import os
 
# Get keys for your project from the project settings page: https://cloud.langfuse.com
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." 
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..."
os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region
# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region

那么,我们配置智能体 Langfuse callback_handler 并通过添加以下内容来配置智能体: langfuse_callback 对图的调用: config={"callbacks": [langfuse_handler]}.

from langfuse.langchain import CallbackHandler

# Initialize Langfuse CallbackHandler for LangGraph/Langchain (tracing)
langfuse_handler = CallbackHandler()

# Process legitimate email
legitimate_result = compiled_graph.invoke(
    input={"email": legitimate_email, "is_spam": None, "spam_reason": None, "email_category": None, "draft_response": None, "messages": []},
    config={"callbacks": [langfuse_handler]}
)

Alfred现已连接🔌!从LangGraph获取的运行数据被记录到Langfuse中,使他能够完全了解智能体的行为。有了这个设置,他可以重新查看之前的运行结果,并进一步完善他的邮件分类智能体。

Langfuse中的示例追踪

使用有效电子邮件的追踪公开链接

可视化我们的图结构

LangGraph 使我们能够可视化我们的工作流程,以便更好地理解和调试其结构:

compiled_graph.get_graph().draw_mermaid_png()
邮件 LangGraph

这会产生一个可视化表示,展示我们的智能体是如何相互连接的,以及可以采取的条件性路径。

我们所构建的

我们创建了一个完整的电子邮件处理工作流程,该流程包括:

  1. 接收传入的电子邮件
  2. 使用大型语言模型来将其分类为垃圾邮件或合法内容
  3. 通过丢弃来处理垃圾信息
  4. 对于合法的电子邮件,智能体会起草回复并通知Hugg先生。

这展示了 LangGraph在利用大型语言模型协调复杂工作流程方面的强大能力,同时还能保持清晰、有序的流程。

关键要点

  • 状态管理我们定义了全面的状态,以跟踪电子邮件处理的所有方面。
  • 节点实现我们创建了与大型语言模型交互的功能性节点。
  • 条件路由我们实现了基于电子邮件分类的分支逻辑。
  • 终端状态我们使用END节点来标记工作流程中的完成点。

接下来是什么?

在下一节中,我们将探讨 LangGraph的更高级功能,包括在处理工作流程中的人类交互以及基于多个条件实现更复杂的分支逻辑。