Skip to content

About

An AI-powered City Assistant built with Streamlit, LangChain, and LLM technologies. The application provides an interactive conversational interface for answering city-related queries, retrieving relevant information, and assisting users through intelligent AI agents and web-based search.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ™οΈ City AI Agent

Python 3.10+ LangChain Streamlit Google Gemini Tavily AI OpenWeatherMap License: MIT

An intelligent, multi-model conversational AI agent designed to provide real-time weather analytics and latest breaking news for cities across India. Powered by LangChain, Google Gemini, Tavily Search, OpenWeatherMap, and an interactive Streamlit dashboard with high-resilience multi-LLM fallback architecture.


πŸ“Œ Table of Contents


🌟 Overview

City AI Agent bridges real-world real-time data with autonomous LLM reasoning. Traditional LLMs suffer from knowledge cutoffs and hallucination risks when asked about current conditions. City AI Agent solves this using LangChain tool binding and autonomous execution:

  1. Weather Analysis: Accurately fetches live meteorological data (temperature, atmospheric pressure, humidity, coordinates) for any city in India via OpenWeatherMap.
  2. News Retrieval: Gathers fresh, verified news articles with headlines, summaries, and source URLs via Tavily Search.
  3. Resilient AI Pipeline: Implements seamless fallbacks across Google Gemini, Mistral AI, and OpenAI to prevent downtime caused by rate limits or outages.
  4. Rich Visual UI: Renders answers alongside live execution badges, KPI metric scorecards, and clickable news cards.

✨ Key Features

  • Autonomous Tool Execution: The agent automatically determines which tools to call (get_weather, get_news, or both) based on natural language intent.
  • Zero-Hallucination Policy: Grounded explicitly in API responses. The agent is strictly instructed never to fabricate real-time data.
  • Enterprise Multi-LLM Fallbacks:
    • Primary: gemini-3.6-flash
    • Fallback 1: gemini-3.1-flash
    • Fallback 2: mistral-small-latest
    • Fallback 3: gpt-5-mini
  • Dynamic Weather Dashboard: Automatically parses JSON responses into interactive Streamlit metric widgets showing temperature (Β°C), atmospheric pressure (hPa), humidity (%), and precise latitude/longitude coordinates.
  • Curated News Feed: Parses search results into responsive article cards with direct links to full news stories.
  • Full Conversational Memory: Multi-turn conversation state retained within Streamlit session state for continuous contextual dialogue.
  • One-Click Quick Actions: Pre-built starter prompts and instant chat reset capabilities.

πŸ—οΈ System Architecture

High-Level Architecture Diagram

flowchart TD
    subgraph UI ["Frontend / Presentation (Streamlit)"]
        User(["πŸ‘€ User Input / Quick Prompts"])
        ChatUI["πŸ’¬ Streamlit Chat Interface (app.py)"]
        Dashboard["πŸ“Š Rich Dashboards (KPIs & News Cards)"]
    end

    subgraph Agent ["Orchestration & Agent Core (LangChain)"]
        Runner["πŸ€– Agent Runner (run_agent)"]
        Prompt["πŸ“ ChatPromptTemplate & Messages"]
        FallbackChain{"⚑ Multi-Model Fallback Chain\n(with_fallbacks)"}
    end

    subgraph LLMs ["LLM Providers"]
        M1["πŸ₯‡ Primary: Gemini 3.6 Flash"]
        M2["πŸ₯ˆ Fallback 1: Gemini 3.1 Flash"]
        M3["πŸ₯‰ Fallback 2: Mistral Small Latest"]
        M4["πŸ… Fallback 3: GPT-5 Mini"]
    end

    subgraph ToolsLayer ["Tools & Integrations (tools.py)"]
        Dispatcher{"Tool Dispatcher\n(tool_map)"}
        WeatherTool["🌦️ get_weather(city)"]
        NewsTool["πŸ“° get_news(city)"]
    end

    subgraph ExternalAPIs ["External Data Services"]
        OWM["🌐 OpenWeatherMap API\n(Current Weather Data)"]
        Tavily["πŸ” Tavily AI Search API\n(Real-time Web Search)"]
    end

    %% Interactions
    User -->|Enter Query| ChatUI
    ChatUI -->|user_input + history| Runner
    Runner --> Prompt
    Prompt --> FallbackChain

    FallbackChain --> M1
    M1 -.->|Failover on Error| M2
    M2 -.->|Failover on Error| M3
    M3 -.->|Failover on Error| M4

    M1 & M2 & M3 & M4 -->|Tool Call Decisions| Dispatcher
    Dispatcher -->|q=city,IN| WeatherTool
    Dispatcher -->|query='latest news in city'| NewsTool

    WeatherTool -->|HTTP GET| OWM
    NewsTool -->|HTTP POST| Tavily

    OWM -->|Metrics JSON| WeatherTool
    Tavily -->|Search Results| NewsTool

    WeatherTool & NewsTool -->|ToolMessage Result| Runner
    Runner -->|Iterative Synthesis| FallbackChain
    FallbackChain -->|Final Answer + Telemetry| ChatUI
    ChatUI --> Dashboard
    Dashboard --> User
