Let’s build something real—an AI assistant that can fetch weather updates, crunch numbers, and even share fun facts on demand. No fluff, just practical steps to create a multi-tool LangChain agent from scratch.
What We’re Building
A single AI assistant that can:
- Fetch live weather for any city
- Solve math problems
- Combine both seamlessly in one response
- (Bonus) Share interesting trivia about places
Think of it like a Swiss Army knife for queries—handling layered requests without breaking a sweat.
Setup: Tools You’ll Need
First, grab these libraries:
bash
Copy
Download
pip install langchain openai requests python-dotenv
Protip: Store your OpenAI API key in a .env file—never hardcode secrets.
Step 1: Build the Weather Fetcher
We’ll use OpenWeatherMap’s free API. Get your API key here.
python
Copy
Download
import requests
from langchain.tools import Tool
def get_weather(city: str) -> str:
api_key = “your_api_key” # Load this from environment variables!
url = f”https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric”
try:
response = requests.get(url)
data = response.json()
if response.status_code == 200:
temp = data[‘main’][‘temp’]
condition = data[‘weather’][0][‘description’]
return f”It’s {condition} in {city} right now, with a temperature of {temp}°C.”
return f”Error: {data.get(‘message’, ‘City not found’)}”
except Exception as e:
return f”Oops—weather service failed: {e}”
weather_tool = Tool(
name=”WeatherLookup”,
func=get_weather,
description=”Fetches current weather for a city. Input format: ‘city_name'”
)
Test it:
python
Copy
Download
print(get_weather(“Tokyo”)) # Should return today’s weather in Tokyo
Step 2: Add a Math Solver
For safe expression evaluation, we’ll use numexpr (install with pip install numexpr):
python
Copy
Download
import numexpr
def calculate(expression: str) -> str:
try:
result = numexpr.evaluate(expression)
return f”The answer to ‘{expression}’ is {result}.”
except Exception as e:
return f”Math error: {e}”
math_tool = Tool(
name=”MathWizard”,
func=calculate,
description=”Solves math expressions. Inputs like ‘3 * (4 + 5)'”
)
Try it:
python
Copy
Download
print(calculate(“2 ** 10 + 5”)) # Outputs “The answer to ‘2 ** 10 + 5’ is 1029.0.”
Step 3: Wire Up the Agent
Now, let’s make these tools work together using OpenAI’s model as the “brain”:
python
Copy
Download
from langchain.llms import OpenAI
from langchain.agents import initialize_agent
llm = OpenAI(model=”gpt-3.5-turbo-instruct”, temperature=0) # Less randomness for precision
agent = initialize_agent(
tools=[weather_tool, math_tool],
llm=llm,
agent=”zero-shot-react-description”, # Good for general-purpose tasks
verbose=True # Shows the agent’s thought process (helpful for debugging)
)
Step 4: Test with Real-World Queries
Example 1:
python
Copy
Download
response = agent.run(“What’s the weather in Berlin right now, and what’s 15% of 200?”)
print(response)
Sample output:
“It’s partly cloudy in Berlin with a temperature of 14°C. 15% of 200 is 30.”
Example 2 (Edge Case):
python
Copy
Download
agent.run(“If it’s 25°C in Rome, how much hotter is that than 77°F?”)
The agent should:
- Convert 77°F to °C (~25°C)
- Return “Both temperatures are nearly identical!”
Bonus: Add City Trivia
Make your assistant more engaging:
python
Copy
Download
def city_fact(city: str) -> str:
facts = {
“Rome”: “Rome has more fountains than any other city on Earth—over 2,000!”,
“Dubai”: “The Burj Khalifa’s elevator travels at 10 meters per second.”,
“Tokyo”: “Tokyo’s Shinjuku Station handles 3 million passengers daily.”
}
return facts.get(city, f”No fun facts for {city}, but it’s probably cool!”)
funfact_tool = Tool(
name=”CityExpert”,
func=city_fact,
description=”Shares a fun fact about a city. Input format: ‘city_name'”
)
# Update the agent:
agent = initialize_agent(
tools=[weather_tool, math_tool, funfact_tool],
llm=llm,
agent=”zero-shot-react-description”
)
Now try:
python
Copy
Download
agent.run(“Tell me about the weather in Dubai and share something interesting.”)
Output:
“It’s sunny in Dubai with a temperature of 33°C. Fun fact: The Burj Khalifa’s elevator travels at 10 meters per second!”
Under the Hood: How the Agent Works
- Decodes the query – Identifies needed tasks (e.g., “weather” + “math”).
- Picks tools – Chooses WeatherLookup for cities, MathWizard for calculations.
- Merges results – Combines answers naturally instead of robotic bullet points.
Where to Take This Next
- Add error recovery – If weather API fails, suggest “Try again in 5 minutes.”
- Support file uploads – Use Tool to analyze CSV data.
- Voice input – Integrate with Whisper for spoken queries.
This is the magic of LangChain—you’re not just calling APIs, you’re building an AI that reasons about which tools to use and how to combine them. Now go break it (then fix it)!