forked from QWED-AI/qwed-verification
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1554 lines (1318 loc) · 50.3 KB
/
Copy pathmain.py
File metadata and controls
1554 lines (1318 loc) · 50.3 KB
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi import FastAPI, HTTPException, Depends, Header, UploadFile, File, Form, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, field_validator
from typing import Optional, Annotated
from sqlmodel import Session, select
import os
import logging
from fractions import Fraction
from qwed_new.core.security import redact_pii
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
INTERNAL_VERIFICATION_ERROR = "Internal verification error"
INTERNAL_PROCESSING_ERROR = "Internal processing error"
from qwed_new.core.control_plane import ControlPlane
from qwed_new.core.tenant_context import get_current_tenant, TenantContext
from qwed_new.core.database import create_db_and_tables, get_session
from qwed_new.core.models import VerificationLog, ApiKey, User
from qwed_new.core.rate_limiter import check_rate_limit
# Import auth router
from qwed_new.auth import auth_router
from qwed_new.auth.audit_routes import router as audit_router
from qwed_new.auth.middleware import get_api_key
from qwed_new.auth.routes import get_current_user_token
from qwed_new.auth.security import hash_api_key
TenantDependency = Annotated[TenantContext, Depends(get_current_tenant)]
SessionDependency = Annotated[Session, Depends(get_session)]
AgentTokenHeader = Annotated[str, Header(...)]
APP_VERSION = "5.1.1"
app = FastAPI(
title="QWED API",
description="The Deterministic Verification Protocol for AI",
version=APP_VERSION
)
# CORS - configurable via environment variable
# Default allows all origins for development, restrict in production
raw_cors_origins = os.environ.get("QWED_CORS_ORIGINS", "")
CORS_ORIGINS = [origin.strip() for origin in raw_cors_origins.split(",") if origin.strip()]
if not CORS_ORIGINS:
logger.critical("QWED_CORS_ORIGINS must be configured")
raise RuntimeError("QWED_CORS_ORIGINS must be configured")
app.add_middleware(
CORSMiddleware,
allow_origins=CORS_ORIGINS,
allow_credentials=CORS_ORIGINS != ["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(auth_router)
app.include_router(audit_router)
STARTUP_ALLOWED_PTH_FILES = {
"__editable__.qwed_a2a-0.1.0.pth",
"__editable__.qwed_finance-2.0.1.pth",
"__editable__.qwed_mcp-0.2.0.pth",
"_qwed.pth",
"_qwed_legal.pth",
"_qwed_new.pth",
"_qwed_ucp.pth",
"a1_coverage.pth",
"pywin32.pth",
}
def _get_env_allowlisted_pth_files() -> set[str]:
"""Parse deployment-provided exact startup hook allowlist entries."""
extra = os.environ.get("QWED_ALLOWED_STARTUP_PTH_FILES", "")
return {name.strip() for name in extra.split(",") if name.strip()}
def _get_startup_hook_allowlist() -> set[str]:
"""Return additional expected startup hook files for this deployment."""
allowlist = set(STARTUP_ALLOWED_PTH_FILES)
allowlist.update(_get_env_allowlisted_pth_files())
return allowlist
def _enforce_environment_integrity() -> None:
"""Fail startup if Python startup hooks cannot be verified as safe."""
if os.environ.get("QWED_SKIP_ENV_INTEGRITY_CHECK") == "true":
logger.warning("Bypassing environment integrity check due to QWED_SKIP_ENV_INTEGRITY_CHECK")
return
from qwed_sdk.guards.environment_guard import StartupHookGuard
guard = StartupHookGuard(allowed_pth_files=_get_startup_hook_allowlist())
result = guard.verify_environment_integrity()
if not result.get("verified"):
logger.critical(f"Startup environment integrity check failed: {result}")
raise RuntimeError(f"Environment integrity verification failed: {result.get('risk')}")
@app.on_event("startup")
def on_startup():
_enforce_environment_integrity()
create_db_and_tables()
# Initialize Kernel (Control Plane)
control_plane = ControlPlane()
class VerifyRequest(BaseModel):
query: str
provider: Optional[str] = None
@app.get("/")
async def root():
return {"message": "QWED OS is Running", "version": APP_VERSION}
def get_optional_current_user(
authorization: Optional[str] = Header(None),
session: Session = Depends(get_session),
) -> Optional[User]:
"""Resolve a JWT-authenticated user when present."""
if not authorization:
return None
if not authorization.startswith("Bearer "):
return None
payload = get_current_user_token(authorization)
user_id = payload.get("sub")
if user_id is None:
raise HTTPException(status_code=401, detail="Missing sub claim in token")
try:
user = session.get(User, int(user_id))
except (TypeError, ValueError) as exc:
raise HTTPException(status_code=401, detail="Invalid token subject") from exc
if not user:
raise HTTPException(status_code=401, detail="User not found")
return user
def get_optional_api_key_record(
x_api_key: Optional[str] = Header(None),
session: Session = Depends(get_session),
) -> Optional[ApiKey]:
"""Resolve an API key record when the caller provides x-api-key."""
if not x_api_key:
return None
hashed_key = hash_api_key(x_api_key)
statement = select(ApiKey).where(ApiKey.key_hash == hashed_key, ApiKey.is_active)
api_key = session.execute(statement).scalars().first()
if not api_key:
raise HTTPException(status_code=403, detail="Invalid or revoked API Key")
return api_key
def _has_metrics_admin_role(user: Optional[User]) -> bool:
"""Return True when the user can access global operational metrics."""
return user is not None and user.is_active and user.role in {"owner", "admin"}
def require_metrics_access(
current_user: Annotated[Optional[User], Depends(get_optional_current_user)],
api_key_record: Annotated[Optional[ApiKey], Depends(get_optional_api_key_record)],
session: Annotated[Session, Depends(get_session)],
) -> None:
"""Restrict operational metrics to admin JWT users or admin-linked API keys."""
if _has_metrics_admin_role(current_user):
return
if api_key_record is not None:
api_key_user = session.get(User, api_key_record.user_id) if api_key_record.user_id else None
if _has_metrics_admin_role(api_key_user):
return
raise HTTPException(status_code=403, detail="Admin access required")
if current_user is not None:
raise HTTPException(status_code=403, detail="Admin access required")
raise HTTPException(status_code=401, detail="Authentication required")
@app.post("/verify/natural_language")
async def verify_natural_language(
request: VerifyRequest,
tenant: TenantContext = Depends(get_current_tenant),
session: Session = Depends(get_session)
):
"""
Main entry point: Verifies a natural language math query.
Now routed through the QWED Control Plane with multi-tenancy.
Rate Limits:
- Per API Key: 100 requests/minute
- Global: 1000 requests/minute
"""
# Check rate limits
check_rate_limit(tenant.api_key)
result = await control_plane.process_natural_language(
request.query,
organization_id=tenant.organization_id,
preferred_provider=request.provider
)
# Log request to audit trail
log = VerificationLog(
organization_id=tenant.organization_id,
user_id=tenant.user_id if hasattr(tenant, 'user_id') else None,
query=request.query,
result=str(result),
is_verified=result.get("status") == "VERIFIED",
domain="MATH"
)
session.add(log)
session.commit()
return result
@app.post("/verify/logic")
async def verify_logic(
request: VerifyRequest,
tenant: TenantContext = Depends(get_current_tenant),
session: Session = Depends(get_session)
):
"""
Verifies a logic puzzle.
Now routed through the QWED Control Plane.
Rate Limits:
- Per API Key: 100 requests/minute
- Global: 1000 requests/minute
"""
# Check rate limits
check_rate_limit(tenant.api_key)
try:
result = await control_plane.process_logic_query(
request.query,
organization_id=tenant.organization_id,
preferred_provider=request.provider
)
if result["status"] == "BLOCKED":
raise HTTPException(status_code=403, detail=result["error"])
# Log to database
log = VerificationLog(
organization_id=tenant.organization_id,
query=request.query,
result=str(result),
is_verified=(result["status"] == "SAT" or result["status"] == "UNSAT"),
domain="LOGIC"
)
session.add(log)
session.commit()
return result
except HTTPException:
raise
except Exception as e:
logger.error(f"Logic verification error: {redact_pii(str(e))}", exc_info=False)
response_result = locals().get("result")
provider_used = (
response_result.get("provider_used")
if isinstance(response_result, dict) and response_result.get("provider_used")
else control_plane.router.route(request.query, request.provider)
)
return {
"status": "ERROR",
"error": INTERNAL_VERIFICATION_ERROR,
"provider_used": provider_used,
}
@app.post(
"/verify/stats",
responses={
403: {"description": "Verification blocked by security policy."},
503: {"description": "Secure execution runtime unavailable."},
},
)
async def verify_stats(
file: UploadFile = File(...),
query: str = Form(...),
tenant: TenantContext = Depends(get_current_tenant),
session: Session = Depends(get_session)
):
"""
Verify statistical claims about uploaded data.
Example:
- Upload: sales.csv
- Query: "Did sales increase by 15% this quarter?"
"""
check_rate_limit(tenant.api_key)
try:
import pandas as pd
df = pd.read_csv(file.file)
from qwed_new.core.stats_verifier import StatsVerifier, SECURE_STATS_BLOCKED_CODE
verifier = StatsVerifier()
result = verifier.verify_stats(query, df, provider=None)
if result.get("status") == "BLOCKED" and result.get("error") == SECURE_STATS_BLOCKED_CODE:
raise HTTPException(status_code=503, detail="Service temporarily unavailable")
if result.get("status") == "BLOCKED":
raise HTTPException(status_code=403, detail="Verification blocked by security policy")
log = VerificationLog(
organization_id=tenant.organization_id,
query=query,
result=str(result),
is_verified=(result["status"] == "SUCCESS"),
domain="STATS"
)
session.add(log)
session.commit()
return result
except HTTPException:
raise
except Exception as e:
logger.error(f"Stats verification error: {redact_pii(str(e))}", exc_info=False)
return {
"status": "ERROR",
"error": INTERNAL_PROCESSING_ERROR
}
@app.post("/verify/fact")
async def verify_fact(
request: dict,
tenant: TenantContext = Depends(get_current_tenant),
session: Session = Depends(get_session)
):
"""
Verify a factual claim against a provided context.
Request body:
{
"claim": "The policy covers water damage",
"context": "Policy document text...",
"provider": "anthropic" (optional)
}
"""
check_rate_limit(tenant.api_key)
try:
from qwed_new.core.fact_verifier import FactVerifier
verifier = FactVerifier()
claim = request.get("claim")
context = request.get("context")
provider = request.get("provider")
if not claim or not context:
raise HTTPException(status_code=400, detail="Missing 'claim' or 'context'")
result = verifier.verify_fact(claim, context, provider=provider)
log = VerificationLog(
organization_id=tenant.organization_id,
query=claim,
result=str(result),
is_verified=(result.get("verdict") == "SUPPORTED"),
domain="FACT"
)
session.add(log)
session.commit()
return result
except Exception as e:
logger.error(f"Fact verification error: {redact_pii(str(e))}", exc_info=False)
return {
"status": "ERROR",
"error": INTERNAL_VERIFICATION_ERROR,
"verdict": "ERROR"
}
@app.post("/verify/code")
async def verify_code(
request: dict,
tenant: TenantContext = Depends(get_current_tenant),
session: Session = Depends(get_session)
):
"""
Verify code for security vulnerabilities using AST analysis.
Request body:
{
"code": "import os\\nos.system('ls')",
"language": "python" (optional, default: python)
}
"""
check_rate_limit(tenant.api_key)
try:
from qwed_new.core.code_verifier import CodeVerifier
verifier = CodeVerifier()
code = request.get("code")
language = request.get("language", "python")
if not code:
raise HTTPException(status_code=400, detail="Missing 'code'")
result = verifier.verify_code(code, language=language)
log = VerificationLog(
organization_id=tenant.organization_id,
query=code[:200], # Truncate for logging
result=str(result),
is_verified=result.get("is_safe", False),
domain="CODE"
)
session.add(log)
session.commit()
return result
except Exception as e:
logger.error(f"Code verification error: {redact_pii(str(e))}", exc_info=False)
return {
"status": "ERROR",
"error": INTERNAL_VERIFICATION_ERROR,
"is_safe": False
}
@app.post("/verify/math")
async def verify_math(
request: dict,
tenant: TenantContext = Depends(get_current_tenant),
session: Session = Depends(get_session)
):
"""
Verify mathematical expression or equation.
Request body:
{
"expression": "2+2=4" or "x**2 - y**2 = (x-y)*(x+y)",
"context": {"domain": "real"} (optional)
}
"""
check_rate_limit(tenant.api_key)
try:
import sympy
from qwed_new.core.safe_parser import safe_parse_expr
from sympy import simplify, symbols, Eq, solve
expression = request.get("expression")
context_data = request.get("context", {})
if not expression:
raise HTTPException(status_code=400, detail="Missing 'expression'")
# Check if it's an equation (contains =) or just an expression
if "=" in expression:
# It's an equation - verify if it's true/false
left_str, right_str = expression.split("=", 1)
# Parse both sides
left = safe_parse_expr(left_str)
right = safe_parse_expr(right_str)
# Simplify and check equivalence
difference = simplify(left - right)
is_valid = difference == 0
result = {
"is_valid": is_valid,
"result": is_valid,
"left_side": str(left),
"right_side": str(right),
"simplified_difference": str(difference),
"message": "Identity is true" if is_valid else "Identity is false"
}
else:
# Just an expression - evaluate or simplify
try:
# Convert implicit multiplication to explicit (e.g., 2(x+1) -> 2*(x+1))
import re
expression_normalized = re.sub(r'(\d)(\()', r'\1*\2', expression)
# Check for ambiguous expressions BEFORE parsing
is_ambiguous = False
if "/" in expression and "(" in expression:
# Match patterns like /2(, /10(, etc. (division followed by number then parenthesis)
if re.search(r'/\d+\(', expression.replace(" ", "")):
is_ambiguous = True
parsed = safe_parse_expr(expression_normalized)
# Check for division by zero before simplifying
if "/0" in expression.replace(" ", "") or "/ 0" in expression:
result = {
"is_valid": False,
"error": "Division by zero",
"message": "Expression contains division by zero"
}
# Check for log(0) or log(negative)
elif "log(0)" in expression.replace(" ", ""):
result = {
"is_valid": False,
"error": "undefined",
"message": "log(0) is undefined"
}
# Check for sqrt of negative in real domain
elif "sqrt(-" in expression.replace(" ", ""):
if context_data.get("domain") == "real":
result = {
"is_valid": False,
"error": "domain error",
"message": "Square root of negative number is undefined in real domain"
}
else:
simplified = simplify(parsed)
result = {
"is_valid": True,
"simplified": str(simplified),
"original": str(parsed),
"is_complex": True
}
# Check for ambiguous expressions (BEFORE simplification)
elif is_ambiguous:
simplified = simplify(parsed)
result = {
"is_valid": False,
"result": False,
"status": "BLOCKED",
"warning": "ambiguous",
"message": "Expression may be ambiguous due to implicit multiplication after division",
"simplified": str(simplified),
"note": "Interpreted using standard order of operations",
"original": str(parsed)
}
# Normal expression - evaluate or simplify
else:
simplified = simplify(parsed)
# Try to evaluate if it's numeric
try:
value = float(simplified)
result = {
"is_valid": True,
"value": value,
"simplified": str(simplified),
"original": str(parsed)
}
except Exception:
# Symbolic expression
result = {
"is_valid": True,
"simplified": str(simplified),
"original": str(parsed),
"is_symbolic": True
}
except ZeroDivisionError:
result = {
"is_valid": False,
"error": "Division by zero",
"message": "Expression contains division by zero"
}
except Exception as e:
if "log" in str(e).lower() or "sqrt" in str(e).lower():
result = {
"is_valid": False,
"error": "Domain error",
"message": str(e)
}
else:
raise
log = VerificationLog(
organization_id=tenant.organization_id,
query=expression,
result=str(result),
is_verified=result.get("is_valid", False),
domain="MATH"
)
session.add(log)
session.commit()
return result
except Exception as e:
logger.error(f"Math verification error: {redact_pii(str(e))}", exc_info=False)
return {
"status": "ERROR",
"error": INTERNAL_VERIFICATION_ERROR,
"is_valid": False
}
@app.post("/verify/sql")
async def verify_sql(
request: dict,
tenant: TenantContext = Depends(get_current_tenant),
session: Session = Depends(get_session)
):
"""
Verify SQL query against a provided schema.
Request body:
{
"query": "SELECT * FROM users",
"schema_ddl": "CREATE TABLE users (id INT, name TEXT)",
"dialect": "sqlite" (optional, default: sqlite)
}
"""
check_rate_limit(tenant.api_key)
try:
from qwed_new.core.sql_verifier import SQLVerifier
verifier = SQLVerifier()
query = request.get("query")
schema_ddl = request.get("schema_ddl")
dialect = request.get("dialect", "sqlite")
if not query or not schema_ddl:
raise HTTPException(status_code=400, detail="Missing 'query' or 'schema_ddl'")
result = verifier.verify_sql(query, schema_ddl, dialect=dialect)
log = VerificationLog(
organization_id=tenant.organization_id,
query=query,
result=str(result),
is_verified=result.get("is_valid", False),
domain="SQL"
)
session.add(log)
session.commit()
return result
except Exception as e:
logger.error(f"SQL verification error: {redact_pii(str(e))}", exc_info=False)
return {
"status": "ERROR",
"error": INTERNAL_VERIFICATION_ERROR,
"is_valid": False
}
@app.post("/verify/image")
async def verify_image(
image: UploadFile = File(...),
claim: str = Form(...),
tenant: TenantContext = Depends(get_current_tenant),
session: Session = Depends(get_session)
):
"""
Verify a claim against an uploaded image.
Form data:
- image: Image file (PNG, JPEG, GIF, WebP)
- claim: The statement to verify (e.g., "The image is 800x600 pixels")
Returns verification result with:
- verdict: SUPPORTED, REFUTED, INCONCLUSIVE, or VLM_REQUIRED
- confidence: 0.0 to 1.0
- reasoning: Explanation of the result
- methods_used: List of verification methods applied
"""
check_rate_limit(tenant.api_key)
try:
from qwed_new.core.image_verifier import ImageVerifier
# Read image bytes
image_bytes = await image.read()
if len(image_bytes) == 0:
raise HTTPException(status_code=400, detail="Empty image file")
if len(image_bytes) > 10 * 1024 * 1024: # 10MB limit
raise HTTPException(status_code=400, detail="Image too large (max 10MB)")
# Verify claim against image
verifier = ImageVerifier(use_vlm_fallback=False)
result = verifier.verify_image(image_bytes, claim)
# Log the verification
log = VerificationLog(
organization_id=tenant.organization_id,
query=f"Image claim: {claim}",
result=str(result),
is_verified=result.get("verdict") == "SUPPORTED",
domain="IMAGE"
)
session.add(log)
session.commit()
return result
except HTTPException:
raise
except Exception as e:
logger.error(f"Image verification error: {redact_pii(str(e))}", exc_info=False)
return {
"status": "ERROR",
"error": "Internal processing error",
"verdict": "INCONCLUSIVE",
"confidence": 0.0
}
class RAGVerifyRequest(BaseModel):
target_document_id: str
chunks: list[dict]
max_drm_rate: str = "0" # Accepts Fraction-compatible strings: "0", "1/10", etc.
@field_validator("target_document_id")
@classmethod
def validate_target_document_id(cls, value: str) -> str:
stripped = value.strip()
if not stripped:
raise ValueError("target_document_id must be a non-empty string.")
return stripped
@field_validator("chunks")
@classmethod
def validate_chunks(cls, value: list[dict]) -> list[dict]:
if not value:
raise ValueError("chunks must be a non-empty list.")
if any(not isinstance(chunk, dict) or not chunk for chunk in value):
raise ValueError("Each chunk must be a non-empty object.")
return value
@field_validator("max_drm_rate")
@classmethod
def validate_max_drm_rate(cls, value: str) -> str:
try:
threshold = Fraction(value)
except (TypeError, ValueError, ZeroDivisionError) as exc:
raise ValueError("max_drm_rate must be a Fraction-compatible string.") from exc
if not Fraction(0) <= threshold <= Fraction(1):
raise ValueError("max_drm_rate must be between 0 and 1.")
return value
@app.post(
"/verify/rag",
responses={
400: {"description": "Invalid RAG verification request payload."},
},
)
async def verify_rag(
request: RAGVerifyRequest,
tenant: TenantDependency,
session: SessionDependency
):
"""
Document-Level Retrieval Mismatch Defender.
Verifies that context chunks align with the target document.
"""
check_rate_limit(tenant.api_key)
try:
from qwed_sdk.guards.rag_guard import RAGGuard
try:
guard = RAGGuard(max_drm_rate=request.max_drm_rate)
result = guard.verify_retrieval_context(
target_document_id=request.target_document_id,
retrieved_chunks=request.chunks
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
audit_result = {
"verified": result.get("verified", False),
"risk": result.get("risk"),
"drm_rate": result.get("drm_rate"),
"chunks_checked": result.get("chunks_checked"),
"mismatched_count": result.get("mismatched_count"),
}
log = VerificationLog(
organization_id=tenant.organization_id,
query=f"RAG Document Verify: {request.target_document_id}",
result=str(audit_result),
is_verified=result.get("verified", False),
domain="RAG"
)
session.add(log)
session.commit()
return result
except HTTPException:
raise
except Exception as e:
logger.error(f"RAG verification error: {redact_pii(str(e))}", exc_info=False)
return {
"status": "ERROR",
"error": INTERNAL_PROCESSING_ERROR,
"verified": False
}
class ProcessVerifyRequest(BaseModel):
trace: str
mode: str = "irac"
milestones: Optional[list[str]] = None
@app.post(
"/verify/process",
responses={
400: {"description": "Invalid process mode or missing milestones for milestones mode."},
},
)
async def verify_process(
request: ProcessVerifyRequest,
tenant: TenantDependency,
session: SessionDependency
):
"""
Glass-Box Reasoning Process Verifier.
Checks IRAC structural compliance or milestone process rates.
"""
check_rate_limit(tenant.api_key)
try:
from qwed_new.guards.process_guard import ProcessVerifier
verifier = ProcessVerifier()
if request.mode == "irac":
result = verifier.verify_irac_structure(request.trace)
elif request.mode == "milestones":
if not request.milestones:
raise HTTPException(
status_code=400,
detail="'milestones' is required when mode=\"milestones\""
)
result = verifier.verify_trace(request.trace, request.milestones)
else:
raise HTTPException(
status_code=400,
detail="Invalid mode. Use 'irac' or 'milestones'."
)
log = VerificationLog(
organization_id=tenant.organization_id,
query=f"Process Verification ({request.mode})",
result=str(result),
is_verified=result.get("verified", False),
domain="PROCESS"
)
session.add(log)
session.commit()
return result
except HTTPException:
raise
except Exception as e:
logger.error(f"Process verification error: {redact_pii(str(e))}", exc_info=False)
return {
"status": "ERROR",
"error": INTERNAL_PROCESSING_ERROR,
"verified": False
}
# ============================================================
# OBSERVABILITY ENDPOINTS
# ============================================================
from qwed_new.core.observability import (
get_prometheus_content_type,
get_prometheus_metrics,
metrics_collector,
)
from datetime import datetime, timezone
from sqlmodel import select
@app.get("/health")
async def health_check():
"""
System health check.
Returns basic status information (no auth required).
"""
return {
"status": "healthy",
"service": "QWED Platform",
"version": APP_VERSION,
"timestamp": datetime.now(timezone.utc).isoformat()
}
@app.get("/metrics")
async def get_global_metrics(
current_user: Annotated[None, Depends(require_metrics_access)],
):
"""
Get system-wide metrics.
"""
del current_user
global_metrics = metrics_collector.get_global_metrics()
all_tenant_metrics = metrics_collector.get_all_tenant_metrics()
return {
"global": global_metrics,
"tenants": all_tenant_metrics
}
@app.get("/metrics/prometheus", tags=["Observability"])
async def prometheus_metrics(
current_user: Annotated[None, Depends(require_metrics_access)],
):
"""
Prometheus-compatible metrics endpoint.
Returns metrics in Prometheus text format for scraping.
"""
del current_user
content = get_prometheus_metrics()
return Response(
content=content,
media_type=get_prometheus_content_type()
)
@app.get("/metrics/{organization_id}")
async def get_tenant_metrics(
organization_id: int,
tenant: TenantContext = Depends(get_current_tenant)
):
"""
Get metrics for a specific tenant.
Tenants can only see their own metrics.
"""
# Authorization: Ensure tenant can only see their own metrics
if tenant.organization_id != organization_id:
raise HTTPException(
status_code=403,
detail="You can only view metrics for your own organization"
)
metrics = metrics_collector.get_tenant_metrics(organization_id)
if not metrics:
return {
"organization_id": organization_id,
"message": "No metrics available yet. Make some requests first!"
}
return metrics
@app.get("/logs")
async def get_tenant_logs(
limit: int = 10,
tenant: TenantContext = Depends(get_current_tenant),
session: Session = Depends(get_session)
):
"""
Get verification logs for the authenticated tenant.
Automatically scoped to the organization.
"""
statement = select(VerificationLog).where(
VerificationLog.organization_id == tenant.organization_id
).order_by(VerificationLog.timestamp.desc()).limit(limit)
logs = session.execute(statement).scalars().all()
return {
"organization_id": tenant.organization_id,
"organization_name": tenant.organization_name,
"total_logs": len(logs),
"logs": [
{
"id": log.id,
"query": log.query,
"is_verified": log.is_verified,
"domain": log.domain,
"timestamp": log.timestamp.isoformat()
}
for log in logs
]
}
# ============================================================
# AGENTIC AI ENDPOINTS (Phase 2)
# ============================================================
from qwed_new.core.agent_registry import agent_registry