LangChain 是一个开源框架,已成为构建 AI 驱动应用最受欢迎的选择之一。它将语言模型与各种工具、API 和外部数据源连接起来,以创建强大的 AI Agent。LangChain 最受欢迎的特点在于它能够无缝地将多个大型语言模型(LLM)调用串联起来,并将其与外部数据源、工具和API 集成。这种模块化、可组合的方法使得开发者能够比直接使用原始 LLM API 更灵活、更轻松地构建复杂的、多步骤的 AI 应用,例如聊天机器人、Agent 和检索增强生成(RAG)系统。### 主要特性:
# 定义 Agent 可以使用的工具 search_tool = DuckDuckGoSearchRun() tools = [ Tool(name="Search", func=search_tool.run, description="Useful for searching the internet for current information" ) ]
# 初始化语言模型 llm = ChatOpenAI(model="gpt-4")
# 使用 React 框架创建 Agent agent = create_react_agent(llm, tools,"You are a helpful AI assistant.")
# 运行 Agent response = agent_executor.invoke({"input":"What are the latest developments in AI agent frameworks?"}) print(response["output"])
2.AutoGen(微软)
AutoGen 是微软研究院开发的一个开源编程框架,专为构建和管理具有高级协作能力的 AI Agent 而设计。
AutoGen 基于 Actor 的架构和对 Agent 协作的专注经常被认为是具有变革性的,它在业务流程自动化、金融、医疗健康等领域实现了新型 AI 驱动解决方案。这种对专业化、可对话和可定制 Agent 的编排,被广泛认为是 AutoGen 最受用户赞赏的特性,因为它使得构建复杂、可扩展且可靠的 AI 应用变得更加容易。
# 定义具有特定角色的 Agent researcher = Agent( role="Research Analyst", goal="Discover and analyze the latest trends inAI technology", backstory="You are an expert in AI research with a keen eye for emerging trends", verbose=True, llm=llm )
writer = Agent( role="TechnicalWriter", goal="Create comprehensive reports based on research findings", backstory="You are a skilled technical writer who can explain complex concepts clearly", verbose=True, llm=llm )# 为每个 Agent 定义任务 research_task = Task( description="Research the latest developments in AI agent frameworks", expected_output="A comprehensive analysis of current AI agent frameworks", agent=researcher )writing_task = Task( description="Write a detailed report on AI agent frameworks based on the research", expected_output="A well-structured report on AI agent frameworks", agent=writer, context=[research_task] # 写作任务依赖于研究任务 )
LangGraph 是 LangChain 创建的一个开源 AI Agent 框架,用于构建和管理复杂的生成式 AI 工作流。
主要特性:
先进的 Agentic 模式(工具调用、React 方法论、Self-Ask 方法)
支持节点(LLM)和边缘(工具)的可视化表示
对工作流流程和状态进行细粒度控制
构建有状态应用的灵活框架
支持复杂的多 Agent 场景
优势:
专为基于语言的 AI Agent 设计的基础架构
能够创建精密的、相互关联的 Agent 系统
支持复杂工作流的设计与管理
劣势:
-复杂度较高,可能需要高级开发者技能
主要专注于基于语言的工作流
应用场景:
对话式 Agent
复杂任务自动化
自定义 LLM 支持的工作流
专注于语言处理的AI Agent 开发
代码示例:
fromtypingimportTypedDict, Annotated, Sequence fromlanggraph.graphimportStateGraph, END fromlangchain_openaiimportChatOpenAI fromlangchain_core.messagesimport HumanMessage, AIMessage
# 定义状态结构 classAgentState(TypedDict): messages: Annotated[Sequence[HumanMessage | AIMessage],"The messages in the conversation"] next_step: Annotated[str,"The next step to take"]
defanalyze(state: AgentState)-> AgentState: messages = state["messages"] response = llm.invoke(messages + [HumanMessage(content="Analyze the research findings.")])return{"messages": state["messages"] + [response],"next_step":"conclude"}
defconclude(state: AgentState)-> AgentState: messages = state["messages"] response =llm.invoke(messages + [HumanMessage(content="rovide a conclusion based on the analysis.")]) return{"messages": state["messages"] + [response],"next_step":"end"}
# 定义一个简单的工具函数 defsearch_documents(query: str)-> str: """Search for information in the document database.""" # 在实际应用中,这里会查询文档存储 returnf"Here are the search results for:{query}"
# 创建一个函数工具 search_tool = FunctionTool.from_defaults( name="search_documents", fn=search_documents, description="Search for information in the document database" )
# 定义输入/输出模式 classResearchQuery(BaseModel): topic: str = Field(description="The topic to research") depth: int = Field(description="The depth of research required (1-5)")
classResearchResult(BaseModel): findings: List[str] = Field(description="Key findings from the research") sources: List[str] =Field(description="Sources of information")
responses: utter_greet: - text: "Hello! How can I help you with AI frameworks today?"
utter_goodbye: - text: "Goodbye! Feel free to ask about AI frameworks anytime."
utter_about_frameworks: - text: "There are several popular AI agent frameworks including LangChain, AutoGen, CrewAI, and more. Which one would you like to know about?"
# data/nlu.yml - 用于 NLU 的训练数据 """ version: "3.1"nlu: - intent: greet examples: | - hey - hello - hi - hello there - good morning
- intent: goodbye examples: | - bye -goodbye - see you around - see you later
- intent: ask_about_ai_frameworks examples: | - tell me about AI frameworks - what are the best AI agent frameworks- I need information about [LangChain](framework_name) - How does [AutoGen](framework_name) work? - Can you explain [CrewAI](framework_name)? """
if framework.lower() == "langchain": dispatcher.utter_message(text="LangChain is an open-source framework for building applications using large language models.") elif framework.lower()== "autogen": dispatcher.utter_message(text="AutoGen is a framework from Microsoft Research that enables the development of LLM applications using multiple agents.") elif framework.lower() == "crewai":dispatcher.utter_message(text="CrewAI is a framework for orchestrating role-playing autonomous AI agents.") else: dispatcher.utter_message(text=f"I don't have specific information about {framework}, but it might be one of the emerging AI agent frameworks.")
asyncdefmain(): # 创建两个具有不同角色的 Agent user_agent = ChatAgent( model_type=ModelType.GPT_4, system_message="You are a user who needs help analyzing data about AI frameworks." )
assistant_agent = ChatAgent( model_type=ModelType.GPT_4, system_message="You are an AI assistant specialized in data analysis and AI frameworks." )
# 用户 Agent 发出的初始消息 user_message = BaseMessage.make_user_message( role_name="User", content="I need to compare different AI agent frameworks for my project. Can you help me analyze their features?")