📚 目录
- [引言:工具系统在 AI Agent 中的核心价值](#引言:工具系统在 AI Agent 中的核心价值 "#%E5%BC%95%E8%A8%80%E5%B7%A5%E5%85%B7%E7%B3%BB%E7%BB%9F%E5%9C%A8-ai-agent-%E4%B8%AD%E7%9A%84%E6%A0%B8%E5%BF%83%E4%BB%B7%E5%80%BC")
- 第一部分:搜索类工具详解
- [第二部分:SQL 工具详解](#第二部分:SQL 工具详解 "#%E7%AC%AC%E4%BA%8C%E9%83%A8%E5%88%86sql-%E5%B7%A5%E5%85%B7%E8%AF%A6%E8%A7%A3")
- [第三部分:文件工具与 Python 执行](#第三部分:文件工具与 Python 执行 "#%E7%AC%AC%E4%B8%89%E9%83%A8%E5%88%86%E6%96%87%E4%BB%B6%E5%B7%A5%E5%85%B7%E4%B8%8E-python-%E6%89%A7%E8%A1%8C")
- [第四部分:MCP 工具详解](#第四部分:MCP 工具详解 "#%E7%AC%AC%E5%9B%9B%E9%83%A8%E5%88%86mcp-%E5%B7%A5%E5%85%B7%E8%AF%A6%E8%A7%A3")
- 第五部分:最佳实践与注意事项
- 总结与下期预告
引言:工具系统在 AI Agent 中的核心价值
为什么工具系统如此重要?
在 AI Agent 开发中,大语言模型(LLM)本身虽然具备强大的推理和语言理解能力,但它们存在一些固有的局限性:
- 知识截止日期限制:模型训练数据有时间边界,无法获取最新信息
- 幻觉问题:模型可能生成看似合理但实际错误的信息
- 缺乏执行能力:无法直接操作文件系统、数据库或调用外部 API
- 上下文窗口限制:无法处理超大规模的数据集
工具系统(Tools System) 正是为了解决这些问题而设计的。它赋予 AI Agent 以下能力:
- 🔍 实时信息检索:通过搜索工具获取最新的网络信息
- 🗄️ 数据持久化:通过数据库工具存储和查询结构化数据
- 📁 文件操作:读写文件、生成报告、处理文档
- 🐍 代码执行:动态运行 Python 代码进行复杂计算
- 🔌 外部集成:通过 MCP 协议连接各种第三方服务
- ....
Agno 工具系统架构概览
Agno 的工具系统采用 "工具包(Toolkit)" 设计模式,具有以下特点:
sql
┌─────────────────────────────────────────────────────────┐
│ Agno Agent Core │
│ ┌───────────────────────────────────────────────────┐ │
│ │ Model (DeepSeek/OpenAI/Gemini...) │ │
│ └───────────────────────────────────────────────────┘ │
│ ↕ │
│ ┌───────────────────────────────────────────────────┐ │
│ │ Tool Management Layer │ │
│ │ • Tool Selection & Filtering │ │
│ │ • Result Caching │ │
│ │ • Error Handling & Retries │ │
│ └───────────────────────────────────────────────────┘ │
│ ↕ │
│ ┌──────────┬──────────┬──────────┬──────────────────┐ │
│ │ Search │ SQL │ File │ MCP │ │
│ │ Tools │ Tools │ Tools │ Tools │ │
│ └──────────┴──────────┴──────────┴──────────────────┘ │
└─────────────────────────────────────────────────────────┘
核心优势:
- ✅ 统一接口:所有工具遵循标准化的注册和调用方式
- ✅ 模块化设计:工具包可独立配置,按需启用
- ✅ 高性能:工具调用经过优化,支持结果缓存
- ✅ 安全可控:支持工具过滤、调用限制和沙箱执行
版本说明
本教程基于 Agno 2.2.6 系列。
第一部分:搜索类工具详解
1.1 搜索工具概述
搜索工具是 AI Agent 获取实时信息的重要途径。Agno 支持超过 15 种搜索工具,涵盖通用搜索、学术搜索、新闻检索等多个领域。
支持的搜索工具列表
| 工具名称 | 适用场景 | 特点 |
|---|---|---|
| Tavily | 通用网络搜索 | 功能最完整,支持深度搜索、结构化输出 |
| DuckDuckGo | 隐私优先搜索 | 无需 API 密钥,支持多搜索引擎 |
| Google Search | 高质量搜索 | Google 官方支持,结果权威 |
| Baidu Search | 中文搜索 | 第三方百度搜索包,中文搜索友好,使用方法类同Google Search |
| Arxiv | 学术论文搜索 | 专注科研文献 |
| Wikipedia | 百科知识检索 | 结构化知识库 |
| Pubmed | 医学文献搜索 | 医疗健康领域权威 |
| HackerNews | 技术资讯 | 科技圈热点新闻 |
| SerperAPI/SerpAPI | SEO 优化搜索 | 支持地理位置、图片、新闻等 |
1.2 Tavily 搜索工具详解
Tavily 是 Agno 官方推荐的搜索工具,提供最完善的功能和最佳的集成体验。
核心功能特性
-
多层次搜索深度:
basic模式:1个 API 积分,快速返回结果advanced模式:2个 API 积分,全面深度搜索
-
灵活的输出格式:
json格式:结构化数据,便于程序处理markdown格式:可读性强,适合直接展示
-
智能内容总结:自动生成 AI 驱动的答案摘要
安装与配置
ini
# 安装依赖
pip install agno tavily-python
# 设置环境变量
export TAVILY_API_KEY="your_tavily_api_key_here"
export DEEPSEEK_API_KEY="your_deepseek_api_key_here"
代码示例:基础搜索
ini
from agno.agent import Agent
from agno.tools.tavily import TavilyTools
from agno.models.deepseek import DeepSeek
import os
# 初始化 Agent,使用 DeepSeek 模型
agent = Agent(
# 使用 DeepSeek Chat 模型(高性价比推理模型)
model=DeepSeek(id="deepseek-chat"),
# 配置 Tavily 搜索工具
tools=[TavilyTools(
search=True, # 启用搜索功能
max_tokens=8000, # 最大返回 8000 个 token
search_depth="advanced", # 使用深度搜索模式
format="markdown", # 以 Markdown 格式返回
include_answer=True, # 包含 AI 生成的答案摘要
max_results=5 # 最多返回 5 条搜索结果
)],
# 显示工具调用过程(便于调试)
show_tool_calls=True,
markdown=True
)
# 执行搜索查询
response = agent.print_response(
"2025年量子计算领域有哪些重大突破?请提供最新进展和技术细节。",
stream=True # 启用流式输出
)
输出示例:
yaml
🔧 Tool Call: web_search_using_tavily
Query: 2025年量子计算重大突破
📊 Search Results:
1. **IBM 推出 1000+ 量子比特处理器**
- 来源: Nature Technology (2025-10-15)
- 摘要: IBM 成功研发出 1,121 量子比特的 Condor 处理器...
2. **谷歌实现量子纠错新突破**
- 来源: Science Journal (2025-09-22)
- 摘要: Google Quantum AI 团队验证了表面码的可扩展性...
💡 AI 总结:
2025年量子计算领域主要有三大突破:
1. IBM 突破 1000 量子比特大关
2. 谷歌实现可扩展的量子纠错
3. 中国科学技术大学的光量子计算机性能提升...
Tavily 高级参数配置
ini
# Tavily 完整参数示例
tavily_tools = TavilyTools(
# 认证参数
api_key=os.getenv("TAVILY_API_KEY"), # API 密钥(可选,默认读取环境变量)
# 功能开关
enable_search=True, # 启用标准搜索
enable_search_context=False, # 启用上下文搜索(使用 Tavily Context API)
all=False, # 启用所有可用功能
# 搜索参数
max_tokens=6000, # 最大返回 token 数(默认 6000)
include_answer=True, # 是否包含 AI 答案摘要
search_depth="advanced", # 搜索深度: "basic" 或 "advanced"
format="markdown", # 输出格式: "json" 或 "markdown"
max_results=5, # 最多返回结果数(0-20)
)
1.3 DuckDuckGo 搜索工具
DuckDuckGo 是一个注重隐私的搜索引擎,无需 API 密钥,适合快速原型开发和小规模应用。
代码示例:DuckDuckGo 集成
ini
from agno.agent import Agent
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.models.deepseek import DeepSeek
# 使用 DuckDuckGo 搜索工具
agent = Agent(
model=DeepSeek(id="deepseek-chat"),
tools=[DuckDuckGoTools()], # 无需配置 API 密钥
show_tool_calls=True,
markdown=True
)
# 查询实时信息
agent.print_response(
"加拿大目前有多少人口?请提供最新的统计数据。"
)
v2.0.5 新增功能:自定义搜索引擎
ini
from agno.tools.duckduckgo import DuckDuckGoTools
# 使用自定义搜索引擎参数(v2.0.5+)
duckduckgo_tools = DuckDuckGoTools(
search_engine="google" # 可选: "google", "bing", "yahoo" 等
)
1.4 Google Search 工具
Google Search 提供高质量的搜索结果,适合需要权威信息的场景。
代码示例:Google Search 集成
python
from agno.agent import Agent
from agno.tools.googlesearch import GoogleSearchTools
from agno.models.deepseek import DeepSeek
import os
# 配置 Google Search
agent = Agent(
model=DeepSeek(id="deepseek-chat"),
tools=[GoogleSearchTools()],
read_tool_call_history=True
)
# 执行搜索
agent.print_response("Python 3.12 有哪些新特性?")
1.5 实战案例:多源信息聚合 Agent
场景描述:构建一个能够从多个搜索引擎聚合信息的智能 Agent,用于技术调研。
ini
from agno.agent import Agent
from agno.tools.googlesearch import GoogleSearchTools
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.models.deepseek import DeepSeek
import os
from dotenv import load_dotenv
load_dotenv()
# 创建多搜索引擎 Agent
research_agent = Agent(
model=DeepSeek(
id="deepseek-reasoner", # 使用推理增强模型
api_key=os.getenv("DEEPSEEK_API_KEY")
),
# 同时配置多个搜索工具
tools=[
GoogleSearchTools(),
DuckDuckGoTools() # 作为备用搜索源
],
# Agent 配置
name="TechResearcher",
description="专业的技术调研助手,能够从多个来源聚合信息",
instructions=[
"优先使用 Google 进行深度搜索",
"如果 Google 结果不足,使用 DuckDuckGo 补充",
"整合多源信息,去重并标注来源",
"以结构化的 Markdown 格式呈现调研结果"
],
read_tool_call_history=True,
markdown=True
)
# 执行复杂调研任务
query = """
请调研以下内容:
1. Rust 编程语言在 2024-2025 年的主要发展方向
2. Rust 在 Web 开发领域的最新框架和工具
3. 与 Go 语言相比的性能基准测试数据
请提供详细的技术分析报告。
"""
research_agent.print_response(input=query, stream=True)
预期输出结构:
markdown
# Rust 编程语言技术调研报告
## 1. 主要发展方向(2024-2025)
### 1.1 异步运行时改进
- **来源**: [Tavily] Rust Blog Official (2024-11-15)
- **内容**: Tokio 1.35 版本引入新的异步调度器...
### 1.2 编译性能优化
- **来源**: [DuckDuckGo] Reddit r/rust (2025-01-03)
- **内容**: 增量编译优化降低 30% 构建时间...
## 2. Web 开发框架
| 框架名称 | 版本 | 特点 | 来源 |
|---------|------|------|------|
| Axum | 0.7.x | 模块化、类型安全 | Tavily |
| Actix-web | 4.5.x | 高性能、成熟稳定 | DuckDuckGo |
## 3. 性能对比(Rust vs Go)
### 基准测试结果
- **来源**: [Tavily] TechEmpower Benchmarks
- **测试环境**: AWS EC2 c5.4xlarge
...
1.6 常见问题与优化建议
Q1: 如何选择合适的搜索工具?
决策树:
需要 API 密钥吗?
├─ 是 → 预算充足?
│ ├─ 是 → 选择 Tavily(功能最全)
│ └─ 否 → 选择 SerperAPI(按量计费)
└─ 否 → 选择 DuckDuckGo(免费)
需要学术文献?
└─ 是 → 选择 Arxiv 或 Pubmed
需要实时新闻?
└─ 是 → 选择 Google News API 或 HackerNews
Q2: 搜索结果太多,如何过滤?
ini
# 策略 1: 限制结果数量
tavily_tools = TavilyTools(max_results=3)
# 策略 2: 提高搜索质量
tavily_tools = TavilyTools(
search_depth="advanced", # 使用深度搜索
include_answer=True # 利用 AI 摘要
)
# 策略 3: 在 Agent 指令中明确要求
agent = Agent(
tools=[tavily_tools],
instructions=[
"只返回最相关的前 3 条结果",
"优先展示权威来源(如官方文档、学术论文)",
"过滤掉广告和低质量内容"
]
)
Q3: 如何提升搜索性能?
优化技巧:
- 结果缓存:启用 Agno 的工具结果缓存功能
- 并行搜索:使用异步 Agent 同时查询多个来源
- 智能降级:优先使用付费 API,失败后降级到免费工具
ini
from agno.agent import Agent
from agno.tools.tavily import TavilyTools
from agno.tools.duckduckgo import DuckDuckGoTools
# 启用结果缓存
agent = Agent(
tools=[
TavilyTools(),
DuckDuckGoTools()
],
store_tool_messages=True, # 启用缓存
tool_call_limit=10 # 限制单次对话的工具调用次数
)
第二部分:SQL 工具详解
2.1 SQL 工具概述
Agno 提供完整的数据库操作能力,支持主流 SQL 数据库,让 AI Agent 能够查询、分析和管理结构化数据。
支持的数据库类型
| 数据库 | 工具类 | 适用场景 | 依赖库 |
|---|---|---|---|
| PostgreSQL | PostgresTools |
企业级应用、复杂查询 | psycopg2 |
| SQLite | SQLTools |
轻量级应用、原型开发 | sqlite3(内置) |
| MySQL | SQLTools |
Web 应用、中等规模项目 | pymysql |
2.2 PostgreSQL 工具详解
PostgreSQL 是 Agno 最完善支持的数据库系统,提供专用的 PostgresTools 工具包。
核心功能
- 表结构探索 :
show_tables()、describe_table() - 数据分析 :
summarize_table()- 自动统计分析 - 查询执行 :
run_query()- 执行只读 SQL 查询 - 性能分析 :
inspect_query()- 查看查询计划 - 数据导出 :
export_table_to_path()- 导出为 CSV
环境准备
ini
# 安装 PostgreSQL 驱动
pip install psycopg2-binary
# 使用 Docker 快速启动 PostgreSQL(可选)
docker run -d \
--name postgres \
-e POSTGRES_PASSWORD=postgres \
-e POSTGRES_USER=postgres \
-p 5432:5432 \
-v pgdata:/var/lib/postgresql/data \
postgres:latest \
代码示例:基础数据库查询
ini
from agno.agent import Agent
from agno.tools.postgres import PostgresTools
from agno.models.deepseek import DeepSeek
import os
from dotenv import load_dotenv
load_dotenv()
# 方式 1: 使用独立连接参数
postgres_tools = PostgresTools(
host="localhost",
port=5432,
db_name="ai",
user="postgres",
password="postgres",
table_schema="public" # 指定 schema
)
# 方式 2: 使用数据库 URL(推荐)
db_url = "postgresql+psycopg://postgres:postgres@localhost:5432/ai"
postgres_tools = PostgresTools(db_url=db_url)
# 创建数据库 Agent
db_agent = Agent(
model=DeepSeek(id="deepseek-chat", api_key=os.getenv("DEEPSEEK_API_KEY")),
tools=[postgres_tools],
name="DatabaseAnalyst",
description="专业的数据库分析助手",
instructions=[
"使用 SQL 查询回答用户问题",
"查询前先了解表结构",
"确保 SQL 语句的安全性(只读操作)",
"以易读的格式展示查询结果"
],
read_tool_call_history=True,
markdown=True
)
# 执行自然语言查询
db_agent.print_response(
input="获取最近 30 天注册的所有用户,按注册时间降序排列"
)
Agent 内部执行流程:
python
用户输入: "获取最近 30 天注册的所有用户,按注册时间降序排列"
↓
1. show_tables() → 发现 `users` 表
↓
2. describe_table("users") → 了解列结构
- id: INTEGER
- username: VARCHAR(50)
- email: VARCHAR(100)
- created_at: TIMESTAMP
↓
3. run_query("""
SELECT id, username, email, created_at
FROM users
WHERE created_at >= NOW() - INTERVAL '30 days'
ORDER BY created_at DESC
""")
↓
4. 格式化结果并返回
高级示例:数据分析 Agent
ini
import os
from agno.agent import Agent
from agno.tools.postgres import PostgresTools
from agno.models.deepseek import DeepSeek
from agno.db.postgres import PostgresDb
from dotenv import load_dotenv
load_dotenv()
# 配置数据库连接
db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
# 创建持久化存储(用于保存对话历史)
db_storage = PostgresDb(db_url=db_url)
# 数据分析 Agent
analytics_agent = Agent(
model=DeepSeek(
id="deepseek-reasoner", # 使用推理模型处理复杂分析
api_key=os.getenv("DEEPSEEK_API_KEY")
),
# 配置数据库工具
tools=[PostgresTools(db_url=db_url)],
# 启用会话存储(记住之前的查询)
db=db_storage,
add_history_to_context=True,
# Agent 配置
name="DataAnalytics",
description="企业级数据分析专家",
instructions=[
"使用 SQL 进行数据分析和洞察挖掘",
"对于复杂问题,分步骤查询",
"先用 summarize_table() 了解数据分布",
"使用 inspect_query() 优化慢查询",
"以可视化建议的形式呈现结果"
],
read_tool_call_history=True,
markdown=True
)
# 复杂分析任务
query = """
分析电商平台的用户购买行为:
1. 统计各类别商品的销售额和订单量
2. 找出复购率最高的 10 个用户
3. 计算平均客单价和订单间隔时间
4. 给出业务优化建议
"""
analytics_agent.print_response(query, stream=True)
2.3 SQLite 工具
SQLite 是轻量级的嵌入式数据库,无需独立服务器,适合快速原型和小规模应用。
代码示例:SQLite 自然语言查询
python
import sqlite3
from agno.agent import Agent
from agno.tools.sql import SQLTools
from agno.models.deepseek import DeepSeek
import os
# Step 1: 创建示例数据库
def create_sample_db():
conn = sqlite3.connect("example.db")
cursor = conn.cursor()
# 创建客户表
cursor.execute("""
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE,
city TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# 创建订单表
cursor.execute("""
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER,
product TEXT,
amount DECIMAL(10, 2),
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (customer_id) REFERENCES customers(id)
)
""")
# 插入示例数据
customers = [
(1, "张三", "zhangsan@example.com", "北京"),
(2, "李四", "lisi@example.com", "上海"),
(3, "王五", "wangwu@example.com", "深圳")
]
cursor.executemany(
"INSERT OR IGNORE INTO customers (id, name, email, city) VALUES (?, ?, ?, ?)",
customers
)
orders = [
(1, 1, "笔记本电脑", 5999.00),
(2, 1, "无线鼠标", 199.00),
(3, 2, "机械键盘", 899.00),
(4, 3, "显示器", 2499.00)
]
cursor.executemany(
"INSERT OR IGNORE INTO orders (id, customer_id, product, amount) VALUES (?, ?, ?, ?)",
orders
)
conn.commit()
conn.close()
# 创建数据库
create_sample_db()
# Step 2: 创建 SQLite Agent
sqlite_agent = Agent(
model=DeepSeek(id="deepseek-chat"),
tools=[SQLTools(db_url="sqlite:///example.db")],
name="SQLiteAssistant",
read_tool_call_history=True,
markdown=True
)
# Step 3: 自然语言查询
print("=== 查询 1: 获取所有客户及其订单 ===")
sqlite_agent.print_response(
"获取所有客户及其订单信息,包括客户姓名、订单产品和金额"
)
print("\n=== 查询 2: 统计分析 ===")
sqlite_agent.print_response(
"统计每个城市的客户数量和总订单金额"
)
预期 SQL 生成:
vbnet
-- 查询 1: Agent 自动生成的 SQL
SELECT
c.name AS customer_name,
o.product,
o.amount,
o.order_date
FROM customers c
JOIN orders o ON c.id = o.customer_id
ORDER BY c.name, o.order_date;
-- 查询 2: Agent 自动生成的 SQL
SELECT
c.city,
COUNT(DISTINCT c.id) AS customer_count,
SUM(o.amount) AS total_amount
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
GROUP BY c.city
ORDER BY total_amount DESC;
2.4 数据库安全最佳实践
1. 只读查询限制
ini
# PostgresTools 默认仅支持 SELECT 查询
# 如需写入操作,需使用自定义工具
from agno.tools.postgres import PostgresTools
# 安全配置:限制查询类型
postgres_tools = PostgresTools(
db_url="postgresql://user:pass@host:5432/db",
# PostgresTools 的 run_query() 会自动检测并阻止非 SELECT 语句
)
2. SQL 注入防护
python
# ❌ 错误示例:容易受 SQL 注入攻击
unsafe_query = f"SELECT * FROM users WHERE username = '{user_input}'"
# ✅ 正确示例:使用参数化查询
def safe_user_query(username: str) -> str:
"""安全的用户查询函数"""
import psycopg2
conn = psycopg2.connect("postgresql://...")
cursor = conn.cursor()
# 使用参数化查询防止 SQL 注入
cursor.execute(
"SELECT id, username, email FROM users WHERE username = %s",
(username,) # 参数会被正确转义
)
result = cursor.fetchall()
conn.close()
return str(result)
# 注册为自定义工具
from agno.agent import Agent
agent = Agent(
tools=[safe_user_query],
model=DeepSeek(id="deepseek-chat")
)
3. 数据库凭证管理
lua
import os
from dotenv import load_dotenv
# 使用 .env 文件管理敏感信息
load_dotenv()
db_config = {
"host": os.getenv("DB_HOST"),
"port": int(os.getenv("DB_PORT", 5432)),
"db_name": os.getenv("DB_NAME"),
"user": os.getenv("DB_USER"),
"password": os.getenv("DB_PASSWORD")
}
# 或使用完整的 URL
db_url = os.getenv("DATABASE_URL")
.env 文件示例:
ini
DB_HOST=localhost
DB_PORT=5432
DB_NAME=production_db
DB_USER=readonly_user
DB_PASSWORD=strong_password_here
DATABASE_URL=postgresql://readonly_user:strong_password_here@localhost:5432/production_db
4. 查询性能监控
ini
from agno.tools.postgres import PostgresTools
postgres_tools = PostgresTools(db_url="postgresql://...")
# 使用 inspect_query 分析慢查询
def analyze_slow_query(agent, query_description):
# 先让 Agent 生成 SQL
response = agent.run(query_description)
# 提取生成的 SQL(从工具调用中)
for tool_call in response.tool_calls:
if tool_call.function.name == "run_query":
sql = tool_call.function.arguments.get("query")
# 分析查询计划
agent.run(f"使用 inspect_query 分析这个 SQL 的执行计划: {sql}")
2.5 实战案例:智能商业分析系统
场景描述:为电商平台构建一个智能 BI 助手,能够回答各种业务分析问题。
ini
from agno.agent import Agent
from agno.tools.postgres import PostgresTools
from agno.models.deepseek import DeepSeek
from agno.db.postgres import PostgresDb
import os
from dotenv import load_dotenv
load_dotenv()
# 数据库连接
db_url = os.getenv("DATABASE_URL")
# 创建专业的商业分析 Agent
bi_agent = Agent(
model=DeepSeek(
id="deepseek-reasoner", # 使用推理增强模型
api_key=os.getenv("DEEPSEEK_API_KEY")
),
tools=[PostgresTools(db_url=db_url)],
db=PostgresDb(db_url=db_url),
add_history_to_context=True,
name="BusinessIntelligence",
role="Senior Data Analyst",
description="""
资深商业分析专家,擅长:
- 销售数据分析和趋势预测
- 用户行为分析和画像构建
- 产品性能评估和优化建议
- 财务指标计算和可视化
""",
instructions=[
# 分析流程
"1. 理解业务问题,明确分析目标",
"2. 探索相关表结构(show_tables, describe_table)",
"3. 使用 summarize_table 了解数据分布",
"4. 设计 SQL 查询,确保逻辑正确",
"5. 执行查询并解读结果",
"6. 提供可视化建议和业务洞察",
# 技术规范
"使用 CTE(Common Table Expression)组织复杂查询",
"添加适当的索引建议(如果查询较慢)",
"计算统计指标时处理 NULL 值",
"使用窗口函数进行同比环比分析",
# 输出规范
"以 Markdown 表格展示数据",
"包含关键指标的变化趋势",
"给出具体的业务建议",
"标注数据时间范围和统计口径"
],
read_tool_call_history=True,
markdown=True
)
# 复杂业务分析示例
analysis_request = """
请分析 2024 年 Q4 季度的业务表现:
1. 核心指标概览:
- 总销售额和同比增长率
- 订单量和客单价
- 新用户数和留存率
2. 品类分析:
- Top 10 畅销品类
- 各品类的利润率
- 库存周转率
3. 用户分析:
- RFM 模型分群
- 高价值用户特征
- 流失预警名单
4. 地域分析:
- 各地区销售分布
- 增长最快的 5 个城市
- 物流时效对比
请提供详细的数据分析报告和优化建议。
"""
# 执行分析
bi_agent.print_response(analysis_request, stream=True)
预期输出结构:
markdown
# 2024 Q4 季度业务分析报告
## 📊 一、核心指标概览
| 指标 | Q4 数据 | Q3 数据 | 环比 | 去年同期 | 同比 |
|-----|---------|---------|------|----------|------|
| 总销售额 | ¥125.8M | ¥98.5M | +27.7% | ¥92.3M | +36.3% |
| 订单量 | 458,932 | 389,021 | +18.0% | 412,856 | +11.2% |
| 客单价 | ¥274 | ¥253 | +8.3% | ¥224 | +22.3% |
| 新用户数 | 89,456 | 76,234 | +17.3% | 68,923 | +29.8% |
| 30天留存 | 68.5% | 65.2% | +3.3pt | 62.1% | +6.4pt |
### 洞察要点
- ✅ 销售额创历史新高,主要得益于客单价提升
- ✅ 新用户获取效率提升,留存率持续改善
- ⚠️ 订单量增长放缓,需关注流量获取效率
---
## 📦 二、品类分析
### Top 10 畅销品类
| 排名 | 品类 | 销售额 | 订单量 | 平均单价 | 利润率 | 库存周转天数 |
|-----|------|--------|--------|----------|--------|-------------|
| 1 | 电子产品 | ¥45.2M | 89,234 | ¥506 | 18.5% | 23 |
| 2 | 家居用品 | ¥28.9M | 156,789 | ¥184 | 32.1% | 18 |
| 3 | 服装配饰 | ¥21.5M | 98,456 | ¥218 | 45.2% | 35 |
...
### 优化建议
1. **电子产品**:虽然销售额最高,但利润率偏低(18.5%),建议:
- 优化供应链,降低采购成本
- 推出高端产品线提升利润空间
2. **服装配饰**:利润率高但库存周转慢(35天),建议:
- 实施快速补货策略
- 开展促销活动清理滞销款
---
## 👥 三、用户分析
### RFM 模型分群结果
| 用户分群 | 用户数 | 占比 | 贡献销售额 | 特征 |
|---------|--------|------|-----------|------|
| 重要价值客户 | 12,456 | 2.7% | ¥38.5M (30.6%) | R≥4, F≥4, M≥4 |
| 重要发展客户 | 28,934 | 6.3% | ¥25.2M (20.0%) | R≥4, F≤3, M≥3 |
| 重要保持客户 | 45,123 | 9.8% | ¥31.8M (25.3%) | R≤3, F≥4, M≥4 |
| 一般价值客户 | 189,456 | 41.3% | ¥22.1M (17.6%) | 中等水平 |
| 潜在客户 | 182,963 | 39.9% | ¥8.2M (6.5%) | 新用户或低活 |
### 高价值用户特征画像
- **年龄分布**:25-40岁占 78%
- **地域分布**:一线城市占 65%
- **消费偏好**:电子产品 (42%)、家居 (28%)、美妆 (18%)
- **购买频次**:平均每月 2.3 次
- **活跃时段**:20:00-22:00 (晚间)、12:00-14:00 (午间)
...
第三部分:文件工具与 Python 执行
3.1 文件工具概述
Agno 2.0.6 版本引入了强大的文件生成工具(FileGenerationTools),允许 AI Agent 创建各种格式的文件。
支持的文件格式
| 文件类型 | 工具方法 | 适用场景 |
|---|---|---|
generate_pdf() |
报告生成、文档归档 | |
| CSV | generate_csv() |
数据导出、批量处理 |
| JSON | generate_json() |
API 响应、配置文件 |
| TXT | generate_txt() |
日志记录、纯文本输出 |
| Markdown | generate_markdown() |
技术文档、博客文章 |
3.2 文件生成工具使用
代码示例:生成多格式报告
python
from pathlib import Path
from agno.agent import Agent
from agno.tools.file import FileTools
from agno.models.deepseek import DeepSeek
import os
from dotenv import load_dotenv
load_dotenv()
# 创建文件操作 Agent
file_agent = Agent(
model=DeepSeek(id="deepseek-chat", api_key=os.getenv("DEEPSEEK_API_KEY")),
tools=[FileTools(base_dir=Path("./outputs"))], # 指定输出目录
name="ReportGenerator",
description="专业的报告生成助手",
instructions=[
"根据用户需求生成格式化的报告文件",
"确保文件命名清晰,包含时间戳",
"为 PDF 报告添加标题页和目录",
"CSV 文件使用 UTF-8 编码,包含表头"
],
read_tool_call_history=True,
markdown=True
)
# 生成销售报告
file_agent.print_response("""
请生成 2024 年 Q4 销售报告,包含以下内容:
1. 生成 PDF 格式的管理层报告(包含图表描述)
2. 生成 CSV 格式的详细销售数据
3. 生成 JSON 格式的 API 数据文件
报告数据:
- 总销售额: 125.8M
- 订单数: 458,932
- 新客户: 89,456
- Top 3 品类: 电子产品(45.2M), 家居(28.9M), 服装(21.5M)
""")
3.3 Python 执行工具详解
PythonTools 允许 AI Agent 动态编写和执行 Python 代码,极大扩展了 Agent 的能力边界。
核心功能
- 代码执行 :
run_python_code()- 直接运行 Python 代码 - 文件执行 :
run_python_file_return_variable()- 运行 .py 文件并返回变量 - 保存并执行 :
save_to_file_and_run()- 保存代码到文件后执行 - 包管理 :
pip_install_package()- 安装 Python 包 - 文件读取 :
read_file()- 读取文件内容 - 文件列表 :
list_files()- 列出目录文件
安全沙箱机制
python
from agno.tools.python import PythonTools
# 配置安全的 Python 执行环境
python_tools = PythonTools(
base_dir="./workspace", # 限制文件操作范围
# 定义安全的全局变量
safe_globals={
"pd": __import__("pandas"),
"np": __import__("numpy"),
"plt": __import__("matplotlib.pyplot")
},
# 定义安全的局部变量
safe_locals={}
)
代码示例:数据分析 Agent
ini
from pathlib import Path
from agno.agent import Agent
from agno.tools.python import PythonTools
from agno.models.deepseek import DeepSeek
import os
from dotenv import load_dotenv
load_dotenv()
# 创建数据分析 Agent
data_agent = Agent(
model=DeepSeek(
id="deepseek-reasoner", # 推理模型更适合复杂计算
api_key=os.getenv("DEEPSEEK_API_KEY")
),
tools=[PythonTools(
base_dir=Path("./data_workspace"),
safe_globals={
"pd": __import__("pandas"),
"np": __import__("numpy"),
"plt": __import__("matplotlib.pyplot"),
"sns": __import__("seaborn")
}
)],
name="DataScientist",
description="数据科学家 Agent,擅长统计分析和可视化",
instructions=[
"使用 Python 进行数据处理和分析",
"优先使用 pandas、numpy 等科学计算库",
"生成清晰的可视化图表",
"代码需包含详细注释",
"处理异常情况并返回友好的错误信息"
],
read_tool_call_history=True,
markdown=True
)
# 复杂数据分析任务
analysis_task = """
请分析以下销售数据并生成可视化报告:
数据:
[
{"date": "2024-10-01", "sales": 12500, "orders": 89},
{"date": "2024-10-02", "sales": 15300, "orders": 102},
{"date": "2024-10-03", "sales": 18900, "orders": 125},
...
]
任务:
1. 计算销售额的均值、中位数、标准差
2. 计算日销售增长率
3. 生成销售趋势折线图(保存为 sales_trend.png)
4. 生成订单量分布直方图(保存为 orders_distribution.png)
5. 计算销售额与订单量的相关系数
请执行完整的分析流程并返回结果。
"""
data_agent.print_response(analysis_task, stream=True)
Agent 内部生成的 Python 代码示例:
ini
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# 1. 数据准备
data = [
{"date": "2024-10-01", "sales": 12500, "orders": 89},
{"date": "2024-10-02", "sales": 15300, "orders": 102},
{"date": "2024-10-03", "sales": 18900, "orders": 125},
# ... 更多数据
]
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
# 2. 统计分析
sales_mean = df['sales'].mean()
sales_median = df['sales'].median()
sales_std = df['sales'].std()
print(f"销售额均值: ¥{sales_mean:,.2f}")
print(f"销售额中位数: ¥{sales_median:,.2f}")
print(f"销售额标准差: ¥{sales_std:,.2f}")
# 3. 计算增长率
df['growth_rate'] = df['sales'].pct_change() * 100
# 4. 生成销售趋势图
plt.figure(figsize=(12, 6))
plt.plot(df['date'], df['sales'], marker='o', linewidth=2, markersize=6)
plt.title('Sales Trend Analysis', fontsize=16, fontweight='bold')
plt.xlabel('Date', fontsize=12)
plt.ylabel('Sales (¥)', fontsize=12)
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig('sales_trend.png', dpi=300)
plt.close()
# 5. 订单量分布直方图
plt.figure(figsize=(10, 6))
plt.hist(df['orders'], bins=20, edgecolor='black', alpha=0.7)
plt.title('Orders Distribution', fontsize=16, fontweight='bold')
plt.xlabel('Number of Orders', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('orders_distribution.png', dpi=300)
plt.close()
# 6. 相关性分析
correlation = df['sales'].corr(df['orders'])
print(f"\n销售额与订单量相关系数: {correlation:.4f}")
# 返回结果摘要
result = {
"mean_sales": sales_mean,
"median_sales": sales_median,
"std_sales": sales_std,
"correlation": correlation,
"charts_generated": ["sales_trend.png", "orders_distribution.png"]
}
result
3.4 高级示例:自动化报告生成系统
场景描述:构建一个完全自动化的周报生成系统,从数据库查询到生成 PDF 报告。
ini
from pathlib import Path
from agno.agent import Agent
from agno.tools.python import PythonTools
from agno.tools.postgres import PostgresTools
from agno.tools.file import FileTools
from agno.models.deepseek import DeepSeek
from agno.db.postgres import PostgresDb
import os
from dotenv import load_dotenv
load_dotenv()
# 数据库连接
db_url = os.getenv("DATABASE_URL")
# 创建自动化报告 Agent
report_agent = Agent(
model=DeepSeek(
id="deepseek-reasoner",
api_key=os.getenv("DEEPSEEK_API_KEY")
),
# 组合多个工具
tools=[
PostgresTools(db_url=db_url), # 数据查询
PythonTools( # 数据处理和可视化
base_dir=Path("./reports"),
safe_globals={
"pd": __import__("pandas"),
"np": __import__("numpy"),
"plt": __import__("matplotlib.pyplot"),
"sns": __import__("seaborn")
}
),
FileTools(base_dir=Path("./reports")) # 文件生成
],
db=PostgresDb(db_url=db_url),
add_history_to_context=True,
name="AutoReportGenerator",
role="Automation Engineer",
description="自动化报告生成专家",
instructions=[
# 工作流程
"步骤 1: 从数据库查询所需数据",
"步骤 2: 使用 Python 进行数据清洗和分析",
"步骤 3: 生成可视化图表(PNG 格式)",
"步骤 4: 汇总分析结果",
"步骤 5: 生成完整的 PDF 报告",
# 技术规范
"确保所有图表清晰美观,使用专业配色",
"PDF 报告包含:封面、目录、内容、图表、结论",
"使用中文字体避免乱码",
"所有数值格式化为易读形式(如千分位分隔符)",
# 错误处理
"遇到错误时记录详细日志",
"数据异常时提供降级方案",
"报告生成失败时发送通知"
],
read_tool_call_history=True,
markdown=True
)
# 执行自动化周报生成
weekly_report_task = """
生成本周(2024-11-01 至 2024-11-07)的业务周报:
## 数据需求
1. 从 orders 表查询本周订单数据
2. 从 users 表查询新增用户数据
3. 从 products 表查询畅销商品数据
## 分析内容
1. 核心指标趋势:销售额、订单量、新用户
2. 品类分析:各品类销售占比(饼图)
3. 时间分布:每日订单量变化(折线图)
4. Top 10 商品排行(柱状图)
## 输出要求
1. 生成包含所有图表的 PDF 报告: weekly_report_2024_W44.pdf
2. 导出原始数据为 CSV: raw_data_2024_W44.csv
3. 保存分析结果为 JSON: analysis_2024_W44.json
请完整执行以上流程。
"""
report_agent.print_response(weekly_report_task, stream=True)
3.5 文件和 Python 工具最佳实践
1. 代码安全性
ini
# ✅ 良好实践:限制文件操作范围
python_tools = PythonTools(
base_dir="./safe_workspace", # 所有文件操作限定在此目录
safe_globals={
# 只导入必要的库
"pd": __import__("pandas"),
"np": __import__("numpy")
}
)
# ❌ 避免:允许执行任意系统命令
# 不要在 safe_globals 中包含 os, subprocess 等危险模块
2. 依赖管理
ini
from agno.tools.python import PythonTools
# 在 Agent 初始化前安装依赖
python_tools = PythonTools()
# 通过工具安装包
agent = Agent(tools=[python_tools])
agent.run("使用 pip_install_package 安装 matplotlib 和 seaborn")
# 或预先安装
# !pip install pandas numpy matplotlib seaborn
3. 错误处理
ini
from agno.agent import Agent
from agno.tools.python import PythonTools
agent = Agent(
tools=[PythonTools()],
instructions=[
"所有 Python 代码必须包含 try-except 错误处理",
"捕获异常并返回友好的错误信息",
"使用 logging 记录执行过程",
# 示例代码模板
"""
import logging
logging.basicConfig(level=logging.INFO)
try:
# 你的代码逻辑
result = perform_analysis()
logging.info(f"Analysis completed: {result}")
return result
except Exception as e:
logging.error(f"Error occurred: {str(e)}")
return {"error": str(e), "status": "failed"}
"""
]
)
4. 性能优化
ini
# 优化策略 1: 使用向量化操作代替循环
agent.run("""
使用 Python 计算大数据集的统计指标,要求:
- 优先使用 pandas 的向量化操作
- 避免 for 循环遍历 DataFrame
- 使用 numpy 进行数值计算加速
示例:
# ❌ 慢速方法
for i, row in df.iterrows():
df.loc[i, 'new_col'] = row['col1'] * row['col2']
# ✅ 快速方法
df['new_col'] = df['col1'] * df['col2']
""")
# 优化策略 2: 分块处理大文件
agent.run("""
处理 100MB 的 CSV 文件,使用 pandas 的 chunksize 参数:
import pandas as pd
chunk_size = 10000
results = []
for chunk in pd.read_csv('large_file.csv', chunksize=chunk_size):
processed = chunk.groupby('category')['sales'].sum()
results.append(processed)
final_result = pd.concat(results).groupby(level=0).sum()
""")
第四部分:MCP 工具详解
4.1 Model Context Protocol (MCP) 简介
MCP(Model Context Protocol) 是由 Anthropic 开发的开放标准协议,旨在解决 AI Agent 与外部系统集成的复杂性。它就像 AI 世界的"USB-C 接口",提供统一的连接方式。
MCP 的核心价值
java
传统方式(每个系统独立集成):
Agent → 专用适配器1 → 数据库
Agent → 专用适配器2 → 文件系统
Agent → 专用适配器3 → API 服务
(需要维护 N 个不同的适配器)
MCP 方式(统一接口):
Agent → MCP Client → MCP Server (Database)
→ MCP Server (Filesystem)
→ MCP Server (API Service)
(只需实现标准的 MCP 协议)
优势:
- 🔌 标准化接口:所有外部系统通过统一协议接入
- 🔒 安全隔离:MCP Server 运行在独立进程,提供安全边界
- 🔄 可扩展性:轻松添加新的 MCP Server
- 📦 生态丰富:社区提供大量现成的 MCP Server
4.2 MCP 架构详解
三层架构模型
arduino
┌─────────────────────────────────────────────────────────┐
│ Host(宿主应用) │
│ 例如:Agno、Claude Desktop │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 创建和管理 MCP Client │ │
│ │ 控制连接权限和生命周期 │ │
│ │ 协调 AI/LLM 集成 │ │
│ └──────────────────────────────────────────────────┘ │
└───────────────────────────┬─────────────────────────────┘
│
↓ JSON-RPC 2.0
┌─────────────────────────────────────────────────────────┐
│ Client(MCP 客户端) │
│ ┌──────────────────────────────────────────────────┐ │
│ │ • 建立与 Server 的有状态会话 │ │
│ │ • 协议版本协商 │ │
│ │ • 能力交换(Capability Negotiation) │ │
│ │ • 消息路由 │ │
│ └──────────────────────────────────────────────────┘ │
└───────────────────────────┬─────────────────────────────┘
│
↓ Transport Layer
│ (stdio / HTTP / SSE)
↓
┌─────────────────────────────────────────────────────────┐
│ Server(MCP 服务端) │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 暴露三大核心能力: │ │
│ │ • Resources(资源) │ │
│ │ • Tools(工具) │ │
│ │ • Prompts(提示模板) │ │
│ └──────────────────────────────────────────────────┘ │
│ │
│ 可以是: │
│ - 本地进程(Local Process) │
│ - 远程服务(Remote Service) │
│ - 数据库连接(Database) │
│ - 文件系统(Filesystem) │
└─────────────────────────────────────────────────────────┘
连接生命周期
arduino
1. 初始化阶段(Initialization)
↓
Client → Server: initialize request
├─ 协议版本: "2024-11-05"
├─ 客户端信息: {name: "agno", version: "2.0.7"}
└─ 客户端能力: {tools: true, resources: true}
↓
Server → Client: initialize response
├─ 服务端信息: {name: "fs-server", version: "1.0.0"}
├─ 服务端能力: {tools: ["read_file", "write_file"]}
└─ 协议版本: "2024-11-05"
↓
2. 操作阶段(Operation)
↓
Client ←→ Server: 正常通信
• tools/list: 列出可用工具
• tools/call: 调用工具
• resources/list: 列出资源
• resources/read: 读取资源
↓
3. 关闭阶段(Shutdown)
↓
Client → Server: disconnect notification
Server: 清理资源,关闭连接
4.3 Agno 中的 MCP 集成
支持的传输方式(Transport)
| 传输类型 | 使用场景 | 配置方式 |
|---|---|---|
| stdio | 本地进程通信(默认) | command="uvx mcp-server-git" |
| streamable-http | HTTP 长连接 | transport="streamable-http", url="https://..." |
| SSE | 服务端事件推送 | transport="sse", url="https://..." |
代码示例:基础 MCP 集成
ini
from agno.agent import Agent
from agno.tools.mcp import MCPTools
from agno.models.deepseek import DeepSeek
import asyncio
import os
from dotenv import load_dotenv
load_dotenv()
async def main():
# 方式 1: 连接到本地 MCP Server(使用 stdio)
mcp_tools = MCPTools(
command="uvx mcp-server-git", # 启动 Git MCP Server
# command 可以是任何能启动 MCP Server 的命令
)
# 建立连接
await mcp_tools.connect()
try:
# 创建 Agent
agent = Agent(
model=DeepSeek(
id="deepseek-chat",
api_key=os.getenv("DEEPSEEK_API_KEY")
),
tools=[mcp_tools],
name="GitAssistant",
description="Git 仓库操作助手",
read_tool_call_history=True,
markdown=True
)
# 使用 MCP 工具
await agent.aprint_response(
"这个项目使用的是什么开源许可证?",
stream=True
)
finally:
# 关闭连接
await mcp_tools.close()
# 运行异步函数
asyncio.run(main())
使用上下文管理器(推荐)
python
import asyncio
from agno.agent import Agent
from agno.tools.mcp import MCPTools
from agno.models.deepseek import DeepSeek
import os
async def main():
# 使用 async with 自动管理连接
async with MCPTools(command="uvx mcp-server-git") as mcp_tools:
agent = Agent(
model=DeepSeek(id="deepseek-chat"),
tools=[mcp_tools],
read_tool_call_history=True
)
await agent.aprint_response(
"列出最近 5 次提交记录",
stream=True
)
asyncio.run(main())
4.4 MCP 实战案例:文件系统 Agent
场景描述:创建一个能够浏览、搜索和分析本地文件系统的智能 Agent。
python
import asyncio
from agno.agent import Agent
from agno.tools.mcp import MCPTools
from agno.models.deepseek import DeepSeek
import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
async def filesystem_agent_demo():
# 获取当前项目路径
project_path = Path.cwd()
# 配置文件系统 MCP Server
async with MCPTools(
command=f"npx -y @modelcontextprotocol/server-filesystem {project_path}"
) as mcp_tools:
# 创建文件系统助手 Agent
fs_agent = Agent(
model=DeepSeek(
id="deepseek-reasoner", # 使用推理模型处理复杂文件结构
api_key=os.getenv("DEEPSEEK_API_KEY")
),
tools=[mcp_tools],
name="FilesystemExplorer",
role="System Administrator",
description="文件系统专家,擅长文件管理和分析",
instructions=[
"你是一个专业的文件系统助手",
"能够浏览目录、搜索文件、分析文件内容",
"对于代码文件,提供结构分析和改进建议",
"对于配置文件,检查潜在问题",
"以清晰的树形结构展示目录",
"标注文件大小、修改时间等元信息"
],
read_tool_call_history=True,
markdown=True
)
# 任务 1: 探索项目结构
print("=== 任务 1: 项目结构分析 ===\n")
await fs_agent.aprint_response(
"""
分析当前项目的文件结构:
1. 列出根目录下的所有文件和文件夹
2. 识别项目类型(Python/Node.js/其他)
3. 查找配置文件(如 package.json, requirements.txt 等)
4. 统计代码文件数量和总大小
""",
stream=True
)
print("\n" + "="*50 + "\n")
# 任务 2: 查找特定文件
print("=== 任务 2: 查找配置文件 ===\n")
await fs_agent.aprint_response(
"查找所有的 .env 和 .config 文件,并分析其内容",
stream=True
)
print("\n" + "="*50 + "\n")
# 任务 3: 代码分析
print("=== 任务 3: 代码质量检查 ===\n")
await fs_agent.aprint_response(
"""
分析 Python 源代码文件:
1. 查找所有 .py 文件
2. 检查是否包含文档字符串
3. 识别潜在的代码异味(如过长函数、重复代码)
4. 提供改进建议
""",
stream=True
)
# 运行示例
asyncio.run(filesystem_agent_demo())
预期输出示例:
yaml
=== 任务 1: 项目结构分析 ===
🔧 Tool Call: list_directory
Path: /Users/project/agno-demo
📁 **项目结构分析报告**
## 目录树
agno-demo/ ├── 📁 src/ │ ├── 📄 main.py (2.3 KB, 修改于 2小时前) │ ├── 📄 config.py (1.1 KB, 修改于 1天前) │ └── 📁 utils/ │ ├── 📄 helpers.py (3.5 KB) │ └── 📄 validators.py (2.8 KB) ├── 📁 tests/ │ └── 📄 test_main.py (4.2 KB) ├── 📄 requirements.txt (0.5 KB) ├── 📄 README.md (3.8 KB) └── 📄 .env (0.2 KB)
markdown
## 项目识别
- **项目类型**: Python 项目
- **依赖管理**: requirements.txt
- **测试框架**: pytest(从 test_ 前缀推断)
## 统计信息
- **总文件数**: 9
- **代码文件**: 5 个 .py 文件
- **配置文件**: requirements.txt, .env
- **文档文件**: README.md
- **总大小**: ~18 KB
## 配置文件位置
✅ 发现 requirements.txt (Python依赖)
✅ 发现 .env (环境变量配置)
❌ 未发现 setup.py 或 pyproject.toml(建议添加)
4.5 MCP Toolbox:数据库工具集成
MCPToolbox 是 Agno 对 MCP 的增强版本,专为数据库场景优化,支持工具过滤。
代码示例:连接 PostgreSQL MCP Toolbox
ini
import asyncio
from agno.agent import Agent
from agno.tools.mcp_toolbox import MCPToolbox
from agno.models.deepseek import DeepSeek
import os
from dotenv import load_dotenv
load_dotenv()
async def database_mcp_demo():
# 连接到 Google MCP Toolbox for Databases
async with MCPToolbox(
url="http://127.0.0.1:5001", # MCP Toolbox 服务地址
toolsets=["hotel-management"], # 只加载 hotel-management 工具集
# 可选:指定具体工具
# tool_names=["search_hotels", "book_room"]
) as toolbox:
# 创建酒店管理 Agent
hotel_agent = Agent(
model=DeepSeek(
id="deepseek-chat",
api_key=os.getenv("DEEPSEEK_API_KEY")
),
tools=[toolbox],
name="HotelConcierge",
description="酒店礼宾服务 AI 助手",
instructions=[
"你是一个专业的酒店服务助手",
"帮助用户查找和预订酒店",
"提供详细的酒店信息和推荐",
"考虑用户的预算、位置偏好和评分要求"
],
read_tool_call_history=True,
markdown=True
)
# 查询酒店
await hotel_agent.aprint_response(
"在苏黎世查找豪华酒店,预算每晚 $300-500,评分 4.5+ 星",
stream=True
)
asyncio.run(database_mcp_demo())
MCPToolbox 高级配置
python
from agno.tools.mcp_toolbox import MCPToolbox
# 完整配置示例
toolbox = MCPToolbox(
url="http://localhost:5001",
# 工具过滤(三选一)
toolsets=["hotel-management", "restaurant-booking"], # 按工具集过滤
# tool_names=["search_hotels", "get_hotel_details"], # 按工具名过滤
# 不指定则加载所有工具
# 认证配置
auth_token_getters={
"hotel-db": lambda: os.getenv("HOTEL_DB_TOKEN"),
"restaurant-db": lambda: os.getenv("RESTAURANT_DB_TOKEN")
},
# 绑定参数(所有工具调用都会包含)
bound_params={
"region": "APAC",
"language": "zh-CN"
}
)
4.6 创建自定义 MCP Server
Python MCP Server 示例
python
# custom_mcp_server.py
from mcp.server import Server, Tool
from mcp.types import TextContent
import json
# 创建 MCP Server 实例
server = Server("custom-data-server")
# 定义工具 1: 数据查询
@server.tool()
async def query_database(query: str) -> list[TextContent]:
"""
查询自定义数据库
Args:
query: SQL 查询语句
Returns:
查询结果(JSON 格式)
"""
# 实际应用中连接真实数据库
mock_data = [
{"id": 1, "name": "Product A", "price": 99.99},
{"id": 2, "name": "Product B", "price": 149.99}
]
result_json = json.dumps(mock_data, ensure_ascii=False, indent=2)
return [TextContent(
type="text",
text=f"查询结果:\n```json\n{result_json}\n```"
)]
# 定义工具 2: 数据分析
@server.tool()
async def analyze_data(data_id: int) -> list[TextContent]:
"""
分析指定数据项
Args:
data_id: 数据 ID
Returns:
分析报告
"""
analysis = {
"data_id": data_id,
"metrics": {
"views": 1250,
"conversions": 85,
"conversion_rate": 0.068
},
"insights": [
"转化率高于平均水平 15%",
"周末流量显著增加",
"移动端占比 62%"
]
}
return [TextContent(
type="text",
text=json.dumps(analysis, ensure_ascii=False, indent=2)
)]
# 启动服务器
if __name__ == "__main__":
import asyncio
from mcp.server.stdio import stdio_server
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
server.create_initialization_options()
)
asyncio.run(main())
在 Agno 中使用自定义 MCP Server
python
import asyncio
from agno.agent import Agent
from agno.tools.mcp import MCPTools
from agno.models.deepseek import DeepSeek
import os
async def custom_mcp_demo():
async with MCPTools(
command="python custom_mcp_server.py" # 启动自定义 Server
) as mcp_tools:
agent = Agent(
model=DeepSeek(id="deepseek-chat"),
tools=[mcp_tools],
read_tool_call_history=True
)
# 使用自定义工具
await agent.aprint_response(
"查询数据库中所有产品,并分析 ID 为 1 的产品数据",
stream=True
)
asyncio.run(custom_mcp_demo())
4.7 MCP 最佳实践
1. 连接管理
csharp
# ✅ 推荐:使用上下文管理器
async with MCPTools(command="...") as mcp:
agent = Agent(tools=[mcp])
await agent.arun("...")
# ✅ 或手动管理(适合长期运行)
mcp = MCPTools(command="...")
await mcp.connect()
try:
# 长期运行的逻辑
pass
finally:
await mcp.close()
# ❌ 避免:不管理连接(会导致资源泄漏)
mcp = MCPTools(command="...")
agent = Agent(tools=[mcp]) # 连接未建立
2. 错误处理
python
import asyncio
import logging
from agno.tools.mcp import MCPTools
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
async def robust_mcp_connection():
try:
async with MCPTools(
command="uvx mcp-server-git",
timeout=30 # 设置连接超时
) as mcp:
# 检查连接状态
logger.info("MCP 连接成功")
# 使用工具
agent = Agent(tools=[mcp])
await agent.arun("...")
except TimeoutError:
logger.error("MCP Server 连接超时")
except ConnectionError as e:
logger.error(f"MCP Server 连接失败: {e}")
except Exception as e:
logger.error(f"未知错误: {e}")
raise
3. 性能优化
ini
from agno.tools.mcp import MCPTools
# 策略 1: 连接复用(避免频繁重连)
mcp_tools = MCPTools(command="...")
await mcp_tools.connect()
# 在 AgentOS 中使用(自动管理生命周期)
from agno.agent import Agent
agent = Agent(
tools=[mcp_tools],
# AgentOS 会自动管理 MCP 连接
)
# 策略 2: 启用连接刷新(针对不稳定的远程 Server)
mcp_tools_remote = MCPTools(
transport="streamable-http",
url="https://unstable-server.com/mcp",
refresh_connection=True # 每次调用前刷新连接
)
# 策略 3: 工具结果缓存
agent = Agent(
tools=[mcp_tools],
store_tool_messages=True, # 缓存 MCP 工具结果
tool_result_ttl=3600 # 缓存 1 小时
)
第五部分:最佳实践与注意事项
5.1 工具选择与组合策略
决策矩阵
| 需求场景 | 推荐工具组合 | 理由 |
|---|---|---|
| 实时信息检索 | Tavily + DuckDuckGo | Tavily 深度搜索 + DuckDuckGo 备用 |
| 数据分析 | PostgresTools + PythonTools | 数据库查询 + Python 计算 |
| 报告生成 | SQL + Python + FileTools | 查询数据 → 分析 → 生成文件 |
| 系统集成 | MCP Tools | 统一接口,易于扩展 |
| 代码执行 | PythonTools (沙箱模式) | 安全隔离 |
工具组合示例
python
from agno.agent import Agent
from agno.tools.tavily import TavilyTools
from agno.tools.postgres import PostgresTools
from agno.tools.python import PythonTools
from agno.tools.file import FileTools
from agno.models.deepseek import DeepSeek
# 全能型 Agent:结合多种工具
super_agent = Agent(
model=DeepSeek(id="deepseek-reasoner"),
tools=[
TavilyTools(search_depth="advanced"), # 网络搜索
PostgresTools(db_url="..."), # 数据库
PythonTools(base_dir=Path("./workspace")), # 代码执行
FileTools(base_dir=Path("./outputs")) # 文件生成
],
# 工具使用优先级(通过 instructions 指导)
instructions=[
"优先使用数据库工具获取结构化数据",
"当需要最新信息时使用搜索工具",
"复杂计算使用 Python 工具",
"最终结果生成文件保存"
]
)
5.2 性能优化技巧
1. 工具调用限制
ini
agent = Agent(
tools=[...],
tool_call_limit=10, # 单次对话最多调用 10 次工具
max_loops=5 # 最多 5 轮思考循环
)
2. 结果缓存
ini
# 启用工具结果缓存
agent = Agent(
tools=[TavilyTools()],
store_tool_messages=True, # 缓存工具结果
tool_result_ttl=3600 # 缓存有效期 1 小时
)
# 第二次相同查询会直接返回缓存结果
agent.run("What is the capital of France?") # 调用工具
agent.run("What is the capital of France?") # 使用缓存
3. 并行工具调用
ini
from agno.agent import Agent
# Agno 会自动并行执行独立的工具调用
agent = Agent(
tools=[TavilyTools(), DuckDuckGoTools()],
instructions=[
"同时使用 Tavily 和 DuckDuckGo 搜索",
"对比两个来源的结果"
]
)
# Agent 会自动并行调用两个搜索工具
agent.run("Compare search results for 'AI trends 2025'")
4. 选择性工具加载
ini
from agno.tools.postgres import PostgresTools
# 只启用必要的工具功能
postgres_tools = PostgresTools(
db_url="...",
# 通过 include_tools / exclude_tools 过滤
)
agent = Agent(
tools=[postgres_tools],
tool_choice=["show_tables", "run_query"], # 只启用这两个工具
# 或
# exclude_tools=["export_table_to_path"], # 禁用导出功能
)
5.3 安全性最佳实践
1. 环境变量管理
ini
# ✅ 推荐:使用 .env 文件
from dotenv import load_dotenv
import os
load_dotenv()
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
DATABASE_URL = os.getenv("DATABASE_URL")
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
# ❌ 避免:硬编码密钥
# API_KEY = "sk-1234567890abcdef" # 不要这样做!
.env 文件示例:
ini
# AI Models
DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxx
OPENAI_API_KEY=sk-yyyyyyyyyyyyyyyy
# Databases
DATABASE_URL=postgresql://user:pass@localhost:5432/db
REDIS_URL=redis://localhost:6379/0
# Search APIs
TAVILY_API_KEY=tvly-zzzzzzzzzzzzzzz
SERPAPI_KEY=xxxxxxxxxxxxxxxxxxxxx
# Application
DEBUG=False
LOG_LEVEL=INFO
2. SQL 注入防护
python
# ✅ 安全:使用参数化查询
from agno.tools.function import FunctionTool
import psycopg2
def safe_query(user_id: int) -> str:
conn = psycopg2.connect("...")
cursor = conn.cursor()
# 参数化查询(自动转义)
cursor.execute(
"SELECT * FROM users WHERE id = %s",
(user_id,)
)
return str(cursor.fetchall())
# ❌ 危险:字符串拼接
def unsafe_query(user_input: str) -> str:
query = f"SELECT * FROM users WHERE name = '{user_input}'"
# 容易受到 SQL 注入攻击!
3. Python 代码沙箱
ini
from agno.tools.python import PythonTools
# 配置安全的执行环境
python_tools = PythonTools(
base_dir="./safe_workspace", # 限制文件访问范围
safe_globals={
# 只允许安全的库
"pd": __import__("pandas"),
"np": __import__("numpy"),
# 禁止: os, subprocess, sys 等危险模块
},
safe_locals={} # 不提供预定义变量
)
# Agent 配置
agent = Agent(
tools=[python_tools],
instructions=[
"不允许执行系统命令(os.system, subprocess)",
"不允许访问文件系统根目录",
"不允许修改系统环境变量",
"代码必须包含异常处理"
]
)
4. API 调用频率限制
python
import time
from functools import wraps
def rate_limit(calls_per_minute=10):
"""API 调用频率限制装饰器"""
min_interval = 60.0 / calls_per_minute
last_called = [0.0]
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
elapsed = time.time() - last_called[0]
wait_time = min_interval - elapsed
if wait_time > 0:
time.sleep(wait_time)
last_called[0] = time.time()
return func(*args, **kwargs)
return wrapper
return decorator
# 应用到自定义工具
@rate_limit(calls_per_minute=5)
def expensive_api_call(query: str) -> str:
# 调用昂贵的 API
pass
5.4 错误处理与重试机制
1. 工具级错误处理
python
import logging
logger = logging.getLogger(__name__)
def robust_tool_function(param: str) -> str:
"""
健壮的工具函数示例
Args:
param: 输入参数
Returns:
处理结果或错误信息
"""
try:
# 主要逻辑
result = perform_operation(param)
logger.info(f"操作成功: {result}")
return result
except ValueError as e:
logger.error(f"参数错误: {e}")
return f"错误:参数 '{param}' 无效 - {str(e)}"
except ConnectionError as e:
logger.error(f"连接失败: {e}")
return "错误:无法连接到服务,请稍后重试"
except Exception as e:
logger.exception(f"未知错误: {e}")
return f"系统错误:{type(e).__name__} - {str(e)}"
# 注册为工具
Agent(tools=[robust_tool_function])
2. Agent 级重试配置
ini
from agno.agent import Agent
agent = Agent(
tools=[...],
# 重试配置
retries=3, # 工具调用失败时最多重试 3 次
delay_between_retries=2, # 重试间隔 2 秒
exponential_backoff=True, # 指数退避(2s, 4s, 8s...)
# 异常处理
instructions=[
"如果工具调用失败,尝试使用备用方法",
"记录所有错误并向用户说明",
"不要在遇到错误时停止,尝试完成任务的其他部分"
]
)
3. 超时控制
python
import asyncio
from agno.agent import Agent
async def run_with_timeout():
agent = Agent(tools=[...])
try:
# 设置 30 秒超时
response = await asyncio.wait_for(
agent.arun("Complex query..."),
timeout=30.0
)
print(response.content)
except asyncio.TimeoutError:
print("任务执行超时(30 秒)")
except Exception as e:
print(f"执行失败: {e}")
asyncio.run(run_with_timeout())
5.5 日志与监控
1. 配置详细日志
ini
import logging
from agno.agent import Agent
# 配置日志系统
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('agno_agent.log'), # 文件日志
logging.StreamHandler() # 控制台日志
]
)
logger = logging.getLogger('AgnoAgent')
# 创建 Agent
agent = Agent(
tools=[...],
read_tool_call_history=True, # 显示工具调用详情
markdown=True
)
# 记录关键操作
logger.info("Agent 初始化完成")
response = agent.run("Query...")
logger.info(f"任务完成,使用了 {len(response.tool_calls)} 次工具调用")
2. 性能监控
python
import time
from agno.agent import Agent
def monitor_agent_performance(agent, query):
"""监控 Agent 性能指标"""
start_time = time.time()
# 执行任务
response = agent.run(query)
# 计算指标
elapsed_time = time.time() - start_time
tool_call_count = len(response.tool_calls) if response.tool_calls else 0
# 记录性能数据
metrics = {
"query": query,
"elapsed_time": f"{elapsed_time:.2f}s",
"tool_calls": tool_call_count,
"tokens_used": response.metrics.get("tokens", 0) if hasattr(response, 'metrics') else 0,
"cost": response.metrics.get("cost", 0) if hasattr(response, 'metrics') else 0
}
print(f"\n📊 性能报告:")
for key, value in metrics.items():
print(f" {key}: {value}")
return response
# 使用示例
agent = Agent(tools=[...])
monitor_agent_performance(agent, "Analyze sales data for Q4")
5.6 常见问题与解决方案
Q1: 工具调用失败:"Tool not found"
原因:工具未正确注册或名称不匹配
解决方案:
ini
# 检查工具是否正确初始化
agent = Agent(
tools=[TavilyTools()], # 确保工具已实例化
show_tool_calls=True # 启用调试输出
)
# 验证工具列表
print(agent.tools) # 查看已注册的工具
Q2: MCP 连接超时
原因:MCP Server 启动慢或网络问题
解决方案:
ini
# 增加超时时间
mcp_tools = MCPTools(
command="uvx mcp-server-git",
timeout=60 # 增加到 60 秒
)
# 或使用已运行的 Server
mcp_tools = MCPTools(
transport="streamable-http",
url="http://localhost:3000/mcp"
)
Q3: Python 工具执行错误:ModuleNotFoundError
原因:缺少必要的 Python 库
解决方案:
python
from agno.agent import Agent
from agno.tools.python import PythonTools
agent = Agent(tools=[PythonTools()])
# 先安装依赖
agent.run("使用 pip_install_package 安装 pandas 和 matplotlib")
# 再执行代码
agent.run("使用 pandas 读取 CSV 文件并生成图表")
Q4: 数据库查询性能差
原因:缺少索引或查询未优化
解决方案:
python
from agno.tools.postgres import PostgresTools
postgres_tools = PostgresTools(db_url="...")
agent = Agent(tools=[postgres_tools])
# 使用 inspect_query 分析慢查询
agent.run("""
先使用 inspect_query 分析这个查询的执行计划:
SELECT * FROM orders WHERE created_at > '2024-01-01'
根据分析结果建议优化方案。
""")
Q5: Agent 输出不稳定或重复调用工具
原因:指令不清晰或模型幻觉
解决方案:
ini
agent = Agent(
tools=[...],
# 明确的指令
instructions=[
"每次只调用必要的工具,避免重复",
"先思考需要哪些工具,再执行",
"如果已有足够信息,直接回答,不要再次调用工具",
"工具调用失败时,不要无限重试"
],
# 限制调用次数
tool_call_limit=5,
)
总结与下期预告
本文核心要点回顾
1. 工具系统的重要性
Agno 的工具系统是 AI Agent 的"手和眼",让 Agent 能够:
- 🔍 通过搜索工具获取实时信息
- 🗄️ 通过数据库工具管理结构化数据
- 📁 通过文件和 Python 工具处理复杂任务
- 🔌 通过 MCP 协议连接各种外部系统
2. 关键技术总结
| 工具类型 | 核心价值 | 推荐使用场景 |
|---|---|---|
| 搜索工具 | 实时信息检索 | 新闻查询、技术调研、知识问答 |
| SQL 工具 | 结构化数据操作 | 数据分析、BI 报表、用户管理 |
| Python 工具 | 复杂计算和处理 | 数据科学、图表生成、算法实现 |
| 文件工具 | 文档生成 | 报告输出、批量导出、归档存储 |
| MCP 工具 | 标准化集成 | 企业系统集成、扩展性需求 |
3. 最佳实践清单
markdown
✅ **安全性**
- [ ] 使用环境变量管理敏感信息
- [ ] 参数化 SQL 查询防止注入
- [ ] Python 工具限制执行范围
- [ ] API 调用实施频率限制
✅ **性能优化**
- [ ] 启用工具结果缓存
- [ ] 设置合理的调用次数限制
- [ ] 选择性加载必要的工具
- [ ] 使用异步 Agent 提升并发
✅ **错误处理**
- [ ] 所有工具函数包含 try-except
- [ ] 配置重试机制和超时控制
- [ ] 详细的日志记录
- [ ] 友好的错误信息提示
✅ **代码质量**
- [ ] 工具函数添加完整的文档字符串
- [ ] 使用类型提示(Type Hints)
- [ ] Agent 指令清晰明确
- [ ] 定期审查和重构代码
实战项目建议
基于本文所学,您可以尝试构建以下项目:
-
智能数据分析平台
- 结合 PostgreSQL + Python + 文件工具
- 自动生成周报、月报
- 数据可视化和洞察挖掘
-
企业知识库助手
- 使用 MCP 连接文件系统
- 集成搜索工具查找最新资料
- 自动整理和归类文档
-
自动化运维 Agent
- MCP 连接服务器和数据库
- 监控系统状态
- 生成运维报告和告警
下期预告:Agno 与 RAG
参考资源
- 官方文档 : docs.agno.com
- GitHub 仓库 : github.com/agno-agi/ag...
- 发布记录 : github.com/agno-agi/ag...
- DeepSeek 文档 : docs.agno.com/concepts/mo...
- Tavily 集成 : docs.tavily.com/documentati...
感谢您的阅读!期待在下一篇教程中与您相见。
Happy Coding with Agno! 🚀