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