天气智能系统

一个基于多代理架构的智能天气服务系统,提供实时天气、预测、警报和旅行规划等功能,支持Docker容器化部署和Streamlit Web UI交互。

  • by Shivbaj
  • Python
  • 本地部署
  • 更新于

使用说明

代理MCP天气情报系统🌤️🤖

全面 代理模型上下文协议(MCP) 通过精心编排的多代理架构提供智能天气服务的系统。专为可扩展的代理应用程序而构建,具有 完全支持Docker 和 流线型Web UI 便于部署和交互。

🌟 主要特点

🌐 web界面

  • 流媒体聊天界面:类似ChatGPT的界面位于 http://localhost:8501
  • 实时交互:与气象机构直接沟通
  • 可视化仪表板:系统健康监测和代理状态
  • 移动响应:适用于台式机、平板电脑和移动设备

🤖 多智能体协调

  • 智能警报代理:主动的天气监测和个性化警报
  • 气象情报员:多源数据聚合和分析
  • 旅行社:基于位置的天气规划和建议
  • 代理商协调中心:所有气象代理的集中编排

🐳 Docker第一架构

  • 完全集装箱化:天气服务器+Ollama LLM+Streamlit UI+设置自动化
  • 多服务编排:生产就绪的微服务架构
  • 生产就绪:通过安全最佳实践和健康检查优化了Dockerfile
  • 一个命令部署:通过以下方式启动整个系统 ./start-docker.sh

🔧 模块化架构

  • 服务器注册表:MCP服务器的自动发现和管理
  • 代理协调器:与本地LLM进行智能工作流协调
  • 多代理支持:专门气象机构的可扩展框架
  • 健康监测:使用全面的健康端点进行实时状态跟踪
  • API-初步设计:带有交互式文档的RESTful API /docs

🤖 高级代理能力

  • 自然语言处理:通过LLM集成了解复杂的天气查询
  • 智能任务路由:自动将查询委托给专门的代理
  • 多地点协调:同时比较和分析多个城市的天气
  • 主动警报系统:具有个性化通知和阈值的智能监控
  • 本地LLM集成:Ollama驱动的推理和决策
  • 上下文感知响应:维护对话历史和学习

🌐 综合气象服务

  • 实时天气:通过多个API了解全球任何城市的当前状况
  • 高级预测:使用美国国家气象局API进行详细预测
  • 智能报警系统:天气警报、紧急通知和自定义阈值
  • 多源情报:来自weather.gov、wttr.in和其他来源的数据融合
  • 旅行计划:基于位置的天气分析,用于行程规划和建议

🏗️ 系统架构

┌─────────────────────────────────────────────────────────────────────────────┐
│                        Docker Network: weather-mcp-network                  │
│                                                                            │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐  ┌─────────┐ │
│  │ Streamlit UI    │  │ Weather MCP     │  │ Ollama LLM      │  │ Setup   │ │
│  │ :8501           │  │ Server :8000    │  │ Server :11434   │  │ Agent   │ │
│  │ ┌─────────────┐ │  │ ┌─────────────┐ │  │ ┌─────────────┐ │  │ (Init)  │ │
│  │ │   Chat UI   │ │  │ │   MCP API   │ │  │ │   Models:   │ │  │ ┌─────┐ │ │
│  │ │   Dashboard │◄┼──┼─┤   Health    │◄┼──┼─┤   - llama3  │ │  │ │Auto │ │ │
│  │ │   Monitoring│ │  │ │   Agent Hub │ │  │ │   - phi3    │ │  │ │Setup│ │ │
│  │ └─────────────┘ │  │ └─────────────┘ │  │ └─────────────┘ │  │ └─────┘ │ │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘  └─────────┘ │
│           │                     │                     │              │      │
└───────────┼─────────────────────┼─────────────────────┼──────────────┼──────┘
            │                     │                     │              │
            │                     │                     │              │
