36氪 - 科技频道 03月28日 07:12
AI智能体(三):框架
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文深入探讨了智能体框架,这些框架正在革新人工智能领域。通过赋能自主系统动态感知、推理和行动,智能体框架如LangChain、LangGraph和CrewAI等,简化了复杂AI应用的开发。文章介绍了智能体框架的核心概念、重要性,并对比了主流框架的特点。此外,还提供了LangGraph的实战指南,包括基础聊天机器人构建、工具集成、记忆功能和人在回路的实现,最后展望了智能体框架在智能客服、AI研究助手等领域的应用前景。

💡 智能体框架是人工智能系统设计范式的转变,它们能够自主感知、推理和行动,将复杂任务分解为子任务,由协作的专用智能体处理,适合动态决策和实时问题解决等高级应用。

🛠️ LangChain、LangGraph与CrewAI等框架简化了智能体构建过程,提供了定义智能体和工具的简易方法、编排机制和状态管理等核心功能,开发者可以专注于应用逻辑。

🤖 LangGraph是LangChain的扩展,支持创建基于图谱的单智能体或多智能体AI应用,通过节点和边构建工作流,支持状态管理,包括对话历史、上下文数据和内部变量等,能够实现工具集成、记忆功能和人在回路的复杂功能。

神译局是36氪旗下编译团队,关注科技、商业、职场、生活等领域,重点介绍国外的新技术、新观点、新风向。

编者按:2025年是AI智能体元年。本系列文章旨在介绍AI智能体的概念、类型、原理、架构、开发等,为进一步了解AI智能体提供入门知识。本文为系列文章的第三篇,文章来自编译。

1. 引言

智能体框架通过赋能自主系统动态感知、推理和行动,彻底改变了人工智能领域。本节将探讨智能体框架的核心概念,同时强调开源解决方案对现代AI开发创新和可扩展性的重要性。

1.1 什么是智能体框架(Agentic Frameworks)?

智能体框架是人工智能系统设计范式转变的标志。与依赖静态预定义工作流的传统AI应用不同,智能体框架引入了动态、自适应的系统,能够自主感知、推理和行动。这些框架将复杂任务分解为子任务,由协作完成目标的专用智能体处理。通过利用大语言模型(LLM),智能体框架可无缝管理工作流、决策和工具集成,因此非常适合动态决策和实时问题解决等高级应用。

LangGraph与CrewAI等智能体框架就是这种动态做法的体现,开发者得以从单智能体线性工作流转向多智能体协作系统。

1.2 为何如此重要?

从零开始构建智能体并非易事。LangGraph、CrewAI与OpenAI Swarm等框架简化了这一过程,让开发者能够专注于应用逻辑,而非重新实现状态管理、编排和工具集成等基础功能。智能体框架的核心功能包括:

我们将在后续章节逐一探讨这些功能。

2. 主流智能体框架与工具库

接下来,我们将深入探讨当前最突出的AI智能体框架和工具:

来源:analyticsvidhya

2.1 LangChain框架

LangChain是一个强大且灵活的框架,可简化基于大语言模型(LLM)应用的开发。凭借丰富的工具和抽象层,开发者能设计出具备复杂推理、任务执行及与外部数据源和API交互能力的AI智能体。

在与LLM协作时,开发者常面临保持长对话上下文、整合外部信息和协调多步骤项目等挑战。LangChain通过模块化架构解决这些问题,其组件可灵活组合以支持多样化用途。

https://github.com/langchain-ai/langchain/tree/master/libs/langchain/langchain/agents

2.2 LangGraph框架

LangGraph是LangChain的扩展,支持利用大语言模型(LLM)创建有状态的多角色应用。对构建涉及规划、反思和多智能体协调的复杂交互式AI系统尤其适用。

2.3 CrewAI

CrewAI是一个用于编排角色扮演AI智能体的框架。开发者可创建由多个AI智能体组成的“团队”,每个智能体承担特定角色和职责,协作完成复杂任务。该框架尤其适合构建需多领域专业知识和协调合作的协作式AI系统。

2.4 Microsoft Semantic Kernel

Microsoft Semantic Kernel旨在弥合传统软件开发与AI能力之间的鸿沟,其关注重点是将大语言模型(LLM)集成到现有应用中。该框架为开发者提供了在不彻底重构现有代码库的前提下整合AI功能的工具。

该框架SDK很轻量,且支持多编程语言,所以可高度适应不同的开发环境。而且它的编排器支持管理复杂的多步骤AI任务,可帮助开发者在应用中创建高级AI驱动工作流。

