|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import random |
| 5 | +from datetime import datetime, timezone |
| 6 | +from typing import Annotated |
| 7 | + |
| 8 | +from agent_framework import ChatAgent |
| 9 | +from agent_framework.observability import create_resource, enable_instrumentation |
| 10 | +from agent_framework.openai import OpenAIChatClient |
| 11 | +from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider |
| 12 | +from azure.monitor.opentelemetry import configure_azure_monitor |
| 13 | +from dotenv import load_dotenv |
| 14 | +from pydantic import Field |
| 15 | +from rich import print |
| 16 | +from rich.logging import RichHandler |
| 17 | + |
| 18 | +# Setup logging |
| 19 | +handler = RichHandler(show_path=False, rich_tracebacks=True, show_level=False) |
| 20 | +logging.basicConfig(level=logging.WARNING, handlers=[handler], force=True, format="%(message)s") |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | +logger.setLevel(logging.INFO) |
| 23 | + |
| 24 | +# Configure OpenTelemetry export to Azure Application Insights |
| 25 | +load_dotenv(override=True) |
| 26 | +configure_azure_monitor( |
| 27 | + connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"], |
| 28 | + resource=create_resource(), |
| 29 | + enable_live_metrics=True, |
| 30 | +) |
| 31 | +enable_instrumentation(enable_sensitive_data=True) |
| 32 | +logger.info("Azure Application Insights export enabled") |
| 33 | + |
| 34 | +# Configure OpenAI client based on environment |
| 35 | +API_HOST = os.getenv("API_HOST", "github") |
| 36 | + |
| 37 | +async_credential = None |
| 38 | +if API_HOST == "azure": |
| 39 | + async_credential = DefaultAzureCredential() |
| 40 | + token_provider = get_bearer_token_provider(async_credential, "https://cognitiveservices.azure.com/.default") |
| 41 | + client = OpenAIChatClient( |
| 42 | + base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT']}/openai/v1/", |
| 43 | + api_key=token_provider, |
| 44 | + model_id=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"], |
| 45 | + ) |
| 46 | +elif API_HOST == "github": |
| 47 | + client = OpenAIChatClient( |
| 48 | + base_url="https://models.github.ai/inference", |
| 49 | + api_key=os.environ["GITHUB_TOKEN"], |
| 50 | + model_id=os.getenv("GITHUB_MODEL", "openai/gpt-5-mini"), |
| 51 | + ) |
| 52 | +else: |
| 53 | + client = OpenAIChatClient( |
| 54 | + api_key=os.environ["OPENAI_API_KEY"], model_id=os.environ.get("OPENAI_MODEL", "gpt-5-mini") |
| 55 | + ) |
| 56 | + |
| 57 | + |
| 58 | +def get_weather( |
| 59 | + city: Annotated[str, Field(description="City name, spelled out fully")], |
| 60 | +) -> dict: |
| 61 | + """Returns weather data for a given city, a dictionary with temperature and description.""" |
| 62 | + logger.info(f"Getting weather for {city}") |
| 63 | + weather_options = [ |
| 64 | + {"temperature": 72, "description": "Sunny"}, |
| 65 | + {"temperature": 60, "description": "Rainy"}, |
| 66 | + {"temperature": 55, "description": "Cloudy"}, |
| 67 | + {"temperature": 45, "description": "Windy"}, |
| 68 | + ] |
| 69 | + return random.choice(weather_options) |
| 70 | + |
| 71 | + |
| 72 | +def get_current_time( |
| 73 | + timezone_name: Annotated[str, Field(description="Timezone name, e.g. 'US/Eastern', 'Asia/Tokyo', 'UTC'")], |
| 74 | +) -> str: |
| 75 | + """Returns the current date and time in UTC (timezone_name is for display context only).""" |
| 76 | + logger.info(f"Getting current time for {timezone_name}") |
| 77 | + now = datetime.now(timezone.utc) |
| 78 | + return f"The current time in {timezone_name} is approximately {now.strftime('%Y-%m-%d %H:%M:%S')} UTC" |
| 79 | + |
| 80 | + |
| 81 | +agent = ChatAgent( |
| 82 | + name="weather-time-agent", |
| 83 | + chat_client=client, |
| 84 | + instructions="You are a helpful assistant that can look up weather and time information.", |
| 85 | + tools=[get_weather, get_current_time], |
| 86 | +) |
| 87 | + |
| 88 | + |
| 89 | +async def main(): |
| 90 | + response = await agent.run("What's the weather in Seattle and what time is it in Tokyo?") |
| 91 | + print(response.text) |
| 92 | + |
| 93 | + if async_credential: |
| 94 | + await async_credential.close() |
| 95 | + |
| 96 | + |
| 97 | +if __name__ == "__main__": |
| 98 | + asyncio.run(main()) |
0 commit comments