┌───────────▼─────────────────────▼─────────────────────▼──────────────▼──────┐
│                              Host System                                      │
│   🌐 http://localhost:8501   (Streamlit Chat Interface)                      │
│   🔧 http://localhost:8000   (Weather API + Agent Coordination)              │
│   🤖 http://localhost:11434  (Ollama LLM Engine)                             │
│   📚 http://localhost:8000/docs (Interactive API Documentation)              │
└───────────────────────────────────────────────────────────────────────────────┘

代理协调流程

User Query ─► Streamlit UI ─► Agent Coordination Hub ─► Specialized Agents
                  │                       │                      │
                  │                       │              ┌─────────────┐
                  │                       └──────────────┤Smart Alert  │
                  │                                      │Agent        │
                  │                              ┌───────┤Weather Intel│
                  │                              │       │Travel Agent │
                  │                              │       └─────────────┘
                  │                              │              │
                  │                              ▼              ▼
                  │                       Ollama LLM ──► API Results
                  │                              │              │
                  └──────────── Response ◄───────┴──────────────┘

⚡ TL;DR-使用3个命令入门

git clone <your-repo-url> && cd weather
chmod +x *.sh && ./start-docker.sh
# ✅ Chat Interface: http://localhost:8501
# ✅ API Server: http://localhost:8000  
# ✅ System ready with Streamlit UI!

您立即获得的内容:

  • 🌐 Streamlit聊天界面 在 http://localhost:8501 -类似ChatGPT的天气助手
  • 🔧 天气API 在 http://localhost:8000 -带代理协调的完整MCP服务器
  • 📚 API文件 在 http://localhost:8000/docs -交互式OpenAPI文档
  • 🤖 奥拉马LLM 在 http://localhost:11434 -用于智能响应的本地AI模型

📋 需求

  • 码头工人 (20.10或更高版本)使用Docker Compose
  • 8GB+内存 (适用于Ollama LLM型号:llama3+phi3)
  • 15GB+磁盘空间 (适用于容器图像+模型+日志)
  • 网络连接 (用于天气API和初始模型下载)
  • 可用端口:8000(API)、8501(Streamlit)、11434(Ollama)

🚀 Docker快速入门

选项1:带有便利脚本的完整系统(推荐)

# 1. Clone the repository
git clone <your-repo-url>
cd weather-mcp-agent

# 2. Make scripts executable (Linux/macOS)
chmod +x *.sh

# 3. Validate your environment (optional but recommended)
./validate-docker.sh

# 4. Start the complete system (one command!)
./start-docker.sh

# 5. For verbose output and logs
./start-docker.sh --verbose

# 6. Stop the system when done
./stop-docker.sh

选项1b:手动Docker命令

# 1. Clone the repository
git clone <your-repo-url>
cd weather-mcp-agent

# 2. Start the complete system (Weather Server + Ollama + Models)
docker-compose up -d

# 3. Monitor the startup process
docker-compose logs -f

# 4. Wait for model downloads (first run only, may take 5-10 minutes)
# You'll see: "Models ready!" when everything is set up

# 5. Test the system
curl http://localhost:8000/health

系统将在以下地点提供:

  • 🌐 流媒体聊天界面: http://localhost:8501(主界面)
  • 🔧 天气API: http://localhost:8000(REST API+代理集线器)
  • 🤖 奥拉马LLM: http://localhost:11434(AI模型)
  • 📚 API文档: http://localhost:8000/docs(交互式文档)

选项2:带演示的开发设置

# Start system and run demo
docker-compose --profile demo up

# Or run demo separately after system is up
docker-compose up -d
docker-compose run weather-demo

选项3:本地开发(非Docker)

# 1. Install Ollama locally
brew install ollama  # macOS
# or download from https://ollama.ai/download

# 2. Start Ollama and pull models
ollama serve &
ollama pull llama3
ollama pull phi3

# 3. Install Python dependencies
pip install -r requirements.txt

# 4. Environment configuration is ready!
# The .env file is already set up for local development
# For production, copy .env.production.template to .env.production and customize

# 5. Start the weather server
python main.py server

🐳 Docker管理命令

便利脚本(推荐)

# Development/testing
./start-docker.sh                    # Default setup
./start-docker.sh --dev              # Development mode (live reload)
./start-docker.sh --demo             # Include demo client
./start-docker.sh --verbose          # Show detailed logs

