AI Agent 正逐渐改变我们与信息系统的交互方式,它们能够自动化执行任务、做出决策,甚至与人类进行协作。但是,从零开始构建强大的 AI Agent 是一项复杂的工作。幸运的是,开源框架的出现大大降低了这一难度,它们为开发者提供了丰富的工具和现成的结构,使得开发智能、交互式的 AI Agent变得更加容易。所以,我趁周末的时光,为大家总结了我日常工具库中经常使用或参考的Agent框架,在这里分享给大家,希望能给各位伙伴带来灵感或有所启发。

img

Agently:快速构建 AI Agent 原生应用的开发框架

Agently 是一个帮助开发者快速构建 AI Agent原生应用的开发框架,它让开发者能够以极其简单的方式在代码中使用和构建 AI Agent。

  • 简单易用 :Agently 提供了极其简单的 API,让开发者能够快速上手,轻松构建 AI Agent应用。
  • 插件增强 :Agently 支持通过插件来增强 AI Agent的功能,开发者无需重建整个Agent,只需添加所需的插件即可。
  • 灵活扩展 :Agently 的架构设计灵活,支持多种扩展方式,满足不同场景下的应用需求。

null

示例 :Workflow工作流管理

"""创建Agent实例和Workflow实例"""
import Agently
agent = (
    Agently.create_agent()
        .set_settings("current_model", "OAIClient")
        .set_settings("model.OAIClient.url", "https://api.moonshot.cn/v1")
        .set_settings("model.OAIClient.options", { "model": "moonshot-v1-8k" })
        .set_settings("model.OAIClient.auth", { "api_key": "********" })
)
workflow = Agently.Workflow()
"""创建执行块(Chunk)"""
# 用户输入块
@workflow.chunk()
def user_input(inputs, storage):
    return input("[User]: ")

# Agent回复块
@workflow.chunk()
def assistant_reply(inputs, storage):
    chat_history = storage.get("chat_history") or []
    reply = (
        agent
            .chat_history(chat_history)
            .input(inputs["default"])
            .start()
    )
    print("[Assistant]: ", reply)
    return reply

# 对话记录更新块
@workflow.chunk()
def update_chat_history(inputs, storage):
    chat_history = storage.get("chat_history", [])
    chat_history.append({ "role": "user", "content": inputs["user_input"] })
    chat_history.append({ "role": "assistant", "content": inputs["assistant_reply"] })
    storage.set("chat_history", chat_history)
    return

# 道别块
@workflow.chunk()
def goodbye(inputs, storage):
    print("Bye~👋")
    return

# 取出对话记录块
@workflow.chunk()
def get_all_chat_history(inputs, storage):
    return storage.get("chat_history")

"""连接执行块"""
workflow.connect_to("user_input")
(
    workflow.chunks["user_input"]
        .if_condition(lambda return_value, storage: return_value == "#exit")
            .connect_to("goodbye")
            .connect_to("get_all_chat_history")
            .connect_to("end")
        .else_condition()
            .connect_to("assistant_reply")
)
workflow.chunks["user_input"].connect_to("update_chat_history.user_input")
workflow.chunks["assistant_reply"].connect_to("update_chat_history.assistant_reply")
workflow.chunks["update_chat_history"].connect_to("user_input")

"""获取工作流Mermaid代码(可绘图)"""
print(workflow.draw())

"""启动工作流"""
"""将需要输出的数据连接到`end`块即可获得返回结果"""
chat_history = workflow.start()
print(chat_history["default"])

执行反馈-工作流节点图

YesNouser_inputassistant_replySTARTuser_inputConditiongoodbyeget_all_chat_historyENDassistant_replyupdate_chat_history

CrewAI:Agent团队的指挥官

CrewAI 是一个专注于多Agent编排的开源框架,使 AI Agent能够以定义的角色和共享目标进行协作,适用于需要Agent团队合作的任务场景。

  • 基于角色的Agent协作 :CrewAI 允许创建具有明确角色和目标的 AI Agent,促进自然、自主的决策和动态任务分配,使Agent团队能够高效协作。
  • 生产级框架 :CrewAI 为可靠性和可扩展性而构建,适用于现实世界的应用场景,为复杂的业务挑战提供了精确的控制和深度的定制化。
    Logo of CrewAI, two people rowing on a boat

