from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import os import json from typing import List, Optional from groq import Groq # --- 1. SETUP --- api_key = os.environ.get("GROQ_API_KEY") client = Groq(api_key=api_key) app = FastAPI(title="Beploo Audit Engine V7") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # --- 2. MODELS --- class ContextAuditRequest(BaseModel): productName: str description: Optional[str] = "" functionalUsecase: Optional[str] = "" material: Optional[str] = "" form: Optional[str] = "" commercialState: Optional[str] = "" remaining_chapters: Optional[List[str]] = [] # --- 3. ENDPOINTS --- @app.get("/") def home(): return {"status": "online", "mode": "Context Aware V7"} @app.post("/analyze_audit_context") async def analyze_audit_context(req: ContextAuditRequest): # We inject the VALID OPTIONS so the AI picks exactly what matches your frontend system_prompt = """ You are a Senior Customs Auditor. 1. Analyze the input product (Name + Description). 2. Suggest the BEST match from the provided lists for each field. 3. Apply GRI 1 and 3(b) logic for the reasoning. VALID LISTS: - Materials: [Live Animals, Vegetable Products, Fats & Oils, Prepared Foodstuffs, Mineral Products, Chemicals, Plastics, Rubber, Leather, Wood, Paper, Textiles, Footwear, Stone/Cement, Ceramics, Glass, Precious Metals, Base Metals, Machinery, Electrical Equipment, Vehicles, Optical Instruments, Arms, Misc Manufactured, Works of Art] - Commercial State: [Retail, Bulk, Semi-Finished, Raw Material, Component, Spare Part, Accessory, Set/Kit, Sample, Waste, Software] - Form: [Gas, Liquid, Paste, Powder, Lumps, Bars, Wire, Plates, Tubes, Roll, Fiber, Fabric, Assembled, Disassembled] Output STRICT JSON: { "dominant_function": "string", "material_dominance": "string", "essential_character_reasoning": "string", "confidence": 0.9, "suggested_values": { "functionalUsecase": "string (best guess)", "material": "string (exact match from list)", "form": "string (exact match from list)", "commercialState": "string (exact match from list)" }, "proposed_binary_question": { "question": "string", "yes_effect": "string", "no_effect": "string" } } """ user_input = f""" TARGET: {req.productName} DESC: {req.description} CURRENT_SELECTIONS: {req.functionalUsecase}, {req.material} """ try: completion = client.chat.completions.create( messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_input}], model="llama-3.3-70b-versatile", temperature=0.1, response_format={"type": "json_object"} ) return json.loads(completion.choices[0].message.content) except Exception as e: return {"error": str(e), "dominant_function": "Error", "suggested_values": {}} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)