DEV Community

Cover image for Building FarmWise: An AI Field Advisor for Subsistence Farmers Using Gemma 4
mo
mo

Posted on

Building FarmWise: An AI Field Advisor for Subsistence Farmers Using Gemma 4

Gemma 4 Challenge: Write about Gemma 4 Submission

This is a submission for the Gemma 4 Challenge: Write About Gemma 4.


A practical guide to building a real-world AI tool with Gemma 4, no cloud required.

Who Is This For?

This tutorial is for beginner Python developers who want to build something with a real use case. No machine learning background needed. If you can run a Python script, you can follow along.

By the end, you will have a working command-line app called FarmWise, an AI field advisor that helps small subsistence farmers with four common daily problems:

  1. Understanding weather forecasts and what they mean for crops
  2. Knowing what to plant and when based on their region and season
  3. Diagnosing crop pests and diseases from symptom descriptions
  4. Getting fair pricing guidance before going to market

Why Gemma 4, and Why the 2B Model Specifically

This project uses Gemma 4 2B, the smallest model in the Gemma 4 family. That is not a workaround. It is the right choice for this use case.

Subsistence farmers in Sub-Saharan Africa, South Asia, and Latin America often live in areas with unreliable or nonexistent internet connectivity. They use low-cost Android phones or shared community devices. A tool that requires a cloud API call is a tool they cannot use when it matters most.

Gemma 4 2B runs on a Raspberry Pi 5. It runs on a mid-range Android phone. It runs fully offline. The model's small footprint is what makes it genuinely useful to the people this app is designed for, not just a demo for people who already have good infrastructure.

Gemma 4 2B is built for edge deployment, ultra-mobile, and low-resource environments. For this project, that is the point.


What We Are Building

FarmWise is a conversational Python CLI app. The farmer types a question in plain language, in any language, and Gemma 4 responds with practical, specific advice.

User: My maize leaves are turning yellow from the bottom up. What is wrong?

FarmWise: This sounds like nitrogen deficiency, which is common in maize.
Yellowing starts at older leaves first because the plant moves nitrogen to
new growth. Here is what you can do:
1. Apply urea fertilizer (46-0-0) at 50kg per hectare if available.
2. If fertilizer is not accessible, mix 1 part cow manure with 3 parts
   soil and apply around the base of each plant.
3. Avoid overwatering. Waterlogged soil blocks nitrogen uptake.
Check again in 7 days. If yellowing spreads to new leaves, bring a leaf
sample to your nearest agricultural extension office.
Enter fullscreen mode Exit fullscreen mode

Straightforward output. No unnecessary formatting. Works without internet.


Prerequisites

  • Python 3.9 or higher
  • A machine or Raspberry Pi with at least 4GB RAM
  • Ollama installed (free, open source, handles local model serving)
  • Basic familiarity with the terminal

Step 1: Install Ollama and Pull Gemma 4

Ollama handles model downloading, serving, and inference locally. Think of it as Docker but for LLMs.

Install Ollama:

# macOS and Linux
curl -fsSL https://ollama.com/install.sh | sh

# Windows: download the installer from https://ollama.com
Enter fullscreen mode Exit fullscreen mode

Pull the Gemma 4 2B model:

ollama pull gemma4:2b
Enter fullscreen mode Exit fullscreen mode

This is a one-time download of approximately 1.5GB. After this, the app runs with no internet connection needed.

Verify it works:

ollama run gemma4:2b "Hello, can you help a farmer?"
Enter fullscreen mode Exit fullscreen mode

If you get a response in your terminal, you are ready to move on.


Step 2: Set Up Your Project

Create a project folder and install the only dependency:

mkdir farmwise
cd farmwise
pip install requests
Enter fullscreen mode Exit fullscreen mode

No ML frameworks. No GPU. Just Python making HTTP calls to Ollama's local API server.


Step 3: Build the App

Create a file called farmwise.py with the following code:

import requests

OLLAMA_URL = "http://localhost:11434/api/generate"
MODEL = "gemma4:2b"

SYSTEM_PROMPT = """
You are FarmWise, a practical AI farming advisor for small subsistence farmers.
Your users grow food to feed their families and sell small surpluses at local markets.
They may have limited formal education and limited access to agricultural experts.

Your role is to help them with:
1. Weather interpretation: explain what weather conditions mean for their crops in plain terms
2. Planting guidance: recommend what to plant and when, based on their region and season
3. Pest and disease diagnosis: identify problems from symptom descriptions and suggest low-cost remedies
4. Market pricing: give fair price benchmarks and basic negotiation guidance

Rules:
- Always respond in the same language the farmer writes in
- Use simple, plain language and avoid technical jargon
- Give specific steps the farmer can act on today
- Recommend low-cost or free solutions before expensive ones
- If you are not confident, say so and suggest they contact a local agricultural extension officer
- Keep responses under 200 words
"""

