File size: 4,473 Bytes
6afc01a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 🌾 Alert Summary Prototype Backend

**Multi-stage MCP Pipeline for Agricultural Intelligence**

---

## 🎯 Overview

Farmer.Chat uses a **4-stage pipeline** to process agricultural queries:

```
Query β†’ Router β†’ Executor (Parallel) β†’ Compiler β†’ Translator β†’ Advice
```

### Architecture

1. **Stage 1: Query Router** - Analyzes farmer's question and selects relevant MCP servers
2. **Stage 2: MCP Executor** - Calls multiple APIs in parallel (weather, soil, water, elevation, pests)
3. **Stage 3: Response Compiler** - Merges data from all sources
4. **Stage 4: Farmer Translator** - Converts technical data to actionable farmer advice

---

## πŸ”Œ API Endpoints

### `POST /api/query`
Process a farmer's question

**Request:**
```json
{
  "query": "Should I plant rice today?",
  "location": {
    "name": "Bangalore",
    "lat": 12.8716,
    "lon": 77.4946
  }
}
```

**Response:**
```json
{
  "success": true,
  "query": "Should I plant rice today?",
  "advice": "...",
  "routing": {...},
  "data": {...},
  "execution_time_seconds": 3.5
}
```

### `POST /api/export-pdf`
Export query result as PDF

**Request:** Same as `/api/query`

**Response:** PDF file download

### `GET /api/health`
Health check

### `GET /api/servers`
List available MCP servers

---

## πŸ› οΈ MCP Servers

| Server | Data Source | Information |
|--------|-------------|-------------|
| **weather** | Open-Meteo | Current weather, 7-day forecasts |
| **soil_properties** | SoilGrids | Clay, sand, pH, nutrients |
| **water** | GRACE Satellite | Groundwater levels, drought status |
| **elevation** | OpenElevation | Field elevation, terrain data |
| **pests** | iNaturalist | Recent pest observations |

---

## πŸš€ Deployment Instructions

### 1. Create Hugging Face Space

1. Go to https://huggingface.co/new-space
2. Space name: `farmer-chat-backend`
3. Owner: `aakashdg`
4. SDK: **Gradio** (we'll use FastAPI inside)
5. Set to **Public**

### 2. Upload Files

Upload all files maintaining this structure:
```
farmer-chat-backend/
β”œβ”€β”€ app.py
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ README.md
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ pipeline.py
β”‚   β”œβ”€β”€ router.py
β”‚   β”œβ”€β”€ executor.py
β”‚   β”œβ”€β”€ compiler.py
β”‚   β”œβ”€β”€ translator.py
β”‚   β”œβ”€β”€ pdf_generator.py
β”‚   └── servers/
β”‚       β”œβ”€β”€ __init__.py
β”‚       └── (all server classes in one file or separate)
```

### 3. Set Environment Variables

In Space Settings β†’ Variables and secrets:
- Add secret: `OPENAI_API_KEY` = your OpenAI API key

### 4. Deploy!

Space will auto-deploy. Access at:
```
https://huggingface.co/spaces/aakashdg/farmer-chat-backend
```

---

## πŸ§ͺ Testing

### Test with cURL:

```bash
curl -X POST https://huggingface.co/spaces/aakashdg/farmer-chat-backend/api/query \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What is the soil composition?",
    "location": {"name": "Bangalore", "lat": 12.8716, "lon": 77.4946}
  }'
```

### Test with Python:

```python
import requests

response = requests.post(
    "https://huggingface.co/spaces/aakashdg/farmer-chat-backend/api/query",
    json={
        "query": "Will it rain this week?",
        "location": {"name": "Bangalore", "lat": 12.8716, "lon": 77.4946}
    }
)

print(response.json())
```

---

## πŸ“Š Performance

- **Parallel execution**: All MCP servers called simultaneously
- **Typical response time**: 3-5 seconds
- **Success rate**: ~95% (graceful degradation if servers fail)

---

## πŸ” Security

- OpenAI API key stored as HF Space secret
- CORS enabled for frontend integration
- Rate limiting: 100 queries/hour per IP (configurable)

---

## πŸ“ˆ Scaling

To add more MCP servers:

1. Create new server class in `src/servers/`
2. Add to `MCP_SERVER_REGISTRY` in `executor.py`
3. Router will automatically include it in routing decisions

---

## πŸ› Troubleshooting

### "OPENAI_API_KEY not set"
- Check HF Space Settings β†’ Variables and secrets
- Ensure secret name is exactly `OPENAI_API_KEY`

### Slow responses
- Normal for first query (cold start)
- Subsequent queries faster due to caching

### Server failures
- System uses graceful degradation
- If one server fails, others still provide data
- Check `failed_servers` in response

---

## πŸ“ž Support

- GitHub Issues: [Link to repo]
- Creator: @aakashdg
- Built for: Farmer.chat product demo

---

## πŸ“„ License

MIT License

---

**Built with ❀️ for farmers**