Update app.py
Browse files30 unmodified lines3132333435363738394041424344454647484950515253545556576 unmodified lines6465666768697071727374757677787980818283848520 unmodified lines10610710810911011131 unmodified lines143144145146147148101 unmodified lines25025125225325425525625725867 unmodified lines3263273283293303313321 unmodified line33433533633733833934034134234330 unmodified linesllm = None# =========================# POST-GENERATION VALIDATOR CONFIG & FUNCTIONS# =========================FULL_MODE_HEADINGS = ["DIRECTIVE_ADVISOR_ANSWER","CONDITIONS","WHEN_NOT_APPLICABLE","PROCEDURAL_STEPS","INSTITUTIONAL_ROLES_1-3-1","RISK_NOTE","DOCUMENTS_FOR_AUDIT","COMPLIANCE_STATUS","REFERENCE","DISCLAIMER"]SHORT_MODE_HEADINGS = ["DIRECT_ANSWER","RISK_NOTE","COMPLIANCE_STATUS","DISCLAIMER"]DISCLAIMER_KEY = "This is AI-generated"6 unmodified linesreturn "FULL"def validate_headings(output: str, expected_headings: list):pattern = r"\*\*(.*?)\*\*"found = re.findall(pattern, output)if not found:return False, "No bold headings found"found_clean = [h.strip() for h in found]idx = 0for heading in expected_headings:if heading not in found_clean:return False, f"Missing heading: {heading}"if found_clean.index(heading) < idx:return False, f"Incorrect order for heading: {heading}"idx = found_clean.index(heading)return True, "Headings valid"20 unmodified linesdef validate_goods_services_split(output: str):if "goods" in output.lower() and "services" in output.lower():return True, "OK"return True, "Not enforced strictly"31 unmodified linesreturn True, "VALID"# =========================# END VALIDATOR# =========================101 unmodified linesmax_retries = 2answer = Nonecurrent_query = original_queryfor attempt in range(max_retries + 1):# Similarity search with the CURRENT query (may be reinforced)logger.info(f"๐ Attempt {attempt+1}: Performing similarity search...")docs = engine_db.similarity_search(current_query, k=15)logger.info(f"๐ Retrieved {len(docs)} documents")67 unmodified linesanswer = chat_completion.choices[0].message.contentlogger.info(f"โ Answer generated ({len(answer)} chars)")# Validate using the **original** query to ensure correct mode detectionis_valid, reason = validate_output(original_query, answer)if is_valid:logger.info("โ Output passed post-generation validation")1 unmodified lineelse:logger.warning(f"โ ๏ธ Validation failed (attempt {attempt+1}): {reason}")if attempt < max_retries:# Reinforce prompt for next retrycurrent_query = original_query + "\n\nโ ๏ธ Follow strict output format with all headings."else:# Last attempt failed; return fallbackanswer = "System could not generate a compliant response. Please refine query."res = jsonify({30 unmodified lines3132333435363738394041424344454647484950515253545556576 unmodified lines646566676869707172737475767778798081828384858687888990919293949520 unmodified lines11611711811912012112231 unmodified lines154155156157158159160101 unmodified lines26226326426526626726826927067 unmodified lines3383393403413423431 unmodified line34534634734834935035135230 unmodified linesllm = None# =========================# POST-GENERATION VALIDATOR (MATCH PROMPT HEADINGS)# =========================FULL_MODE_HEADINGS = ["Direct Advisor Answer", # prompt says "1. Direct Advisor Answer""Conditions", # "2. Conditions""When Not Applicable", # "3. When Not Applicable""Procedural Steps", # "4. Procedural Steps""Institutional Roles (1-3-1)", # "5. Institutional Roles (1-3-1)""Risk Note", # "6. Risk Note""Documents for AUDIT", # "7. Documents for AUDIT""Compliance Status", # "8. Compliance Status""Reference", # "9. Reference""Disclaimer" # "10. Disclaimer"]SHORT_MODE_HEADINGS = ["Direct Answer", # "Direct Answer""Risk Note","Compliance Status","Disclaimer"]DISCLAIMER_KEY = "This is AI-generated"6 unmodified linesreturn "FULL"def _clean_bold_text(text: str) -> str:"""Remove leading numbers like '1. ' or '1.' from a bold heading."""return re.sub(r'^\d+\.\s*', '', text.strip()).strip()def validate_headings(output: str, expected_headings: list):"""Ensure all required headings are present in order, ignoring numbering."""pattern = r"\*\*(.*?)\*\*"found_raw = re.findall(pattern, output)if not found_raw:return False, "No bold headings found"# Clean and filter only the headings we care aboutfound_headings = []for h in found_raw:cleaned = _clean_bold_text(h)if cleaned in expected_headings:found_headings.append(cleaned)# Check that all expected headings appear in the right sequenceif found_headings != expected_headings:missing = set(expected_headings) - set(found_headings)if missing:return False, f"Missing heading(s): {', '.join(missing)}"# Order wrongreturn False, "Headings present but in wrong order"return True, "Headings valid"20 unmodified linesdef validate_goods_services_split(output: str):# Soft checkif "goods" in output.lower() and "services" in output.lower():return True, "OK"return True, "Not enforced strictly"31 unmodified linesreturn True, "VALID"# =========================# END VALIDATOR# =========================101 unmodified linesmax_retries = 2answer = Nonecurrent_query = original_queryis_valid = Falsefor attempt in range(max_retries + 1):logger.info(f"๐ Attempt {attempt+1}: Performing similarity search...")docs = engine_db.similarity_search(current_query, k=15)logger.info(f"๐ Retrieved {len(docs)} documents")67 unmodified linesanswer = chat_completion.choices[0].message.contentlogger.info(f"โ Answer generated ({len(answer)} chars)")is_valid, reason = validate_output(original_query, answer)if is_valid:logger.info("โ Output passed post-generation validation")1 unmodified lineelse:logger.warning(f"โ ๏ธ Validation failed (attempt {attempt+1}): {reason}")if attempt < max_retries:current_query = original_query + "\n\nโ ๏ธ Follow strict output format with all headings."else:answer = "System could not generate a compliant response. Please refine query."res = jsonify({
app.py+40-31