File size: 14,116 Bytes
42bba47 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 |
#!/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))
|