示例 :AI 驱动的股票分析,为金融团队提供全面的股票市场分析报告,通过不同角色的Agent协作,收集市场数据、分析财务状况并生成投资报告,帮助金融团队做出明智的投资决策。

import os
from crewai import Crew, Agent, Task
from dotenv import load_dotenv
from langchain.tools import DuckDuckGoSearchRun
from langchain.agents import load_tools

load_dotenv()

# Replace with your actual API keys and model configuration
# You might use OpenAI, Gemini, or another LLM provider
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"# Or load it from your .env file
llm_model = "gpt-4"# Or "gpt-3.5-turbo", etc.  Choose based on your budget and needs.

# 1. Tools (Example: DuckDuckGo for search)
search_tool = DuckDuckGoSearchRun()
#Alternative method:
#tools = load_tools(["ddg-search", "wikipedia"])

# 2. Define the Agents

data_gatherer = Agent(
    role='Data Gathering Expert',
    goal='Collect comprehensive data for stock analysis using web scraping and financial APIs',
    backstory="""You are an expert data gatherer with 5 years of experience. You collect data via web scraping and using any appropriate tools.""",
    verbose=True,
    allow_delegation=False,
    tools = [search_tool],
    llm=llm_model
)

financial_analyst = Agent(
    role='Financial Expert',
    goal='Analyze financial data and identify investment opportunities, looking for key trends and ratios',
    backstory="""You are an expert financial analyst with 10 years of experience.  You are skilled in analyzing financial data and identifying promising investment opportunities.""",
    verbose=True,
    allow_delegation=True, #Allows this agent to delegate tasks.
    tools = [search_tool],
    llm=llm_model
)

report_generator = Agent(
    role='Report Writer',
    goal='Generate clear and concise investment reports, summarizing findings and recommendations',
    backstory="""You are a skilled report writer with a background in finance. You are excellent at communicating complex financial information in an accessible manner.""",
    verbose=True,
    allow_delegation=False,
    llm=llm_model
)

# 3. Define the Tasks

task1 = Task(
    description="""Gather the latest market data, including stock prices, trading volumes, and relevant news articles, for Tesla (TSLA).
        Focus on data from the last month. Provide direct URLs to the data sources.""",
    agent=data_gatherer
)

task2 = Task(
    description="""Analyze the gathered data for Tesla (TSLA), identify key trends, compute relevant financial ratios (e.g., P/E ratio, debt-to-equity ratio),
        and assess potential investment opportunities and risks. Include a bulleted list of key findings.""",
    agent=financial_analyst
)

task3 = Task(
    description="""Compile the analysis into a structured report with key findings, recommendations, and supporting data.
        The report should be well-formatted and easy to understand for a finance team.  Include a section on potential risks and mitigation strategies.""",
    agent=report_generator
)

# 4. Form the Crew

stock_analysis_crew = Crew(
    agents=[data_gatherer, financial_analyst, report_generator],
    tasks=[task1, task2, task3],
    verbose=2, # Show what tasks are being worked on
    process=Process.sequential # Sequential task execution
)

# 5. Kickoff the Crew
report = stock_analysis_crew.kickoff()

print("Generated Report:")
print(report)

Phidata:AI 工程的简化利器

Phidata(现更名为 Agno)是一个轻量级的框架,用于构建多模态 AI Agent,它允许开发者将LLM转化为 AI 产品中的Agent,支持来自 OpenAI、Anthropic 等供应商的闭源和开源 LLM。

Phidata 的架构以构建具有记忆、知识、工具和推理能力的Agent为中心,同时还支持Agent团队的协作。

  • 记忆与知识管理 :Phidata 能够记住过去的对话和信息,使 AI Agent在每次交互时不必从头开始,为用户提供更加连贯和个性化的体验。
  • 多Agent编排 :当需要多个 AI Agent协同工作时,Phidata 可以有效地管理它们,确保它们能够友好协作,共同完成复杂的任务。
  • 内置Agent UI :Phidata 提供了一个用户友好的界面,方便开发者快速、轻松地测试和查看Agent的表现。
  • 部署与监控 :借助 Phidata,开发者可以轻松部署 AI Agent,并实时跟踪其在实际应用中的性能,及时进行优化和调整。
    img