Loading

Agent Execution & Tool Calling Flow

sequenceDiagram
    autonumber
    actor User as πŸ‘€ User
    participant App as πŸ–₯️ Streamlit App (app.py)
    participant Agent as 🧠 Agent Runner (agent.py)
    participant Chain as ⛓️ Multi-Model Fallback Chain
    participant Tools as πŸ”§ Tool Dispatcher (tools.py)
    participant APIs as 🌐 External APIs (OpenWeather / Tavily)

    User->>App: Submits question ("Weather and news in Delhi")
    App->>Agent: run_agent(prompt, history)
    loop ReAct Autonomous Decision Loop
        Agent->>Chain: invoke({"messages": messages})
        Chain-->>Agent: AIMessage with tool_calls (get_weather, get_news)
        alt Has Tool Calls
            Agent->>Tools: Dispatch tool by name with arguments
            Tools->>APIs: Execute API request (OpenWeather / Tavily)
            APIs-->>Tools: Raw API payload
            Tools-->>Agent: Structured Tool Result (JSON/Text)
            Agent->>Agent: Append ToolMessage to conversation messages
        else No Tool Calls (Final Answer Ready)
            Agent-->>App: Return {answer, history, tool_results}
        end
    end
    App->>App: Render text response + Weather Metric KPIs + News Cards
    App-->>User: Display complete interactive response
Loading

Multi-Model Fallback Failover Hierarchy

LangChain's with_fallbacks() ensures that transient outages, rate limits (HTTP 429), quota exhaustion, or service degradation are handled gracefully without manual retry loops:

stateDiagram-v2
    [*] --> Primary_Gemini36: Request Initiated
    Primary_Gemini36 --> Success: 200 OK
    Primary_Gemini36 --> Fallback1_Gemini31: Error / Rate Limit / Timeout
    Fallback1_Gemini31 --> Success: 200 OK
    Fallback1_Gemini31 --> Fallback2_Mistral: Error / Rate Limit / Timeout
    Fallback2_Mistral --> Success: 200 OK
    Fallback2_Mistral --> Fallback3_OpenAI: Error / Rate Limit / Timeout
    Fallback3_OpenAI --> Success: 200 OK
    Fallback3_OpenAI --> Failure: All Models Failed
    Success --> [*]
    Failure --> [*]
Loading

πŸ“‚ Project Structure

City_AI_Agent/
β”œβ”€β”€ .env.example          # Environment variable template
β”œβ”€β”€ .gitignore            # Git ignore file (excludes .env, venv, pycache)
β”œβ”€β”€ agent.py              # LangChain agent core: multi-model chain & execution loop
β”œβ”€β”€ app.py                # Streamlit web application: UI, dashboard & state management
β”œβ”€β”€ requirements.txt      # Project Python dependencies
β”œβ”€β”€ tools.py              # Custom LangChain tools for OpenWeather and Tavily
└── README.md             # Project documentation & architecture

Module Responsibilities

