Estimated reading time: 4 minutes

Building a Weather Chatbot with Langchain

Building a Weather Chatbot with Langchain

This article demonstrates how to create a simple using Langchain that can fetch and provide current weather information based on city names or zip codes. We’ll utilize the power of Large Language Models () and a simple custom tool to achieve this.

Prerequisites

  • 3.6+
  • Langchain Library: Install using pip install langchain
  • OpenAI Key: You’ll need an API key from OpenAI.
  • A way to fetch weather data: This example uses a simplified approach. For a real application, you would typically integrate with a weather API (like OpenWeatherMap, AccuWeather, etc.). For simplicity, we’ll define a basic function here.

The Python Code

Here’s the Python code that implements the weather chatbot:


import os
from langchain.chat_models import ChatOpenAI
from langchain.agents import create_openapi_agent
from langchain.tools import tool

# You'll need an OpenAI API key
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"  # Replace with your actual API key

# Initialize the ChatOpenAI model
 = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)

# In a real application, you'd integrate with a weather API.
# This is a simplified placeholder.
def _get_weather(location: str) -> str:
    \"\"\"Simulates fetching weather data for a given city or zip code.\"\"\"
    if location.lower() == "rogers, ar" or location == "72758":
        return "The current weather in Rogers, AR is sunny with a temperature of 75°F."
    elif location.lower() == "new york, ny" or location == "10001":
        return "The current weather in New York, NY is cloudy with a temperature of 68°F."
    else:
        return f"Weather information not available for {location}."

@tool
def get_current_weather(location: str) -> str:
    \"\"\"Get the current weather for a given city or zip code.\"\"\"
    return _get_weather(location)

tools = [get_current_weather]

# Create the agent
weather_agent = create_openapi_agent(
    llm=llm,
    tools=tools,
    prompt=(
        "You are a helpful chatbot that can provide current weather information."
        "Use the available tool to answer user questions about the weather in a specific city or based on a zip code."
        "Be concise and informative in your responses."
    )
)

# Example usage:
if __name__ == "__main__":
    while True:
        query = input("Ask about the weather (e.g., 'What's the weather in London?' or 'Weather for 90210?' or type 'exit'): ")
        if query.lower() == 'exit':
            break
        response = weather_agent.run(query)
        print(response)
    

Explanation of the Code

  1. Import Libraries: We import necessary libraries from Langchain (for the LLM and agent creation) and os for environment variables.
  2. Set OpenAI API Key: Ensure you replace "YOUR_OPENAI_API_KEY" with your actual OpenAI API key.
  3. Initialize Language Model: We initialize a ChatOpenAI model (gpt-3.5-turbo) with a temperature of 0.
  4. Define the Weather Fetching Function (Placeholder): The _get_weather function is a simplified placeholder. In a real application, this function would make an API call to a weather service using libraries like requests. It currently provides hardcoded responses for “Rogers, AR”, “72758”, “New York, NY”, and “10001”.
  5. Define the Tool (`@tool` decorator): The get_current_weather function is decorated with @tool, making it accessible to the Langchain agent. It takes a location (city name or zip code) as input and uses our _get_weather function to get the weather information.
  6. Create Tools List: We create a list containing our get_current_weather tool.
  7. Create the Agent: We use create_openapi_agent to instantiate our Langchain agent, providing the LLM, the list of tools, and a prompt that defines the agent’s role.
  8. Example Usage: The if __name__ == "__main__": block demonstrates how to run the chatbot, taking user input and printing the agent’s response.

Running the Chatbot

  1. Save the code as a Python file (e.g., weather_chatbot.py).
  2. Install the required libraries using pip install langchain openai. You would also install your chosen weather API library (e.g., pip install pyowm for OpenWeatherMap).
  3. Replace "YOUR_OPENAI_API_KEY" with your actual OpenAI API key.
  4. Implement Real Weather Fetching: Replace the placeholder _get_weather function with code that interacts with a weather API using the location provided. You’ll likely need to sign up for an API key with your chosen weather service.
  5. Run the script from your terminal using python weather_chatbot.py.
  6. You can then ask questions like “What’s the weather in London?” or “Weather for 90210?”.

Further Exploration

You can enhance this weather chatbot by:

  • Integrating with a robust weather API for accurate and detailed information.
  • Adding the ability to get weather forecasts.
  • Handling different units (Celsius, Fahrenheit).
  • Improving the prompt for more natural and informative responses.
  • Adding location detection based on IP address (with user permission).

Explore the Langchain documentation to learn more about its capabilities and how to build more interactive and useful chatbots.

Agentic AI (40) AI Agent (27) airflow (7) Algorithm (29) Algorithms (70) apache (51) apex (5) API (115) Automation (59) Autonomous (48) auto scaling (5) AWS (63) aws bedrock (1) Azure (41) BigQuery (22) bigtable (2) blockchain (3) Career (6) Chatbot (20) cloud (128) cosmosdb (3) cpu (41) cuda (14) Cybersecurity (9) database (121) Databricks (18) Data structure (16) Design (90) dynamodb (9) ELK (2) embeddings (31) emr (3) flink (10) gcp (26) Generative AI (18) gpu (23) graph (34) graph database (11) graphql (4) image (39) indexing (25) interview (7) java (33) json (73) Kafka (31) LLM (48) LLMs (41) Mcp (4) monitoring (109) Monolith (6) mulesoft (4) N8n (9) Networking (14) NLU (5) node.js (14) Nodejs (6) nosql (26) Optimization (77) performance (167) Platform (106) Platforms (81) postgres (4) productivity (20) programming (41) pseudo code (1) python (90) pytorch (19) RAG (54) rasa (5) rdbms (5) ReactJS (1) realtime (2) redis (15) Restful (6) rust (2) salesforce (15) Spark (34) sql (58) tensor (11) time series (18) tips (12) tricks (29) use cases (67) vector (50) vector db (5) Vertex AI (21) Workflow (57)

Leave a Reply