Download backend/app.py from zkwr1081/Agent-Observability-Lab: direct link, hf CLI and curl.
- Browser
- Download file 4.71 kB
-
https://huggingface.co/spaces/zkwr1081/Agent-Observability-Lab/resolve/main/backend/app.py
- Command line
-
hf download hf://spaces/zkwr1081/Agent-Observability-Lab/backend/app.py
-
curl -L -o app.py https://huggingface.co/spaces/zkwr1081/Agent-Observability-Lab/resolve/main/backend/app.py
4.71 kB
| from __future__ import annotations | |
| import hmac, json, os, sqlite3, time, uuid | |
| from pathlib import Path | |
| from typing import Literal | |
| from fastapi import FastAPI, Header, HTTPException, Query | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel, Field, ConfigDict | |
| BASE = Path(__file__).resolve().parent | |
| ROOT = BASE.parent | |
| def load_env(path: Path) -> None: | |
| if not path.exists(): return | |
| for line in path.read_text(encoding="utf-8").splitlines(): | |
| if not line or line.lstrip().startswith("#") or "=" not in line: continue | |
| k, v = line.split("=", 1) | |
| os.environ.setdefault(k.strip(), v.strip()) | |
| load_env(ROOT / ".env") | |
| API_KEY = os.environ.get("AGENT_OBS_API_KEY", "") | |
| DB_PATH = os.environ.get("AGENT_OBS_DB", str(BASE / "traces.sqlite3")) | |
| app = FastAPI(title="Agent Observability API", version="1.0.0", docs_url="/api/docs", redoc_url=None) | |
| app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["Content-Type", "X-API-Key"]) | |
| class TraceIn(BaseModel): | |
| model_config = ConfigDict(extra="forbid") | |
| agent_name: str = Field(min_length=1, max_length=120) | |
| status: Literal["success", "error", "timeout"] | |
| duration_ms: int = Field(ge=0, le=86_400_000) | |
| input_tokens: int = Field(default=0, ge=0, le=100_000_000) | |
| output_tokens: int = Field(default=0, ge=0, le=100_000_000) | |
| estimated_cost_usd: float = Field(default=0, ge=0, le=1_000_000) | |
| error_type: str | None = Field(default=None, max_length=160) | |
| request_id: str | None = Field(default=None, max_length=128) | |
| def db(): | |
| con=sqlite3.connect(DB_PATH, timeout=10) | |
| con.row_factory=sqlite3.Row | |
| return con | |
| def init_db(): | |
| Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True) | |
| with db() as c: | |
| c.execute("PRAGMA journal_mode=WAL") | |
| c.execute("""CREATE TABLE IF NOT EXISTS traces ( | |
| id TEXT PRIMARY KEY, created_at INTEGER NOT NULL, agent_name TEXT NOT NULL, | |
| status TEXT NOT NULL, duration_ms INTEGER NOT NULL, input_tokens INTEGER NOT NULL, | |
| output_tokens INTEGER NOT NULL, estimated_cost_usd REAL NOT NULL, | |
| error_type TEXT, request_id TEXT)""") | |
| c.execute("CREATE INDEX IF NOT EXISTS idx_traces_created ON traces(created_at DESC)") | |
| c.execute("CREATE INDEX IF NOT EXISTS idx_traces_agent ON traces(agent_name)") | |
| init_db() | |
| def authorize(x_api_key: str | None): | |
| if not API_KEY: | |
| raise HTTPException(503, "API key is not configured on the server") | |
| if not x_api_key or not hmac.compare_digest(x_api_key, API_KEY): | |
| raise HTTPException(401, "Invalid or missing API key") | |
| def health(): | |
| return {"status":"ok", "service":"agent-observability-api", "version":"1.0.0"} | |
| def ingest_trace(trace: TraceIn, x_api_key: str | None = Header(default=None)): | |
| authorize(x_api_key) | |
| trace_id=str(uuid.uuid4()); now=int(time.time()) | |
| with db() as c: | |
| c.execute("INSERT INTO traces VALUES (?,?,?,?,?,?,?,?,?,?)", ( | |
| trace_id, now, trace.agent_name, trace.status, trace.duration_ms, | |
| trace.input_tokens, trace.output_tokens, trace.estimated_cost_usd, | |
| trace.error_type, trace.request_id)) | |
| return {"accepted":True,"trace_id":trace_id,"created_at":now} | |
| def list_traces(limit: int=Query(100, ge=1, le=500), offset: int=Query(0, ge=0), x_api_key: str | None=Header(default=None)): | |
| authorize(x_api_key) | |
| with db() as c: | |
| rows=c.execute("SELECT * FROM traces ORDER BY created_at DESC LIMIT ? OFFSET ?",(limit,offset)).fetchall() | |
| return {"items":[dict(r) for r in rows],"limit":limit,"offset":offset} | |
| def summary(x_api_key: str | None=Header(default=None)): | |
| authorize(x_api_key) | |
| with db() as c: | |
| row=c.execute("""SELECT COUNT(*) total, | |
| SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) successes, | |
| SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) errors, | |
| SUM(CASE WHEN status='timeout' THEN 1 ELSE 0 END) timeouts, | |
| AVG(duration_ms) avg_duration_ms, | |
| SUM(input_tokens+output_tokens) total_tokens, | |
| SUM(estimated_cost_usd) estimated_cost_usd FROM traces""").fetchone() | |
| d=dict(row) | |
| for k in ("successes","errors","timeouts","total_tokens","estimated_cost_usd"): | |
| d[k]=d[k] or 0 | |
| d["avg_duration_ms"]=round(d["avg_duration_ms"] or 0,2) | |
| d["estimated_cost_usd"]=round(d["estimated_cost_usd"],6) | |
| return d | |
| def home(): | |
| return FileResponse(ROOT / "index.html") | |