# Production deployment
./start-docker.sh --prod             # Production configuration
./start-docker.sh --prod --build     # Production with fresh build

# Management
./stop-docker.sh                     # Stop (can restart)
./stop-docker.sh --cleanup           # Remove containers
./stop-docker.sh --remove-data       # Remove everything including models

手动Docker命令

# Default setup
docker-compose up -d

# Development mode (with live reload)
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -d

# Production mode (optimized settings)  
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d

# View logs (all services)
docker-compose logs -f

# View logs (specific service)
docker-compose logs -f weather-server
docker-compose logs -f ollama

# Stop all services
docker-compose down

# Restart services
docker-compose restart

# Rebuild and restart (after code changes)
docker-compose up -d --build

# Pull latest images
docker-compose pull

环境配置

环境 功能 用例
默认 标准设置,禁用API密钥 本地开发和测试
发展 实时重新加载、调试日志记录、宽松的安全性 主动开发
生产 优化性能、启用安全性、资源限制 生产部署

维护命令

# Check service status
docker-compose ps

# Access container shell
docker-compose exec weather-server bash
docker-compose exec ollama bash

# View system resources
docker-compose top

# Clean up (removes containers, networks, volumes)
docker-compose down -v --remove-orphans

# Remove all unused Docker resources
docker system prune -a

开发命令

# Run with demo profile
docker-compose --profile demo up

# Override environment variables
ENVIRONMENT=development docker-compose up -d

# Run single command in container
docker-compose run weather-server python --version
docker-compose run weather-server python demo.py

# Mount local code for development
# (uncomment volume in docker-compose.yml: - .:/app)

📚 用法示例

🌐 主要:Streamlit聊天界面 (推荐)

打开http://localhost:8501试试这些:

💬 "What's the weather like in San Francisco right now?"
💬 "Set up weather alerts for New York with temperature thresholds"  
💬 "Compare weather conditions in London, Paris, and Tokyo"
💬 "Plan my outdoor activities for this weekend in Seattle"
💬 "Any severe weather alerts for California today?"
💬 "What's the best time to travel to Miami this week?"

特征:

  • 🤖 自然语言处理:键入内容就像您在与ChatGPT聊天一样
  • 📊 可视化仪表板:实时代理状态和系统健康监测
  • 💾 对话历史:跨多个查询维护上下文
  • 📱 移动响应:适用于手机和平板电脑

🔧 API测试(高级用户)

# System Health Check
curl http://localhost:8000/health

# Agent Coordination Status
curl http://localhost:8000/info

# Direct Weather Query
curl -X POST http://localhost:8000/tools/get_weather \
  -H "Content-Type: application/json" \
  -d '{"city": "San Francisco"}'

# Smart Alert Setup via API
curl -X POST http://localhost:8000/tools/setup_smart_alerts \
  -H "Content-Type: application/json" \
  -d '{
    "locations": ["New York", "Boston"], 
    "alert_types": ["severe_weather", "temperature_extreme"],
    "thresholds": {"temperature_high": 85, "temperature_low": 32}
  }'

# Multi-Location Weather Intelligence
curl -X POST http://localhost:8000/tools/get_weather_intelligence \
  -H "Content-Type: application/json" \
  -d '{"locations": ["London", "Paris", "Rome"], "analysis_type": "comparison"}'

🐍 Python集成

# Direct Agent Usage
from agent_coordination_hub import AgentCoordinationHub
from smart_alert_agent import AlertAgent

# Initialize coordination system
hub = AgentCoordinationHub()
result = await hub.process_request("Weather in Tokyo with travel recommendations")

# Smart alerts with custom thresholds
alert_agent = AlertAgent()
config = {
    "locations": ["San Francisco", "Seattle"],
    "alert_types": ["severe_weather", "temperature_extreme"], 
    "thresholds": {"temperature_high": 80, "temperature_low": 40}
}
alerts = await alert_agent.setup_smart_alerts(config)

🛠️ Docker故障排除

常见问题及解决方法

问题:Ollama容器无法启动