示例 :Github Readme Writer Agent,它可以根据用户提供的代码仓库链接或名称,自动生成高质量的 README 文件,帮助开发者更好地展示和管理他们的项目。

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.github import GithubTools
from agno.tools.local_file_system import LocalFileSystemTools

readme_gen_agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    name="Readme Generator Agent",
    tools=[GithubTools(), LocalFileSystemTools()],
    markdown=True,
    debug_mode=True,
    instructions=[
        "You are readme generator agent",
        "You'll be given repository url or repository name from user.",
        "You'll use the `get_repository` tool to get the repository details.",
        "You have to pass the repo_name as argument to the tool. It should be in the format of owner/repo_name. If given url extract owner/repo_name from it.",
        "Also call the `get_repository_languages` tool to get the languages used in the repository.",
        "Write a useful README for a open source project, including how to clone and install the project, run the project etc. Also add badges for the license, size of the repo, etc",
        "Don't include the project's languages-used in the README",
        "Write the produced README to the local filesystem",
    ],
)

readme_gen_agent.print_response(
    "Get details of https://github.com/agno-agi/agno", markdown=True
)

AutoGen:对话式 AI Agent的专家

AutoGen 是由微软开发的一个框架,旨在使用多个可以相互对话的Agent来构建 AI 应用程序,它专注于创建可定制的、对话式的 AI Agent,通过协作支持复杂的工作流程。

  • 可扩展与分布式 :AutoGen 能够在各种环境中无缝部署大规模、分布式的Agent网络,满足不同场景下的应用需求。

  • 强大的调试功能 :内置的跟踪、追踪和调试工具确保了可靠的Agent工作流程,同时支持 OpenTelemetry,为开发者提供了可观测性,方便进行性能监控和问题排查。

  • AutoGen

示例 :将原始笔记重新组织为包含摘要和待办事项列表的文档,通过多个Agent的协作,能够快速将杂乱无章的笔记转化为结构清晰、信息丰富的文档,提高工作效率。

from autogen import AssistantAgent, UserProxyAgent, config_list_from_json

# Load LLM inference endpoints from an environment variable or a file
config_list = config_list_from_json(env_or_file="OAI_CONFIG_LIST")

# Create the agents
summarizer = AssistantAgent(
    name="Summarizer",
    llm_config={"config_list": config_list, "model": "gpt-3.5-turbo"} #Or whatever model you want
)

title_generator = AssistantAgent(
    name="TitleGenerator",
    llm_config={"config_list": config_list, "model": "gpt-3.5-turbo"}
)

todo_extractor = AssistantAgent(
    name="ToDoExtractor",
    llm_config={"config_list": config_list, "model": "gpt-3.5-turbo"}
)

user_proxy = UserProxyAgent(
    name="User_Proxy",
    code_execution_config={"work_dir": "coding"},
    human_input_mode="NEVER", #Set this to ALWAYS if you want to manually approve every message
    max_consecutive_auto_reply=10
)

#Start the process
user_proxy.initiate_chat(
    summarizer,
    message="Please summarize this note: [Your Raw Note Here]"
)

#Example of extracting the summary from the conversation history
summary = user_proxy.last_message()

user_proxy.initiate_chat(
    title_generator,
    message=f"Please generate a concise title for this summary: {summary}"
)

title = user_proxy.last_message()

user_proxy.initiate_chat(
    todo_extractor,
    message=f"Please generate a To Do List based on this note: [Your Raw Note Here]"
)

todo_list = user_proxy.last_message()

print ("Summary: " + summary)
print ("Title: " + title)
print ("To Do List:" + todo_list)

LangGraph:构建复杂 AI 工作流程的能手

