File size: 15,234 Bytes
993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c 2886587 993588c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 |
# Bihar AgMCP - Agricultural Weather Alert System
## Table of Contents
- [System Overview](#system-overview)
- [Architecture](#architecture)
- [Installation & Setup](#installation--setup)
- [Core Components](#core-components)
- [API Reference](#api-reference)
- [Data Models](#data-models)
- [Configuration](#configuration)
- [Deployment](#deployment)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
## System Overview
### Purpose
The Bihar AgMCP (Agricultural Model Control Protocol) is an AI-powered weather alert system designed to provide personalized agricultural advisories to farmers in Bihar, India. The system generates location-specific weather alerts with crop-specific recommendations.
### Key Features
- **AI-Enhanced Weather Alerts**: OpenAI-powered intelligent alert generation
- **Multi-Channel Communication**: SMS, WhatsApp, USSD, IVR, and Telegram support
- **Regional Crop Intelligence**: District-specific crop recommendations based on seasons
- **Real-time Weather Data**: Integration with multiple weather APIs
- **Geographic Intelligence**: Village-level weather data and coordinates
- **Web Interface**: User-friendly Gradio interface for easy access
- **CSV Export**: Data export functionality for analysis
### Target Users
- Agricultural extension workers
- Farmers and farmer organizations
- Government agricultural departments
- Research institutions
- NGOs working in agriculture
## Architecture
### System Architecture Diagram
```
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Weather APIs β β OpenAI API β β Geographic APIs β
β β β β β β
β β’ Open-Meteo β β β’ GPT Models β β β’ Geocoding β
β β’ Tomorrow.io β β β’ Alert Gen β β β’ Village Data β
β β’ OpenWeather β β β β β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β β β
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
β
βββββββββββββββββββ
β FastAPI Core β
β β
β β’ Alert Engine β
β β’ Crop Calendar β
β β’ Workflow Mgmt β
βββββββββββββββββββ
β
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
β β β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β A2A Agents β β Web Interface β β API Clients β
β β β β β β
β β’ SMS Agent β β β’ Gradio UI β β β’ MCP Protocol β
β β’ WhatsApp β β β’ CSV Export β β β’ REST API β
β β’ USSD/IVR β β β’ District Sel β β β’ JSON-RPC β
β β’ Telegram β β β β β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
```
### Technology Stack
- **Backend**: FastAPI (Python 3.8+)
- **AI**: OpenAI GPT
- **Weather Data**: Open-Meteo, Tomorrow.io, OpenWeatherMap
- **Frontend**: Gradio
- **Data Processing**: Pandas, CSV
- **Async Operations**: asyncio
- **Configuration**: dotenv
- **Logging**: Python logging
## Installation & Setup
### Prerequisites
- Python 3.8 or higher
- pip package manager
- Internet connection for API access
### Environment Setup
1. **Clone the repository**
```bash
git clone <repository-url>
cd bihar-agmcp
```
2. **Install dependencies**
```bash
pip install fastapi uvicorn gradio pandas python-dotenv pydantic
```
3. **Create environment file**
Create a `.env` file in the root directory:
```env
# Required
OPENAI_API_KEY=your_openai_api_key_here
# Optional Weather APIs
TOMORROW_IO_API_KEY=your_tomorrow_io_key
GOOGLE_WEATHER_API_KEY=your_google_weather_key
OPENWEATHERMAP_API_KEY=your_openweathermap_key
ACCUWEATHER_API_KEY=your_accuweather_key
# Logging
LOG_LEVEL=INFO
```
4. **Tool dependencies**
Ensure the following modules are available:
- `tools/` - Weather and geographic tools
- `a2a_agents/` - Communication agents
- `utils/` - Utility functions
### Quick Start
```bash
python main.py
```
## Core Components
### 1. Server-side
#### a. Alert Generation Engine
- **Primary Function**: `generate_dynamic_alert(district, state)`
- **Purpose**: Generates comprehensive weather alerts for specific districts.
**Process Flow:**
1. **Village Selection**: Randomly selects a village from the district
2. **Coordinate Resolution**: Gets GPS coordinates for location
3. **Crop Intelligence**: Selects appropriate crop based on:
- Current season (Kharif/Rabi/Zaid)
- District crop preferences
- Regional agricultural patterns
4. **Weather Data Collection**: Fetches weather data from APIs
5. **Alert Generation**: Creates weather-based alerts
6. **AI Enhancement**: Applies OpenAI analysis (if available)
**Example Usage:**
```python
alert_data = await generate_dynamic_alert("Patna", "Bihar")
```
#### b. Crop Calendar System
**Crop Definitions**
The system includes detailed crop calendars for major Bihar crops:
- **Rice (Kharif)**: June-July planting, October-November harvest
- **Wheat (Rabi)**: November-December planting, March-April harvest
- **Maize (Kharif/Zaid)**: Dual season crop
- **Sugarcane (Annual)**: February-March planting
- **Mustard (Rabi)**: October-November planting
**District Crop Mapping**
Each district has specific crop preferences:
```python
DISTRICT_CROPS = {
'patna': {
'primary': ['rice', 'wheat', 'potato'],
'secondary': ['mustard', 'gram'],
'specialty': ['sugarcane']
},
# ... other districts
}
```
#### c. Weather Integration
**Supported Weather APIs:**
- **Open-Meteo** (Primary): Free, reliable weather data
- **Tomorrow.io**: Professional weather services
- **OpenWeatherMap**: Popular weather API
- **AccuWeather**: Commercial weather data
- **Google Weather**: Google's weather services
**Weather Alert Types:**
- **Heavy Rain Warning**: >25mm rainfall expected
- **Moderate Rain Warning**: 10-25mm rainfall expected
- **Heat/Drought Warning**: High temperature + low rainfall
- **Cold Warning**: Temperature <10Β°C
- **High Wind Warning**: Wind speed >30 km/h
- **Weather Update**: Normal conditions
### 2. Client-side
#### A2A Communication Agents
**SMS Agent**
Creates concise SMS messages (160 characters max):
```python
def create_sms_message(alert_data):
return f"BIHAR ALERT: {crop} in {location} - {weather_summary}"
```
**WhatsApp Agent**
Generates rich WhatsApp messages with emojis and formatting:
```python
def create_whatsapp_message(alert_data):
return {
"text": formatted_message,
"buttons": action_buttons
}
```
**USSD Agent**
Creates interactive USSD menu structures:
```python
def create_ussd_menu(alert_data):
return {
"menu": "CON Weather Alert...\n1. Details\n2. Actions"
}
```
**IVR Agent**
Generates voice script for phone systems:
```python
def create_ivr_script(alert_data):
return {
"script": "Welcome to Bihar weather alert...",
"menu_options": [...]
}
```
**Telegram Agent**
Creates Telegram messages with inline keyboards:
```python
def create_telegram_message(alert_data):
return {
"text": message,
"reply_markup": inline_keyboard
}
```
## API Reference
### Core Endpoints
#### 1. Workflow Execution
```http
POST /api/run-workflow
```
**Request Body:**
```json
{
"state": "bihar",
"district": "patna"
}
```
**Response:**
```json
{
"message": "workflow_results",
"status": "success",
"csv": "csv_data",
"raw_data": {
"alert_data": {...},
"agent_responses": {...}
}
}
```
#### 2. Health Check
```http
GET /api/health
```
**Response:**
```json
{
"status": "healthy",
"openai_available": true,
"timestamp": "2025-08-13T10:30:00"
}
```
#### 3. MCP Tool Execution
```http
POST /mcp
```
**Request Body:**
```json
{
"tool": "get_current_weather",
"parameters": {
"latitude": 25.5941,
"longitude": 85.1376
}
}
```
#### 4. Geographic Data
```http
GET /api/districts/{state}
GET /api/villages/{state}/{district}
```
#### 5. Weather Data
```http
GET /api/weather/{latitude}/{longitude}
```
### A2A Agent Endpoints
- **SMS**: `POST /a2a/sms`
- **WhatsApp**: `POST /a2a/whatsapp`
- **USSD**: `POST /a2a/ussd`
- **IVR**: `POST /a2a/ivr`
- **Telegram**: `POST /a2a/telegram`
## Data Models
### AlertRequest
```python
class AlertRequest(BaseModel):
alert_json: dict
```
### WorkflowRequest
```python
class WorkflowRequest(BaseModel):
state: str
district: str
```
### MCPRequest
```python
class MCPRequest(BaseModel):
tool: str
parameters: dict
```
### Alert Data Structure
```json
{
"alert_id": "BH_PAT_VIL_20250813_103000",
"timestamp": "2025-08-13T10:30:00Z",
"location": {
"village": "Danapur",
"district": "Patna",
"state": "Bihar",
"coordinates": [25.5941, 85.1376],
"coordinates_source": "village_danapur"
},
"crop": {
"name": "rice",
"stage": "Tillering",
"season": "kharif",
"planted_estimate": "2025-06-15"
},
"alert": {
"type": "heavy_rain_warning",
"urgency": "high",
"message": "Heavy rainfall expected...",
"action_items": ["delay_fertilizer", "check_drainage"],
"ai_generated": true
},
"weather": {
"temperature": "28.5Β°C",
"expected_rainfall": "35.2mm",
"wind_speed": "15.3 km/h",
"rain_probability": "85%"
}
}
```
## Configuration
### Environment Variables
#### Required
- `OPENAI_API_KEY`: OpenAI API key for AI features
#### Optional
- `TOMORROW_IO_API_KEY`: Tomorrow.io weather API
- `GOOGLE_WEATHER_API_KEY`: Google Weather API
- `OPENWEATHERMAP_API_KEY`: OpenWeatherMap API
- `ACCUWEATHER_API_KEY`: AccuWeather API
- `LOG_LEVEL`: Logging level (DEBUG, INFO, WARNING, ERROR)
### CORS Configuration
```python
app.add_middleware(
CORSMiddleware,
allow_origins=["https://mcp-ui.vercel.app", "*"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["*"]
)
```
### Bihar Districts Configuration
The system supports 39 Bihar districts:
- Patna, Gaya, Bhagalpur, Muzaffarpur, Darbhanga
- Siwan, Begusarai, Katihar, Nalanda, Rohtas
- And 29 others...
## Deployment
### Local Development
```bash
python main.py
```
- FastAPI server: http://localhost:8000
- Gradio interface: http://localhost:7860
### Production Deployment
#### Docker Deployment
```dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000 7860
CMD ["python", "main.py"]
```
#### HuggingFace Spaces
The application automatically detects HuggingFace Spaces environment and configures accordingly:
```python
if os.getenv("SPACE_ID") or os.getenv("GRADIO_SERVER_NAME"):
# HuggingFace Spaces mode
fastapi_thread = threading.Thread(target=run_fastapi, daemon=True)
fastapi_thread.start()
demo.launch(server_name="0.0.0.0", server_port=7860)
```
## Troubleshooting
### Common Issues
#### 1. OpenAI API Key Missing
- **Error**: `OpenAI API key not found - AI features will be limited`
- **Solution**: Add `OPENAI_API_KEY` to `.env` file
#### 2. Weather API Failures
- **Error**: `Failed to get weather data`
- **Solutions**:
- Check internet connectivity
- Verify API keys in `.env`
- Check API quotas and limits
#### 3. Geographic Data Issues
- **Error**: `District 'xyz' not found in Bihar`
- **Solutions**:
- Use correct district spelling
- Check district name in `BIHAR_DISTRICTS` list
- Verify state parameter is "bihar"
#### 4. Import Errors
- **Error**: `ModuleNotFoundError: No module named 'tools'`
- **Solution**: Ensure all required modules are in the project directory:
- `tools/`
- `a2a_agents/`
- `utils/`
### Logging and Debugging
#### Enable Debug Logging
```bash
export LOG_LEVEL=DEBUG
python main.py
```
#### Check Log Output
```python
logger.info(f"Selected village: {village}")
logger.error(f"Weather API error: {error}")
```
### Performance Optimization
#### 1. API Response Caching
Consider implementing Redis caching for weather data:
```python
# Pseudo-code
@cache.cached(timeout=300) # 5 minute cache
async def get_weather_data(lat, lon):
return await weather_api.fetch(lat, lon)
```
#### 2. Database Integration
For production, consider using PostgreSQL/MongoDB:
```python
# Store alert history
await db.alerts.insert_one(alert_data)
```
## Contributing
### Development Guidelines
#### 1. Code Style
- Follow PEP 8 Python style guide
- Use type hints for function parameters
- Add docstrings for all functions
- Maximum line length: 100 characters
#### 2. Testing
```python
import pytest
def test_crop_selection():
crop = select_regional_crop("patna", "bihar")
assert crop in ["rice", "wheat", "potato"]
async def test_weather_api():
result = await open_meteo.get_current_weather(25.5941, 85.1376)
assert "temperature" in result
```
#### 3. Documentation
- Update this documentation for new features
- Add inline comments for complex logic
- Create examples for new API endpoints
#### 4. Version Control
```bash
git checkout -b feature/new-weather-provider
git commit -m "Add new weather API integration"
git push origin feature/new-weather-provider
```
### Adding New Features
#### 1. New Weather Provider
```python
# tools/new_weather_api.py
async def get_current_weather(latitude, longitude, api_key):
# Implementation
return weather_data
```
#### 2. New Communication Channel
```python
# a2a_agents/slack_agent.py
def create_slack_message(alert_data):
return {
"text": message,
"attachments": []
}
```
#### 3. New Crop Types
```python
CROP_CALENDAR["new_crop"] = {
"season": "Rabi",
"planting": "December",
"harvesting": "May",
"duration_days": 150,
"stages": ["Sowing", "Growth", "Harvest"]
}
```
---
**Last Updated**: August 13, 2025 |