#!/usr/bin/env python3 """ Agent Gateway for Elizabeth — OpenAI-compatible tool execution proxy. Responsibilities: - Expose OpenAI-compatible endpoints (subset): - POST /v1/chat/completions - GET /v1/models (proxy) - GET /health - GET /v1/tools (registry) - Forward chat requests to vLLM; when tool_calls are returned, execute tools server-side and loop until a final assistant message (no tool_calls) is produced. - Log actions; integrate with existing session store when available. Config (env): - API_KEY: Bearer token to accept (default: elizabeth-secret-key-2025) - VLLM_BASE_URL: Default http://localhost:8000/v1 - PROJECT_DIR: Default /data/adaptai/projects/elizabeth - SECRETS_DIR: Default /data/adaptai/secrets/dataops (optional) - ALLOWED_ROOTS: Colon-separated roots for file operations (default: /data:/data/adaptai/projects/elizabeth) - POSTGRES_DSN, DFLY_URL/REDIS_URL, AWS/R2/HF tokens loaded from SECRETS_DIR if present Run: uvicorn mlops.agent_gateway:app --host 0.0.0.0 --port 15000 """ from __future__ import annotations import json import logging import os import time import uuid import tempfile import subprocess from typing import Any, Dict, List, Optional import requests from fastapi import Depends, FastAPI, Header, HTTPException, Request from fastapi.responses import JSONResponse from .agent_tools.registry import ToolRegistry, load_default_registry from .agent_tools.runtime import ToolRuntime logging.basicConfig(level=logging.INFO) logger = logging.getLogger("agent_gateway") API_KEY = os.getenv("API_KEY", "elizabeth-secret-key-2025") VLLM_BASE_URL = os.getenv("VLLM_BASE_URL", "http://localhost:8000/v1") PROJECT_DIR = os.getenv("PROJECT_DIR", "/data/adaptai/projects/elizabeth") SECRETS_DIR = os.getenv("SECRETS_DIR", "/data/adaptai/secrets/dataops") SLACK_WEBHOOK_RECEIPTS = os.getenv("SLACK_WEBHOOK_RECEIPTS", os.getenv("SLACK_WEBHOOK", "")) ENABLE_RECEIPTS = os.getenv("ENABLE_RECEIPTS", "1") != "0" def _load_secrets_dir(path: str) -> None: """Load secrets from a directory. Supports: - .env-style file named .env (KEY=VALUE lines) - file-per-secret: each file's basename is the KEY, content is the value Does not overwrite existing env variables. """ try: if not path or not os.path.isdir(path): return # .env file first env_path = os.path.join(path, ".env") if os.path.exists(env_path): with open(env_path, "r", encoding="utf-8") as f: for line in f: s = line.strip() if not s or s.startswith("#") or "=" not in s: continue k, v = s.split("=", 1) if k and v and k not in os.environ: os.environ[k] = v # key files for name in os.listdir(path): fp = os.path.join(path, name) if not os.path.isfile(fp) or name == ".env": continue key = name.strip().upper() try: with open(fp, "r", encoding="utf-8") as f: val = f.read().strip() if key and val and key not in os.environ: os.environ[key] = val except Exception: continue except Exception as e: logger.warning("Failed to load secrets from %s: %s", path, e) _load_secrets_dir(SECRETS_DIR) def require_auth(authorization: Optional[str] = Header(None)) -> None: if not authorization or not authorization.lower().startswith("bearer "): raise HTTPException(status_code=401, detail="Unauthorized") token = authorization.split(" ", 1)[1] if token != API_KEY: raise HTTPException(status_code=401, detail="Invalid token") app = FastAPI(title="Elizabeth Agent Gateway") @app.get("/health") def health() -> Dict[str, Any]: try: r = requests.get(f"{VLLM_BASE_URL.rstrip('/')}/health", timeout=3) upstream = r.status_code except Exception: upstream = 0 return {"status": "ok", "upstream": upstream, "project": PROJECT_DIR} @app.get("/v1/models") def list_models(dep: None = Depends(require_auth)) -> JSONResponse: url = f"{VLLM_BASE_URL.rstrip('/')}/models" try: resp = requests.get(url, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=10) return JSONResponse(status_code=resp.status_code, content=resp.json()) except Exception as e: raise HTTPException(status_code=502, detail=f"Upstream error: {e}") @app.get("/v1/tools") def list_tools(dep: None = Depends(require_auth)) -> Dict[str, Any]: reg = load_default_registry() return {"tools": reg.describe_all()} def _post_upstream_chat(payload: Dict[str, Any]) -> Dict[str, Any]: url = f"{VLLM_BASE_URL.rstrip('/')}/chat/completions" headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"} r = requests.post(url, headers=headers, data=json.dumps(payload), timeout=300) if r.status_code >= 400: raise HTTPException(status_code=r.status_code, detail=r.text) return r.json() def _post_upstream_completions(payload: Dict[str, Any]) -> Dict[str, Any]: url = f"{VLLM_BASE_URL.rstrip('/')}/completions" headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"} r = requests.post(url, headers=headers, data=json.dumps(payload), timeout=300) if r.status_code >= 400: raise HTTPException(status_code=r.status_code, detail=r.text) return r.json() def _extract_tool_calls(resp: Dict[str, Any]) -> List[Dict[str, Any]]: try: msg = resp["choices"][0]["message"] return msg.get("tool_calls", []) or [] except Exception: return [] def _append_tool_result(messages: List[Dict[str, Any]], call_id: str, name: str, content: str) -> None: messages.append({ "role": "tool", "tool_call_id": call_id, "name": name, "content": content, }) @app.post("/v1/chat/completions") async def chat_completions(req: Request, dep: None = Depends(require_auth)) -> JSONResponse: try: payload: Dict[str, Any] = await req.json() except Exception: raise HTTPException(status_code=400, detail="Invalid JSON") messages: List[Dict[str, Any]] = payload.get("messages") or [] if not messages: raise HTTPException(status_code=400, detail="messages required") reg: ToolRegistry = load_default_registry() runtime = ToolRuntime(registry=reg, project_dir=PROJECT_DIR) max_loops = int(os.getenv("MAX_TOOL_LOOPS", "8")) summarize_tools = os.getenv("SUMMARIZE_TOOL_RESULTS", "1") != "0" summary_hint = os.getenv( "TOOL_RESULT_SUMMARY_PROMPT", "After executing tools, respond in your own words summarizing what you did and the essential results." ) include_tool_results = os.getenv("INCLUDE_TOOL_RESULTS", "0") == "1" # Loop guard: prevent repeated identical tool calls within a request disallow_repeat_tools = os.getenv("DISALLOW_REPEAT_TOOLS", "1") != "0" max_tool_loops = int(os.getenv("MAX_TOOL_LOOPS_TOTAL", "16")) loop_count = 0 last_resp: Optional[Dict[str, Any]] = None tool_execs: List[Dict[str, Any]] = [] seen_calls: set[tuple] = set() def audit_tool(name: str, args: Dict[str, Any], result: str, duration_sec: float) -> None: try: import time as _t from pathlib import Path as _P log_dir = _P(PROJECT_DIR) / "logs" log_dir.mkdir(parents=True, exist_ok=True) audit_path = log_dir / "tools.jsonl" try: parsed = json.loads(result) except Exception: parsed = {"raw": result[:8000]} rec = { "ts": int(_t.time()), "tool": name, "arguments": args, "result": parsed, "duration_sec": round(duration_sec, 3), } with audit_path.open("a", encoding="utf-8") as f: f.write(json.dumps(rec) + "\n") except Exception: pass total_loops = 0 while True: if total_loops >= max_tool_loops: logger.warning("Global max tool loops exceeded (%s)", max_tool_loops) break loop_count += 1 total_loops += 1 payload["messages"] = messages last_resp = _post_upstream_chat(payload) tool_calls = _extract_tool_calls(last_resp) if not tool_calls: break if loop_count > max_loops: logger.warning("Max tool loops exceeded") break for call in tool_calls: call_id = call.get("id") or f"tool-{int(time.time()*1000)}" fn = call.get("function", {}) name = fn.get("name") args_str = fn.get("arguments") or "{}" try: args = json.loads(args_str) if isinstance(args_str, str) else (args_str or {}) except Exception: args = {"_raw": args_str} # Loop guard: skip repeated identical tool invocations key = (name or "", json.dumps(args, sort_keys=True)) if disallow_repeat_tools and key in seen_calls: logger.info("Skipping repeated tool call: %s args=%s", name, args) continue seen_calls.add(key) logger.info("Executing tool: %s args=%s", name, args) start_t = time.time() result = runtime.execute(name=name or "", arguments=args) dur = time.time() - start_t _append_tool_result(messages, call_id, name or "", result) audit_tool(name or "", args, result, dur) # Collect metadata for caller if requested if include_tool_results: try: parsed = json.loads(result) except Exception: parsed = {"raw": result} tool_execs.append({ "id": call_id, "name": name, "arguments": args, "result": parsed, "duration_sec": round(dur, 3), }) # Nudge the model to produce a human-readable answer based on tool outputs, # without fabricating content. This is a system hint; the response is the LLM's own. if summarize_tools: messages.append({ "role": "system", "content": summary_hint, }) if last_resp is None: # Fallback: get a direct model response without tools try: last_resp = _post_upstream_chat({**payload, "messages": messages}) except Exception: raise HTTPException(status_code=502, detail="Upstream unavailable and no tool response") # If the final assistant content is blank, do one clarifying pass asking the model # to explain what it did with the tool results. This yields an actual LLM response. try: content = (last_resp.get("choices", [{}])[0] .get("message", {}) .get("content", "")) except Exception: content = "" if summarize_tools and (not content or not str(content).strip()): messages.append({ "role": "system", "content": "Your last message was empty. In your own words, summarize what you did with the tool results and provide the answer succinctly.", }) last_resp = _post_upstream_chat({**payload, "messages": messages}) # Attach non-standard metadata if toggled on (keeps OpenAI response intact) # Optionally emit a receipt (and Slack) per turn try: if ENABLE_RECEIPTS: # Use provided ids if present; otherwise generate session_id = payload.get("session_id") or str(uuid.uuid4()) turn_id = payload.get("turn_id") or str(uuid.uuid4()) # Persist tool_execs for the collector with tempfile.NamedTemporaryFile("w", delete=False, suffix=".json") as tf: json.dump({"nova_tool_results": tool_execs}, tf) tools_path = tf.name # Build args for the collector collector = os.path.join(PROJECT_DIR, "scripts", "collect_receipt.py") args = [ "python3", collector, "--type", "turn", "--session-id", session_id, "--turn-id", turn_id, "--persona-score", "0", "--style-div", "0", "--tools-json", tools_path, "--delta-norm", "0", "--lr", "0", "--mask-size-pct", "0", "--notes", f"model={payload.get('model','')}", "--eval-gate-script", os.path.join(PROJECT_DIR, "scripts", "eval_gate.py") ] if SLACK_WEBHOOK_RECEIPTS: args += ["--slack-webhook", SLACK_WEBHOOK_RECEIPTS] subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except Exception: pass if include_tool_results: enriched = dict(last_resp) enriched["nova_tool_results"] = tool_execs return JSONResponse(status_code=200, content=enriched) else: return JSONResponse(status_code=200, content=last_resp) @app.post("/v1/completions") async def text_completions(req: Request, dep: None = Depends(require_auth)) -> JSONResponse: try: payload: Dict[str, Any] = await req.json() except Exception: raise HTTPException(status_code=400, detail="Invalid JSON") try: resp = _post_upstream_completions(payload) return JSONResponse(status_code=200, content=resp) except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=str(e))