使用MCP工具和Gemini 2.0 Flash的AI代理
一个端到端的人工智能代理,使用谷歌的Gemini 2.0 Flash模型和模型上下文协议(MCP)工具发送电子邮件、生成图表/仪表板和读取PDF文件。
🎯 概述
该项目展示了一个复杂的人工智能代理,可以:
- 理解自然语言 使用Gemini 2.0 Flash的请求
- 执行多步骤工作流 组合多种工具
- 处理复杂任务 比如阅读PDF、创建可视化效果和发送电子邮件
- 传递上下文 智能自动化工具之间
🏗️ 架构流程
┌─────────────────────────────────────────────────────────────────┐
│ USER INPUT │
│ "Read PDF, create dashboard, and email it to manager@co.com" │
└────────────────────────────┬────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ GEMINI 2.0 FLASH AI │
│ • Analyzes user request │
│ • Identifies required tools │
│ • Structures workflow with multiple steps │
└────────────────────────────┬────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ WORKFLOW ORCHESTRATOR │
│ Executes tools in sequence: │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Step 1: │ │ Step 2: │ │ Step 3: │ │
│ │ read_pdf │→ │ create_chart │→ │ send_email │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ • Context passing between steps │
│ • Auto-summarization of PDF content │
│ • Auto-attachment of generated charts │
└────────────────────────────┬────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ MCP TOOL LAYER │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌──────────┐ │
│ │ read_pdf │ │ generate │ │ create │ │ send │ │
│ │ │ │ _chart │ │ _dashboard │ │ _email │ │
│ │ • Extract │ │ • Bar │ │ • Multi │ │ • SMTP │ │
│ │ text │ │ • Line │ │ chart │ │ • Attach │ │
│ │ • Pages │ │ • Pie │ │ • Custom │ │ • Send │ │
│ │ │ │ • Scatter │ │ layouts │ │ │ │
│ └────────────┘ └────────────┘ └────────────┘ └──────────┘ │
└────────────────────────────┬────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ OUTPUT │
│ • Charts saved to outputs/charts/ │
│ • Email sent with summary + attachment │
│ • Conversational response to user │
└─────────────────────────────────────────────────────────────────┘📊 详细的工作流程图
graph TD
A[User Request] --> B{Gemini AI Parser}
B --> C{Single Tool?}
C -->|Yes| D[Direct Tool Execution]
C -->|No| E[Multi-Tool Workflow]
E --> F[Step 1: Read PDF]
F --> G[Context: PDF Content Stored]
G --> H[Step 2: Generate Chart]
H --> I[Context: Chart Path Stored]
I --> J[Step 3: Prepare Email]
J --> K{Has PDF Content?}
K -->|Yes| L[Generate Summary with Gemini]
L --> M[Set Email Body]
J --> N{Has Chart Path?}
N -->|Yes| O[Add Attachment Path]
M --> P[Send Email via SMTP]
O --> P
P --> Q[Return Success Response]
D --> R[Single Tool Result]
R --> S[Generate Response]
Q --> S
S --> T[Display to User]
style B fill:#ff9800
style E fill:#4caf50
style L fill:#2196f3
style P fill:#f44336🔄 工作原理-一步一步
1. 用户输入处理
# User types a natural language request
"Read example.pdf, create a dashboard, and email it"2. 人工智能分析(Gemini 2.0 Flash)
{
"action": "use_tools",
"workflow": [
{"tool": "read_pdf", "arguments": {...}},
{"tool": "create_dashboard", "arguments": {...}},
{"tool": "send_email", "arguments": {...}}
]
}3. 上下文感知执行
- 步骤1:阅读PDF→ 将内容存储在
context_data['pdf_content'] - 步骤2:创建图表→ 存储路径位于
context_data['chart_path'] - 步骤3:发送电子邮件:
- 自动生成摘要 pdf_content - 自动附加文件 chart_path
4. 智能功能
- ✅ 自动摘要:Gemini自动汇总PDF内容
- ✅ 自动附件:图表自动附加到电子邮件中
- ✅ 上下文传递:数据在工具之间无缝流动
- ✅ 错误处理:优雅的失败,信息丰富
✨ 特性
- 📧 电子邮件工具:使用SMTP发送带有附件的电子邮件(支持Gmail)
- 📊 图表生成:使用Matplotlib创建条形图、折线图、饼图和散点图
- 📈 仪表板创建:生成具有自定义布局的多图表仪表板
- 📄 PDF阅读:使用页面选择支持从PDF文件中提取文本
- 🤖 双子座2.0闪光灯:采用谷歌最新、最快的人工智能模型
- 🔧 MCP集成:通过模型上下文协议公开的工具
- 🔄 工作流程编排:通过上下文传递执行多步骤任务
- 🎯 智能自动化:自动摘要和自动附件功能
🎬 演示示例
示例1:简单图表创建
You: Create a bar chart showing Q1 sales: Jan (15000), Feb (18000), Mar (22000)
Agent: ✓ Chart created at outputs/charts/q1_sales.png示例2:完整工作流
You: Read example.pdf, create a regional sales chart (NA: 75k, EU: 45k, APAC: 30k),
and email it with summary to manager@company.com
Agent:
✓ PDF read (794 chars extracted)
✓ Chart created: outputs/charts/regional_sales.png
✓ Email sent with PDF summary and chart attachment示例3:PDF分析
You: Read example.pdf and send a summary to team@company.com
Agent: ✓ Email sent with AI-generated summary🚀 安装和设置
先决条件
- Python 3.11+
- 诗歌(用于依赖管理)
- 启用了应用程序密码的Gmail帐户
- 谷歌人工智能API密钥(Gemini)
步骤1:克隆存储库
git clone https://github.com/AI-Projects-list/AI-Agent-with-MCP-Tools-Gemini-2.0-Flash.git
cd AI-Agent-with-MCP-Tools-Gemini-2.0-Flash步骤2:安装依赖项
# Using Poetry (recommended)
poetry install
# Or using pip
pip install google-generativeai mcp python-dotenv aiosmtplib email-validator matplotlib seaborn pandas pypdf2 pdfplumber pillow anyio步骤3:配置环境变量
创建一个 .env 项目根目录中的文件:
# Gemini API Configuration (get from https://aistudio.google.com/apikey)
GEMINI_API_KEY=your_gemini_api_key_here
# Gmail SMTP Configuration
SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_gmail_app_password
# SMTP Server Settings
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
# File Paths
PDF_PATH=example.pdf
CHART_OUTPUT_DIR=outputs/charts重要:
步骤4:创建示例PDF(可选)
poetry run python create_sample_pdf.py步骤5:验证设置
poetry run python setup_check.py这验证了:
- ✓ 已安装所有依赖项
- ✓ 已配置环境变量
- ✓ 已创建输出目录
- ✓ Gemini API连接工程
- ✓ SMTP凭据有效
💻 用法
交互模式
poetry run python examples.py然后用自然语言键入您的请求:
> Create a bar chart showing Q1 sales: Jan (15000), Feb (18000), Mar (22000)
> Read example.pdf and summarize it
> Create a dashboard with sales data and email it to team@company.com程序化使用
from agent import AIAgent
# Initialize the agent
agent = AIAgent()
# Single tool request
result = agent.process_query(
"Create a line chart showing temperature trends: Mon (72), Tue (75), Wed (71), Thu (78)"
)
# Multi-tool workflow
result = agent.process_query(
"Read example.pdf, create a chart with key metrics, and email summary to manager@company.com"
)示例工作流
看 USAGE.md 详细示例和 examples.py 用于工作代码示例。
🛠️ 可用工具
1.📧 send_邮件
发送带有可选附件(PDF、PNG、图像)的电子邮件。
参数:
to:收件人电子邮件地址subject:电子邮件主题行body:电子邮件正文内容attachment_path:要附加的可选文件路径
例子:
Send email to team@company.com with subject "Monthly Report" and attach sales_chart.png2.📊 生成图表
创建条形图、折线图、饼图或散点图。
参数:
chart_type:条形|线条|饼状|散点data:带标签和值的图表数据title:图表标题filename:输出文件名(保存到输出/图表/)
数据格式:
{
"labels": ["Product A", "Product B", "Product C"],
"values": [45000, 32000, 28000],
"xlabel": "Products",
"ylabel": "Revenue ($)"
}3.📈 create_dashboard
使用自定义布局生成多图表仪表板。
参数:
charts:图表配置数组dashboard_title:总体仪表板标题filename:输出文件名
例子:
{
"charts": [
{"type": "bar", "data": {...}, "title": "Sales by Region"},
{"type": "line", "data": {...}, "title": "Trend Over Time"}
],
"dashboard_title": "Q4 Performance Dashboard"
}4.📄 read_pdf
通过页面选择从PDF文件中提取文本。
参数:
pdf_path:PDF文件的路径pages:页面范围(例如,“1-3”、“全部”、“1,3,5”)
例子:
Read example.pdf pages 1-5📁 项目结构
AI_Agent_MCP_Gemini/
├── .env # Environment variables (API keys, SMTP config)
├── .gitignore # Git ignore patterns
├── pyproject.toml # Poetry dependencies
├── README.md # This file
├── USAGE.md # Detailed usage guide
├── agent.py # AI Agent with Gemini integration
├── mcp_server.py # MCP server with 4 tools
├── examples.py # Interactive examples
├── setup_check.py # Environment verification
├── create_sample_pdf.py # Sample PDF generator
├── test_workflow.py # Workflow tests
├── test_complete.py # End-to-end test
├── utils.py # Utility functions
└── outputs/
├── charts/ # Generated charts and dashboards
└── pdfs/ # PDF output directory🧪 测试
运行完整的工作流测试
poetry run python test_complete.py这将:
- ✓ Read
example.pdf - ✓ 创建区域销售仪表板
- ✓ 通过电子邮件向仪表板发送PDF摘要
运行单个示例
poetry run python examples.py从6个示例工作流中选择:
- 图表生成
- 仪表板创建
- PDF阅读
- 电子邮件发送
- 复杂工作流
- 完整的端到端工作流程
🔧 故障排除
常见问题
“找不到GEMINI_API_KEY”
- 确保
.env文件存在于项目根目录中 - 检查API密钥是否在有效https://aistudio.google.com/apikey
“SMTP身份验证失败”
- 使用Gmail应用程序密码,而不是常规密码
- 首先在Google帐户上启用2FA
- 验证
SMTP_USER和SMTP_PASSWORD在.env
“找不到模块”
- 跑
poetry install安装所有依赖项 - 激活虚拟环境:
poetry shell
“未创建图表”
- 在您的请求中提供具体的数据值
- 示例:“创建柱状图:一月(100),二月(150),三月(200)”
“仪表板没有图表”
- 确保指定图表数据,而不仅仅是标题
- 每个图表都需要标签、值和类型
🤝 贡献
欢迎投稿!请随时提交拉取请求。
📄 许可证
该项目根据MIT许可证获得许可。
🙏 致谢
- 谷歌双子座2.0 Flash -快速强大的AI模型
- 模型上下文协议(MCP) -工具集成框架
- Anthropic -MCP规范和参考实施
📞 支持
如有疑问或问题:
- 在GitHub上打开一个问题
- 检查
USAGE.md详细示例 - 审查
examples.py用于工作代码
______________________________________________________________________
由以下材料制成❤️ 使用Gemini 2.0闪存和MCP
生成图表
等待代理进程查询( “创建第一季度销售额柱状图:1月(15k)、2月(18k)、3月(22k)。另存为'Q1_sales'” )
发送带有图表的电子邮件
等待代理进程查询( “发送电子邮件至manager@company.com主题为“Q1报告” “并附加文件outputs/charts/q1_sales.png” )
### Analyze PDF and Create Summary Dashboard
Read PDF
result = await agent.process_query("Read example.pdf and extract key metrics")
Create dashboard based on PDF data
await agent.process_query( "Create a dashboard with the metrics from the PDF" )
## 故障排除
**导入错误:没有名为“mcp”的模块**
pip install mcp
**电子邮件发送失败:**
- 确保您使用的是应用程序密码,而不是常规的Gmail密码
- 检查您的Google帐户是否启用了2FA
- 验证中的SMTP设置 `.env`
**Gemini API错误:**
- 在中验证您的API密钥是否正确 `.env`
- 检查您是否有可用的API配额
- 确保使用正确的型号名称: `gemini-2.0-flash`
## 许可证
MIT许可证
## 贡献
请随时提交问题和拉取请求!