Skip to content

Instantly share code, notes, and snippets.

@bizrockman
Created July 21, 2024 12:14
Show Gist options
  • Save bizrockman/82c9d4ff2c9c7e8c0924d634117380ed to your computer and use it in GitHub Desktop.
Save bizrockman/82c9d4ff2c9c7e8c0924d634117380ed to your computer and use it in GitHub Desktop.
AutoGen - Eigener Agent
import autogen
from autogen import AssistantAgent, runtime_logging
from typing import Dict, List, Optional
import requests
sys_msg = """You are a weather reporter who provides a short weather report for a given city.
Make your response short. ONLY the weather information. Noting more. NO excuses, that you can only talk about the
weather. Do not make an introduction. Just start with the weather information.
If no city is provided, tell the user that you need a city name. But you will generate a weather report for the city
Berlin instead.
Beende deine Eingabe mit dem Wort TERMINATE.
"""
class WeatherAgent(AssistantAgent):
def __init__(self, openweath_api_key, **kwargs):
self.weather_api_key = openweath_api_key
super().__init__(
name="Weather Reporter",
system_message=sys_msg,
**kwargs,
)
self.register_reply(AssistantAgent, self._generate_weather_report())
def _get_current_weather(self, city_name):
# URL and parameters for the OpenWeatherMap API
base_url = "https://api.openweathermap.org/data/2.5/weather?"
complete_url = f"{base_url}q={city_name}&appid={self.weather_api_key}"
# Make a request to the API
response = requests.get(complete_url)
weather_data = response.json()
if weather_data['cod'] != 200:
return f"Error: {weather_data['message']}"
# Extracting weather information
weather = weather_data['weather'][0]['description']
temperature = weather_data['main']['temp'] - 273.15 # Convert from Kelvin to Celsius
return weather, temperature
def _generate_weather_report(
self,
messages: Optional[List[Dict]] = None,
sender: Optional[AssistantAgent] = None,
config=None,
):
city_check_msg = [{'content': 'Prüfen ob der User eine Stadt genannt hat und gibt den Namen dieser Stadt als '
'Antwort zurück. Falls nein, schreibe "Keine Stadt"', 'role': 'user'}]
final, city_response = self.generate_oai_reply(city_check_msg, config)
if "Keine Stadt" in city_response:
city_response = "Berlin"
weather = self._get_current_weather(city_response)
messages = [{
'content': f"Bitte erstelle einen kurzen Wetterbericht für die Stadt {city_response}. Das Wetter ist "
f"{weather}. Keine Erläuterungen NUR den Wetterbericht.",
'role': 'system'}]
final, response = self.generate_oai_reply(messages, config)
...
return True, response
if __name__ == "__main__":
import os
from autogen import UserProxyAgent
os.environ["AUTOGEN_USE_DOCKER"] = "False"
config_list = [
{
"model": "gpt-4o",
"api_key": "sk-..."
}
]
llm_config = {
"config_list": config_list,
"cache_seed": None
}
user_proxy = UserProxyAgent(
name="user_proxy",
is_termination_msg=lambda msg: "TERMINATE" in msg["content"],
human_input_mode="TERMINATE",
)
#autogen.runtime_logging.start()
weather_reporter = WeatherAgent(
openweath_api_key="<API_KEY>",
llm_config=llm_config)
user_proxy.initiate_chat(weather_reporter, message="Wie ist das Wetter heute in Hamburg?")
#autogen.runtime_logging.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment