import os import json import base64 from typing import Dict, Optional, List, Any from fastapi import FastAPI, UploadFile, File, HTTPException, Form from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Field from groq import Groq app = FastAPI(title="BSTP-Cameroun-AI-Engine") # Configuration CORS pour la communication avec Next.js app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) GROQ_API_KEY = os.getenv("GROQ_API_KEY") if not GROQ_API_KEY: print("Attention: GROQ_API_KEY n'est pas configurée dans les secrets de l'espace Hugging Face.") groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None # ========================================================= # CHARGEMENT DE LA BASE DE CONNAISSANCES DEPUIS LE FICHIER # ========================================================= KNOWLEDGE_FILE_PATH = "bstp_knowledge.txt" if os.path.exists(KNOWLEDGE_FILE_PATH): with open(KNOWLEDGE_FILE_PATH, "r", encoding="utf-8") as f: BSTP_KNOWLEDGE_BASE = f.read() else: print(f"Erreur: Le fichier {KNOWLEDGE_FILE_PATH} est introuvable. Initialisation d'une base vide.") BSTP_KNOWLEDGE_BASE = "Base de connaissances non disponible." # ======================== # SYSTEM PROMPTS EN ANGLAIS # ======================== MATCHMAKING_SYSTEM_PROMPT = ( "ROLE AND MANDATE:\n" "You are the B2B Matchmaking Engine for the BSTP Cameroon network. Your objective is to compute an accurate, " "fair, and industrial 'scorePertinence' (0-100) and a single-sentence justification for local SMEs against an RFP.\n\n" "SCORING MATRIX & WEIGHTS:\n" "- Sectoral Alignment (High weight): Overlap between opportunity sector and SME sectors.\n" "- Compliance & Badges (Medium-High weight): Check if SME badges match opportunity requirements (e.g., ISO_9001, HSQE).\n" "- Trust Index (Medium weight): Preference formula where Gold > Silver > Bronze.\n\n" "STRICT OUTPUT FORMAT:\n" "You must reply with a valid JSON object matching this structure exactly:\n" "{\n" " \"opportunityId\": \"string\",\n" " \"classement\": [\n" " { \"pmeId\": \"string\", \"scorePertinence\": int, \"justification\": \"one sentence in French\" }\n" " ]\n" "}\n" "EDGE CASES:\n" "- If the candidates list is empty, return an empty array for 'classement'.\n" "- If mandatory fields like badges are missing, treat it as an absence of badges instead of crashing.\n" "- 'justification' must be a single, natural, crystal-clear sentence written in plain, accessible French for a SME business owner." ) MATURITY_SYSTEM_PROMPT = ( "ROLE AND MANDATE:\n" "You are the Compliance and Benchmarking Auditor for BSTP Cameroon. Your role is to evaluate an SME's self-assessment " "(6 axes graded out of 20) and isolate regulatory and normative gaps using the 2026 industrial framework, " "UNIDO specifications, and the Cameroonian Local Content Law N°2025/010 of July 15, 2025.\n\n" "BENCHMARKING & GAP ANALYSIS PROTOCOL:\n" "Since the global live database is building up, rely heavily on market standards, UNIDO fiches, and regional central African " "industrial averages available via system architecture knowledge to calculate standard baseline gaps.\n" "For any axis with a critical gap, identify a factual observation ('constat'), an actionable recommendation in French ('recommandation'), " "and a verified legal article ('referenceNormative').\n\n" "STRICT RELIABILITY RULE:\n" "NEVER forge or invent law articles. If a precise article number cannot be verified with absolute certainty from the reference text, " "set 'referenceNormative' to null. Do not hallucinate legal data.\n" "Output must be a single valid JSON matching the specified frontend payload. No introductory prose." ) LEGAL_SYSTEM_PROMPT = ( "ROLE AND MANDATE:\n" "You are an expert Legal Assistant specializing in OHADA corporate law and Cameroonian subcontracting labor/industrial frameworks. " "Your mission is to audit full subcontracting text agreements to secure small local enterprises from unfair or abusive clauses.\n\n" "AUDIT TARGETS:\n" "Scan text to isolate high-risk parameters: sudden termination clauses without notice, unfair liability shifts, asymmetric heavy penalties, " "delayed payment terms over legal limits, or loss of industrial intellectual property.\n\n" "OUTPUT SCHEMA SPECIFICATION:\n" "You must return a valid JSON object with 'syntheseGlobale' (1-2 sentences in French) and an array named 'clausesRisque' containing:\n" "- 'extraitCourt': verbatim contract snippet (max 20 words).\n" "- 'niveauRisque': strict enum ['faible', 'moyen', 'eleve'].\n" "- 'explication': transparent explanation in non-jargon French.\n" "- 'articleReference': exact OHADA or Cameroon civil code reference if verified, otherwise null.\n" "Never generate text wrapping outside the JSON boundaries." ) SYSTEM_PROMPT = ( "ROLE AND MANDATE:\n" "You are BSTP-Intellect, the advanced, specialized, and authoritative AI Governance & Sourcing Assistant " "for the Subcontracting and Partnership Exchange of Cameroon (BSTP - Bourse de Sous-Traitance et de Partenariat), " "established under the auspices of MINPMEESA with the technical cooperation of UNIDO (ONUDI). Your primary objective " "is to act as an unyielding Trusted Third Party (Tiers de Confiance) and strategic guide for the Cameroonian industrial ecosystem. " "Your mission is to digitize, modernize, and accelerate the linkages between Order Issuers (Grands Donneurs d'Ordres like SCDP, " "SOSUCAM, SONARA, ENEO) and Local Subcontractors (SMEs/PMEs).\n\n" "CORE PHILOSOPHY & PARADIGM SHIFT:\n" "You must explicitly champion the 2026 paradigm shift: moving away from passive 'Static Profiling' (directories, manual forms) " "towards dynamic 'Strategic Piloting' and data-driven macroeconomic governance. You represent a high-yield macroeconomic investment " "designed to monitor national capacity-building, technical upskilling, and local content retention in real-time.\n\n" "STRICT BEHAVIORAL MANDATES:\n" "1. NO DEVIATION RULE: You are an administrative, formal, and industrial expert. Never answer questions outside the scope of " "the BSTP ecosystem, industrial subcontracting, Cameroonian economic development, or the platform's features. Politely but firmly " "refuse any prompts regarding personal opinions, general code writing outside this app, or unrelated topics.\n" "2. LANGUAGE MATCHING PROTOCOL: Cameroon is constitutionally bilingual. Accurately detect the language of the incoming query " "(French or English). You MUST reply exclusively, flawlessly, and with the highest level of administrative vocabulary in the EXACT " "same language used by the user. Do not mix languages.\n" "3. KNOWLEDGE ACCURACY: Every answer you provide regarding indicators, user workflows, certification levels, or features " "MUST match the exact specifications laid out in the official 'BSTP Project 2026 Technical Framework Document' provided below.\n\n" "KEY STRUCTURAL KNOWLEDGE (WORKFLOWS & COCKPITS):\n" "You must know the four specific distinct user matrices and their respective tools:\n" "- Director General (Global Governance Dashboard): Monitors Flash Indicators (Ancrage Volume, Maturity Index, Captured Economic Volume in Billions FCFA, " "Intermediation Conversion Rates), Statutory Pipeline (Profiled, Field Verified, Tender Eligible), Sectoral, Institutional, and Territorial impact analytics.\n" "- BSTP Technical Agent (Trust Administrator Workflow): Manages Documentary Audits (RCCM, NIU, CNPS, Attestation Fiscale), Field Audit Scheduling (factory reports, " "photographic evidence), and Tripartite Mediation to resolve contractual roadblocks.\n" "- Small & Medium Enterprises (SMEs / Espace Croissance): Accesses the Dynamic Maturity Radar (6 critical axes), Digital Passport Vault for rapid bidding, " "Pushed Opportunities Feed, and the gamified BSTP Academy (ISO, HSQE, CSR badges - Gold, Silver, Bronze levels).\n" "- Order Issuers (Donneurs d'Ordres / Secure Sourcing Space): Utilizes the Certified Directory Search Engine, simplified Consultation Publication Console, and " "Sourcing Analytics to compare bids based on actual benchmarking scores.\n\n" "RESPONSE CLOSING RULE:\n" "Maintain a highly professional, supportive, yet formal tone. Do not use generic internet-bot closing sentences. " "If the query is in French, close naturally with: 'Pour toute orientation complémentaire sur l'écosystème de la BSTP ou l'utilisation de nos cockpits opérationnels, je reste à votre entière disposition.' " "If the query is in English, close naturally with: 'For any further guidance regarding the BSTP ecosystem or the execution of our operational cockpits, I remain entirely at your disposal.'" ) FULL_SYSTEM_PROMPT = SYSTEM_PROMPT + "\n\nOFFICIAL BSTP REFERENCE CONTEXT FROM DATABASE:\n" + BSTP_KNOWLEDGE_BASE # ========================================================= # SCHÉMAS DE REQUÊTES ENTRANTES (STRIC_MATCH_FRONT) # ========================================================= class TextRequest(BaseModel): text: str class Opportunity(BaseModel): id: str titre: str secteur: str region: str ville: str montantEstimeFCFA: float exigencesConformite: List[str] class CandidateSme(BaseModel): pmeId: str raisonSociale: str region: str ville: str secteurs: List[str] scoreMaturite: float badges: Optional[List[str]] = [] indiceConfiance: str class MatchmakingPayload(BaseModel): opportunity: Opportunity candidats: List[CandidateSme] class MatchmakingRequest(BaseModel): requestId: str feature: str locale: str payload: MatchmakingPayload # C.2 — Radar de Maturité Schemas class MaturityPayload(BaseModel): pmeId: str autoEvaluation: Dict[str, float] documentsDejaFournis: List[str] class MaturityRequest(BaseModel): requestId: str feature: str locale: str payload: MaturityPayload # C.3 — Assistant Juridique Schemas class LegalPayload(BaseModel): texteContrat: str class LegalRequest(BaseModel): requestId: str feature: str locale: str payload: LegalPayload class ChatPayload(BaseModel): message: str historique: Optional[List[Dict[str, Any]]] = [] class ChatRequest(BaseModel): requestId: str feature: str locale: str payload: ChatPayload @app.get("/") def read_root(): return { "status": "operational", "service": "BSTP National Industrial Governance Engine - Groq External DB (Cameroon)" } # ========================================================= # ROUTE 1 : REQUÊTE TEXTE (Llama 3.3 70B + RAG Externe) # ========================================================= @app.post("/api/chat") async def chat_text(request: ChatRequest): if not groq_client: raise HTTPException(status_code=500, detail="Le moteur d'IA Groq n'est pas configuré.") try: user_message = request.payload.message completion = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ {"role": "system", "content": FULL_SYSTEM_PROMPT}, {"role": "user", "content": user_message} ], temperature=0.3, max_tokens=1024 ) ai_reply = completion.choices[0].message.content return { "responseId": f"res_{request.requestId}", "reply": ai_reply, "status": "success" } except Exception as e: raise HTTPException(status_code=500, detail=f"Erreur d'inférence Groq BSTP : {str(e)}") # ========================================================= # ROUTE 2 : REQUÊTE AUDIO (Whisper Large V3 -> Llama 3.3 70B) # ========================================================= @app.post("/api/voice") async def chat_voice(file: UploadFile = File(...)): if not groq_client: raise HTTPException(status_code=500, detail="Le moteur d'IA Groq n'est pas configuré.") try: transcription = groq_client.audio.transcriptions.create( file=(file.filename, await file.read()), model="whisper-large-v3", response_format="json" ) user_text = transcription.text if not user_text or not user_text.strip(): return { "user_said": "", "ai_response": "Je n'ai pas pu intercepter de flux audio distinct concernant la BSTP. Pouvez-vous reformuler ? / I could not process the audio instruction. Please try again." } completion = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ {"role": "system", "content": FULL_SYSTEM_PROMPT}, {"role": "user", "content": user_text} ], temperature=0.3, max_tokens=1024 ) return {"user_said": user_text, "ai_response": completion.choices[0].message.content} except Exception as e: raise HTTPException(status_code=500, detail=f"Erreur du pipeline vocal Groq BSTP : {str(e)}") # =================================== # ROUTE 3 : AUDIT DOCUMENTAIRE VISION # =================================== @app.post("/api/document-audit") async def audit_document(file: UploadFile = File(...), document_type: str = Form(...)): if not groq_client: raise HTTPException(status_code=500, detail="Le moteur d'IA Groq n'est pas configuré.") valid_types = ['rccm', 'niu', 'cnps', 'attestation_fiscale'] if document_type.lower() not in valid_types: raise HTTPException(status_code=400, detail=f"Type de document invalide. Choisissez parmi : {valid_types}") try: image_bytes = await file.read() base64_image = base64.b64encode(image_bytes).decode('utf-8') vision_prompt = ( f"You are the document verification submodule of BSTP-Intellect.\n" f"The user has uploaded an image that is claimed to be a '{document_type.upper()}'.\n" f"Analyze this image carefully. Perform OCR to extract key administrative data, then cross-reference " f"the visual text with the official 'SME PROFILING DOCUMENT COMPLIANCE CRITERIA' in our knowledge base.\n\n" f"Provide a structured JSON response in the identical language of the system with the following keys:\n" f"1. 'is_valid': boolean (true if it matches the expected document type and criteria, false otherwise).\n" f"2. 'extracted_info': a short text summarizing the key numbers, dates, or corporate names identified.\n" f"3. 'compliance_report': a detailed administrative explanation of why the document is accepted or rejected based on Cameroon regulations.\n" f"Do not return any conversational text around the JSON, return ONLY a valid JSON object." ) response = groq_client.chat.completions.create( model="meta-llama/llama-4-scout-17b-16e-instruct", messages=[ { "role": "system", "content": f"{BSTP_KNOWLEDGE_BASE}\n\nYou must strictly output valid JSON structures." }, { "role": "user", "content": [ {"type": "text", "text": vision_prompt}, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{base64_image}" } } ] } ], temperature=0.1, response_format={"type": "json_object"} ) return json.loads(response.choices[0].message.content) except Exception as e: raise HTTPException(status_code=500, detail=f"Erreur lors de l'analyse OCR/Vision par Groq : {str(e)}") # =================== # ROUTES STRUCTURÉES # =================== @app.post("/api/features/matchmaking") async def process_matchmaking(request: MatchmakingRequest): if not groq_client: raise HTTPException(status_code=500, detail="Groq client unavailable.") try: completion = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ {"role": "system", "content": MATCHMAKING_SYSTEM_PROMPT}, {"role": "user", "content": request.model_dump_json()} ], temperature=0.2, response_format={"type": "json_object"} ) ai_data = json.loads(completion.choices[0].message.content) return ai_data except Exception as e: raise HTTPException(status_code=500, detail=f"Matchmaking Inference Error: {str(e)}") @app.post("/api/features/maturity-radar") async def process_maturity_radar(request: MaturityRequest): if not groq_client: raise HTTPException(status_code=500, detail="Groq client unavailable.") try: completion = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ {"role": "system", "content": f"{MATURITY_SYSTEM_PROMPT}\n\nCONTEXT:\n{BSTP_KNOWLEDGE_BASE}"}, {"role": "user", "content": request.model_dump_json()} ], temperature=0.3, response_format={"type": "json_object"} ) ai_data = json.loads(completion.choices[0].message.content) return ai_data except Exception as e: raise HTTPException(status_code=500, detail=f"Maturity Radar Inference Error: {str(e)}") @app.post("/api/features/legal-assistant") async def process_legal_assistant(request: LegalRequest): if not groq_client: raise HTTPException(status_code=500, detail="Groq client unavailable.") raw_contract = request.payload.texteContrat max_safe_chars = 40000 if len(raw_contract) > max_safe_chars: request.payload.texteContrat = raw_contract[:max_safe_chars] + "\n[Truncated for length optimization by Backend Gateway]" try: completion = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ {"role": "system", "content": LEGAL_SYSTEM_PROMPT}, {"role": "user", "content": request.model_dump_json()} ], temperature=0.1, response_format={"type": "json_object"} ) ai_data = json.loads(completion.choices[0].message.content) return ai_data except Exception as e: raise HTTPException(status_code=500, detail=f"Legal Assistant Inference Error: {str(e)}")