Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

feat: add LLM Agri Bot - multi-tool farming assistant

Tiioluwanid5683b7cb26e
diff --git a/ai_agents/llm_agri_bot/.env.example b/ai_agents/llm_agri_bot/.env.example
new file mode 100644
index 0000000..a0d6707
--- /dev/null
+++ b/ai_agents/llm_agri_bot/.env.example
@@ -0,0 +1,7 @@
+# Mistral API key for the LLM agent
+# Get your key at https://console.mistral.ai/
+MISTRAL_API_KEY=your_mistral_api_key_here
+
+# OpenWeatherMap API key for weather tool queries
+# Sign up at https://openweathermap.org/api and create a free API key
+OPENWEATHER_API_KEY=your_openweather_api_key_here
diff --git a/ai_agents/llm_agri_bot/.gitignore b/ai_agents/llm_agri_bot/.gitignore
new file mode 100644
index 0000000..35236e6
--- /dev/null
+++ b/ai_agents/llm_agri_bot/.gitignore
@@ -0,0 +1,3 @@
+.env
+.venv/
+__pycache__/
diff --git a/ai_agents/llm_agri_bot/README.md b/ai_agents/llm_agri_bot/README.md
new file mode 100644
index 0000000..c2c3c2f
--- /dev/null
+++ b/ai_agents/llm_agri_bot/README.md
@@ -0,0 +1,104 @@
+# LLM Agri Bot
+> A multi-tool farming assistant that helps farmers make informed decisions about crop health, weather, pest control, and planting seasons.
+
+## Overview
+LLM Agri Bot is a Streamlit chat application powered by LangChain and Mistral. Farmers type questions in plain English and an agent selects the right tool to fetch weather data, search the web for pest and disease guidance, or look up crop calendar information. Mistral then turns that data into practical, actionable advice.
+
+## Demo
+![Demo](assets/demo.gif)
+
+## Features
+- Streamlit chat interface with conversation history
+- LangChain tool-calling agent powered by Mistral (mistral-small-latest)
+- OpenWeatherMap integration for real-time local weather queries
+- DuckDuckGo search for crop disease and pest control guidance
+- Static crop calendar covering 18 common crops with planting and harvest guidance
+- Sidebar with app description and example questions
+
+## Tech Stack
+**Agent Framework:**
+- LangChain - agent orchestration and tool calling
+
+**LLM:**
+- Mistral (mistral-small-latest) via langchain-mistralai
+
+**Tools:**
+- OpenWeatherMap API - real-time weather data
+- DuckDuckGo Search - crop disease and pest control lookup
+- Crop Calendar - static knowledge base for 18 common crops
+
+**UI:**
+- Streamlit
+
+## Prerequisites
+- Python 3.10+
+- Mistral API key - get one at https://console.mistral.ai/
+- OpenWeatherMap API key - get one at https://openweathermap.org/api
+
+## Setup
+
+### 1. Clone the Repository
+```bash
+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git
+cd Hands-On-AI-Engineering/ai_agents/llm_agri_bot
+```
+
+### 2. Create Virtual Environment
+```bash
+python -m venv .venv
+.venv\Scripts\activate # Windows
+source .venv/bin/activate # macOS/Linux
+```
+
+### 3. Install Dependencies
+```bash
+pip install -r requirements.txt
+```
+
+### 4. Configure Environment Variables
+```bash
+cp .env.example .env
+copy .env.example .env # Windows
+```
+Open `.env` and add your API keys: `MISTRAL_API_KEY` and `OPENWEATHER_API_KEY`.
+
+### 5. Run the App
+```bash
+streamlit run app.py
+```
+
+## Usage
+Type a farming question in the chat box and the agent will select the right tool and return practical advice. Example questions:
+
+- "What is the weather like in Lagos today?"
+- "My tomato leaves are turning yellow, what should I do?"
+- "When should I plant maize?"
+- "How do I control aphids on my pepper farm?"
+
+## Project Structure
+llm_agri_bot/
+
+├── app.py # Streamlit chat UI
+
+├── agent.py # LangChain agent and Mistral setup
+
+├── tools.py # Weather, search, and crop calendar tools
+
+├── requirements.txt
+
+├── .env.example
+
+├── .gitignore
+
+├── README.md
+
+└── assets/
+
+└── demo.gif
+
+## How It Works
+1. The farmer types a question in the Streamlit chat input.
+2. The LangChain agent powered by Mistral decides which tool to call.
+3. Tools fetch weather data, web search results, or crop calendar entries.
+4. Mistral processes the tool output and generates a concise, actionable response.
+5. The response is displayed in the chat UI and stored in session history.
diff --git a/ai_agents/llm_agri_bot/agent.py b/ai_agents/llm_agri_bot/agent.py
new file mode 100644
index 0000000..c23d0af
--- /dev/null
+++ b/ai_agents/llm_agri_bot/agent.py
@@ -0,0 +1,109 @@
+import os
+
+from dotenv import load_dotenv
+from langchain_classic.agents import AgentExecutor, create_tool_calling_agent
+from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
+from langchain_mistralai import ChatMistralAI
+
+from tools import get_tools
+
+load_dotenv()
+
+SYSTEM_PROMPT = """You are an expert agricultural assistant helping farmers make informed decisions.
+You have access to weather data, web search for crop diseases and pest control, and a crop calendar.
+Always give practical, actionable advice. Be concise and clear.
+
+When answering:
+- Use the weather tool for current conditions and forecasts when location is known or can be inferred.
+- Use the search tool for recent pest outbreaks, disease symptoms, and treatment options.
+- Use the crop calendar for planting and harvest timing questions.
+- Combine tool results into clear steps farmers can follow today.
+- If a tool fails or data is missing, say so and provide the best general guidance you can."""
+
+
+def build_llm() -> ChatMistralAI:
+ """Create a streaming Mistral chat model from environment config."""
+ api_key = os.getenv("MISTRAL_API_KEY")
+ if not api_key:
+ raise ValueError("MISTRAL_API_KEY is not set. Add it to your .env file.")
+
+ return ChatMistralAI(
+ model="mistral-small-latest",
+ api_key=api_key,
+ streaming=True,
+ )
+
+
+def build_agent_executor() -> AgentExecutor:
+ """Assemble the LangChain tool-calling agent and executor."""
+ llm = build_llm()
+ tools = get_tools()
+
+ prompt = ChatPromptTemplate.from_messages(
+ [
+ ("system", SYSTEM_PROMPT),
+ MessagesPlaceholder("chat_history", optional=True),
+ ("human", "{input}"),
+ MessagesPlaceholder("agent_scratchpad"),
+ ]
+ )
+
+ agent = create_tool_calling_agent(llm, tools, prompt)
+ return AgentExecutor(
+ agent=agent,
+ tools=tools,
+ verbose=True,
+ handle_parsing_errors=True,
+ )
+
+
+def format_chat_history(messages: list[dict]) -> list[tuple[str, str]]:
+ """Convert UI message dicts to LangChain chat history tuples."""
+ history: list[tuple[str, str]] = []
+ for message in messages[:-1]:
+ role = message.get("role")
+ content = message.get("content", "")
+ if role == "user":
+ history.append(("human", content))
+ elif role == "assistant":
+ history.append(("ai", content))
+ return history
+
+
+def run_agent(
+ user_input: str,
+ chat_history: list[dict] | None = None,
+ callbacks: list | None = None,
+) -> str:
+ """Invoke the agent and return the full text response."""
+ executor = build_agent_executor()
+ history = format_chat_history(chat_history or [])
+
+ result = executor.invoke(
+ {
+ "input": user_input,
+ "chat_history": history,
+ },
+ config={"callbacks": callbacks or []},
+ )
+ return result["output"]
+
+
+def stream_agent_response(
+ user_input: str,
+ chat_history: list[dict] | None = None,
+):
+ """Stream agent response tokens as they are generated."""
+ executor = build_agent_executor()
+ history = format_chat_history(chat_history or [])
+
+ for chunk in executor.stream(
+ {
+ "input": user_input,
+ "chat_history": history,
+ },
+ stream_mode="messages",
+ ):
+ message_chunk, _metadata = chunk
+ if message_chunk.content:
+ yield message_chunk.content
diff --git a/ai_agents/llm_agri_bot/app.py b/ai_agents/llm_agri_bot/app.py
new file mode 100644
index 0000000..bd959c5
--- /dev/null
+++ b/ai_agents/llm_agri_bot/app.py
@@ -0,0 +1,136 @@
+"""Streamlit entry point for the LLM Agri Bot chat UI."""
+
+import os
+
+import streamlit as st
+from dotenv import load_dotenv
+from langchain_community.callbacks.streamlit import StreamlitCallbackHandler
+
+from agent import run_agent, stream_agent_response
+
+load_dotenv()
+
+st.set_page_config(
+ page_title="LLM Agri Bot",
+ page_icon="🌾",
+ layout="wide",
+)
+
+WELCOME_MESSAGE = (
+ "Welcome to LLM Agri Bot! I can help with crop health, weather, pest control, "
+ "and planting seasons. Ask a question like: "
+ "'When should I plant tomatoes in spring?' or "
+ "'What is the weather in Des Moines?'"
+)
+
+EXAMPLE_QUESTIONS = [
+ "When should I plant corn in Iowa?",
+ "What is the weather in Nairobi today?",
+ "How do I control aphids on tomato plants?",
+ "When is the best time to harvest wheat?",
+ "What planting season does rice follow in tropical regions?",
+]
+
+
+def init_session_state() -> None:
+ """Initialize chat message history in Streamlit session state."""
+ if "messages" not in st.session_state:
+ st.session_state.messages = [
+ {"role": "assistant", "content": WELCOME_MESSAGE}
+ ]
+
+
+def render_sidebar() -> None:
+ """Render the sidebar with app info and example questions."""
+ with st.sidebar:
+ st.title("LLM Agri Bot")
+ st.markdown(
+ """
+ **Your multi-tool farming assistant**
+
+ Ask questions in plain English about:
+ - Crop health and diseases
+ - Local weather conditions
+ - Pest control strategies
+ - Planting and harvest timing
+ """
+ )
+ st.divider()
+ st.subheader("Example questions")
+ for question in EXAMPLE_QUESTIONS:
+ st.markdown(f"- {question}")
+
+
+def render_chat_history() -> None:
+ """Display stored messages in the chat interface."""
+ for message in st.session_state.messages:
+ with st.chat_message(message["role"]):
+ st.markdown(message["content"])
+
+
+def get_assistant_response(user_prompt: str) -> str:
+ """Run the agent and return the assistant reply for a user prompt."""
+ if not os.getenv("MISTRAL_API_KEY"):
+ return (
+ "MISTRAL_API_KEY is missing. Copy `.env.example` to `.env` and add your API keys."
+ )
+
+ with st.chat_message("assistant"):
+ response_placeholder = st.empty()
+ full_response = ""
+
+ try:
+ with st.spinner("Thinking and checking tools..."):
+ callback_container = st.container()
+ st_callback = StreamlitCallbackHandler(callback_container)
+
+ streamed_parts: list[str] = []
+ try:
+ for token in stream_agent_response(
+ user_prompt,
+ chat_history=st.session_state.messages,
+ ):
+ streamed_parts.append(token)
+ full_response = "".join(streamed_parts)
+ response_placeholder.markdown(full_response + "▌")
+ except Exception:
+ full_response = run_agent(
+ user_prompt,
+ chat_history=st.session_state.messages,
+ callbacks=[st_callback],
+ )
+ response_placeholder.markdown(full_response)
+
+ if full_response.endswith("▌"):
+ full_response = full_response[:-1]
+ response_placeholder.markdown(full_response)
+ return full_response
+ except Exception as exc:
+ error_message = f"Sorry, something went wrong: {exc}"
+ response_placeholder.markdown(error_message)
+ return error_message
+
+
+def main() -> None:
+ """Run the Streamlit app entry point."""
+ init_session_state()
+ render_sidebar()
+
+ st.title("LLM Agri Bot")
+ st.caption("Multi-tool farming assistant powered by Mistral and LangChain")
+
+ render_chat_history()
+
+ if user_prompt := st.chat_input("Ask about crops, weather, pests, or planting seasons..."):
+ st.session_state.messages.append({"role": "user", "content": user_prompt})
+ with st.chat_message("user"):
+ st.markdown(user_prompt)
+
+ assistant_response = get_assistant_response(user_prompt)
+ st.session_state.messages.append(
+ {"role": "assistant", "content": assistant_response}
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/llm_agri_bot/assets/demo.gif b/ai_agents/llm_agri_bot/assets/demo.gif
new file mode 100644
index 0000000..13e22ad
Binary files /dev/null and b/ai_agents/llm_agri_bot/assets/demo.gif differ
diff --git a/ai_agents/llm_agri_bot/requirements.txt b/ai_agents/llm_agri_bot/requirements.txt
new file mode 100644
index 0000000..01d3c85
--- /dev/null
+++ b/ai_agents/llm_agri_bot/requirements.txt
@@ -0,0 +1,9 @@
+langchain>=1.3.0,<2.0.0
+langchain-classic>=1.0.0,<2.0.0
+langchain-core>=1.4.0,<2.0.0
+langchain-mistralai>=1.1.0,<2.0.0
+langchain-community>=0.4.0,<1.0.0
+streamlit
+python-dotenv
+ddgs
+pyowm
diff --git a/ai_agents/llm_agri_bot/tools.py b/ai_agents/llm_agri_bot/tools.py
new file mode 100644
index 0000000..ecc49bf
--- /dev/null
+++ b/ai_agents/llm_agri_bot/tools.py
@@ -0,0 +1,159 @@
+import os
+
+from dotenv import load_dotenv
+from langchain_community.tools import DuckDuckGoSearchRun, OpenWeatherMapQueryRun
+from langchain_community.utilities import OpenWeatherMapAPIWrapper
+from langchain_core.tools import tool
+
+load_dotenv()
+
+CROP_CALENDAR_DATA = {
+ "tomato": {
+ "planting_season": "Start seeds indoors 6-8 weeks before last frost; transplant after soil reaches 60F (15C).",
+ "harvest_season": "Harvest 60-85 days after transplant when fruit is firm and fully colored.",
+ "notes": "Needs full sun, consistent moisture, and support stakes or cages. Avoid overhead watering to reduce blight risk.",
+ },
+ "corn": {
+ "planting_season": "Direct sow 2 weeks after last frost when soil is at least 60F (15C). Plant in blocks for pollination.",
+ "harvest_season": "Pick 18-24 days after silks appear when kernels release milky fluid when pierced.",
+ "notes": "Heavy nitrogen feeder. Rotate with legumes. Watch for corn earworm and fall armyworm.",
+ },
+ "wheat": {
+ "planting_season": "Winter wheat: sow in fall 6-8 weeks before first hard frost. Spring wheat: sow as soon as soil can be worked.",
+ "harvest_season": "Harvest when grain is hard and moisture is below 20%, typically early to mid summer for spring types.",
+ "notes": "Prefers well-drained loam. Scout for rust, aphids, and Hessian fly in winter wheat.",
+ },
+ "rice": {
+ "planting_season": "Transplant seedlings 4-5 weeks after sowing when monsoon rains begin or after flooding paddies in warm regions.",
+ "harvest_season": "Harvest 120-150 days after transplant when grains turn golden and moisture drops to 18-22%.",
+ "notes": "Requires flooded or saturated fields in many systems. Manage blast, stem borer, and weeds early.",
+ },
+ "potato": {
+ "planting_season": "Plant seed pieces 2-4 weeks before last frost when soil is workable and above 45F (7C).",
+ "harvest_season": "New potatoes at flowering; main crop 2-3 weeks after foliage dies back.",
+ "notes": "Hill soil around stems to prevent green tubers. Rotate to reduce scab and late blight pressure.",
+ },
+ "soybean": {
+ "planting_season": "Direct sow when soil is 60F (15C) or warmer, typically late spring after last frost.",
+ "harvest_season": "Harvest when pods are dry and seeds rattle, usually late summer to early fall.",
+ "notes": "Fixes nitrogen in soil. Inoculate seed in new fields. Watch for aphids, bean leaf beetle, and white mold.",
+ },
+ "cotton": {
+ "planting_season": "Plant when soil reaches 65F (18C), often 4-6 weeks after last frost in warm climates.",
+ "harvest_season": "Harvest when bolls open fully, typically late summer through fall depending on variety.",
+ "notes": "Long frost-free season required. Monitor for bollworm, aphids, and timely defoliation before pick.",
+ },
+ "lettuce": {
+ "planting_season": "Sow early spring and late summer for fall crops; prefers cool soil below 75F (24C).",
+ "harvest_season": "Harvest 30-70 days after sowing; pick outer leaves or whole heads before bolting.",
+ "notes": "Shade in hot weather to delay bolting. Succession plant every 2 weeks for steady supply.",
+ },
+ "carrot": {
+ "planting_season": "Direct sow in early spring as soon as soil can be worked; late summer sowing for fall harvest.",
+ "harvest_season": "Harvest 60-80 days after sowing when roots reach desired size and color.",
+ "notes": "Needs loose, stone-free soil. Thin seedlings to 2-3 inches apart. Consistent moisture prevents cracking.",
+ },
+ "onion": {
+ "planting_season": "Sets or transplants in early spring; direct seed as soon as soil is workable in cool regions.",
+ "harvest_season": "Harvest when tops fall over and necks soften, usually mid to late summer.",
+ "notes": "Day-length sensitive varieties matter. Cure bulbs in dry shade for 2-3 weeks before storage.",
+ },
+ "pepper": {
+ "planting_season": "Start indoors 8-10 weeks before last frost; transplant when nights stay above 55F (13C).",
+ "harvest_season": "Pick green peppers from 60-90 days; allow extra time for full color ripening.",
+ "notes": "Heat-loving crop. Mulch to retain moisture. Watch for aphids, blossom end rot, and sunscald.",
+ },
+ "cucumber": {
+ "planting_season": "Direct sow or transplant 1-2 weeks after last frost when soil is above 65F (18C).",
+ "harvest_season": "Harvest 50-70 days after planting while fruit is firm and before seeds harden.",
+ "notes": "Provide trellis in humid areas to improve airflow. Pick regularly to keep plants producing.",
+ },
+ "beans": {
+ "planting_season": "Direct sow after last frost when soil is at least 60F (15C); avoid soaking wet soil.",
+ "harvest_season": "Snap beans in 50-60 days; dry beans when pods are brown and brittle.",
+ "notes": "Do not soak seeds before planting. Rotate with grains to break root rot cycles.",
+ },
+ "barley": {
+ "planting_season": "Spring barley: sow as early as soil can be worked. Winter barley: sow in fall in mild climates.",
+ "harvest_season": "Harvest when grain is hard and straw is golden, typically 90-110 days after planting.",
+ "notes": "Tolerates cooler conditions than corn. Good cover crop option. Scout for scald and net blotch.",
+ },
+ "sunflower": {
+ "planting_season": "Direct sow after last frost when soil is 55F (13C) or warmer, through early summer.",
+ "harvest_season": "Harvest when back of head turns yellow-brown and seeds are plump, late summer to fall.",
+ "notes": "Deep roots help drought tolerance. Protect from birds near maturity with mesh or early harvest.",
+ },
+ "spinach": {
+ "planting_season": "Sow in early spring and again in late summer; germinates best below 70F (21C).",
+ "harvest_season": "Harvest outer leaves from 37-45 days or cut whole plant before bolting in heat.",
+ "notes": "Fast cool-season crop. Use row cover against leaf miners. Succession sow for continuous harvest.",
+ },
+ "broccoli": {
+ "planting_season": "Transplant 2-3 weeks before last frost for spring crop; late summer for fall harvest.",
+ "harvest_season": "Cut central head 60-90 days after transplant when buds are tight and green.",
+ "notes": "Side shoots follow main head. Fertilize steadily. Watch for cabbage worm and aphids.",
+ },
+ "apple": {
+ "planting_season": "Plant dormant bare-root trees in late winter or early spring before bud break.",
+ "harvest_season": "Harvest varies by cultivar from late summer through fall when fruit separates easily with a lift-and-twist.",
+ "notes": "Requires cross-pollination from compatible varieties. Prune annually for light penetration and fruit quality.",
+ },
+}
+
+
+def _normalize_crop_name(crop_name: str) -> str:
+ return crop_name.strip().lower().replace("-", " ").split()[0]
+
+
+def _build_crop_calendar_response(crop_name: str) -> str:
+ key = _normalize_crop_name(crop_name)
+ if key not in CROP_CALENDAR_DATA:
+ available = ", ".join(sorted(CROP_CALENDAR_DATA.keys()))
+ return (
+ f"No calendar entry found for '{crop_name}'. "
+ f"Available crops: {available}."
+ )
+
+ data = CROP_CALENDAR_DATA[key]
+ return (
+ f"Crop calendar for {key.title()}:\n"
+ f"- Planting season: {data['planting_season']}\n"
+ f"- Harvest season: {data['harvest_season']}\n"
+ f"- Notes: {data['notes']}"
+ )
+
+
+@tool
+def crop_calendar(crop_name: str) -> str:
+ """Look up planting and harvesting season information for common crops.
+
+ Use this when farmers ask about when to plant or harvest a specific crop,
+ growing seasons, or crop timing guidance.
+
+ Args:
+ crop_name: Name of the crop, such as tomato, corn, wheat, or rice.
+ """
+ return _build_crop_calendar_response(crop_name)
+
+
+def get_weather_tool() -> OpenWeatherMapQueryRun:
+ """Return an OpenWeatherMap query tool configured from env vars."""
+ api_key = os.getenv("OPENWEATHER_API_KEY")
+ if not api_key:
+ raise ValueError(
+ "OPENWEATHER_API_KEY is not set. Add it to your .env file."
+ )
+
+ os.environ["OPENWEATHERMAP_API_KEY"] = api_key
+ wrapper = OpenWeatherMapAPIWrapper()
+ return OpenWeatherMapQueryRun(api_wrapper=wrapper)
+
+
+def get_search_tool() -> DuckDuckGoSearchRun:
+ """Return a DuckDuckGo search tool for web lookups."""
+ return DuckDuckGoSearchRun()
+
+
+def get_tools() -> list:
+ """Return all agent tools: weather, search, and crop calendar."""
+ return [get_weather_tool(), get_search_tool(), crop_calendar]