2.5 Microsoft AutoGen

Microsoft AutoGen是一个开源框架,可用于构建高级AI智能体和多智能体系统。由微软研究院开发,其设计强调模块化、可扩展性和易用性,可帮助开发者高效构建复杂AI系统。

2.6 Smolagents

Smolagents是一个前沿的开源框架,旨在革新AI智能体开发。它为开发者提供构建智能协作多智能体系统的全套工具,强调灵活性与模块化,支持创建独立运行或与人类协同的复杂AI系统。

2.7 AutoGPT

AutoGPT基于健壮的GPT-4语言模型,可通过语言输入执行目标导向活动,是自主AI智能体领域的重大突破。这个AI助手将决策能力提升至新高度,超越基础的反射型智能体,能集成高级功能,是多领域应用的有用工具。

2.8 Agno(Phidata)框架

最后一个AI智能体框架是Phidata。它是一个多模态智能体框架,支持开发协作式智能体系统。其设计整合了记忆和工具组件,可令智能体能够自主稳定运行。Phidata智能体默认支持文本、图像和音频等多模态数据,无需依赖外部工具。该框架还提供用于视觉交互的Agentic UI,并率先实现了Agentic RAG,支持智能体搜索知识库。

3. 智能体框架对比

下图对本文讨论的主要AI智能体框架进行了概略对比,旨在突出各框架的独特优势与专注领域,帮助开发者和研究者选择最适合需求的工具。

4. LangGraph深度解析

LangGraph是由LangChain团队构建的库,旨在帮助开发者创建基于图谱的单智能体或多智能体AI应用。作为底层框架,LangGraph可让开发者控制智能体间的交互方式、工具选择及信息流管理。

4.1 什么是Graph?

假设有一组数据可表示为网络,其中每个数据或实体与其他数据或实体存在多种类型关系(如一对一、一对多、多对多)。图的两大核心组件是节点(nodes)与边(edges)。

示例: 交通数据或社交媒体网络中的实体/用户关系可用图直观表示。

图可分为有向图与无向图:

来源:ionio

4.2 核心概念

4.2.1 图的结构

LangGraph的核心设计是基于图的工作流表示,包含两大要素:

简单边(Simple Edges):节点间的直接无条件流转。

4.2.2 状态管理

LangGraph通过集中的状态对象管理状态,会记录:

5. LangGraph实战

5.1 安装

打开终端运行以下命令:

pip install -U langgraph

-U 确保安装的是最新版

5.2 创建一个基础版的聊天机器人

下述代码是理解LangGraph基本概念的一个好的起点。

代码示例:

步骤:

1.导入必要的库

from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages

2.定义状态结构:

class State(TypedDict):

     # 'messages' will store the chatbot conversation history.

     # The 'add_messages' function ensures new messages are appended to the list.

     messages: Annotated[list, add_messages]

 # Create an instance of the StateGraph, passing in the State class

 graph_builder = StateGraph(State)

3.初始化大语言模型:

#pip install -U langchain_anthropic

 from langchain_anthropic import ChatAnthropic

 llm = ChatAnthropic(model="claude-3-5-sonnet-20240620")

4.创建Chatbot节点:

def chatbot(state: State):

     # Use the LLM to generate a response based on the current conversation history.

     response = llm.invoke(state["messages"])

 

     # Return the updated state with the new message appended

     return {"messages": [response]}

 

 # Add the 'chatbot' node to the graph,

 graph_builder.add_node("chatbot", chatbot)

5.定义入口与出口:

# For this basic chatbot, the 'chatbot' node is both the entry and finish point

 graph_builder.add_edge(START, "chatbot")

 graph_builder.add_edge("chatbot", END)

6.编译:

graph = graph_builder.compile()

7.可视化:

from IPython.display import Image, display

 try:
     display(Image(graph.get_graph().draw_mermaid_png()))
 except Exception:
     # This requires some extra dependencies and is optional
     pass

8.运行:

while True:
     user_input = input("User: ")
     if user_input.lower() in ["quit", "exit", "q"]:
         print("Goodbye!")
         break

     # Process user input through the LangGraph
     for event in graph.stream({"messages": [("user", user_input)]}):
         for value in event.values():
             print("Assistant:", value["messages"][-1].content)

这个代码片段演示了LangGraph聊天机器人的基本结构,引入更复杂的状态管理和不同的LLM模型,或者连接上外部工具和API就可以进行拓扩展。关键是要定义清楚承担不同任务的节点,用边来建立希望达成的信息流,并且做好机器人内部的控制。

