本文来源公众号“数据派THU”,仅用于学术分享,侵权删,干货满满。
原文链接:独家|5 个难度级别的人工智能代理(含完整代码实现)
在一个重要产品上线前两周,我的人工智能原型代理以最糟糕的方式崩溃了。
我的原型代理看起来很好。它可以获取数据,调用工具,甚至可以解释其步骤。但从本质上看,它只是在虚张声势。它既没有状态管理,没有内存,也没有推理能力,本质上只是在不断地循环提示,假装自己很聪明的样子。
直到一个边缘用例把它彻底搞崩,这时我才意识到:我建立的根本不是一个代理,建立的只是一个花哨的提示链。
修复这个代理问题意味着要重新设计整个系统 — 不仅仅是堆提示链,还要包括管理状态、决策和长期工作流。一旦解决了这个问题,一切都变得简单了:代码更简单、逻辑更通顺、结果更稳定。
本指南的内容如下:将代理设计分为五个实际难度级别— 每个级别都有可工作的代码。
无论您是刚刚入门还是正在尝试扩展实际任务,这些经验都将帮助您避免我踩过的坑,构建真正有效的代理。
这些级别是:
-
第1 级:带工具和指令的代理
-
第2 级:具有知识和记忆的代理
-
第3 级:具有长期记忆和推理能力的代理
-
第4 级:多代理协作团队
-
第5 级:代理系统
好了,让现在我们开始吧。
第1级:带工具和指令的代理
这是基本设置— 一个遵循指令并在循环中调用工具的 LLM。当人们说“ 代理只是 LLM 加上工具使用 ”时,他们指的正是这个层级(也顺带暴露了他们探索代理的深度)。
指令告诉代理应该做什么,工具让它动起来 — 获取数据、调用 API 或触发工作流。虽然很简单,但已经足够强大,可以自动执行某些任务。
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.duckduckgo import DuckDuckGoTools
agno_assist = Agent(
name="Agno AGI",
model=0penAIChat(id="gpt-4.1"),
description=dedent("""\
You are "Agno AGI, an autonomous AI Agent that can build agents using the Agno)
framework. Your goal is to help developers understand and use Agno by providing
explanations, working code examples, and optional visual and audio explanations
of key concepts."""),
instructions="Search the web for information about Agno.",
tools=[DuckDuckGoTools()],
add_datetime_to_instructions=True,
markdown=True,
)
agno_assist.print_response("What is Agno?", stream=True)
第2级:具有知识和记忆的代理
大多数任务需要模型本身没有的信息。因为你不能把所有东西都塞进上下文中,所以代理就需要一种方法在运行时获取知识——这就是代理 RAG 或动态 few-shoting 提示的用武之地。
搜索应该是混合的(全文+语义),并且必须重排序。混合搜索+重排序是实现代理检索的最佳的即插即用方案。
储存为代理提供记忆能力。默认情况下,LLM 是无状态的;通过保存过去的操作、消息和观察,让代理具有状态,能够参考到目前为止已有的信息并做出更优决策。
... imports
# You can also use https://docs.agno.com/llms-full.txt for the full documentation
knowledge_base = UrlKnowledge(
urls=["https://docs.agno.com/introduction.md"],
vector_db=LanceDb(
uri="tmp/lancedb",
table_name="agno_docs",
search_type=SearchType.hybrid,
embedder=0penAIEmbedder(id="text-embedding-3-small"),
reranker=CohereReranker(model="rerank-multilingual-v3.0"),
),
)
storage = SqliteStorage(table_name="agent_sessions", db_file="tmp/agent.db")
agno_assist = Agent(
name="Agno AGI",
model=OpenAIChat(id="gpt-4.1"),
description=...,
instructions=...,
tools=[PythonTools(), DuckDuckGoTools()],
add_datetime_to_instructions=True,
# Agentic RAG is enabled by default when 'knowledge' is provided to the Agent.
knowledge=knowledge_base,
# Store Agent sessions in a sqlite database
storage=storage,
# Add the chat history to the messages
add_history_to_messages=True,
# Number of history runs
num_history_runs=3,
markdown=True,
)
if __name_ == "__main__":
# Load the knowledge base, comment after first run
# agno_assist.knovledge.load(recreate=True)
agno _assist.print_response("What is Agno?", stream=True)
第3级:具有长期记忆和推理能力的代理
记忆功能让代理可以跨会话调用详细信息(例如用户首选项偏好、过去的操作或失败的尝试),并随着时间的推移进行调整优化。这解锁了个性化和连续性。我们在这里只是触及了表面,但最让我兴奋的是自学能力:代理根据过去的经验改进自身行为。
推理再更进一步。
推理可以帮助代理分解问题,做出更优决策,并更可靠地执行多步骤指示。这不仅仅是在于理解——而是在于提高每个步骤的成功率。每个认真的代理构建者都需要知道何时以及如何应用推理能力。
... imports
knowledge_base = ...
memory = Memory(
# Use any model for creating nemories
model=0penAIChat(id="gpt-4.1"),
db=SqliteMemoryDb(table_name="user_menories", db_file="tmp/agent.db"),
delete_memories=True,
clear_memories=True,
)
storage =
agno_assist = Agent(
name="Agno AGI",
model=Claude (id="claude-3-7-sonnet-latest"),
# User for the memories
user_id="ava",
description=...,
instructions=...,
# Give the Agent the ability to reason
tools=[PythonTools(), DuckDuckGoTools(),
ReasoningTools(add_instructions=True)],
...
# Store memories in a sqlite database
memory=memory,
# Let the Agent manage its menories
enable_agentic_memory=True,
)
if __name__ == "__main__":
# You can comment this out after the first run and the agent will remember
agno_assist.print_response("Always start your messages with 'hi ava'", stream=True)
agno_assist.print_response("What is Agno?", stream=True)
第4级:多代理协作团队
代理在专注时最有效— 专注于一个领域,具有紧凑的工具集(理想情况下少于10 个)。为了处理更复杂或更广泛的任务,我们会将多个代理合并为团队。每个代理负责处理一个问题,多个代理一起覆盖更多的领域。
但有一个问题:如果没有强有力的推理,团队领导会在一些细微的复杂情况上崩溃。根据我目前的观察,自主多代理系统仍然不能可靠地工作,成功率不到一半 — 这还不够好。
也就是说,一些架构使协调更容易。例如,Agno 支持三种执行模式 —— 协调、路由和协作 —— 以及内置的内存和上下文管理功能。虽然仍然需要谨慎设计,但这些基础模块使多代理工作更加可行。↳
... imports
web agent = Agent(
name="Web Search Agent",
role="Handle web search requests",
model= OpenAIChat(id="gpt-4o-mini"),
tools=[DuckDuckGoTools()],
instructions="Always include sources",
)
finance_agent= Agent(
name="Finance Agent",
role="Handle financial data requests",
model=OpenAIChat(id="gpt-4o-mini"),
tools=[YFinanceTools()],
instructions=[
"You are a financial data specialist. Provide concise and accurate data.",
"Use tables to display stock prices, fundamentals (P/E, Market Cap)",
],
)
team_leader = Team (
name="Reasoning Finance Team Leader",
mode="coordinate",
model=Claude(id="claude-3-7-sonnet-latest"),
members=[web_agent, finance_agent],
tools=[ReasoningTools(add_instructions=True)],
instructions=[
"Use tables to display data",
"Only output the final answer, no other text.",
],
show_members_responses=True,
enable_agentic_context=True,
add_datetime_to_instructions=True,
success_criteria="The team has successfully completed the task.",
)
if __name__ == "__main__":
team_leader.print_response(
"""\
Analyze the impact of recent US tariffs on market performance across
these key sectors:
- Steel & Aluminum: (X, NUE, AA)
- Technology Hardware: (AAPL, DELL, HPQ)
For each sector:
1. Compare stock performance before and after tariff implementation
2. Identify supply chain disruptions and cost impact percentages
3. Analyze companies' strategic responses (reshoring, price adjustments, supplier
diversification)""",
stream=True,
stream_intermediate_steps=True,
show_full_reasoning=True,
)
第5级:代理系统
在这一级,代理从“工具”变成“基础设施”。代理系统是一整套完整的API,用于接收用户请求、启动异步工作流,并在结果可用时将其逐步传输回去。
这样听起来很简单。但在实践中,这很难,真的很难。
您需要在请求到达时保留状态,启动后台任务,实时跟踪进度,并在生成时逐步输出内容。Websockets 可以提供帮助,但扩展和维护的问题很棘手。大多数团队往往都低估了这里的后端复杂性。
这些是将代理转化为真实产品所需要的。在这个级别上,您不是在构建功能,而是在构建一个系统。
从演示翻车到真正的胜利:代理设计的关键经验教训
构建AI 代理不是为了追逐热点或堆叠功能,而是要掌握正确的基础知识。从基本工具调用到完全异步的代理系统,每个级别只有在底层架构健全时才能增加功能。
大多数失败的根源并不是没赶上最新的框架潮流,而是忽略了核心要素:清晰的边界、可靠的推理、有效的记忆机制,以及清楚什么时候该交由人类来决策。
如果你从简单开始,有目的地构建系统,一开始不要急于追求过高的复杂度,只有在解决实际问题时才增加复杂性,那么你不仅会构建一些很酷的项目,还会构建一些有效的系统。
原文标题:
Tracing the Transformer in Diagrams
原文链接:
https://medium.com/data-science-collective/ai-agents-in-5-levels-of-difficulty-with-full-code-implementation-15d794becfb8
THE END !
文章结束,感谢阅读。您的点赞,收藏,评论是我继续更新的动力。大家有推荐的公众号可以评论区留言,共同学习,一起进步。