# Check if port 11434 is already in use
lsof -i :11434
# If occupied, stop the local Ollama service
brew services stop ollama

# Check container logs
docker-compose logs ollama

问题:模型下载失败或超时

# Manually pull models with more verbose output
docker-compose exec ollama ollama pull llama3
docker-compose exec ollama ollama pull phi3

# Check available disk space (models are 4GB+ each)
docker system df

问题:天气服务器无法连接到Ollama

# Check network connectivity
docker-compose exec weather-server curl http://ollama:11434/api/version

# Verify Ollama health
curl http://localhost:11434/api/version

# Check container network
docker network ls
docker network inspect weather-mcp-network

问题:内存不足错误

# Check Docker memory limits
docker stats

# Increase Docker Desktop memory limit to 8GB+
# Docker Desktop > Settings > Resources > Memory

# Monitor container memory usage
docker-compose exec weather-server free -h

问题:端口冲突

# Check what's using port 8000
lsof -i :8000

# Use different ports
SERVER_PORT=8080 docker-compose up -d

# Or modify docker-compose.yml ports section

性能优化

# Pre-pull all images
docker-compose pull

# Build with cache optimization
DOCKER_BUILDKIT=1 docker-compose build

# Limit container resources
# Add to docker-compose.yml under services:
#   weather-server:
#     deploy:
#       resources:
#         limits:
#           memory: 2g
#         reservations:
#           memory: 1g

日志和调试

# Detailed logging
LOG_LEVEL=DEBUG docker-compose up -d

# Follow all logs with timestamps
docker-compose logs -f -t

# Export logs for analysis
docker-compose logs > system-logs.txt

# Access container filesystems
docker-compose exec weather-server ls -la /app/logs/

⚙️ 环境配置

环境文件概述

该项目包括一个承诺 .env 针对本地开发进行了优化的文件:

文件 目的 致力于Git
.env 本地开发默认值 ✅ 是的
.env.example 带所有选项的模板 ✅ 是的
.env.production.template 生产模板 ✅ 是的
.env.production 您的生产配置 ❌ 否(在本地创建)
.env.local 个人覆盖 ❌ 否(忽略)

地方发展

这 .env 文件是 随时可用 使用安全默认值:

# Clone and run immediately - no .env setup needed!
git clone <your-repo>
cd weather-mcp-agent
./start-docker.sh

当地发展特点:

  • ✅ ENVIRONMENT=development
  • ✅ 已启用调试日志记录
  • ✅ CORS允许本地主机源
  • ✅ API密钥要求已禁用
  • ✅ 测试的高速率限制
  • ✅ 包括原始数据和执行日志

定制

创建 .env.local 对于个人覆盖(被git忽略):

# .env.local - personal overrides
LOG_LEVEL=DEBUG
OLLAMA_MODEL=phi3
SERVER_PORT=8001

环境变量优先级

  1. 环境变量 (最高优先级)
  2. .env.local (个人优先权)
  3. .env (承诺违约)

🚀 使用Docker进行生产部署

步骤1:生产环境配置

# 1. Clone to production server
git clone <your-repo-url>
cd weather-mcp-agent

# 2. Create production environment file
cp .env.production.template .env.production

# 3. Edit production settings (REQUIRED - update all sensitive values)
nano .env.production

关键生产设置:

ENVIRONMENT=production
API_KEY_REQUIRED=true
API_KEY=your-secure-production-key
ALLOWED_ORIGINS=https://yourdomain.com
RATE_LIMIT_PER_MINUTE=60
LOG_LEVEL=INFO

步骤2:SSL/TLS配置(可选)

# Add SSL certificates to docker-compose.yml
mkdir -p ./ssl
# Copy your cert.pem and key.pem to ./ssl/

# Update .env.production
SSL_CERT_PATH=/app/ssl/cert.pem
SSL_KEY_PATH=/app/ssl/key.pem

步骤3:生产部署

# Method 1: Using convenience script (recommended)
./start-docker.sh --build

# Method 2: Manual deployment
docker-compose -f docker-compose.yml --env-file .env.production up -d

