Files
microdao-daarion/gateway-bot/router_client.py
Apple ef3473db21 snapshot: NODE1 production state 2026-02-09
Complete snapshot of /opt/microdao-daarion/ from NODE1 (144.76.224.179).
This represents the actual running production code that has diverged
significantly from the previous main branch.

Key changes from old main:
- Gateway (http_api.py): expanded from ~40KB to 164KB with full agent support
- Router: new /v1/agents/{id}/infer endpoint with vision + DeepSeek routing
- Behavior Policy: SOWA v2.2 (3-level: FULL/ACK/SILENT)
- Agent Registry: config/agent_registry.yml as single source of truth
- 13 agents configured (was 3)
- Memory service integration
- CrewAI teams and roles

Excluded from snapshot: venv/, .env, data/, backups, .tgz archives

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-09 08:46:46 -08:00

98 lines
3.2 KiB
Python

"""
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