File Primary Responsibility
agent.py Initializes LLMs, configures tool binding, sets up multi-model fallback chain (with_fallbacks), defines prompt instructions, and manages the iterative tool execution loop.
app.py Streamlit web frontend. Houses custom CSS styles, sidebar navigation, conversation state, message rendering, weather KPI dashboard widgets, and news link cards.
tools.py Houses @tool decorated functions: get_weather (OpenWeatherMap) and get_news (Tavily AI Search) with structured response parsing and error handling.
.env.example Documents all necessary API keys required to run the primary and fallback LLMs, weather, and news tools.

πŸ’» Tech Stack

  • Framework: LangChain (langchain-core, langchain-google-genai, langchain-mistralai, langchain-openai)
  • LLM Providers:
    • Google AI Studio (gemini-3.6-flash, gemini-3.1-flash)
    • Mistral AI (mistral-small-latest)
    • OpenAI (gpt-5-mini)
  • Frontend / UI: Streamlit with responsive custom HTML/CSS styling
  • Search & News API: Tavily Search API
  • Weather API: OpenWeatherMap REST API
  • Runtime Environment: Python 3.10+

πŸš€ Getting Started

Prerequisites

  • Python 3.10 or higher installed on your machine.
  • Valid API keys for:
    • Google AI Studio (required for primary LLM)
    • OpenWeatherMap (required for weather lookup)
    • Tavily Search (required for news search)
    • Optional but recommended for fallback: Mistral AI & OpenAI

Installation

  1. Clone the repository:

    git clone https://github.com/thecoder-prog/City_AI_Agent.git
    cd City_AI_Agent
  2. Create and activate a virtual environment:

    • Windows:
      python -m venv .venv
      .venv\Scripts\activate
    • macOS / Linux:
      python3 -m venv .venv
      source .venv/bin/activate
  3. Install dependencies:

    pip install -r requirements.txt

Environment Configuration

  1. Copy .env.example to create your .env file:

    • Windows:
      Copy-Item .env.example .env
    • macOS / Linux:
      cp .env.example .env
  2. Open .env in your text editor and add your API keys:

    GOOGLE_API_KEY=AIzaSy...
    MISTRAL_API_KEY=...
    OPENAI_API_KEY=sk-...
    OPENWEATHER_API_KEY=...
    TAVILY_API_KEY=tvly-...

Running the Application

Launch the Streamlit web application:

streamlit run app.py

Once launched, open your browser to the local URL (typically http://localhost:8501).


πŸ”‘ Environment Variables

Variable Provider Purpose Required?
GOOGLE_API_KEY Google AI Studio Powers primary gemini-3.6-flash and secondary fallback gemini-3.1-flash. Yes
OPENWEATHER_API_KEY OpenWeatherMap Fetches current weather, temperature, humidity, pressure, and coordinates. Yes
TAVILY_API_KEY Tavily AI Fetches up-to-the-minute local news headlines and URLs. Yes
MISTRAL_API_KEY Mistral AI Powers fallback model (mistral-small-latest) if Gemini is rate limited. Recommended
OPENAI_API_KEY OpenAI Powers fallback model (gpt-5-mini) as final failover layer. Recommended

πŸ’‘ Usage & Sample Queries

Try asking the agent any of the following queries:

  • Weather Queries:
    • "What is the current weather in Mumbai?"
    • "How is the temperature in Bengaluru today?"
  • News Queries:
    • "What is the latest news in Pune?"
    • "Any updates on traffic and events in Hyderabad?"
  • Combined Queries:
    • "Give me the current weather and latest news in Delhi."
    • "What is happening in Kolkata right now and is it raining?"

πŸ‘¨β€πŸ’» Author & Acknowledgments

  • Designed & Developed by: Yogesh Bhore (@thecoder-prog)
  • Core Technologies: LangChain, Google DeepMind, Streamlit, Tavily AI, OpenWeatherMap.

πŸ“„ License

This project is licensed under the MIT License β€” feel free to use and adapt it for your projects!

About

An AI-powered City Assistant built with Streamlit, LangChain, and LLM technologies. The application provides an interactive conversational interface for answering city-related queries, retrieving relevant information, and assisting users through intelligent AI agents and web-based search.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages