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