# Method 3: With custom configuration
docker-compose up -d --build

步骤4:生产验证

# Check all services are running
docker-compose ps

# Verify health endpoints
curl https://yourdomain.com:8000/health
curl https://yourdomain.com:8000/info

# Check logs for any issues
docker-compose logs -f --tail=100

# Method 4: Docker with external Ollama
docker build -t weather-mcp .
docker run -p 8000:8000 --env-file .env --add-host=host.docker.internal:host-gateway weather-mcp

生产终点:

  • 🏥 GET /health -全面的健康检查和服务验证
  • ⚡ GET /health/quick -无需外部电话即可快速进行健康检查
  • 📊 GET /info -服务器功能和元数据
  • 🌤️ POST /tools/get_weather -当前天气(限速)
  • 📅 POST /tools/get_forecast -天气预报(验证坐标)
  • 🚨 POST /tools/get_alerts -天气警报(仅限美国各州)

管理命令:

# Production server management
python main.py start         # Start production server
python main.py status        # System health and status
python main.py config        # View current configuration
python main.py validate      # Validate configuration

# Development/testing (disabled in production)
python main.py interactive   # Interactive client mode
python main.py demo          # System demonstration
python main.py servers       # Server registry info

📁 项目结构

weather/
├── 🌐 Web Interface
│   └── streamlit_app.py             # Streamlit Chat UI (Primary Interface)
├── 🤖 Agent Coordination System  
│   ├── agent_coordination_hub.py    # Central agent coordinator
│   ├── smart_alert_agent.py         # Proactive weather monitoring agent
│   ├── weather_intelligence_agent.py # Multi-source data analysis agent
│   └── travel_agent.py              # Location-based travel planning agent
├── � Core MCP Server
│   ├── main.py                      # Production entry point & CLI management
│   ├── weather.py                   # Weather MCP server implementation
│   ├── config.py                    # Configuration management
│   ├── server_registry.py           # Server discovery & health monitoring
│   └── health_server.py             # Health check endpoints
├── 🚀 Orchestration & Workflows
│   ├── simple_orchestrator.py       # Basic agentic workflow orchestrator
│   └── agent_orchestrator.py        # Advanced LangGraph orchestrator
├── 🛠️ Development & Testing
│   ├── mcp_client.py               # Interactive client for testing
│   ├── demo.py                     # System demonstration scripts
│   └── run_server.py               # Alternative server startup
├── � Docker & Deployment
│   ├── Dockerfile                   # Production container image
│   ├── docker-compose.yml           # Multi-service orchestration
│   ├── start-docker.sh              # Comprehensive startup script
│   ├── stop-docker.sh               # Clean shutdown script
│   └── setup-ollama.sh              # Ollama model setup automation
├── 📋 Configuration & Dependencies
│   ├── requirements.txt             # Python dependencies
│   ├── pyproject.toml              # Project metadata (v0.2.0)
│   ├── .env                        # Environment variables (Docker-ready)
│   └── .env.example                # Configuration template
└── 📚 Documentation
    ├── README.md                   # This comprehensive guide
    ├── SETUP.md                    # Quick setup instructions
    ├── DOCKER.md                   # Docker-specific documentation
    ├── DEPLOYMENT.md               # Production deployment guide
    ├── WORKING_SYSTEM_SUMMARY.md   # System status & test cases
    ├── AGENT_COORDINATION_GUIDE.md # Agent development guide
    └── CONTRIBUTING.md             # Contribution guidelines

💬 交互式使用示例

