源码级别解析 · 源码解析 · 企业级AI智能体框架
2026-05-27 | 每日技术深度解读
AI智能体从概念走向工业化部署
三层架构,提供完整的智能体开发到部署解决方案
无需重新构建基础设施,开箱即用
from agno.agent import Agent
from agno.tools.workspace import Workspace
from pathlib import Path
folder = Path(__file__).parent
sorting_hat = Agent(
name="Sorting Hat",
model="openai:gpt-5.5",
tools=[Workspace(root=str(folder), allowed=["read", "list", "search", "shell"])],
instructions=(
"Walk the folder, figure out what's there, and propose a clean organization. "
"Decide the categories yourself. Use shell commands when they help."
),
markdown=True,
)
sorting_hat.print_response(f"Inventory and organize {folder}", stream=True)
最简单的智能体实现,20行代码完成文件整理智能体
同一个智能体,从临时脚本到生产级API服务
from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.os import AgentOS
from agno.tools.workspace import Workspace
workbench = Agent(
name="Workbench",
model="openai:gpt-5.5",
db=SqliteDb(db_file="workbench.db"), # 会话存储
tools=[Workspace(".")], # 操作目录
enable_agentic_memory=True, # 跨会话记忆
add_history_to_context=True, # 历史上下文
num_history_runs=3, # 最近3次运行
)
# 通过AgentOS提供服务,支持流式传输、认证、会话隔离
agent_os = AgentOS(agents=[workbench], tracing=True)
app = agent_os.get_app()
添加了会话存储、记忆、认证等生产级功能
AgentOS是Agno的核心运行时引擎
AgentOS的三层架构分离了构建、运行和管理的关注点
三个核心原语通过共享的AgentOS运行时层统一
所有组件最终都追溯到这三个核心原语
支持任意模型提供商,无需修改智能体代码
# 同时支持多个模型
from agno.models import OpenAIModel, AnthropicModel
agents = [
Agent(
name="Code Assistant",
model=OpenAIModel(model="gpt-5.5-turbo"),
tools=[...]
),
Agent(
name="Creative Writer",
model=AnthropicModel(model="claude-3-5-sonnet-20241022"),
tools=[...]
),
Agent(
name="Data Analyst",
model=OpenAIModel(model="gpt-4o"),
tools=[...]
)]
# 统一管理
agent_os = AgentOS(agents=agents, tracing=True)
同一平台运行不同模型的专业智能体
支持多种数据库,智能体代码无需关心存储细节
| 数据库类型 | 适用场景 | 特性 |
|---|---|---|
| SQLite | 开发/测试 | 轻量级,文件存储 |
| PostgreSQL | 生产环境 | ACID事务,复杂查询 |
| Redis | 缓存层 | 高性能内存存储 |
| MongoDB | 文档存储 | 灵活的文档结构 |
Agno自动处理复杂的会话管理逻辑
# 会话存储示例
session_data = {
"session_id": "uuid",
"user_id": "user123",
"agent_id": "workbench",
"messages": [
{"role": "user", "content": "帮我整理文档"},
{"role": "assistant", "content": "好的,我来帮您..."}
],
"memory": {
"user_preferences": {"format": "markdown"},
"project_context": {"files_processed": 15}
},
"created_at": "2026-05-27T16:00:00Z",
"updated_at": "2026-05-27T16:05:00Z"
}
会话数据结构,包含完整的对话历史和智能体记忆
开箱即用的可观测性,无需额外配置
遵循OpenTelemetry标准,支持主流监控平台
# 启用完整追踪
from agno.providers.opentelemetry import OpenTelemetryProvider
agent_os = AgentOS(
agents=[workbench],
tracing=True, # 启用追踪
telemetry=OpenTelemetryProvider(
service_name="agno-platform",
resource_attributes={
"service.version": "1.0.0",
"deployment.environment": "production"
}
)
)
配置OpenTelemetry提供者,自动收集智能体运行数据
丰富的工具库,支持各种智能体任务
涵盖智能体开发所需的常见工具类型
# 工具权限控制
workspace_tool = Workspace(
root="/project/data",
allowed=["read", "list", "search"], # 只允许读操作
blocked=["delete", "write"] # 禁止写操作
)
# 工具组合使用
class DataAnalysisTool:
def __init__(self, db_connection):
self.db = db_connection
def analyze_data(self, query):
# 数据分析逻辑
pass
def generate_report(self, analysis):
# 报告生成逻辑
pass
# 智能体使用工具
agent = Agent(
name="Data Scientist",
model="openai:gpt-5.5",
tools=[workspace_tool, DataAnalysisTool(db)]
)
工具权限控制和组合使用示例
Agno为智能体提供结构化的长期记忆能力
不同类型的记忆服务于不同的智能体需求
# 智能体记忆管理
agent.enable_agentic_memory = True
# 自动记忆更新
agent.update_user_memory({
"user_preferences": {
"response_format": "detailed",
"tone": "professional",
"focus_areas": ["data_analysis", "visualization"]
},
"project_context": {
"current_task": "季度数据分析",
"deadline": "2026-06-15",
"team_members": ["Alice", "Bob", "Charlie"]
}
})
# 记忆检索和注入
current_context = agent.get_user_memory("user_preferences")
# 记忆自动注入到后续对话中
自动化的记忆管理和上下文注入
Agno Team支持复杂的多智能体协作场景
# 多智能体协作示例
from agno.team import Team
from agno.role import Role
# 定义角色
researcher = Role(
name="Researcher",
model="openai:gpt-5.5",
instructions="负责市场调研和分析"
)
analyst = Role(
name="Analyst",
model="anthropic:claude-3-5-sonnet",
instructions="负责数据分析和趋势识别"
)
writer = Role(
name="Writer",
model="openai:gpt-4o",
instructions="负责撰写分析报告"
)
# 创建团队
research_team = Team(
name="Market Research Team",
roles=[researcher, analyst, writer],
workflow="sequential" # 顺序执行
)
# 执行团队任务
result = research_team.execute("分析Q2市场趋势")
定义不同角色,执行复杂的多智能体协作任务
Workflow引擎支持复杂的业务逻辑实现
# 复杂工作流定义
from agno.workflow import Workflow, Step, Condition
content_pipeline = Workflow(
name="Content Creation Pipeline",
steps=[
Step(
name="Research",
agent=research_agent,
inputs="{topic}"
),
Step(
name="Outline",
agent=outliner_agent,
depends_on="Research",
inputs="{topic}, {research_results}"
),
Step(
name="Draft",
agent=draft_writer_agent,
depends_on="Outline",
inputs="{outline}"
),
Step(
name="Review",
agent=reviewer_agent,
depends_on="Draft",
condition=Condition(
condition="review_score > 7",
true_action="Publish",
false_action="Revise"
)
)
]
)
result = content_pipeline.execute(topic="AI发展趋势")
定义完整的内容创作工作流,包含条件分支
开箱即用的企业级安全功能
# RBAC 配置
from agno.security import RBAC
rbac_config = RBAC(
roles={
"admin": {
"permissions": ["*"], # 超级管理员
"agents": ["*"]
},
"analyst": {
"permissions": ["read", "execute"],
"agents": ["data-analyzer", "report-generator"]
},
"viewer": {
"permissions": ["read"],
"agents": ["report-viewer"]
}
},
users={
"alice": {"role": "admin"},
"bob": {"role": "analyst"},
"charlie": {"role": "viewer"}
}
)
# 应用到AgentOS
agent_os = AgentOS(
agents=[...],
rbac=rbac_config
)
基于角色的访问控制,精细化的权限管理
完整的RESTful API,支持各种集成场景
| 类别 | 端点 | 功能 |
|---|---|---|
| 智能体 | POST /agents | 创建智能体 |
| 智能体 | GET /agents | 获取智能体列表 |
| 会话 | POST /sessions | 创建会话 |
| 会话 | GET /sessions/{id} | 获取会话详情 |
| 追踪 | GET /traces | 查询追踪数据 |
| 工具 | POST /tools/execute | 执行工具 |
支持低延迟的实时通信场景
// 客户端WebSocket连接
const ws = new WebSocket('ws://localhost:8000/ws/chat');
ws.onopen = () => {
// 发送消息
ws.send(JSON.stringify({
type: 'message',
sessionId: 'uuid',
content: '帮我分析销售数据',
stream: true // 启用流式响应
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'stream') {
// 处理流式响应
document.getElementById('response').textContent += data.content;
} else if (data.type === 'complete') {
// 处理完成状态
console.log('响应完成:', data.summary);
}
};
ws.onerror = (error) => {
console.error('WebSocket错误:', error);
};
客户端WebSocket连接实现,支持流式响应
支持多种数据类型的智能体处理能力
基于计算机视觉的智能体工具集
# 图像分析智能体
from agno.tools.image import ImageAnalyzer, ImageGenerator
image_analyzer = ImageAnalyzer(
model="openai:gpt-4-vision-preview",
capabilities=[
"description",
"ocr",
"object_detection",
"classification"
]
)
image_generator = ImageGenerator(
model="dall-e-3",
size="1024x1024",
quality="hd"
)
# 创建图像处理智能体
image_agent = Agent(
name="Image Processing Assistant",
model="openai:gpt-5.5",
tools=[image_analyzer, image_generator],
instructions="专业的图像处理和分析助手"
)
# 执行图像分析
result = image_agent.process("分析这张产品图片,提取关键信息")
集成图像分析、OCR和生成功能的专业智能体
支持多种实时数据源的上下文注入
深度集成Slack,实现团队智能体协作
# Slack 上下文提供者
from agno.context.slack import SlackContextProvider
slack_provider = SlackContextProvider(
workspace_id="T1234567890",
bot_token="xoxb-...",
channels=["#general", "#dev-team"],
time_range="7d" # 最近7天
)
# 创建Slack分析智能体
slack_agent = Agent(
name="Slack Analytics",
model="openai:gpt-5.5",
context_providers=[slack_provider],
instructions="分析团队Slack活动,生成洞察报告"
)
# 分析团队讨论
analysis = slack_agent.analyze("分析最近的技术讨论趋势")
基于Slack上下文的团队分析智能体
确保AI决策的准确性和安全性
多层次审核系统平衡效率与准确性
# 人类审核配置
from agno.review import HumanReviewConfig
review_config = HumanReviewConfig(
trigger_conditions={
"confidence_score": 0.7, # 置信度低于70%需要审核
"content_length": 1000, # 超过1000字需要审核
"sensitive_keywords": ["财务", "合同", "法律"]
},
review_channel="#admin-review",
timeout=300, # 5分钟等待时间
auto_approve=True # 达到条件自动批准
)
# 应用审核配置
agent = Agent(
name="Financial Assistant",
model="openai:gpt-5.5",
review=review_config,
tools=[...]
)
# 执行需要审核的任务
result = agent.execute("分析财务报表并生成投资建议")
配置智能体在特定条件下请求人类审核
内置调度系统,无需外部依赖
# 定时任务配置
from agno.scheduling import CronSchedule
# 定义每日报告任务
daily_report = Agent(
name="Daily Report Generator",
model="openai:gpt-4o",
instructions="生成每日业务报告"
)
# 配置Cron调度
report_schedule = CronSchedule(
agent=daily_report,
cron="0 9 * * *", # 每天9点执行
timezone="Asia/Shanghai",
enabled=True
)
# 配置后台任务
cleanup_agent = Agent(
name="System Cleanup",
model="openai:gpt-4o",
instructions="清理过期会话和日志"
)
cleanup_schedule = CronSchedule(
agent=cleanup_agent,
cron="0 2 * * 0", # 每周日2点执行
enabled=True
)
# 应用调度配置
agent_os = AgentOS(
agents=[...],
schedules=[report_schedule, cleanup_schedule]
)
配置定时任务,实现自动化运维
支持多种部署模式,从开发到生产
典型的微服务部署架构,支持水平扩展
通过多种渠道与用户交互
在Slack中直接使用智能体功能
# Slack 机器人配置
from agno.interfaces.slack import SlackBot
# 创建Slack接口
slack_interface = SlackBot(
bot_token="xoxb-...",
app_token="xapp-...",
signing_secret="...",
agents={
"help": help_agent,
"analytics": analytics_agent,
"code-review": review_agent
},
commands={
"help": "帮助信息",
"analyze": "数据分析",
"review": "代码审查"
}
)
# 部署到Slack
agent_os.add_interface(slack_interface)
# 启动服务
if __name__ == "__main__":
agent_os.start()
配置Slack机器人,支持多种智能体命令
全面的系统监控和日志管理
结构化的日志系统,便于分析和查询
# 日志配置
import logging
from agno.logging import AgnoLogger
# 配置日志格式
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('agno.log'),
logging.StreamHandler()
]
)
# Agno专用日志配置
logger = AgnoLogger(
name="agno-platform",
log_format="json",
include_trace_id=True,
include_user_id=True,
log_file="/var/log/agno/platform.log"
)
# 使用日志
logger.info("Agent started", extra={
"agent_id": "data-analyzer",
"model": "gpt-5.5-turbo",
"version": "1.0.0"
})
配置结构化的JSON日志,包含跟踪和用户信息
为生产环境优化的性能特性
多级缓存提升响应速度
# 缓存配置
from agno.cache import RedisCache
# 配置Redis缓存
cache = RedisCache(
host="localhost",
port=6379,
db=0,
ttl=3600, # 1小时TTL
prefix="agno:"
)
# 配置智能体缓存策略
caching_agent = Agent(
name="Cached Assistant",
model="openai:gpt-5.5",
cache=cache,
cache_policy={
"query_cache": True, # 查询结果缓存
"memory_cache": True, # 记忆缓存
"response_cache": True, # 响应缓存
"cache_ttl": 1800 # 30分钟缓存
}
)
# 执行会缓存的查询
result = caching_agent.ask("什么是机器学习?")
配置智能体的多级缓存策略
完善的错误处理保证系统稳定性
直观的系统监控界面
开发者友好的设计和文档
Agno平台的开发和使用最佳实践
Agno在各行业的实际应用
帮助产品团队实现智能化转型
提升AI团队工作效率
优化数据科学工作流程
数据工程工作自动化
灵活的扩展机制满足定制需求
丰富的插件生态系统支持各种场景
Agno平台的长期技术规划
活跃的开源社区支持
感谢阅读!
访问 https://atcfu.com/ai-articles/agno/ 回顾本文