def ask_farmwise(question: str) -> str:
    payload = {
        "model": MODEL,
        "prompt": f"[SYSTEM]\n{SYSTEM_PROMPT}\n\n[FARMER]\n{question}\n\n[FARMWISE]",
        "stream": False,
        "options": {
            "temperature": 0.7,
            "num_predict": 300
        }
    }

    try:
        response = requests.post(OLLAMA_URL, json=payload, timeout=60)
        response.raise_for_status()
        data = response.json()
        return data.get("response", "Could not generate a response. Please try again.")
    except requests.exceptions.ConnectionError:
        return "Cannot connect to Ollama. Make sure it is running: ollama serve"
    except requests.exceptions.Timeout:
        return "Response timed out. Your device may need more time. Try again."
    except Exception as e:
        return f"Something went wrong: {str(e)}"


def print_banner():
    print("\n" + "=" * 50)
    print("  FarmWise - Your AI Field Advisor")
    print("  Powered by Gemma 4 2B (runs offline)")
    print("=" * 50)
    print("\nAsk me anything about your crops, weather, pests, or market prices.")
    print("Type 'quit' to exit.\n")


def main():
    print_banner()

    while True:
        try:
            question = input("You: ").strip()
        except (EOFError, KeyboardInterrupt):
            print("\n\nGoodbye. Good harvest.")
            break

        if not question:
            continue

        if question.lower() in ("quit", "exit", "bye"):
            print("\nGoodbye. Good harvest.")
            break

        print("\nFarmWise: ", end="", flush=True)
        answer = ask_farmwise(question)
        print(answer)
        print()


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Step 4: Run FarmWise

Start Ollama in one terminal window:

ollama serve
Enter fullscreen mode Exit fullscreen mode

Then in a second terminal, run the app:

python farmwise.py
Enter fullscreen mode Exit fullscreen mode

Step 5: Test It With Real Scenarios

Here are practical questions to test each feature:

Pest and disease diagnosis:

My tomato leaves have brown spots with yellow rings around them. What is this?
Enter fullscreen mode Exit fullscreen mode

Planting guidance:

I am in Kenya, it is October. I have a small plot of 0.5 acres. What should I plant?
Enter fullscreen mode Exit fullscreen mode

Weather interpretation:

The forecast says 80% humidity and 32 degrees Celsius for the next week. Is it safe to plant?
Enter fullscreen mode Exit fullscreen mode

Market pricing:

A buyer offered me 20 shillings per kilo of maize. Is this a fair price?
Enter fullscreen mode Exit fullscreen mode

Multilingual input (Swahili):

Mahindi yangu yanageuka manjano. Nifanye nini?
Enter fullscreen mode Exit fullscreen mode

Translation: My maize is turning yellow. What should I do?

The app responds in the same language the user writes in. No extra configuration needed.


How the System Prompt Works

The Python code in this app is straightforward. The more important part to understand is the system prompt, because it is doing most of the work.

Who the user is. Subsistence farmers with limited education and limited access to experts. This changes how the model frames its language and what solutions it prioritizes.

What the app does. Four specific domains: weather, planting, pests, and pricing. Keeping the scope focused produces more reliable answers than a general-purpose prompt.

How responses should be structured. Short, actionable, plain language, cheap solutions first. This is where you shape output quality without touching the model weights.

Multilingual behavior. One line, "always respond in the same language the farmer writes in", handles localization completely. No translation APIs, no language detection code.

This pattern, prompt-driven behavior on top of a small local model, scales to many other applications with similar constraints.


Extending the App

Once the base app is working, these are practical next steps:

1. Persist crop context across the conversation

Ask the farmer what they grow at startup and append it to the system prompt. This makes every subsequent answer more specific.

crops = input("What crops are you growing this season? ")
SYSTEM_PROMPT += f"\n\nThis farmer is currently growing: {crops}"
Enter fullscreen mode Exit fullscreen mode

2. Add a topic menu

Route each topic to a focused sub-prompt rather than relying on one general prompt for everything. Pest diagnosis benefits from a different structure than market pricing.

3. Log conversations to a text file

Farmers can share printed logs with agricultural extension officers or revisit advice later.

4. Run it on Android via Termux

Ollama runs inside Termux on Android. That means FarmWise can run on a $50 Android phone with no data connection, which is the real deployment target for this kind of tool.


Why This Problem Is Worth Solving

There are approximately 500 million smallholder farming households worldwide. They produce around 70 percent of the food consumed in developing countries. The vast majority have never had access to an agronomist, a market analyst, or an extension officer who speaks their language.

Gemma 4 2B fits on a cheap phone. It runs without internet. It responds in whatever language the user writes in. That combination is what makes a tool like this actually deployable to the people who need it.


Summary

In under 100 lines of Python, this tutorial covered:

  • Running Gemma 4 2B locally via Ollama with no cloud dependency
  • Building a multi-domain conversational advisor with a single focused system prompt
  • Handling multilingual input without any extra libraries
  • Deploying to low-resource hardware including Raspberry Pi and Android

The model choice, Gemma 4 2B, was deliberate. Larger models would produce marginally better responses but would not run on the hardware the target users actually have. Matching the model to the deployment environment is part of good engineering, not a compromise.


Resources


Submitted to the Gemma 4 Challenge on DEV Community.

Tags: #gemma4challenge #python #ai #agriculture

Top comments (0)