""" Multi-Agent Autonomous Procurement System — FastAPI + Auth Hugging Face Spaces Docker entry-point · uvicorn app:app --host 0.0.0.0 --port 7860 Auth: POST /auth/login → Bearer JWT (HS256, 2-hour expiry) UI: GET / → full SPA (login + dashboard, no framework) API: all /workflow/* routes require Authorization: Bearer """ import json import time import hmac import hashlib import base64 import traceback from contextlib import asynccontextmanager from typing import Any from fastapi import FastAPI, HTTPException, Depends, Request, status from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse, JSONResponse from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from pydantic import BaseModel, Field from procurement_system import build_procurement_graph, create_llm, ProcurementWorkflowExecutor # ── Auth config ──────────────────────────────────────────────────────────────── _JWT_SECRET = "procurement-demo-secret-2024" _JWT_EXPIRY = 7200 # 2 hours # Dummy user store { username: { password, role, display_name } } USERS = { "admin": {"password": "admin123", "role": "admin", "name": "Admin User"}, "buyer": {"password": "buyer123", "role": "buyer", "name": "Sarah (Buyer)"}, "manager": {"password": "manager123", "role": "manager", "name": "John (Manager)"}, "analyst": {"password": "analyst123", "role": "analyst", "name": "Priya (Analyst)"}, } # ── Preset test scenarios exposed to the UI ──────────────────────────────────── TEST_CASES = [ { "id": "tc1", "label": "✅ Cloud – within budget", "request": "We need enterprise cloud infrastructure with auto-scaling and 99.99% uptime SLA for our data pipeline.", "budget": 5500, "expected": "Analysis APPROVED → awaiting human approval", }, { "id": "tc2", "label": "❌ Cloud – budget too low", "request": "We need enterprise cloud infrastructure with auto-scaling and high availability SLA.", "budget": 2000, "expected": "Analysis REJECTED – all vendors exceed budget", }, { "id": "tc3", "label": "✅ Software – within budget", "request": "We need enterprise software licensing for 1500 users with cloud deployment.", "budget": 3000, "expected": "Analysis APPROVED → awaiting human approval", }, { "id": "tc4", "label": "❌ Software – budget too low", "request": "We need software licensing with custom integrations and quarterly updates.", "budget": 1500, "expected": "Analysis REJECTED – all vendors exceed budget", }, { "id": "tc5", "label": "✅ Cloud – tight budget (cheapest vendor)", "request": "We need basic cloud infrastructure with auto-scaling for our startup workloads.", "budget": 3500, "expected": "Analysis APPROVED (cheapest vendor selected)", }, ] # ── Graph singleton ──────────────────────────────────────────────────────────── _graph = None _memory = None @asynccontextmanager async def lifespan(app: FastAPI): global _graph, _memory llm = create_llm() _graph, _memory, _ = build_procurement_graph(llm) print("Procurement graph ready.") yield app = FastAPI(title="Procurement System", version="1.0.0", lifespan=lifespan) app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): tb = traceback.format_exc() print(f"Unhandled exception on {request.url}:\n{tb}") return JSONResponse( status_code=500, content={"detail": str(exc), "type": type(exc).__name__}, ) _sessions: dict[str, ProcurementWorkflowExecutor] = {} _bearer = HTTPBearer() # ── Minimal JWT (no external lib) ───────────────────────────────────────────── def _b64(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode() def _sign(msg: str) -> str: return _b64(hmac.new(_JWT_SECRET.encode(), msg.encode(), hashlib.sha256).digest()) def create_token(username: str, role: str) -> str: header = _b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode()) payload = _b64(json.dumps({"sub": username, "role": role, "exp": int(time.time()) + _JWT_EXPIRY}).encode()) return f"{header}.{payload}.{_sign(header + '.' + payload)}" def verify_token(token: str) -> dict: try: h, p, sig = token.split(".") if _sign(h + "." + p) != sig: raise ValueError("bad sig") claims = json.loads(base64.urlsafe_b64decode(p + "==")) if claims["exp"] < int(time.time()): raise ValueError("expired") return claims except Exception: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired token") def current_user(creds: HTTPAuthorizationCredentials = Depends(_bearer)) -> dict: return verify_token(creds.credentials) # ── Helpers ──────────────────────────────────────────────────────────────────── def _ser(state: Any) -> dict: if state is None: return {} return dict(state) def _fmt_events(events: list) -> list[dict]: out = [] for e in (events or []): try: if not isinstance(e, dict) or not e: continue node = next(iter(e)) updates = e[node] if not isinstance(updates, dict): out.append({"node": node, "updates": {}}) continue safe = {} for k, v in updates.items(): if isinstance(v, str): safe[k] = v[:400] elif isinstance(v, (int, float, bool, type(None))): safe[k] = v elif isinstance(v, list): safe[k] = [str(x)[:200] if not isinstance(x, (int, float, bool, dict)) else x for x in v[:5]] else: safe[k] = str(v)[:200] out.append({"node": node, "updates": safe}) except Exception: pass return out # ── Auth routes ──────────────────────────────────────────────────────────────── class LoginRequest(BaseModel): username: str password: str @app.post("/auth/login", tags=["auth"]) def login(body: LoginRequest): user = USERS.get(body.username) if not user or user["password"] != body.password: raise HTTPException(status_code=401, detail="Invalid credentials") token = create_token(body.username, user["role"]) return {"access_token": token, "token_type": "bearer", "username": body.username, "name": user["name"], "role": user["role"]} @app.get("/auth/me", tags=["auth"]) def me(user: dict = Depends(current_user)): u = USERS[user["sub"]] return {"username": user["sub"], "name": u["name"], "role": user["role"]} # ── Workflow routes ──────────────────────────────────────────────────────────── class ParseRequest(BaseModel): raw_input: str = Field(..., example="We need servers for our startup, budget around 4k a month") class StartRequest(BaseModel): procurement_request: str = Field(default="", example="We need enterprise cloud infrastructure") budget_limit: float = Field(default=5000.0, gt=0, example=5500.0) raw_input: str = Field(default="", example="") class DecideRequest(BaseModel): approve: bool = Field(..., example=True) @app.get("/health") def health(): return {"status": "ok", "graph_ready": _graph is not None} @app.get("/testcases", tags=["workflow"]) def get_test_cases(): return TEST_CASES @app.post("/workflow/parse", tags=["workflow"]) def parse_prose(body: ParseRequest, user: dict = Depends(current_user)): """Use the LLM to extract structured fields from free-form prose. Preview before running agents.""" try: from langchain_core.prompts import PromptTemplate llm = create_llm() prompt = PromptTemplate( input_variables=["raw"], template=( "You are a procurement intake assistant. Extract structured procurement details " "from the user's free-form description below.\n\n" "User input:\n{raw}\n\n" "Reply with ONLY valid JSON — no markdown, no explanation:\n" '{{\n' ' "procurement_request": "",\n' ' "budget_limit": ,\n' ' "confidence": "",\n' ' "assumptions": ""\n' '}}' ), ) response = llm.invoke(prompt.format(raw=body.raw_input)) content = response.content.strip() if content.startswith("```"): content = content.split("```")[1] if content.startswith("json"): content = content[4:] content = content.strip() parsed = json.loads(content) return { "raw_input": body.raw_input, "procurement_request": parsed.get("procurement_request", body.raw_input), "budget_limit": float(parsed.get("budget_limit", 5000)), "confidence": parsed.get("confidence", "medium"), "assumptions": parsed.get("assumptions", ""), } except json.JSONDecodeError: return { "raw_input": body.raw_input, "procurement_request": body.raw_input, "budget_limit": 5000.0, "confidence": "low", "assumptions": "Could not parse LLM response; using raw input verbatim.", } except Exception as exc: tb = traceback.format_exc() print(f"parse_prose error:\n{tb}") raise HTTPException(status_code=500, detail=f"{type(exc).__name__}: {exc}") @app.post("/workflow/start", tags=["workflow"]) def start_workflow(body: StartRequest, user: dict = Depends(current_user)): try: executor = ProcurementWorkflowExecutor(_graph, _memory) _sessions[executor.thread_id] = executor state, events = executor.start_workflow( body.procurement_request, body.budget_limit, raw_input=body.raw_input, ) s = _ser(state) return { "thread_id": executor.thread_id, "status": "awaiting_approval" if s.get("analysis_approved") else "rejected", "analysis_approved": s.get("analysis_approved"), "selected_vendor": s.get("selected_vendor"), "vendor_options": s.get("vendor_options"), "budget_limit": s.get("budget_limit"), "procurement_request": s.get("procurement_request"), "logs": s.get("logs"), "events": _fmt_events(events), "triggered_by": user["sub"], } except Exception as exc: tb = traceback.format_exc() print(f"start_workflow error:\n{tb}") raise HTTPException(status_code=500, detail=f"{type(exc).__name__}: {exc}") @app.get("/workflow/{thread_id}", tags=["workflow"]) def get_workflow(thread_id: str, user: dict = Depends(current_user)): ex = _sessions.get(thread_id) if not ex: raise HTTPException(404, f"Thread '{thread_id}' not found") return {"thread_id": thread_id, "state": _ser(ex.get_state())} @app.post("/workflow/{thread_id}/decide", tags=["workflow"]) def decide(thread_id: str, body: DecideRequest, user: dict = Depends(current_user)): ex = _sessions.get(thread_id) if not ex: raise HTTPException(404, f"Thread '{thread_id}' not found") try: state, events = ex.approve_vendor(body.approve) s = _ser(state) outcome = ("contract_generated" if s.get("contract_draft") else "approved_pending_contract") if body.approve else "rejected_by_human" return { "thread_id": thread_id, "outcome": outcome, "human_approved": s.get("human_approved"), "contract_draft": s.get("contract_draft"), "selected_vendor": s.get("selected_vendor"), "logs": s.get("logs"), "events": _fmt_events(events), "decided_by": user["sub"], } except Exception as exc: tb = traceback.format_exc() print(f"decide error:\n{tb}") raise HTTPException(status_code=500, detail=f"{type(exc).__name__}: {exc}") # ── SPA ──────────────────────────────────────────────────────────────────────── @app.get("/", response_class=HTMLResponse, include_in_schema=False) def root(): return HTMLResponse(content=r""" Procurement AI System

Multi-Agent Procurement System

LangGraph · LangChain · Groq llama-3.3-70b · LangSmith

👤

📋 Procurement Input

Parsed by AI →

⚡ Preset Test Cases

📊 Agent Pipeline

🤖 Parse
🔍 Research
💰 Analysis
👤 Gate
Run a workflow to see live results.

🪵 Agent Audit Log

Logs will appear here…
""")