Create a weather assistant that can fetch weather data:
import asynciofrom typing import Annotatedfrom autogen_agentchat.agents import AssistantAgentfrom autogen_agentchat.ui import Consolefrom autogen_ext.models.openai import OpenAIChatCompletionClient# Define a custom tooldef get_weather( location: Annotated[str, "The city name, e.g., 'San Francisco'"],) -> str: """Get the current weather for a location.""" # In a real application, this would call a weather API return f"The weather in {location} is sunny with a temperature of 72°F."def get_forecast( location: Annotated[str, "The city name"], days: Annotated[int, "Number of days for forecast"] = 3,) -> str: """Get weather forecast for multiple days.""" return f"{days}-day forecast for {location}: Sunny, Cloudy, Rainy"async def main() -> None: model_client = OpenAIChatCompletionClient(model="gpt-4o") # Create agent with tools agent = AssistantAgent( "weather_assistant", model_client=model_client, system_message="You are a helpful weather assistant. Use the tools to provide accurate weather information.", tools=[get_weather, get_forecast], model_client_stream=True, ) # Test the agent await Console( agent.run_stream(task="What's the weather like in San Francisco?") ) await Console( agent.run_stream(task="Can you give me a 5-day forecast for Seattle?") ) await model_client.close()asyncio.run(main())
---------- weather_assistant ----------[Calling get_weather(location='San Francisco')...][Tool result: The weather in San Francisco is sunny with a temperature of 72°F.]The weather in San Francisco is currently sunny with a temperature of 72°F.---------- weather_assistant ----------[Calling get_forecast(location='Seattle', days=5)...][Tool result: 5-day forecast for Seattle: Sunny, Cloudy, Rainy]Here's the 5-day forecast for Seattle: Sunny, Cloudy, Rainy
def tool_name( param1: Annotated[type, "description"], param2: Annotated[type, "description"] = default_value,) -> str: """Tool description that helps the LLM understand when to use it.""" # Implementation return result