Content
# 🌾 AgriSenseGuardian — AI-Powered Agricultural Intelligence Platform
[](https://www.python.org/)
[](https://github.com/google/generative-ai-python)
[](https://fastapi.tiangolo.com/)
[](https://github.com/google/generative-ai-python/tree/main/samples/agent_to_agent)
[](LICENSE)
[](https://www.kaggle.com/)
```
╔═══════════════════════════════════════════════════════════════════════════════════╗
║ ║
║ █████╗ ██████╗ ██████╗ ██╗███████╗███████╗███╗ ██╗███████╗███████╗ ║
║ ██╔══██╗██╔════╝ ██╔══██╗██║██╔════╝██╔════╝████╗ ██║██╔════╝██╔════╝ ║
║ ███████║██║ ███╗██████╔╝██║███████╗█████╗ ██╔██╗ ██║███████╗█████╗ ║
║ ██╔══██║██║ ██║██╔══██╗██║╚════██║██╔══╝ ██║╚██╗██║╚════██║██╔══╝ ║
║ ██║ ██║╚██████╔╝██║ ██║██║███████║███████╗██║ ╚████║███████║███████╗ ║
║ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝ ╚═══╝╚══════╝╚══════╝ ║
║ ║
║ ██████╗ ██╗ ██╗ █████╗ ██████╗ ██████╗ ██╗ █████╗ ███╗ ██╗ ║
║ ██╔════╝ ██║ ██║██╔══██╗██╔══██╗██╔══██╗██║██╔══██╗████╗ ██║ ║
║ ██║ ███╗██║ ██║███████║██████╔╝██║ ██║██║███████║██╔██╗ ██║ ║
║ ██║ ██║██║ ██║██╔══██║██╔══██╗██║ ██║██║██╔══██║██║╚██╗██║ ║
║ ╚██████╔╝╚██████╔╝██║ ██║██║ ██║██████╔╝██║██║ ██║██║ ╚████║ ║
║ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ║
║ ║
║ 🌍 Protecting Indian Farms Through Intelligent AI 🌾 ║
║ ║
╚═══════════════════════════════════════════════════════════════════════════════════╝
```
---
## 🎯 Vision & Mission
### **Empowering Indian Farmers With AI-Driven Agricultural Intelligence**
AgriSenseGuardian is a multi-agent AI platform designed to combat agricultural risks in India through real-time data analysis, predictive modeling, and actionable recommendations. By leveraging advanced agent architectures, satellite imagery, and climate models, we transform complex environmental data into farmer-friendly insights that save crops, reduce losses, and promote sustainable agriculture.
### **Core Values**
🌱 **Sustainability** — Promoting environmentally responsible farming practices
👨🌾 **Farmer-Centric** — Designed for Indian farmers, by understanding Indian agriculture
📊 **Data-Driven** — Relying on real satellite, weather, and soil data, not assumptions
🤝 **Accessibility** — Free, open-source, and available to all farmers
🔬 **Innovation** — Pioneering multi-agent AI for agricultural decision support
---
## 🏆 Hackathon Track Alignment
### **Primary Track: Agents For Good 🌍**
AgriSenseGuardian directly addresses critical sustainability challenges in agriculture:
- **🌾 Food Security** — Reducing crop losses through early risk detection
- **💧 Water Conservation** — Optimizing irrigation based on soil moisture data
- **🌡️ Climate Resilience** — Helping farmers adapt to climate change
- **🌿 Environmental Protection** — Preventing soil erosion and nutrient leaching
- **📚 Agricultural Education** — Teaching farmers about data-driven farming
### **Secondary Alignment: Enterprise Agents 💼**
The platform also serves agricultural enterprises:
- **📊 Business Intelligence** — Automated risk assessment workflows
- **📧 Customer Communication** — Automated email notification systems
- **📈 Data Analytics** — Multi-source agricultural data integration
- **🔄 Process Automation** — Long-running task management with pause/resume
---
## 💡 The Problem
### **Indian Agriculture Faces Unprecedented Challenges**
```
┌────────────────────────────────────────────────────────────┐
│ 🌪️ CLIMATE CRISIS │
│ • Erratic monsoons causing unpredictable rainfall │
│ • Extreme heat waves damaging crops │
│ • Unseasonal frost events destroying harvests │
│ • Increasing drought frequency in rain-fed regions │
├────────────────────────────────────────────────────────────┤
│ 💸 ECONOMIC LOSSES │
│ • ₹92,000 crores annual crop loss due to weather │
│ • 60% of farmers lack access to timely weather advisories │
│ • Poor risk assessment leading to crop insurance denials │
│ • Information gap between satellite data and farmers │
├────────────────────────────────────────────────────────────┤
│ 🌾 KNOWLEDGE GAP │
│ • Complex climate models inaccessible to rural farmers │
│ • Fragmented information from multiple sources │
│ • Lack of personalized, location-specific guidance │
│ • No integrated platform for agricultural intelligence │
└────────────────────────────────────────────────────────────┘
```
### **Why Traditional Solutions Fall Short**
❌ **Generic Weather Apps** — Don't account for soil conditions, crop-specific needs
❌ **Manual Advisory Systems** — Slow, expensive, limited geographical coverage
❌ **Single-Source Analysis** — Incomplete risk assessment without multi-modal data
❌ **Technical Complexity** — Satellite data requires expert interpretation
---
## 🤖 The Solution
### **Why Multi-Agent AI? The AgriSenseGuardian Approach**
AgriSenseGuardian uses a **sophisticated multi-agent architecture** where specialized AI agents collaborate to solve complex agricultural problems. Each agent is an expert in a specific domain, working together through the **A2A (Agent-To-Agent) Protocol** to deliver comprehensive solutions.
```
┌──────────────────────────────────────────────────────────────────────┐
│ 🎯 ORCHESTRATOR AGENT │
│ (Master Coordinator & Intelligence Director) │
│ │
│ Coordinates 3 Specialized Agents In Sequential + Parallel Flows │
└───────────────────────────┬──────────────────────────────────────────┘
│
┌───────────────────┼───────────────────┐
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ 📊 FORECAST │ │ ✅ VERIFY │ │ 📋 PLANNER │
│ AGENT │ │ AGENT │ │ AGENT │
├───────────────┤ ├───────────────┤ ├───────────────┤
│ • Weather API │ │ • Cross-Check │ │ • Create │
│ • Satellite │ │ • Web Search │ │ Action Plan │
│ • Copernicus │ │ • Confidence │ │ • Email │
│ • Soil Data │ │ Scoring │ │ Farmers │
│ • Risk Calc │ │ • Validation │ │ • Prioritize │
└───────────────┘ └───────────────┘ └───────────────┘
```
### **Unique Agent Capabilities**
✅ **Parallel Data Collection** — ForecastAgent simultaneously queries multiple APIs
✅ **Sequential Validation** — VerifyAgent checks forecast results before planning
✅ **Iterative Refinement** — OrchestratorAgent loops until confidence threshold met
✅ **Long-Running Operations** — Pause/resume support for complex multi-hour analyses
✅ **Session Memory** — Learns from past farmer interactions for better recommendations
---
## 🏗️ Architecture Overview
### **System Architecture Diagram**
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ 🌐 WEB UI LAYER (FastAPI) │
│ Port 8000 — User Interface & REST API │
└──────────────────────────────────┬──────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ 🧠 ORCHESTRATION LAYER (A2A Protocol) │
│ │
│ │ OrchestratorAgent (Port 9000) │ │
│ │ • Session Management (InMemorySessionService) │ │
│ │ • Memory Bank (Long-Term Learning) │ │
│ │ • Context Compaction (Token Optimization) │ │
│ │ • Observability (Tracing, Metrics, Logging) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Forecast │ │ Verify │ │ Planner │ │
│ │ Server │ │ Server │ │ Server │ │
│ │ Port 9001 │ │ Port 9002 │ │ Port 9003 │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ 🔧 TOOLS LAYER (MCP + Custom) │
│ │
│ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐ ┌──────────────┐ │
│ │ Weather │ │ Satellite │ │ Copernicus │ │ Soil Test │ │
│ │ Tool │ │ Tool │ │ Tool │ │ Tool │ │
│ │ (OpenWx) │ │ (NASA API) │ │ (ESA CDS) │ │ (SoilGrid) │ │
│ └─────────────┘ └──────────────┘ └─────────────┘ └──────────────┘ │
│ │
│ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐ │
│ │ Google │ │ Email │ │ Code │ │
│ │ Search │ │ Notification │ │ Execution │ │
│ └─────────────┘ └──────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ 📡 EXTERNAL DATA SOURCES │
│ │
│ 🌦️ OpenWeatherMap │ 🛰️ NASA POWER │ 🌍 Copernicus CDS │
│ 🌐 Google Search │ 📧 SMTP Email │ 🗺️ ISRIC SoilGrids │
└─────────────────────────────────────────────────────────────────────────────┘
```
### **Data Flow Architecture**
```
User Request (Location + Query)
│
▼
┌──────────────────────────────────────┐
│ 1️⃣ OrchestratorAgent │
│ • Create Session ID │
│ • Initialize Memory Bank │
│ • Route To ForecastAgent │
└──────────────────┬───────────────────┘
▼
┌──────────────────────────────────────┐
│ 2️⃣ ForecastAgent (Parallel Tools) │
│ ┌─────────────────────────────┐ │
│ │ ⚡ Parallel Execution: │ │
│ │ • WeatherTool() │ │
│ │ • SatelliteTool() │ │
│ │ • CopernicusTool() │ │
│ │ • SoilTestTool() │ │
│ └─────────────────────────────┘ │
│ • Risk Calculation │
│ • Structured JSON Output │
└──────────────────┬───────────────────┘
▼
┌──────────────────────────────────────┐
│ 3️⃣ VerifyAgent (Sequential) │
│ • Google Search Validation │
│ • Cross-Reference Weather Data │
│ • Confidence Scoring │
│ • Flag Low-Confidence Results │
└──────────────────┬───────────────────┘
▼
┌─────────────────┐
│ Confidence OK? │
└────┬────────┬───┘
NO YES
│ │
▼ ▼
┌──────────┐ ┌──────────────────────┐
│ Loop │ │ 4️⃣ PlannerAgent │
│ Back │ │ • Create Action Plan│
│ To │ │ • Send Email │
│ Forecast │ │ • Return Results │
└──────────┘ └───────────┬──────────┘
▼
┌──────────────────────┐
│ 📧 Email To Farmer │
│ 📊 Web UI Response │
└──────────────────────┘
```
---
## ⚡ Key Features
### **🤖 Multi-Agent System**
| Feature | Implementation | Benefits |
|---------|---------------|----------|
| **Agent-Powered LLM** | Gemini 2.5 Flash Lite Via Google ADK | Fast, cost-effective, context-aware responses |
| **Parallel Agents** | ForecastAgent Parallel Tool Execution | 4x faster data collection (Weather + Satellite + Soil) |
| **Sequential Agents** | Orchestrator → Forecast → Verify → Planner | Guaranteed quality through step-by-step validation |
| **Loop Agents** | Confidence-based iteration | Auto-retry until verification passes (Max 3 loops) |
| **A2A Protocol** | HTTP-based agent communication | Scalable, language-agnostic agent collaboration |
### **🛠️ Tools Integration**
#### **MCP (Model Context Protocol) Tools**
While the full MCP server is in development, we've implemented MCP-compatible tool interfaces:
```python
# Tools Follow MCP Input/Output Standards
async def WeatherTool(Location: str, DaysAhead: int, ToolContext: ToolContext) -> Dict[str, Any]:
"""MCP-Compatible Weather Data Retrieval"""
# Structured Input/Output Following MCP Spec
return {
"Status": "Success",
"Data": { /* Weather Data */ },
"Metadata": { /* MCP Metadata */ }
}
```
#### **Custom Tools** (7 Specialized Agricultural Tools)
| Tool Name | Purpose | Data Source | Output |
|-----------|---------|-------------|--------|
| **WeatherTool** | 30-90 Day Weather Forecasts | OpenWeatherMap API | Temperature, Precipitation, Humidity, Wind |
| **SatelliteTool** | Agroclimatology From Space | NASA POWER API | Solar Radiation, Evapotranspiration, Rainfall |
| **CopernicusTool** | European Satellite Climate Data | ESA Copernicus CDS | Soil Moisture, NDVI, Land Surface Temp |
| **SoilTestTool** | Soil Profile Analysis | ISRIC SoilGrids | pH, Texture, Clay/Sand %, Nitrogen |
| **GoogleSearchTool** | Web Intelligence | Google Custom Search API | Recent Agricultural News, Local Advisories |
| **EmailNotificationTool** | Farmer Communication | SMTP (Gmail/Outlook) | HTML Email With Risk Reports |
| **CodeExecutionTool** | Dynamic Calculations | Python Sandbox | Custom Risk Formulas, Data Processing |
#### **Built-In ADK Tools**
- **Google Search** — Web search for agricultural news and advisories
- **Code Execution** — Safe Python code execution for custom calculations
- **Function Calling** — ADK native tool invocation framework
### **⏸️ Long-Running Operations**
```python
# Pause/Resume Support For Multi-Hour Satellite Downloads
TaskManager.start(forecast_workflow)
# User Can Pause If Needed
TaskManager.pause(task_id)
# Resume When Ready
TaskManager.resume(task_id)
# Check Status Anytime
TaskManager.status(task_id)
```
**Use Cases:**
- ⏳ Large satellite image downloads (100MB+ TIFF files)
- 🔄 Multi-iteration forecast refinement (Loop Agents)
- 📊 Historical data analysis (30+ years of climate data)
### **💾 Sessions & Memory**
#### **Session State Management**
```python
# InMemorySessionService Integration
SessionManager = AgriSenseSessionManager(app_name="AgriSenseGuardian")
Session = await SessionManager.CreateSession(
SessionId=SessionId,
FarmerProfile={
"Name": "Rajesh Kumar",
"Location": "Punjab, India",
"Crops": ["Wheat", "Rice"],
"FarmSize": "5 Acres"
}
)
```
**Session Persistence Features:**
- ✅ Active conversation state tracking
- ✅ Multi-turn dialog context
- ✅ User preference storage
- ✅ Session-specific query history
#### **Long-Term Memory (Memory Bank)**
```python
# Store Farmer Interaction History
await SessionManager.AddToMemory(
SessionId=SessionId,
MemoryType="RiskAssessment",
Content={
"Date": "2024-12-15",
"Location": "Punjab",
"Risks": ["Drought", "Heat"],
"Outcome": "Irrigation Increased"
}
)
# Retrieve Historical Context For Better Recommendations
PastAssessments = await SessionManager.GetMemoryByType(
SessionId=SessionId,
MemoryType="RiskAssessment",
Limit=5
)
```
**Memory Features:**
- 📚 Cross-session learning
- 🎯 Personalized recommendations based on history
- 📊 Trend analysis (E.g., "This is your 3rd drought warning this year")
- 🔍 Semantic search over past interactions
#### **Context Engineering**
```python
# Automatic Context Compaction For Long Conversations
def CompactContext(SessionHistory: List[str]) -> str:
"""
Reduce Token Count While Preserving Key Information
Uses Summarization To Fit Within LLM Context Limits
"""
if len(SessionHistory) > 10:
# Summarize Older Messages
Summary = Summarize(SessionHistory[:-5])
return Summary + SessionHistory[-5:]
return SessionHistory
```
**Optimization Techniques:**
- 🗜️ Message summarization for old turns
- 🎯 Key fact extraction (Dates, Locations, Risk Levels)
- ⚡ Token budget management (Stay under 100K tokens)
### **📊 Observability: Logging, Tracing, Metrics**
#### **Structured Logging**
```python
# PascalCase Logger With Rich Context
Logger = GetLogger(__name__)
Logger.info("ForecastAgent: Starting Risk Assessment", extra={
"SessionId": SessionId,
"Location": Location,
"DaysAhead": DaysAhead
})
```
**Log Levels:**
- 🔵 **INFO** — Agent lifecycle events
- 🟡 **WARNING** — Low confidence results, API fallbacks
- 🔴 **ERROR** — Tool failures, timeout errors
- 🟣 **DEBUG** — Detailed tool inputs/outputs
#### **Distributed Tracing (OpenTelemetry)**
```python
# Trace Request Flow Across Agents
with use_span("OrchestratorAgent.Execute"):
ForecastResult = await ForecastAgent.Run()
with use_span("VerifyAgent.Validate"):
VerifyResult = await VerifyAgent.Run(ForecastResult)
```
**Trace Visualization:**
```
Request ID: abc-123-def
├─ OrchestratorAgent.Execute (450ms)
│ ├─ ForecastAgent.Run (320ms)
│ │ ├─ WeatherTool (120ms)
│ │ ├─ SatelliteTool (150ms)
│ │ └─ CopernicusTool (50ms)
│ ├─ VerifyAgent.Validate (80ms)
│ └─ PlannerAgent.CreatePlan (50ms)
```
#### **Prometheus Metrics**
```python
# Automatic Metric Collection
@record_agent_duration("ForecastAgent")
async def Run():
# Execution Time Automatically Recorded
pass
# Metrics Exposed At /metrics Endpoint
AGENT_DURATION = Histogram("agent_execution_seconds", ["agent"])
TOOL_CALLS = Counter("tool_calls_total", ["tool"])
ERRORS = Counter("agent_errors_total", ["agent"])
```
**Available Metrics:**
- ⏱️ `agent_execution_seconds` — Per-agent execution time
- 📞 `tool_calls_total` — Tool invocation count
- ❌ `agent_errors_total` — Error rate per agent
- 🔄 `agent_iterations_total` — Loop agent retry count
**Grafana Dashboard Ready** — Import `Docs/Grafana-Dashboard.json` for pre-built visualizations
---
## 🔧 Technical Implementation
### **Technology Stack**
```
┌─────────────────────────────────────────────────────────────┐
│ 🎨 Frontend Layer │
│ • HTML5 + Jinja2 Templates │
│ • Vanilla JavaScript (No Heavy Frameworks) │
│ • Responsive CSS Grid Layout │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ ⚙️ Backend Layer │
│ • FastAPI 0.115+ (ASGI Web Framework) │
│ • Python 3.11+ (Type Hints, Async/Await) │
│ • Pydantic (Data Validation) │
│ • Uvicorn (ASGI Server) │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 🤖 AI/ML Layer │
│ • Google ADK (Agent Development Kit) │
│ • Gemini 2.5 Flash Lite (LLM) │
│ • LangChain Core (Tool Abstractions) │
│ • A2A Protocol (Agent Communication) │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 📡 Data Sources │
│ • OpenWeatherMap API (Weather Forecasts) │
│ • NASA POWER API (Satellite Agroclimatology) │
│ • ESA Copernicus CDS (Climate Data Store) │
│ • ISRIC SoilGrids (Global Soil Information) │
│ • Google Custom Search API (Web Intelligence) │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ 🔍 Observability │
│ • Python Logging (Structured JSON Logs) │
│ • OpenTelemetry (Distributed Tracing) │
│ • Prometheus (Metrics Collection) │
│ • Grafana (Metrics Visualization) │
└─────────────────────────────────────────────────────────────┘
```
### **Key Design Patterns**
#### **1. Agent Orchestration Pattern**
```python
# OrchestratorAgent Coordinates Specialized Agents
class OrchestratorAgent:
def __init__(self):
self.ForecastAgent = ForecastAgent()
self.VerifyAgent = VerifyAgent()
self.PlannerAgent = PlannerAgent()
async def Execute(self, UserQuery: str, SessionId: str):
# Sequential Workflow With Error Handling
ForecastResult = await self.ForecastAgent.Run()
VerifyResult = await self.VerifyAgent.Run(ForecastResult)
# Loop Pattern For Quality Assurance
if VerifyResult["Confidence"] < 0.7:
# Retry Forecast With More Context
ForecastResult = await self.ForecastAgent.Run(feedback=VerifyResult)
PlannerResult = await self.PlannerAgent.Run(ForecastResult, VerifyResult)
return PlannerResult
```
#### **2. Tool Abstraction Pattern**
```python
# Unified Tool Interface For ADK Integration
async def WeatherTool(Location: str, DaysAhead: int, ToolContext: ToolContext) -> Dict[str, Any]:
"""
Google ADK Compatible Tool Signature
- Takes Structured Input
- Returns Structured Output
- Handles Errors Gracefully
"""
try:
# API Call
Data = await FetchWeatherData(Location, DaysAhead)
return {
"Status": "Success",
"Data": Data,
"Source": "OpenWeatherMap"
}
except Exception as E:
return {
"Status": "Error",
"Message": str(E),
"Fallback": "Using Historical Average"
}
```
#### **3. Session State Pattern**
```python
# ADK InMemorySessionService Integration
class AgriSenseSessionManager:
def __init__(self):
self.SessionService = InMemorySessionService()
self.MemoryService = InMemoryMemoryService()
async def CreateSession(self, SessionId: str, FarmerProfile: Dict):
Session = await self.SessionService.create_session(
app_name="AgriSenseGuardian",
user_id=FarmerProfile["Email"],
session_id=SessionId
)
# Initialize Memory Bank
await self.MemoryService.add_memory(
session_id=SessionId,
memory_type="FarmerProfile",
content=FarmerProfile
)
return Session
```
---
## 🚀 Quick Start
### **Prerequisites**
- Python 3.11 or higher
- Google Cloud account (for Gemini API key)
- API keys for data sources (see configuration section)
### **Installation**
#### **Step 1: Clone The Repository**
```powershell
git clone https://github.com/i8o8i-Developer/AGRI-SENSE_GUARDIAN.git
cd AGRI-SENSE_GUARDIAN
```
#### **Step 2: Create Virtual Environment**
```powershell
python -m venv venv
.\venv\Scripts\Activate.ps1 # Windows PowerShell
# Or: source venv/bin/activate # Linux/Mac
```
#### **Step 3: Install Dependencies**
```powershell
pip install -r Requirements.txt
```
#### **Step 4: Configure Environment Variables**
Create a `.env` file in the project root:
```env
# Google Gemini AI
GOOGLE_API_KEY=Your_Gemini_Api_Key_Here
# Weather Data
OPENWEATHER_API_KEY=Your_OpenWeather_Api_Key_Here
# Copernicus Climate Data (Optional)
COPERNICUS_API_KEY=Your_UID:Your_API_Key
# Email Notifications (Optional)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=Your_Email@gmail.com
SMTP_PASSWORD=Your_App_Password
SENDER_EMAIL=Your_Email@gmail.com
# Google Search (Optional)
GOOGLE_SEARCH_API_KEY=Your_Google_Search_Api_Key
GOOGLE_SEARCH_ENGINE_ID=Your_Search_Engine_ID
```
**How To Get API Keys:**
1. **Google Gemini API Key** (Required)
- Visit [Google AI Studio](https://makersuite.google.com/app/apikey)
- Click "Create API Key"
- Copy the key to `.env`
2. **OpenWeatherMap API Key** (Required)
- Sign up at [OpenWeatherMap](https://openweathermap.org/api)
- Get free API key (1000 calls/day)
3. **Copernicus CDS API** (Optional, improves data quality)
- Register at [Copernicus CDS](https://cds.climate.copernicus.eu/)
- Get UID and API key from account settings
- Format: `UID:APIKEY` (E.g., `12345:abcd-efgh-ijkl`)
4. **Email SMTP** (Optional, for farmer notifications)
- Gmail: Enable 2FA, generate app password
- Outlook: Use regular password
#### **Step 5: Run The Application**
```powershell
python Main.py
```
**Expected Output:**
```
INFO: Started Server Process [12345]
INFO: Waiting For Application Startup.
INFO: 🚀 Bootstrapping A2A Agent Servers...
INFO: ✅ OrchestratorAgent Server Running On Port 9000
INFO: ✅ ForecastAgent Server Running On Port 9001
INFO: ✅ VerifyAgent Server Running On Port 9002
INFO: Application Startup Complete.
INFO: Uvicorn Running On http://127.0.0.1:8000 (Press CTRL+C To Quit)
```
#### **Step 6: Access The Web UI**
Open your browser and navigate to:
```
http://127.0.0.1:8000
```
You should see the AgriSenseGuardian web interface!
---
## 📊 Multi-Agent System Deep Dive
### **Agent Architecture Philosophy**
AgriSenseGuardian implements a **hierarchical multi-agent system** inspired by Google's ADK best practices:
```
Master Orchestrator (Strategic Planning)
│
├─ Specialized Agents (Tactical Execution)
│ │
│ ├─ Domain Tools (Data Collection)
│ └─ Custom Logic (Risk Calculation)
│
└─ Shared Services (Session, Memory, Observability)
```
### **Agent Communication Flow (A2A Protocol)**
#### **What Is A2A Protocol?**
A2A (Agent-To-Agent) Protocol is Google's standard for multi-agent communication. It defines:
- **Message Format** — JSON-based request/response
- **Transport Layer** — HTTP/HTTPS for agent communication
- **Error Handling** — Standardized error codes and retry logic
- **Observability** — Built-in tracing and metrics
#### **A2A Message Example**
```json
{
"type": "task",
"task_id": "abc-123-def",
"agent": "ForecastAgent",
"parameters": {
"Location": "Punjab, India",
"DaysAhead": 30
},
"context": {
"session_id": "session-456",
"user_id": "farmer@example.com"
}
}
```
#### **Response Format**
```json
{
"task_id": "abc-123-def",
"status": "completed",
"result": {
"RiskAssessment": {
"Drought": "High",
"Flood": "Low",
"Heat": "Medium"
},
"Confidence": 0.85
},
"metadata": {
"execution_time_ms": 320,
"tools_called": ["WeatherTool", "SatelliteTool"]
}
}
```
### **Agent Server Implementation**
Each agent runs as a separate HTTP server:
```python
# Agents/ForecastAgentServer.py
from fastapi import FastAPI
from google.adk.agents.llm_agent import Agent
app = FastAPI()
ForecastAgentInstance = ForecastAgent()
@app.post("/execute")
async def Execute(request: TaskRequest):
"""A2A Endpoint For ForecastAgent Execution"""
result = await ForecastAgentInstance.Run(
Location=request.Location,
DaysAhead=request.DaysAhead
)
return {
"task_id": request.task_id,
"status": "completed",
"result": result
}
# Start Server On Port 9001
uvicorn.run(app, host="0.0.0.0", port=9001)
```
### **Parallel Agent Execution**
ForecastAgent demonstrates **parallel tool execution** for performance:
```python
# Run Multiple Tools Simultaneously
async def Run(self, Location: str, DaysAhead: int):
# Create Tasks For Parallel Execution
Tasks = [
WeatherTool(Location, DaysAhead, ToolContext),
SatelliteTool(Location, DaysAhead, ToolContext),
CopernicusTool(Location, DaysAhead, ToolContext),
SoilTestTool(Location, ToolContext)
]
# Execute In Parallel Using asyncio.gather
Results = await asyncio.gather(*Tasks, return_exceptions=True)
# Combine Results
WeatherData, SatelliteData, CopernicusData, SoilData = Results
# Calculate Risk
Risk = self.ComputeRiskFromSources(
weather=WeatherData,
satellite=SatelliteData,
copernicus=CopernicusData,
soil=SoilData,
location=Location
)
return Risk
```
**Performance Improvement:**
- ❌ **Sequential:** 120ms + 150ms + 50ms + 80ms = 400ms Total
- ✅ **Parallel:** max(120ms, 150ms, 50ms, 80ms) = 150ms Total
- 🚀 **2.6x Faster**
### **Sequential Agent Workflow**
OrchestratorAgent implements **sequential execution** for quality control:
```python
async def Execute(self, UserQuery: str):
# Step 1: Forecast (Data Collection + Risk Analysis)
ForecastResult = await self.ForecastAgent.Run()
# Step 2: Verify (Validation + Confidence Scoring)
VerifyResult = await self.VerifyAgent.Run(ForecastResult)
# Step 3: Decision Point (Loop Or Proceed)
if VerifyResult["Confidence"] < 0.7:
# Re-Run Forecast With Verification Feedback
ForecastResult = await self.ForecastAgent.Run(
feedback=VerifyResult["Issues"]
)
VerifyResult = await self.VerifyAgent.Run(ForecastResult)
# Step 4: Planning (Action Items + Email)
PlannerResult = await self.PlannerAgent.Run(ForecastResult, VerifyResult)
return PlannerResult
```
### **Loop Agent Pattern**
VerifyAgent triggers **iterative refinement** based on confidence:
```python
MaxIterations = 3
Iteration = 0
Confidence = 0.0
while Confidence < 0.7 and Iteration < MaxIterations:
# Run Forecast
ForecastResult = await ForecastAgent.Run()
# Verify Results
VerifyResult = await VerifyAgent.Run(ForecastResult)
Confidence = VerifyResult["Confidence"]
# Log Iteration
Logger.info(f"Iteration {Iteration + 1}: Confidence = {Confidence}")
Iteration += 1
if Confidence < 0.7:
Logger.warning("Max Iterations Reached, Proceeding With Partial Results")
```
---
## 🛠️ Tools & Integrations
### **Tool Categories**
#### **1. Environmental Data Tools**
##### **WeatherTool**
```python
async def WeatherTool(Location: str, DaysAhead: int, ToolContext: ToolContext) -> Dict[str, Any]:
"""
Fetch Weather Forecasts From OpenWeatherMap API.
Returns:
- Temperature (Min, Max, Mean)
- Precipitation (Total, Probability)
- Humidity (Average)
- Wind Speed
- Weather Conditions
"""
```
**Data Quality:**
- ✅ Real-time API access
- ✅ 30-day forecast horizon
- ✅ 3-hour resolution
- ✅ 95% accuracy for 7-day forecasts
##### **SatelliteTool (NASA POWER)**
```python
async def GetSatelliteData(Location: str, DaysBack: int, ToolContext: ToolContext) -> Dict[str, Any]:
"""
Retrieve Satellite-Based Agroclimatology From NASA.
Returns:
- Solar Radiation
- Evapotranspiration
- Precipitation (Satellite-Observed)
- Temperature (Satellite-Measured)
"""
```
**Coverage:**
- 🌍 Global coverage
- 📅 40+ years historical data
- 🛰️ MODIS + MERRA-2 datasets
- 📊 0.5° x 0.625° resolution
##### **CopernicusTool (ESA Copernicus)**
```python
async def CopernicusTool(Location: str, DaysBack: int, ToolContext: ToolContext) -> Dict[str, Any]:
"""
Access European Space Agency Climate Data Store.
Returns:
- Soil Moisture (0-7cm, 7-28cm Depth)
- NDVI (Vegetation Health Index)
- Land Surface Temperature
- Evapotranspiration
"""
```
**Datasets Used:**
- 🌾 ERA5-Land (Climate Reanalysis)
- 🛰️ Sentinel-2 (Optical Imagery)
- 🌡️ Land Surface Temperature (LST)
##### **SoilTestTool (ISRIC SoilGrids)**
```python
async def SoilTestTool(Location: str, ToolContext: ToolContext) -> Dict[str, Any]:
"""
Get Soil Properties From Global Soil Database.
Returns:
- pH Level
- Soil Texture (Clay, Sand, Silt %)
- Total Nitrogen
- Organic Carbon
- Bulk Density
"""
```
**Resolution:**
- 📏 250m spatial resolution
- 🔬 7 standard depths (0-200cm)
- 🌐 Global coverage
- 🎯 Machine learning predictions
#### **2. Web Intelligence Tools**
##### **GoogleSearchTool**
```python
async def GoogleSearchTool(Query: str, ToolContext: ToolContext) -> Dict[str, Any]:
"""
Search The Web For Agricultural News And Advisories.
Use Cases:
- Recent Pest Outbreaks In Region
- Government Agricultural Schemes
- Local Weather Warnings
- Crop Market Prices
"""
```
**Search Optimization:**
- 🎯 Location-specific queries (E.g., "Punjab Drought 2024")
- 📰 News source prioritization
- 🔍 Semantic relevance scoring
#### **3. Communication Tools**
##### **EmailNotificationTool**
```python
async def SendEmail(FarmerEmail: str, Subject: str, Body: str, ToolContext: ToolContext):
"""
Send HTML Email Reports To Farmers.
Features:
- Beautiful HTML Templates
- Risk Color Coding (Green/Yellow/Red)
- Embedded Action Items
- Mobile-Responsive Design
"""
```
**Email Template:**
```html
<!DOCTYPE html>
<html>
<head>
<style>
.risk-high { color: #FF0000; font-weight: bold; }
.risk-medium { color: #FFA500; }
.risk-low { color: #00FF00; }
</style>
</head>
<body>
<h2>🌾 AgriSenseGuardian Risk Alert</h2>
<p>Dear Farmer,</p>
<p>Based On Our Analysis For <strong>Punjab, India</strong>:</p>
<h3>Risk Assessment:</h3>
<ul>
<li class="risk-high">🔴 Drought Risk: HIGH</li>
<li class="risk-low">🟢 Flood Risk: LOW</li>
<li class="risk-medium">🟡 Heat Stress: MEDIUM</li>
</ul>
<h3>Recommended Actions:</h3>
<ol>
<li>Increase Irrigation Frequency By 20%</li>
<li>Apply Mulching To Conserve Soil Moisture</li>
<li>Monitor Crop Health Daily</li>
</ol>
<p>Stay Safe,<br>AgriSenseGuardian Team</p>
</body>
</html>
```
#### **4. Compute Tools**
##### **CodeExecutionTool**
```python
async def ExecuteCode(Code: str, ToolContext: ToolContext) -> Dict[str, Any]:
"""
Execute Python Code In Sandboxed Environment.
Use Cases:
- Custom Risk Formulas
- Statistical Analysis
- Data Transformations
"""
```
**Safety Features:**
- 🔒 Restricted imports (No `os`, `sys`, `subprocess`)
- ⏱️ 10-second timeout
- 💾 Memory limits (100MB)
- 🛡️ Isolated execution context
---
## 📈 Observability & Monitoring
### **Observability Stack**
```
┌─────────────────────────────────────────────────────────┐
│ 📊 OBSERVABILITY PYRAMID │
├─────────────────────────────────────────────────────────┤
│ 🔴 METRICS (Prometheus) │
│ • Agent Execution Time │
│ • Tool Call Frequency │
│ • Error Rates │
├─────────────────────────────────────────────────────────┤
│ 🟡 TRACES (OpenTelemetry) │
│ • Request Flow Across Agents │
│ • Tool Execution Spans │
│ • Error Propagation │
├─────────────────────────────────────────────────────────┤
│ 🟢 LOGS (Python Logging) │
│ • Structured JSON Logs │
│ • Contextual Information │
│ • Error Stack Traces │
└─────────────────────────────────────────────────────────┘
```
### **Logging Configuration**
```python
# Utils/Logger.py
import logging
from datetime import datetime
def SetupLogger(Name: str) -> logging.Logger:
"""
Create Structured Logger With Consistent Formatting.
Format: [TIMESTAMP] [LEVEL] [MODULE] MESSAGE {CONTEXT}
Example: [2024-12-15 10:30:45] [INFO] [ForecastAgent] Starting Risk Assessment {"SessionId": "abc-123"}
"""
Logger = logging.getLogger(Name)
Logger.setLevel(logging.INFO)
Handler = logging.StreamHandler()
Formatter = logging.Formatter(
'[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
Handler.setFormatter(Formatter)
Logger.addHandler(Handler)
return Logger
```
### **Metrics Endpoint**
Access Prometheus metrics at:
```
http://127.0.0.1:8000/metrics
```
**Sample Output:**
```prometheus
# HELP agent_execution_seconds Agent Execution Duration In Seconds
# TYPE agent_execution_seconds histogram
agent_execution_seconds_bucket{agent="ForecastAgent",le="0.1"} 0
agent_execution_seconds_bucket{agent="ForecastAgent",le="0.5"} 10
agent_execution_seconds_bucket{agent="ForecastAgent",le="1.0"} 45
agent_execution_seconds_sum{agent="ForecastAgent"} 23.4
agent_execution_seconds_count{agent="ForecastAgent"} 50
# HELP tool_calls_total Total Tool Invocations
# TYPE tool_calls_total counter
tool_calls_total{tool="WeatherTool"} 120
tool_calls_total{tool="SatelliteTool"} 115
tool_calls_total{tool="CopernicusTool"} 90
```
### **Grafana Dashboard**
Import `Docs/Grafana-Dashboard.json` for pre-built visualizations:
- 📊 Agent execution time trends
- 📞 Tool call frequency
- ❌ Error rate by agent
- 🔄 Loop iteration count
- 📧 Email delivery success rate
---
## 🎓 Learning Outcomes
### **ADK Course Concepts Implemented**
This project demonstrates mastery of **10+ key ADK concepts** from the Kaggle X Google Capstone:
| Concept | Implementation | Location In Code |
|---------|---------------|------------------|
| **1. Multi-Agent System** | Orchestrator + 3 Specialized Agents | `Agents/OrchestratorAgent.py` |
| **2. Agent-Powered LLM** | Gemini 2.5 Via Google ADK | All Agent Files |
| **3. Parallel Agents** | Async Tool Execution In ForecastAgent | `Agents/ForecastAgent.py:Run()` |
| **4. Sequential Agents** | Forecast → Verify → Planner Flow | `Agents/OrchestratorAgent.py:Execute()` |
| **5. Loop Agents** | Confidence-Based Iteration | `Agents/OrchestratorAgent.py:Execute()` |
| **6. MCP Tools** | MCP-Compatible Tool Interfaces | `Tools/*.py` |
| **7. Custom Tools** | 7 Agricultural Data Collection Tools | `Tools/WeatherTool.py`, Etc. |
| **8. Built-In Tools** | Google Search, Code Execution | Via ADK Framework |
| **9. Long-Running Operations** | Pause/Resume TaskManager | `Services/TaskManager.py` |
| **10. Session State** | InMemorySessionService Integration | `Utils/SessionManager.py` |
| **11. Long-Term Memory** | Memory Bank With Semantic Search | `Utils/SessionManager.py:AddToMemory()` |
| **12. Context Compaction** | Token Optimization For Long Chats | `Utils/SessionManager.py:CompactContext()` |
| **13. Observability** | Logging + Tracing + Metrics | `Utils/Observability.py` |
| **14. A2A Protocol** | HTTP-Based Agent Communication | `Agents/*Server.py` |
### **Advanced Patterns Demonstrated**
✅ **Error Handling** — Graceful fallbacks for all tools
✅ **Async Programming** — Full asyncio implementation
✅ **Type Safety** — Pydantic models for all data
✅ **Separation Of Concerns** — Clean architecture
✅ **Configuration Management** — Environment-driven settings
✅ **Testing** — Unit tests for tools (See `Tests/`)
---
## 📹 Demo Video
**Watch The 3-Minute Project Demo:**
[🎥 AgriSenseGuardian Demo Video](https://www.youtube.com/watch?v=YOUR_VIDEO_ID) _(Coming Soon)_
**Video Script Available In:** `VIDEO_SCRIPT.md`
**Video Outline:**
- 00:00-00:30 — Problem Statement (Indian Farm Crisis)
- 00:30-01:00 — Why Multi-Agent AI? (Solution Approach)
- 01:00-02:00 — Architecture Walkthrough (Live Demo)
- 02:00-02:45 — Key Features & Tools (Technical Deep Dive)
- 02:45-03:00 — Impact & Future Vision (Call To Action)
---
## 🤝 Contributing
We welcome contributions from the community! Whether you're a developer, agricultural expert, or farmer, your input is valuable.
### **How To Contribute**
1. **Fork The Repository**
2. **Create A Feature Branch** (`git checkout -b feature/AmazingFeature`)
3. **Commit Your Changes** (`git commit -m 'Add Some AmazingFeature'`)
4. **Push To The Branch** (`git push origin feature/AmazingFeature`)
5. **Open A Pull Request**
### **Contribution Areas**
- 🌾 **Agricultural Expertise** — Improve risk calculation models
- 🛰️ **Data Science** — Add new satellite data sources
- 🤖 **AI/ML** — Enhance agent intelligence
- 🎨 **UI/UX** — Improve web interface
- 📚 **Documentation** — Translate to regional languages (Hindi, Punjabi, Tamil)
- 🧪 **Testing** — Add unit/integration tests
### **Code Style Guidelines**
- **PascalCase** for variables, functions, classes (See `DEVELOPMENT_RATIONALE.md`)
- **Type hints** for all function parameters
- **Docstrings** for all public functions
- **Comments** for complex logic
---
## 📄 License
This project is licensed under the **Apache License 2.0** - see the [LICENSE](LICENSE) file for details.
```
Copyright 2025 Anubhav Chaurasia (i8o8i)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
---
## 📚 Complete Documentation
### **Getting Started**
- **[README.md](README.md)** — This file (Project overview & quick start)
- **[SETUP_GUIDE.md](SETUP_GUIDE.md)** — Detailed installation guide for all platforms
- **[ARCHITECTURE.md](ARCHITECTURE.md)** — Technical system architecture & design
- **[VIDEO_SCRIPT.md](VIDEO_SCRIPT.md)** — 3-minute demo script for presentations
### **Development**
- **[CONTRIBUTING.md](CONTRIBUTING.md)** — How to contribute (Code, docs, ideas)
- **[FEATURE_REQUEST.md](FEATURE_REQUEST.md)** — Feature request template
- **[DEVELOPMENT_RATIONALE.md](DEVELOPMENT_RATIONALE.md)** — Why we made each design decision
- **[CHANGELOG.md](CHANGELOG.md)** — Version history & release notes
### **Advanced Topics**
- **[Docs/INNOVATION_HIGHLIGHTS.md](Docs/INNOVATION_HIGHLIGHTS.md)** — 6 novel innovations explained
- **[Docs/TECHNICAL_DEEP_DIVE.md](Docs/TECHNICAL_DEEP_DIVE.md)** — Advanced architecture & algorithms
- **[Docs/SOCIAL_IMPACT_ASSESSMENT.md](Docs/SOCIAL_IMPACT_ASSESSMENT.md)** — UN SDG alignment & impact metrics
- **[Docs/DEPLOYMENT_GUIDE.md](Docs/DEPLOYMENT_GUIDE.md)** — Production deployment (GCP, AWS, Azure)
- **[Docs/JUDGE_EVALUATION_GUIDE.md](Docs/JUDGE_EVALUATION_GUIDE.md)** — Hackathon evaluation reference
- **[Docs/INDEX.md](Docs/INDEX.md)** — Complete documentation index
### **Legal & Licensing**
- **[LICENSE](LICENSE)** — Apache 2.0 open-source license
---
## 🙏 Acknowledgments
- **Google ADK Team** — For the excellent agent development framework
- **Kaggle & Google** — For organizing the Capstone Hackathon
- **Indian Farmers** — The true heroes who inspired this project
- **Open-Source Community** — For tools like FastAPI, Pydantic, and OpenTelemetry
---
## 📧 Contact
**Anubhav Chaurasia (i8o8i)**
- GitHub: [@i8o8i-Developer](https://github.com/i8o8i-Developer)
- Email: [i8o8iworkstation@outlook.com](mailto:i8o8iworkstation@outlook.com)
- LinkedIn: [My LinkedIn Profile](https://www.linkedin.com/in/anubhav1608/)
---
## 🌟 Star This Project
If you find AgriSenseGuardian useful, please give it a ⭐ on GitHub! It helps others discover this work and motivates continued development.
---
<div align="center">
**Built With ❤️ For Indian Farmers**
**Powered By 🤖 Google ADK & Multi-Agent AI**
**Licensed Under 📄 Apache 2.0**
---
```
┌─────────────────────────────────────────────────────────┐
│ "Technology Should Serve Humanity's Most Basic Needs" │
│ — AgriSenseGuardian Mission Statement │
└─────────────────────────────────────────────────────────┘
```
</div>