LangGraph 是一个用于使用LLM构建有状态、多Agent应用程序的开源框架,它将工作流程结构化为图,其中每个节点代表一个特定的任务或功能,使开发者能够对应用程序的流程和状态进行细粒度的控制。

  • 基于图的工作流程 :LangGraph 将任务作为图中的节点,使决策过程更加灵活,支持迭代和复杂的任务流程。
  • 有状态Agent :Agent能够在不同任务之间保留上下文和记忆,使多步骤的交互更加流畅自然,为用户提供更好的体验。
  • 精确控制 :开发者可以对Agent的行为和工作流程进行精细的调整和定制,满足特定的应用需求。
  • 无缝集成 :LangGraph 与 LangChain 和 LangSmith 无缝协作,为开发者提供了更强大的工具、监控和优化功能,提升了开发效率和应用性能。
    img

示例 :自动化博客文章创作,通过两个Agent的协作,一个Agent根据主题生成详细的大纲,另一个Agent根据大纲撰写完整的博客文章内容,展示了简单的内容生成流程,为内容创作者提供了高效的内容生产工具。

import os
from typing import TypedDict, List, Dict, Any

from langchain_core.messages import BaseMessage, SystemMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import chain

import langgraph.graph as lgraph
from langchain_openai import ChatOpenAI # Import OpenAI Chat model

# 1. Define the State:

class GraphState(TypedDict):
    """
    Represents the state of our graph.

    Attributes:
        keys: Dictionary where we can store arbitrary values relevant to
        our graph.
    """

    keys: Dict[str, Any]

# 2. Define Nodes (Functions/Agents):
#Load API key
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"#Replace with your API Key or load it from environment variables

#Configure LLM - replace with your LLM or configuration
your_llm = ChatOpenAI(temperature=0.7)

def generate_outline(state: GraphState):
    """Generates a blog post outline."""
    topic = state["keys"]["topic"]

    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are an expert blog post outline generator.  Given a topic, you create a detailed and well-structured outline."),
        ("human", "Please generate a detailed outline for a blog post on the topic: {topic}")
    ])

    chain = prompt | your_llm
    outline = chain.invoke({"topic": topic})
    return {"keys": {"outline": outline.content}} #Return the extracted text from the LLM's result

def write_content(state: GraphState):
    """Writes the blog post content based on the outline."""
    outline = state["keys"]["outline"]

    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are an expert blog post writer.  Given an outline, you write high-quality, engaging, and informative content."),
        ("human", "Please write a blog post based on the following outline:\n{outline}")
    ])

    chain = prompt | your_llm
    content = chain.invoke({"outline": outline})
    return {"keys": {"content": content.content}} #Return the extracted text from the LLM's result

# 3. Define the Graph:

workflow = lgraph.GraphState(GraphState)

workflow.add_node("generate_outline", generate_outline)
workflow.add_node("write_content", write_content)

workflow.set_entry_point("generate_outline")

workflow.add_edge("generate_outline", "write_content")

# Compile the graph
app = workflow.compile()

# 4. Run the Workflow:

# Input topic
topic = "The Future of AI in Education"

# Initial state
state = {"keys": {"topic": topic}}

# Run the graph
result = app.invoke(state)

# Print the results
print("Blog Post Outline:\n", result['keys']['outline'])
print("\nBlog Post Content:\n", result['keys']['content'])

OpenAI Swarm:轻量级Agent协调的先锋

OpenAI 的 Swarm 是一个实验性的开源框架,旨在帮助开发者协调多Agent AI 系统,专注于轻量级的协调,使Agent之间的交互更加可控和易于测试。

  • 轻量级协调 :Swarm 设计用于快速、高效的Agent协调,避免了不必要的开销,提高了系统的响应速度和性能。
  • 可控性 :该框架赋予开发者轻松测试和定制Agent交互方式的能力,使开发者能够根据需求灵活调整Agent的行为和协作方式。
  • 客户端操作 :Swarm 几乎完全在客户端运行,为开发者提供了对系统行为和状态管理的更大控制权,增强了系统的可预测性和测试的便捷性。
    Swarm Logo

示例 :分诊Agent根据用户的输入,将用户请求定向到销售Agent或退款Agent,通过简单的规则和流程,实现了对用户请求的有效分类和处理,提高了客户服务的效率和质量。

from swarm import Swarm, Agent

# Initialize the Swarm client
client = Swarm()

# Define the Refunds Agent
def process_refund(item_id, reason="NOT SPECIFIED"):
    """Refund an item. Ensure you have the item_id and ask for user confirmation before processing."""
    print(f"[mock] Refunding item {item_id} because {reason}...")
    return"Success!"

