|
| 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 configure_otel_providers |
| 10 | +from agent_framework.openai import OpenAIChatClient |
| 11 | +from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider |
| 12 | +from dotenv import load_dotenv |
| 13 | +from pydantic import Field |
| 14 | +from rich import print |
| 15 | +from rich.logging import RichHandler |
| 16 | + |
| 17 | +# Configura logging |
| 18 | +handler = RichHandler(show_path=False, rich_tracebacks=True, show_level=False) |
| 19 | +logging.basicConfig(level=logging.WARNING, handlers=[handler], force=True, format="%(message)s") |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | +logger.setLevel(logging.INFO) |
| 22 | + |
| 23 | +# Configura la exportación de OpenTelemetry al Aspire Dashboard (si el endpoint está configurado) |
| 24 | +otlp_endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT") |
| 25 | +if otlp_endpoint: |
| 26 | + os.environ.setdefault("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc") |
| 27 | + os.environ.setdefault("OTEL_SERVICE_NAME", "agent-framework-demo") |
| 28 | + configure_otel_providers(enable_sensitive_data=True) |
| 29 | + logger.info(f"Exportación OpenTelemetry habilitada — enviando a {otlp_endpoint}") |
| 30 | +else: |
| 31 | + logger.info( |
| 32 | + "Configura OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 en .env" |
| 33 | + " para exportar telemetría al Aspire Dashboard" |
| 34 | + ) |
| 35 | + |
| 36 | +# Configura el cliente para usar Azure OpenAI, GitHub Models u OpenAI |
| 37 | +load_dotenv(override=True) |
| 38 | +API_HOST = os.getenv("API_HOST", "github") |
| 39 | + |
| 40 | +async_credential = None |
| 41 | +if API_HOST == "azure": |
| 42 | + async_credential = DefaultAzureCredential() |
| 43 | + token_provider = get_bearer_token_provider(async_credential, "https://cognitiveservices.azure.com/.default") |
| 44 | + client = OpenAIChatClient( |
| 45 | + base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT']}/openai/v1/", |
| 46 | + api_key=token_provider, |
| 47 | + model_id=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"], |
| 48 | + ) |
| 49 | +elif API_HOST == "github": |
| 50 | + client = OpenAIChatClient( |
| 51 | + base_url="https://models.github.ai/inference", |
| 52 | + api_key=os.environ["GITHUB_TOKEN"], |
| 53 | + model_id=os.getenv("GITHUB_MODEL", "openai/gpt-5-mini"), |
| 54 | + ) |
| 55 | +else: |
| 56 | + client = OpenAIChatClient( |
| 57 | + api_key=os.environ["OPENAI_API_KEY"], model_id=os.environ.get("OPENAI_MODEL", "gpt-5-mini") |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +def get_weather( |
| 62 | + city: Annotated[str, Field(description="City name, spelled out fully")], |
| 63 | +) -> dict: |
| 64 | + """Devuelve datos meteorológicos para una ciudad: temperatura y descripción.""" |
| 65 | + logger.info(f"Obteniendo el clima para {city}") |
| 66 | + weather_options = [ |
| 67 | + {"temperature": 22, "description": "Soleado"}, |
| 68 | + {"temperature": 15, "description": "Lluvioso"}, |
| 69 | + {"temperature": 13, "description": "Nublado"}, |
| 70 | + {"temperature": 7, "description": "Ventoso"}, |
| 71 | + ] |
| 72 | + return random.choice(weather_options) |
| 73 | + |
| 74 | + |
| 75 | +def get_current_time( |
| 76 | + timezone_name: Annotated[ |
| 77 | + str, Field(description="Timezone name, e.g. 'US/Eastern', 'America/Mexico_City', 'UTC'") |
| 78 | + ], |
| 79 | +) -> str: |
| 80 | + """Devuelve la fecha y hora actual en UTC (timezone_name es solo para contexto de visualización).""" |
| 81 | + logger.info(f"Obteniendo la hora actual para {timezone_name}") |
| 82 | + now = datetime.now(timezone.utc) |
| 83 | + return f"La hora actual en {timezone_name} es aproximadamente {now.strftime('%Y-%m-%d %H:%M:%S')} UTC" |
| 84 | + |
| 85 | + |
| 86 | +agent = ChatAgent( |
| 87 | + name="weather-time-agent", |
| 88 | + chat_client=client, |
| 89 | + instructions="Eres un asistente útil que puede consultar información del clima y la hora.", |
| 90 | + tools=[get_weather, get_current_time], |
| 91 | +) |
| 92 | + |
| 93 | + |
| 94 | +async def main(): |
| 95 | + response = await agent.run("¿Cómo está el clima en Ciudad de México y qué hora es en Buenos Aires?") |
| 96 | + print(response.text) |
| 97 | + |
| 98 | + if async_credential: |
| 99 | + await async_credential.close() |
| 100 | + |
| 101 | + |
| 102 | +if __name__ == "__main__": |
| 103 | + asyncio.run(main()) |
0 commit comments