""" DAGI Router Client Sends requests to DAGI Router from Bot Gateway """ import logging import os import time import httpx from typing import Dict, Any logger = logging.getLogger(__name__) # Import metrics try: from metrics import ROUTER_CALLS_TOTAL, ROUTER_LATENCY, ERRORS_TOTAL METRICS_AVAILABLE = True except ImportError: METRICS_AVAILABLE = False # Router configuration from environment ROUTER_BASE_URL = os.getenv("ROUTER_URL", "http://127.0.0.1:9102") ROUTER_TIMEOUT = float(os.getenv("ROUTER_TIMEOUT", "180.0")) async def send_to_router(body: Dict[str, Any]) -> Dict[str, Any]: """Send request to DAGI Router.""" _start = time.time() agent_id = body.get("agent", "devtools") message = body.get("message", "") metadata = body.get("metadata", {}) context = body.get("context", {}) system_prompt = body.get("system_prompt") or context.get("system_prompt") if system_prompt: logger.info(f"Using system prompt ({len(system_prompt)} chars) for agent {agent_id}") infer_url = f"{ROUTER_BASE_URL}/v1/agents/{agent_id}/infer" metadata["agent_id"] = agent_id infer_body = { "prompt": message, "system_prompt": system_prompt, "metadata": metadata } images = context.get("images", []) if images: infer_body["images"] = images logger.info(f"Including {len(images)} image(s) in request") if metadata.get("provider"): infer_body["provider_override"] = metadata["provider"] prov = metadata.get("provider", "default") logger.info(f"Sending to Router ({infer_url}): agent={agent_id}, provider={prov}, has_images={bool(images)}, prompt_len={len(message)}") try: async with httpx.AsyncClient(timeout=ROUTER_TIMEOUT) as client: response = await client.post(infer_url, json=infer_body) response.raise_for_status() result = response.json() latency = time.time() - _start if METRICS_AVAILABLE: ROUTER_CALLS_TOTAL.labels(status="success").inc() ROUTER_LATENCY.observe(latency) logger.info(f"Router response in {latency:.2f}s") return { "ok": True, "data": { "text": result.get("response", result.get("text", "")), "image_base64": result.get("image_base64") }, "response": result.get("response", result.get("text", "")), "model": result.get("model"), "backend": result.get("backend"), "image_base64": result.get("image_base64") } except httpx.TimeoutException as e: if METRICS_AVAILABLE: ROUTER_CALLS_TOTAL.labels(status="timeout").inc() ERRORS_TOTAL.labels(type="timeout", source="router").inc() logger.error(f"Router request timeout after {time.time() - _start:.2f}s: {e}") raise except httpx.HTTPError as e: if METRICS_AVAILABLE: ROUTER_CALLS_TOTAL.labels(status="error").inc() ERRORS_TOTAL.labels(type="http_error", source="router").inc() logger.error(f"Router request failed: {e}") raise