darkfrostx commited on
Commit
d47ae8b
·
verified ·
1 Parent(s): ffaceb6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -72
app.py CHANGED
@@ -1,97 +1,61 @@
1
  from fastapi import FastAPI
2
- from pydantic import BaseModel, Field, confloat
3
  from typing import Dict, Any, List, Literal
4
  from datetime import datetime
5
- import os
6
-
7
- # Optional tracing: initialize ONLY if key exists (won't crash if missing)
8
- TRACING = False
9
- try:
10
- if os.getenv("TRACELOOP_API_KEY"):
11
- from traceloop.sdk import Traceloop
12
- from traceloop.sdk.decorators import workflow
13
- Traceloop.init(app_name="ssra-auditor")
14
- TRACING = True
15
- except Exception:
16
- TRACING = False
17
-
18
- # Guardrails: schema guard only (semantic validators optional)
19
- from guardrails import Guard
20
 
21
  app = FastAPI()
22
 
23
  class Metrics(BaseModel):
24
- TCS: confloat(ge=0, le=1) = 0.0
25
  HDI: float = 0.0
26
- PDS: confloat(ge=0, le=1) = 0.0
27
  EVI: int = 0
28
- CBS: confloat(ge=0, le=1) = 0.0
29
- LQS: confloat(ge=0, le=1) = 0.0
30
 
31
  class AuditResult(BaseModel):
32
  metrics: Metrics
33
  decision: Literal['APPROVE','REWORK']
34
- # Pydantic v2 uses min_length/max_length instead of v1's conlist(min_items)
35
- deltas: List[str] = Field(default_factory=list, min_length=0)
36
-
37
- AUDIT_SCHEMA = {
38
- "type": "object",
39
- "properties": {
40
- "decision": {"type":"string","enum":["APPROVE","REWORK"]},
41
- "metrics": {"type":"object"},
42
- "deltas": {"type":"array","items":{"type":"string"}}
43
- },
44
- "required": ["decision","metrics","deltas"]
45
- }
46
- guard = Guard().configure(output_schema=AUDIT_SCHEMA)
47
- # Pydantic v2 migration: min_items → min_length etc. :contentReference[oaicite:1]{index=1}
48
 
49
  @app.get("/health")
50
  def health():
51
- return {"ok": True, "service": "auditor", "ts": datetime.utcnow().isoformat(), "tracing": TRACING}
52
-
53
- def _audit_logic(payload: Dict[str, Any]) -> AuditResult:
54
- bundle = payload.get("bundle", {}) or {}
55
- m_in = payload.get("metrics", {}) or {}
56
-
57
- m = {
58
- "TCS": float(m_in.get("TCS", 0.0)),
59
- "HDI": float(m_in.get("HDI", 0.0)),
60
- "PDS": float(m_in.get("PDS", 0.0)),
61
- "EVI": int(m_in.get("EVI", 0)),
62
- "CBS": float(m_in.get("CBS", 0.0)),
63
- "LQS": float(m_in.get("LQS", 0.0)),
64
- }
 
 
65
 
66
  edges = len(bundle.get("network",{}).get("data",[]) or [])
67
  regions = len((bundle.get("regions",{}).get("data") or {}).get("regions_ranked",[]) or [])
68
  lit_ok = bool(bundle.get("literature"))
69
 
70
- m["TCS"] = min(1.0, (1 if edges>0 else 0) + (1 if regions>0 else 0) + (1 if lit_ok else 0)) * 0.9
71
- m["HDI"] = 1.2 if regions>8 else (1.0 if regions>4 else 0.8)
72
- m["EVI"] = (1 if edges>0 else 0) + (1 if regions>0 else 0) + (1 if lit_ok else 0)
73
- m["CBS"] = max(0.2, m["CBS"])
74
- m["LQS"] = max(0.6, m["LQS"])
 
 
75
 
76
- decision: Literal['APPROVE','REWORK'] = 'APPROVE'
77
  deltas: List[str] = []
