3
Weather Bot Agent
BeginnerLearn data processing, tool coordination, and structured output formatting with a weather information bot.
What You'll Learn
Data Processing
Handle structured data and dictionaries
Tool Coordination
Multiple tools working together
Output Formatting
Convert data into readable reports
Error Handling
Graceful handling of missing data
Basic Weather Bot
1from connectonion import Agent
2
3def get_weather(city: str) -> dict:
4 """Get weather information for a city."""
5 # Simulated weather data
6 weather_db = {
7 "new york": {"temp": 72, "condition": "sunny", "humidity": 45},
8 "london": {"temp": 65, "condition": "cloudy", "humidity": 80},
9 "tokyo": {"temp": 78, "condition": "partly cloudy", "humidity": 55}
10 }
11
12 city_lower = city.lower()
13 if city_lower in weather_db:
14 return weather_db[city_lower]
15 return {"error": f"Weather data not available for {city}"}
16
17def format_weather(weather_data: dict) -> str:
18 """Format weather information nicely."""
19 if "error" in weather_data:
20 return weather_data["error"]
21
22 return f"""Weather Report:
23🌡️ Temperature: {weather_data['temp']}°F
24☁️ Condition: {weather_data['condition']}
25💧 Humidity: {weather_data['humidity']}%"""
26
27# Create weather agent
28agent = Agent(
29 name="weather_bot",
30 tools=[get_weather, format_weather]
31)
32
33response = agent.input("What's the weather like in Tokyo?")
34print(response)
Complete Weather Bot
1# weather_bot.py
2import os
3from connectonion import Agent
4from typing import Dict, Any
5
6# Set your OpenAI API key
7os.environ['OPENAI_API_KEY'] = 'your-api-key-here'
8
9def get_weather(city: str) -> Dict[str, Any]:
10 """Get current weather information for a specific city."""
11 # In a real application, you'd use a weather API like OpenWeatherMap
12 # For this demo, we use simulated data
13 weather_database = {
14 "new york": {
15 "temp": 72, "condition": "sunny", "humidity": 45,
16 "wind": "5 mph", "pressure": "30.1 inHg"
17 },
18 "london": {
19 "temp": 65, "condition": "cloudy", "humidity": 80,
20 "wind": "12 mph", "pressure": "29.8 inHg"
21 },
22 "tokyo": {
23 "temp": 78, "condition": "partly cloudy", "humidity": 55,
24 "wind": "8 mph", "pressure": "30.0 inHg"
25 },
26 "paris": {
27 "temp": 68, "condition": "rainy", "humidity": 85,
28 "wind": "15 mph", "pressure": "29.7 inHg"
29 },
30 "sydney": {
31 "temp": 82, "condition": "sunny", "humidity": 40,
32 "wind": "10 mph", "pressure": "30.2 inHg"
33 }
34 }
35
36 city_key = city.lower().strip()
37 if city_key in weather_database:
38 return weather_database[city_key]
39
40 return {"error": f"Weather data not available for {city}. Available cities: {', '.join(weather_database.keys()).title()}"}
41
42def format_weather_report(weather_data: Dict[str, Any]) -> str:
43 """Format weather data into a nice readable report."""
44 if "error" in weather_data:
45 return f"❌ {weather_data['error']}"
46
47 # Create a formatted weather report
48 report = f"""🌤️ Weather Report
49
50🌡️ Temperature: {weather_data['temp']}°F
51☁️ Condition: {weather_data['condition'].title()}
52💧 Humidity: {weather_data['humidity']}%
53💨 Wind: {weather_data['wind']}
54🌀 Pressure: {weather_data['pressure']}"""
55
56 return report
57
58def get_available_cities() -> str:
59 """Get list of cities with available weather data."""
60 cities = ["New York", "London", "Tokyo", "Paris", "Sydney"]
61 return f"🌍 Available cities: {', '.join(cities)}"
62
63def compare_weather(city1: str, city2: str) -> str:
64 """Compare weather between two cities."""
65 weather1 = get_weather(city1)
66 weather2 = get_weather(city2)
67
68 if "error" in weather1:
69 return f"❌ Could not get weather for {city1}: {weather1['error']}"
70 if "error" in weather2:
71 return f"❌ Could not get weather for {city2}: {weather2['error']}"
72
73 temp_diff = weather1['temp'] - weather2['temp']
74 humidity_diff = weather1['humidity'] - weather2['humidity']
75
76 comparison = f"""🔄 Weather Comparison: {city1.title()} vs {city2.title()}
77
78🌡️ Temperature:
79 • {city1.title()}: {weather1['temp']}°F
80 • {city2.title()}: {weather2['temp']}°F
81 • Difference: {abs(temp_diff)}°F {'warmer' if temp_diff > 0 else 'cooler'} in {city1.title() if temp_diff > 0 else city2.title()}
82
83☁️ Conditions:
84 • {city1.title()}: {weather1['condition'].title()}
85 • {city2.title()}: {weather2['condition'].title()}
86
87💧 Humidity:
88 • {city1.title()}: {weather1['humidity']}%
89 • {city2.title()}: {weather2['humidity']}%
90 • Difference: {abs(humidity_diff)}% {'more humid' if humidity_diff > 0 else 'less humid'} in {city1.title() if humidity_diff > 0 else city2.title()}"""
91
92 return comparison
93
94# Create the weather bot agent
95agent = Agent(
96 name="weather_bot",
97 system_prompt="""You are a helpful weather assistant. You can:
98 1. Get weather information for specific cities
99 2. Format weather reports in a nice, readable way
100 3. Compare weather between two cities
101 4. Show available cities
102
103 Always be friendly and provide useful weather information!""",
104 tools=[get_weather, format_weather_report, get_available_cities, compare_weather]
105)
106
107if __name__ == "__main__":
108 print("=== Weather Bot Demo ===\n")
109
110 # Test various weather queries
111 test_queries = [
112 "What's the weather like in Tokyo?",
113 "Show me available cities",
114 "Compare the weather in New York and London",
115 "What's the weather in Miami?", # This will show error handling
116 "Get weather for Paris"
117 ]
118
119 for i, query in enumerate(test_queries, 1):
120 print(f"Query {i}: {query}")
121 response = agent.input(query)
122 print(f"Response: {response}\n")
123 print("-" * 60)
Expected Output
=== Weather Bot Demo === Query 1: What's the weather like in Tokyo? Response: 🌤️ Weather Report 🌡️ Temperature: 78°F ☁️ Condition: Partly Cloudy 💧 Humidity: 55% 💨 Wind: 8 mph 🌀 Pressure: 30.0 inHg Query 2: Compare the weather in New York and London Response: 🔄 Weather Comparison: New York vs London 🌡️ Temperature: • New York: 72°F • London: 65°F • Difference: 7°F warmer in New York ☁️ Conditions: • New York: Sunny • London: Cloudy
Tool Coordination
🔄 Data Flow
get_weather() → format_weather_report() creates a seamless data pipeline.
🎯 Smart Selection
Agent automatically chooses which tools to use based on user questions.
📊 Structured Output
Raw data gets transformed into beautiful, readable weather reports.
Advanced Features
🌍 Multi-City Support
New York, London, Tokyo, Paris, Sydney weather data available
🔄 Weather Comparison
Side-by-side comparison between any two cities
❌ Error Handling
Graceful handling of cities not in database
Try It Yourself
Download Complete Example
Ready-to-run weather bot with multiple cities and comparison features