DEV Community

Prath
Prath

Posted on

FarmSense AI - An intelligent farming companion

DEV Weekend Challenge: Earth Day

This is a submission for Weekend Challenge: Earth Day Edition

Please comment if the api token is expired. I'll update it.

Note: Most of the context is generated by AI reviewed by me. I think it did a pretty good job explaining, Thanks.

What I Built

FarmSense AI β€” an intelligent farming companion that gives small
and mid-size farmers access to expert-level agronomic advice,
real-time weather-aware irrigation scheduling, crop disease diagnosis,
soil health planning, and proactive alerts β€” all in a conversational
interface powered by Google Gemini.

Farming is one of the largest contributors to climate change, yet small
farmers lack access to the precision tools that could help them use
water, fertilizer, and land more efficiently. FarmSense AI democratizes
precision agriculture β€” the same science that large agribusinesses use β€”
and puts it in the pocket of every farmer, for free.

Three core AI modules:

  • 🌿 Crop Doctor β€” Upload a photo or describe symptoms. Get disease diagnosis with severity rating and organic treatment recommendations first, chemicals only as a last resort.
  • πŸ’§ Irrigation Advisor β€” Real-time weather (temperature, humidity, precipitation, wind) fetched from Open-Meteo and injected into every response. Get water requirements in liters per acre, optimal watering times, and drought/overwatering risk flags.
  • πŸͺ± Soil Health Advisor β€” Soil assessment, region-specific cover crop recommendations, composting timelines, and 3-season crop rotation plans to restore soil carbon.

What makes it different from just asking ChatGPT:

  • πŸ“ Auto-detects GPS location silently on load, reverse-geocodes to city/region via OpenStreetMap β€” injected into every prompt automatically
  • πŸ”” Proactive weather-aware alerts generated from your session history
    • 7-day forecast, cached and refreshed every hour
  • πŸ’° AI recommendations auto-parsed for expenses β†’ "βž• Log to Tracker" chips appear below messages β†’ one-click finance logging
  • 🌾 Persistent multi-turn sessions per module with full conversation memory

Demo

πŸ”— Live: https://radiant-axolotl-99d2d9.netlify.app/

Key flows to try:

  1. Allow location β†’ see "πŸ“ Your City" pill appear in chat header
  2. Go to Irrigation Advisor β†’ ask about your crop β†’ watch real-time weather data appear in the response
  3. Ask the AI to recommend fertilizer β†’ see "βž• Log to Tracker" chips appear below the message
  4. Check the πŸ”” bell icon on the dashboard β€” weather-based alerts generated automatically from your session

Code

🌱 FarmSense AI

Your intelligent farming companion β€” powered by Gemini 2.5 Flash

FarmSense AI is a full-stack precision agriculture assistant that gives small and mid-size farmers access to expert-level crop disease diagnosis, irrigation scheduling, soil health advice, financial tracking, and proactive weather-aware alerts β€” all in a conversational interface.


πŸš€ What Makes It Different

Feature FarmSense AI Generic AI Chatbot
Location-aware by default βœ… Auto-detects GPS, injects region into every prompt ❌ User must describe location every time
Real-time weather in responses βœ… Open-Meteo API injected into irrigation prompts ❌ No live data
Proactive alerts βœ… AI scans sessions + 7-day forecast, pushes warnings ❌ Reactive only
Finance loop βœ… AI recommends β†’ "Log to Tracker" chip β†’ expense logged ❌ Advice stays in chat
Streaming responses βœ… Token-by-token SSE stream ❌ Full response wait
Multi-module memory βœ… Persistent sessions per module per user ❌ Stateless
Image diagnosis βœ…
…

How I Built It

Architecture

The diagram above shows the full system. The browser layer handles
GPS detection, streaming rendering, and the one-click tracker chips.
The Express backend owns session state β€” every module gets its own
Map<sessionId, Session> entry holding full message history and
persistent context (crop type, location, soil) so Gemini always has
the complete conversation. Three external services power the
intelligence: Gemini for AI, Open-Meteo for real-time weather,
and Nominatim for reverse geocoding β€” all injected server-side
before each Gemini call.

Tech Stack

Layer Tech
Frontend Next.js 15, React 19, Zustand, Tailwind CSS
Backend Express, TypeScript, Prisma, PostgreSQL
AI Google Gemini 2.5 Flash via LangChain
Weather Open-Meteo API (free, no key)
Geocoding Nominatim / OpenStreetMap (free)
Deploy Netlify (frontend) + Railway (backend + DB)

Interesting Technical Decisions

1. Location without asking

Most farming apps ask "where are you?" on every session. FarmSense
calls navigator.geolocation silently on app load, reverse-geocodes
via Nominatim, and injects the result into every AI prompt. The user
sees a πŸ“ Thane, Maharashtra pill in the header and never has to type
their location.

2. SSE streaming to fix truncation

The original implementation used model.invoke() with
maxOutputTokens: 2048 β€” long irrigation schedules were getting cut
mid-sentence. Switching to model.stream() with SSE eliminated the
token ceiling entirely and made responses feel alive. The frontend adds
an empty assistant bubble immediately, fills it token-by-token, and
shows thinking dots until the first token arrives.

3. Finance loop — closing the advice→action gap

After every AI reply, a background call to gemini-2.0-flash extracts
any purchase recommendations as a JSON array without touching the DB.
This runs on a separate /extract-items endpoint so it never pollutes
the chat session. Result: expense chips appear below the message
automatically β€” the gap between advice and action is one click.

4. Proactive alerts without blocking

Generating alerts for multiple sessions sequentially was causing 30–60
second timeouts. Fixed with Promise.allSettled for parallel calls,
a 15-second per-session timeout, a fully-cached fast path, and feeding
only user messages (not giant AI replies) to the alert prompt to keep
token usage lean.

5. Why this matters for Earth Day

  • Organic treatments recommended first β†’ less chemical runoff into soil and water
  • Precision irrigation β†’ reduces water waste (agriculture uses 70% of global freshwater)
  • Soil health + crop rotation β†’ carbon sequestration and reduced tillage emissions
  • Region-specific cover crops β†’ biodiversity and natural pest control
  • Finance tracker β†’ helps farmers measure ROI on sustainable practices, making green choices economically visible

Prize Categories

πŸ† Best Use of Google Gemini

FarmSense AI uses Gemini Models as its core intelligence across
three distinct use cases:

  • Multi-turn conversational farming advice β€” full session history
    • specialized system prompts per module streamed via SSE using LangChain's model.stream()
  • Expense extraction β€” a lightweight background call to gemini-* after every AI reply, structured JSON output only, zero DB writes, never pollutes chat history
  • Proactive alert generation β€” parallel Gemini calls per session with 7-day weather forecast context, strict JSON output with title/message/type/module fields, 1-hour in-memory cache

Model selection is fully configurable via GEMINI_MODEL and
GEMINI_FAST_MODEL


Built for Earth Day 2026 β€” because every farmer deserves a precision
agriculture advisor in their pocket, and because sustainable farming
at scale is one of the most impactful levers we have against climate change.

Top comments (0)