🌐 Streamlit聊天界面 (http://localhost:8501)

这 主要方式 与您的天气情报系统交互:

🔮 智能天气查询:

💬 "What's the weather like in London right now?"
🤖 "🌤️ London Weather Update:
    🌡️ Temperature: 15°C (feels like 13°C)  
    🌧️ Conditions: Light drizzle
    💨 Wind: 12 mph from the west
    📊 Humidity: 78%"

💬 "Set up weather alerts for my commute route"  
🤖 "I'll set up smart alerts for your locations. What cities should I monitor?"

💬 "Compare weather in New York, London, and Tokyo"
🤖 "🌍 Multi-City Weather Comparison:
    🗽 New York: 22°C, Sunny, Perfect for outdoor activities
    🇬🇧 London: 15°C, Overcast, Light jacket recommended  
    🗾 Tokyo: 28°C, Humid, Stay hydrated!"

� 高级功能:

  • 对话记忆:跨问题保持上下文
  • 可视化仪表板:实时系统运行状况和代理状态
  • 移动响应:手机和平板电脑的完美界面
  • 多智能体协调:自动路由到专门的气象机构

🛠️ API命令示例 (高级用户)

# System Status & Health
curl http://localhost:8000/health
curl http://localhost:8000/info

# Agent Coordination
curl -X POST http://localhost:8000/agent/coordinate \
  -H "Content-Type: application/json" \
  -d '{"query": "Weather alerts for California with travel advice"}'

🛠️ API集成示例

直接服务器API调用

# Get current weather
curl -X POST http://localhost:8000/tools/get_weather \
  -H "Content-Type: application/json" \
  -d '{"city": "London"}'

# Get forecast (requires coordinates)  
curl -X POST http://localhost:8000/tools/get_forecast \
  -H "Content-Type: application/json" \
  -d '{"latitude": 51.5074, "longitude": -0.1278}'

# Get weather alerts (US states only)
curl -X POST http://localhost:8000/tools/get_alerts \
  -H "Content-Type: application/json" \
  -d '{"state": "CA"}'

服务器发现和运行状况

# Check server health
curl http://localhost:8000/health

# Get server capabilities
curl http://localhost:8000/info

🔧 扩展系统

添加新的MCP服务器

# Register a new server in server_registry.py
from server_registry import registry, MCPServer

# Define new server
finance_server = MCPServer(
    name="finance-server",
    host="localhost", 
    port=8001,
    description="Financial data and stock information",
    tools=["get_stock_price", "get_market_news", "analyze_portfolio"],
    tags=["finance", "stocks", "market"]
)

# Register it
registry.register_server(finance_server)

自定义任务类型

# Extend TaskType enum in simple_orchestrator.py
class TaskType(Enum):
    WEATHER_QUERY = "weather_query"
    FORECAST_ANALYSIS = "forecast_analysis"
    ALERT_MONITORING = "alert_monitoring"
    MULTI_LOCATION = "multi_location"
    FINANCIAL_ANALYSIS = "financial_analysis"  # New!
    GENERAL_INQUIRY = "general_inquiry"

🎯 代理设计原则

1.模块化

  • 每个组件都有一个明确的责任
  • 易于扩展新的服务器和功能
  • 编排器和服务器之间的松耦合

2.智能路由

  • 任务分类决定工作流路径
  • 位置提取支持多位置查询
  • 使用优雅的回退进行错误处理

3.可扩展性

  • 服务器注册表支持动态添加服务器
  • 自动故障转移的运行状况监控
  • 并发处理的异步操作

4.可观察性

  • 用于调试的详细执行日志
  • 绩效指标和时间安排
  • 健康状态监测

🔮 高级功能(可选)

LangGraph集成

对于更复杂的代理工作流,请启用高级编排器:

# Install additional dependencies
uv add langgraph langchain-ollama

# Use agent_orchestrator.py instead of simple_orchestrator.py
from agent_orchestrator import WeatherOrchestrator

# Requires Ollama running locally
ollama serve

多智能体协调

该系统旨在支持多代理场景:

# Example: Weather + Travel planning agent
travel_query = "What's the weather like in my travel destinations this week?"
# → Orchestrator coordinates:
#   1. Extract travel destinations  
#   2. Get weather for each location
#   3. Get forecasts for travel dates
#   4. Provide travel recommendations

📊 监控与调试

健康检查

# Check all servers
💬 You: servers

📊 Found 1 registered servers:
   ✅ Online: 1
   ❌ Offline: 0  
   ⚠️  Error: 0
   ❓ Unknown: 0

执行日志

每个查询都提供详细的执行跟踪:

🔍 Execution Log:
   1. Classified task as: weather_query
   2. Extracted locations: ['London']
   3. Gathered weather data for 1 locations
   4. Generated response

🔒 生产安全

环境变量

生产部署所需:

# Server Configuration
SERVER_HOST=0.0.0.0
SERVER_PORT=8000
ENVIRONMENT=production

# Security
API_KEY_REQUIRED=true
API_KEY=your-secure-api-key-here
RATE_LIMIT_PER_MINUTE=100
ALLOWED_ORIGINS=https://yourdomain.com

# Logging
LOG_LEVEL=INFO
LOG_FILE_PATH=/var/log/weather-mcp/server.log

安全功能

  • 输入验证 使用Pydantic模型
  • 速率限制 每个端点(可配置)
  • API密钥验证 (可选)
  • CORS保护 具有可配置的来源
  • 请求大小限制 防止DoS
  • 综合录井 用于审计跟踪
  • 错误清理 防止信息泄露

� 生产监控

健康检查

# Quick health check
curl http://localhost:8000/health/quick

# Comprehensive health check (includes external APIs)
curl http://localhost:8000/health

# Server info and capabilities
curl http://localhost:8000/info

日志记录

生产日志的结构包括:

  • 请求/响应日志记录
  • 使用堆栈跟踪进行错误跟踪
  • 性能指标
  • 安全事件(速率限制、身份验证失败)
# View logs (if using file logging)
tail -f /var/log/weather-mcp/server.log

# Check log level
python main.py config | grep -i log

性能优化

  • 异步请求处理 使用httpx
  • 连接池 用于外部API
  • 请求超时控制
  • 指数退避 用于API重试
  • 响应缓存 (可配置)
  • 资源限制 以及速率限制

�🚨 故障排除

常见生产问题:

  1. 服务器无法启动:检查端口可用性和环境变量

    # Check port usage
    lsof -ti:8000
    
    # Validate configuration
    python main.py validate
    
    # Check environment
    python main.py config
    
  2. Ollama连接问题:确保Olama正在运行且可访问

    # Check if Ollama is running
    ollama list
    
    # If not running, start Ollama
    ollama serve
    
    # Test connection to Ollama
    curl http://localhost:11434/api/version
    
    # Verify model is available
    ollama run llama3 "Hello, test message"
    
  3. 内存使用率高:调整工作人员数量和连接限制

    # Reduce workers in production
    uvicorn weather:app --workers 2 --max-requests 1000
    
  4. API超时:外部气象服务可能很慢

    # Check API status
    curl -w "%{time_total}\n" http://localhost:8000/health
    
  5. 利率限制问题:调整环境变量的限制

    # In .env file
    RATE_LIMIT_PER_MINUTE=200
    SERVER_TIMEOUT=45.0
    

日志分析

# Find errors in logs
grep -i error /var/log/weather-mcp/server.log

# Check API performance
grep "response_time" /var/log/weather-mcp/server.log

# Monitor rate limiting
grep "rate.*limit" /var/log/weather-mcp/server.log

🤝 贡献

我们欢迎捐款!以下是如何开始:

  1. 分叉存储库
  2. 创建要素分支: git checkout -b feature/amazing-feature
  3. 进行更改
  4. 添加测试 对于新功能
  5. 运行测试套件: uv run main.py test
  6. 提交您的更改: git commit -m 'Add amazing feature'
  7. 推到分支: git push origin feature/amazing-feature
  8. 打开拉取请求

贡献领域:

  • 新MCP服务器:添加天气邻近服务(交通、活动等)
  • 增强NLP:改进位置提取和查询理解
  • 高级编排:实施复杂的多步骤工作流程
  • 数据源:集成其他天气API和服务
  • 文档:改进指南和示例
  • 生产特点:添加监控、缓存和性能改进
  • 增强的安全性:其他身份验证方法和安全强化

✅ Docker部署清单

预部署

  • []已安装Docker引擎20.10+
  • []已安装Docker Compose v2.0+或Docker Compose v1.29+
  • []系统有8GB+RAM可用
  • []Ollama型号的10GB+磁盘空间
  • []用于API访问和模型下载的互联网连接

环境设置

  • []克隆存储库并使脚本可执行(chmod +x *.sh)
  • []环境已验证(./validate-docker.sh)
  • []已配置生产环境(.env.production)
  • []已配置SSL证书(如果使用HTTPS)

部署验证

  • []所有容器均已成功启动(docker-compose ps)
  • []健康检查通过(curl localhost:8000/health)
  • []Ollama模型已下载(docker-compose logs ollama-setup)
  • []天气API端点响应(curl localhost:8000/tools/get_weather)
  • []日志显示没有错误(docker-compose logs)

生产就绪

  • []API密钥已配置且安全
  • []适当配置速率限制
  • []为您的域配置的CORS设置
  • []已配置监控和警报
  • []配置和数据的备份策略
  • []为容器设置的资源限制

📄 许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

🎬 演示场景

🌐 打开http://localhost:8501并尝试这些智能天气工作流程:

🏃‍♂️ 个人计划

💬 "Plan my outdoor workout routine for San Francisco this week"
💬 "Should I bring an umbrella to my meeting in Seattle tomorrow?"
💬 "What's the best day for a picnic in Central Park this weekend?"  
💬 "When should I schedule my outdoor photography session in London?"

✈️ 旅游情报

💬 "I'm flying from New York to Los Angeles tomorrow - any weather concerns?"
💬 "Compare weather conditions for my business trip: Boston, Chicago, Denver"
💬 "Best time to visit Tokyo this month based on weather patterns?"
💬 "Should I pack winter clothes for my trip to Montreal next week?"

🚨 智能监控

💬 "Set up weather alerts for my daily commute from Brooklyn to Manhattan"
💬 "Monitor severe weather for my company's offices in California and Texas"
💬 "Alert me if temperature drops below freezing in Chicago this week"
💬 "Watch for storm systems affecting my weekend camping trip in Yosemite"

🏢 业务应用程序

💬 "Weather impact analysis for our retail stores in Florida, Georgia, and South Carolina"  
💬 "Construction weather forecast for our project sites in Denver and Phoenix"
💬 "Event planning weather assessment for outdoor venues this month"

每个查询都演示了:

  • 🤖 多智能体协调:自动路由到专业代理
  • 🧠 情境感知:了解复杂的多部分请求
  • 📊 智能分析:来自多个天气源的数据融合
  • 💡 主动建议:超越原始数据的可操作见解

📚 依赖项

看 requirements.txt 查看完整的依赖关系列表。关键包:

  • 快速API:REST API框架
  • LangChain:LLM集成(高级功能可选)
  • LangGraph:高级代理编排
  • 主控程序:模型上下文协议实现
  • 请求/HTTPX:HTTP客户端库
  • 派丹蒂克:数据验证

🙏 致谢

📊 当前系统状态 (更新日期:2025年10月16日)

✅ 现场服务

  • 🌐 Streamlit聊天界面: http://localhost:8501 ✅ 健康
  • 🔧 Weather API+代理中心: http://localhost:8000 ✅ 健康
  • 🤖 Ollama LLM发动机: http://localhost:11434 ✅ 健康
  • 📚 交互式API文档: http://localhost:8000/docs ✅ 可用的

🤖 活性剂

  • 智能警报代理: ✅ 具有自定义阈值的主动天气监测
  • 气象情报员: ✅ 多源数据分析和预测
  • 旅行社: ✅ 基于位置的规划和建议
  • 代理商协调中心: ✅ 中央编排和路由系统

💡 现在试试

  1. 打开: http://localhost:8501(流媒体聊天)
  2. 问: “为旧金山设置带温度阈值的天气警报”
  3. 手表:多智能体协同行动!

📈 系统健康

{
  "status": "healthy",
  "services": {
    "nws_api": "available",
    "wttr_in": "available", 
    "ollama": "healthy"
  },
  "performance": {
    "response_time_ms": 2135.61,
    "memory_usage": "available"
  },
  "environment": "production"
}

内置于❤️ 面向代理AI社区 | 可扩展•模块化•生产就绪 版本0.2.0 | 多智能体协调 | Docker原生 | 流媒体接口