de fapply_discount():
    """Apply a discount to the user's cart."""
    print("[mock] Applying discount...")
    return"Applied discount of 10%"

refunds_agent = Agent(
    name="Refunds Agent",
    instructions="Assist the user with refunds. If the reason is that it was too expensive, offer a discount. If they insist, then process the refund.",
    functions=[process_refund, apply_discount],
)

# Define the Sales Agent
sales_agent = Agent(
    name="Sales Agent",
    instructions="Be super enthusiastic about selling our products.",
)

# Define functions to transfer control between agents
def transfer_to_sales():
    return sales_agent

def transfer_to_refunds():
    return refunds_agent

def transfer_back_to_triage():
    return triage_agent

# Define the Triage Agent
triage_agent = Agent(
    name="Triage Agent",
    instructions="Determine which agent is best suited to handle the user's request, and transfer the conversation to that agent.",
    functions=[transfer_to_sales, transfer_to_refunds],
)

# Add transfer function to Sales and Refunds agents
sales_agent.functions.append(transfer_back_to_triage)
refunds_agent.functions.append(transfer_back_to_triage)

# User message
messages = [{"role": "user", "content": "I would like a refund for my recent purchase."}]

# Run the Swarm client starting with the Triage Agent
response = client.run(agent=triage_agent, messages=messages)

# Print the response from the active agent
print(response.messages[-1]["content"])

如何选择合适的框架

这六大框架各有特点,(排名不分先后)

  • Agently 以其简单易用和插件增强的特点,让开发者能够快速构建 AI Agent 原生应用
  • CrewAI 适用于多Agent协作和角色定义的场景
  • Phidata 在记忆管理和多Agent编排方面表现出色
  • AutoGen 专注于对话式 AI 和工作流程支持
  • LangGraph 简化了复杂 AI 工作流程的创建
  • OpenAI Swarm 则提供了轻量级的Agent协调框架

选择合适的框架取决于 AI Agent应用的具体需求,开发者应考虑任务的复杂性、对记忆和知识管理的需求、多Agent协作的重要性以及所需的控制和定制化程度等因素,以确保选择最适合项目需求的框架。

如何学习大模型 AI ?

由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。

但是具体到个人,只能说是:

“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。

这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。

在这里插入图片描述

第一阶段(10天):初阶应用

该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。

  • 大模型 AI 能干什么?
  • 大模型是怎样获得「智能」的?
  • 用好 AI 的核心心法
  • 大模型应用业务架构
  • 大模型应用技术架构
  • 代码示例:向 GPT-3.5 灌入新知识
  • 提示工程的意义和核心思想
  • Prompt 典型构成
  • 指令调优方法论
  • 思维链和思维树
  • Prompt 攻击和防范

第二阶段(30天):高阶应用

该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。

  • 为什么要做 RAG
  • 搭建一个简单的 ChatPDF
  • 检索的基础概念
  • 什么是向量表示(Embeddings)
  • 向量数据库与向量检索
  • 基于向量检索的 RAG
  • 搭建 RAG 系统的扩展知识
  • 混合检索与 RAG-Fusion 简介
  • 向量模型本地部署

第三阶段(30天):模型训练

恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。

到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?

  • 为什么要做 RAG
  • 什么是模型
  • 什么是模型训练
  • 求解器 & 损失函数简介
  • 小实验2:手写一个简单的神经网络并训练它
  • 什么是训练/预训练/微调/轻量化微调
  • Transformer结构简介
  • 轻量化微调
  • 实验数据集的构建

第四阶段(20天):商业闭环

对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。

  • 硬件选型
  • 带你了解全球大模型
  • 使用国产大模型服务
  • 搭建 OpenAI 代理
  • 热身:基于阿里云 PAI 部署 Stable Diffusion
  • 在本地计算机运行大模型
  • 大模型的私有化部署
  • 基于 vLLM 部署大模型
  • 案例:如何优雅地在阿里云私有部署开源大模型
  • 部署一套开源 LLM 项目
  • 内容安全
  • 互联网信息服务算法备案

学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。

如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。

这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费

在这里插入图片描述

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