This article demonstrates how to create a simple chatbot 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 (LLMs) and a simple custom tool to achieve this.
Prerequisites
- Python 3.6+
- Langchain Library: Install using
pip install langchain
- OpenAI API 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
llm = 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
- Import Libraries: We import necessary libraries from Langchain (for the LLM and agent creation) and
os
for environment variables. - Set OpenAI API Key: Ensure you replace
"YOUR_OPENAI_API_KEY"
with your actual OpenAI API key. - Initialize Language Model: We initialize a
ChatOpenAI
model (gpt-3.5-turbo
) with atemperature
of 0. - 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 likerequests
. It currently provides hardcoded responses for “Rogers, AR”, “72758”, “New York, NY”, and “10001”. - Define the Tool (`@tool` decorator): The
get_current_weather
function is decorated with@tool
, making it accessible to the Langchain agent. It takes alocation
(city name or zip code) as input and uses our_get_weather
function to get the weather information. - Create Tools List: We create a list containing our
get_current_weather
tool. - 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. - 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
- Save the code as a Python file (e.g.,
weather_chatbot.py
). - 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). - Replace
"YOUR_OPENAI_API_KEY"
with your actual OpenAI API key. - 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. - Run the script from your terminal using
python weather_chatbot.py
. - 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.
Leave a Reply