5.3 高级LangGraph技巧

工具集成:集成工具进LangGraph可显著增强智能体的能力。

下面就用工具集成来增强前面那个基础版机器人的能力

我们修改一下,把一个可以在web上搜索信息的工具纳入进来。用的是langchain_community.tools.tavily_search的TavilySearchResults工具。当然,你得配置Tavily API key

#pip install -U tavily-python langchain_community
from typing import Annotated
from langchain_anthropic import ChatAnthropic
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import BaseMessage
from typing_extensions import TypedDict

from langgraph.graph import StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition


class State(TypedDict):
    messages: Annotated[list, add_messages]


graph_builder = StateGraph(State)


tool = TavilySearchResults(max_results=2)
tools = [tool]
llm = ChatAnthropic(model="claude-3-5-sonnet-20240620")
llm_with_tools = llm.bind_tools(tools)


def chatbot(state: State):
    return {"messages": [llm_with_tools.invoke(state["messages"])]}


graph_builder.add_node("chatbot", chatbot)

tool_node = ToolNode(tools=[tool])
graph_builder.add_node("tools", tool_node)

graph_builder.add_conditional_edges(
    "chatbot",
    tools_condition,
)
# Any time a tool is called, we return to the chatbot to decide the next step
graph_builder.add_edge("tools", "chatbot")
graph_builder.set_entry_point("chatbot")
graph = graph_builder.compile()

6. 给Chatbot添加记忆功能

记忆功能对创建可参与会话的聊天机器人十分关键,因为机器人得记住过去的互动。

LangGraph的检查点系统通过thread_id来保存状态,支持跨会话的连续性。

实现方法:

# ... (Previous code to define State, graph_builder, nodes, and edges)

from langgraph.checkpoint.memory import MemorySaver

# Create a MemorySaver object to act as the checkpointer
memory = MemorySaver()

# Compile the graph, passing in the 'memory' object as the checkpointer
graph = graph_builder.compile(checkpointer=memory)

# ... (Rest of the code to run the chatbot)

7.人在回路

对于希望将人类监督、验证或决策纳入到AI应用的情况来说,人在回路(Human-in-the-loop)工作流是必不可少的。

用中断实现人在回路

下述代码演示的是利用LangGraph的interrupt_before 或 interrupt_after功能实现人在回路:

from typing import Annotated

from langchain_anthropic import ChatAnthropic
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import BaseMessage
from typing_extensions import TypedDict

from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition


class State(TypedDict):
    messages: Annotated[list, add_messages]


graph_builder = StateGraph(State)


tool = TavilySearchResults(max_results=2)
tools = [tool]
llm = ChatAnthropic(model="claude-3-5-sonnet-20240620")
llm_with_tools = llm.bind_tools(tools)


def chatbot(state: State):
    return {"messages": [llm_with_tools.invoke(state["messages"])]}


graph_builder.add_node("chatbot", chatbot)

tool_node = ToolNode(tools=[tool])
graph_builder.add_node("tools", tool_node)

graph_builder.add_conditional_edges(
    "chatbot",
    tools_condition,
)
graph_builder.add_edge("tools", "chatbot")
graph_builder.set_entry_point("chatbot")

memory = MemorySaver()
graph = graph_builder.compile(
    checkpointer=memory,
    # This is new!
    interrupt_before=["tools"],
    # Note: can also interrupt __after__ actions, if desired.
    # interrupt_after=["tools"]
)

8. 真实世界用例

智能客服: 支持记忆和人工转接的聊天机器人。

AI研究助手: 文献搜索与总结。

个性化学习: 自适应教育平台。

高效业务: 自动化工作流与数据分析。

9. 结论

智能体框架正在彻底改变AI系统的运作方式,让其得以通过智能、自主的智能体实现动态推理、规划和交互。本文探讨了智能体框架的重要性,梳理了主流工具库并对比了各自优势。实战部分展示了LangGraph在构建记忆功能、人类介入流程和可扩展应用方面的能力。

随着AI的持续发展,LangGraph、LangChain和CrewAI等框架将在塑造下一代智能应用中发挥关键作用。现在正是开始实验与创新的最佳时机。

祝编程愉快!

延伸阅读:

AI智能体(一):介绍

AI智能体(二):从零开始构建智能体

译者:boxi。

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

智能体框架 LangGraph LangChain AI
相关文章