78
- if (m["HDI"] < 1.0) or (m["EVI"] < 3) or (m["CBS"] > 0.6):
79
- decision = 'REWORK'
80
- if m["HDI"] < 1.0: deltas.append("Increase hypothesis diversity (broaden regions).")
81
- if m["EVI"] < 3: deltas.append("Add one more evidence type (review/trials).")
82
- if m["CBS"] > 0.6: deltas.append("Surface/address contrary findings explicitly.")
83
 
84
- out_raw = {"metrics": m, "decision": decision, "deltas": deltas}
85
- _, validated, *_ = guard.parse(out_raw)
86
- return AuditResult(**validated)
 
 
87
 
88
- if TRACING:
89
- from traceloop.sdk.decorators import workflow
90
- @workflow(name="audit_workflow")
91
- @app.post("/audit", response_model=AuditResult)
92
- def audit(payload: Dict[str, Any]):
93
- return _audit_logic(payload)
94
- else:
95
- @app.post("/audit", response_model=AuditResult)
96
- def audit(payload: Dict[str, Any]):
97
- return _audit_logic(payload)
 
1
  from fastapi import FastAPI
2
+ from pydantic import BaseModel, Field
3
  from typing import Dict, Any, List, Literal
4
  from datetime import datetime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  app = FastAPI()
7
 
8
  class Metrics(BaseModel):
9
+ TCS: float = Field(ge=0.0, le=1.0, default=0.0)
10
  HDI: float = 0.0
11
+ PDS: float = Field(ge=0.0, le=1.0, default=0.0)
12
  EVI: int = 0
13
+ CBS: float = Field(ge=0.0, le=1.0, default=0.0)
14
+ LQS: float = Field(ge=0.0, le=1.0, default=0.0)
15
 
16
  class AuditResult(BaseModel):
17
  metrics: Metrics
18
  decision: Literal['APPROVE','REWORK']
19
+ deltas: List[str] = Field(default_factory=list)
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @app.get("/health")
22
  def health():
23
+ return {"ok": True, "service": "auditor", "ts": datetime.utcnow().isoformat()}
24
+
25
+ @app.post("/audit", response_model=AuditResult)
26
+ def audit(payload: Dict[str, Any]):
27
+ bundle = payload.get("bundle", {})
28
+ m_in = payload.get("metrics", {})
29
+
30
+ # seed metrics from input
31
+ m = Metrics(**{
32
+ "TCS": float(m_in.get("TCS", 0.0)),
33
+ "HDI": float(m_in.get("HDI", 0.0)),
34
+ "PDS": float(m_in.get("PDS", 0.0)),
35
+ "EVI": int(m_in.get("EVI", 0)),
36
+ "CBS": float(m_in.get("CBS", 0.0)),
37
+ "LQS": float(m_in.get("LQS", 0.0)),
38
+ })
39
 
40
  edges = len(bundle.get("network",{}).get("data",[]) or [])
41
  regions = len((bundle.get("regions",{}).get("data") or {}).get("regions_ranked",[]) or [])
42
  lit_ok = bool(bundle.get("literature"))
43
 
44
+ # heuristic patches
45
+ m.TCS = min(1.0, (1 if edges>0 else 0) + (1 if regions>0 else 0) + (1 if lit_ok else 0)) * 0.9
46
+ if regions > 8: m.HDI = max(m.HDI, 1.2)
47
+ elif regions > 4: m.HDI = max(m.HDI, 1.0)
48
+ else: m.HDI = max(m.HDI, 0.8)
49
+ m.EVI = (1 if edges>0 else 0) + (1 if regions>0 else 0) + (1 if lit_ok else 0)
50
+ m.CBS = max(0.2, float(m.CBS))
51
 
 
52
  deltas: List[str] = []
53
+ decision: Literal['APPROVE','REWORK'] = 'APPROVE'
 
 
 
 
54
 
55
+ if (m.HDI < 1.0) or (m.EVI < 3) or (m.CBS > 0.6):
56
+ decision = 'REWORK'
57
+ if m.HDI < 1.0: deltas.append("Increase hypothesis diversity: broaden regions search.")
58
+ if m.EVI < 3: deltas.append("Add at least one more evidence type (e.g., trials or review).")
59
+ if m.CBS > 0.6: deltas.append("Surface and address contrary findings explicitly.")
60
 
61
+ return AuditResult(metrics=m, decision=decision, deltas=deltas)