Spaces:
Sleeping
Sleeping
add step 3: safety validation
Browse filesFiles changed (2)
- app.py+78-69
- nlproxy/service/compression.py+1-3
1234279 unmodified lines2842852862872882892908 unmodified lines2993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283291 unmodified line3313323333343353363373382 unmodified lines3413423433443453463473483493503513523533543553563573583594 unmodified lines3643653663673683693702 unmodified lines3733743753763773783793803813823833843853863873883893903913925 unmodified lines398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455104 unmodified lines56056156256356456556618 unmodified lines58558658758858959059159259359421 unmodified lines616617618619620621from __future__ import annotationsimport osimport reimport sys279 unmodified linesdef execute_pipeline(raw_prompt: str,llm_response: str,privacy_mode: bool,mode: str,8 unmodified linesraise gr.Error("Dirty User Prompt cannot be empty.")if not llm_response.strip():raise gr.Error("Simulated LLM Response cannot be empty.")try:pipeline = NLProxyPipeline.get_instance()pipeline.verifier.use_nli = use_nli# STEP 1: FIREWALLaction, violations = pipeline.firewall.check_prompt(raw_prompt)firewall_md = f"**π‘οΈ Action:** `{action.name}`\n"if violations:firewall_md += "**Violations:**\n" + "\n".join([f"- π¨ {v['rule']} ({v['severity']})" for v in violations])else:firewall_md += "*β No malicious injections detected.*"# STEP 2 & 3: COMPRESS & SHIELD (With Manual Rule Injection)shield_res = pipeline.service._shield_with_cache(raw_prompt,mode=mode)# INJECT MANUALmanual_rules_list = parse_manual_rules(manual_rules)if manual_rules_list:shield_res.restrictions.extend(manual_rules_list)# Now run compressionres = pipeline.service.compress_batch([raw_prompt],mode=mode,1 unmodified lineprivacy_mode=privacy_mode)[0]compressed_text = res.get("compressed_text", "")# --- TRUTHTABLE VISUALIZATION ---tt_md = "**π Shielded Entities (PII/Secrets):**\n"entity_groups = {}for ent in shield_res.entities:2 unmodified linesentity_groups[etype].append(ent.value)for etype, values in entity_groups.items():tt_md += f"- **{etype}**: `{', '.join(values[:3])}` {'...' if len(values)>3 else ''}\n"if not entity_groups:tt_md += "- *None detected*\n"tt_md += "\n**π Semantic Restrictions (TruthTable):**\n"if shield_res.restrictions:for r in shield_res.restrictions:resolved = resolve_entity(r.entity, shield_res.placeholder_map)tt_md += f"- **{r.type}**: `{resolved}`\n"else:tt_md += "- *None detected*\n"# METRICStokens_saved = res.get('tokens_saved', 0)ratio = res.get('compression_ratio', 0)raw_cost = res.get('cost_saved_usd', 0)4 unmodified linesf"### π Compression & Security Metrics\n"f"- **π Security Overhead:** `{abs(tokens_saved)} tokens` *(Placeholders + Rules)*\n"f"- **π° Net Cost Impact:** `+${abs(real_cost):.6f}`\n"f"- **π‘οΈ Safety Score:** `{res.get('safety_score', 'N/A')}`\n"f"\n> βΉοΈ *Negative compression = Security features added more tokens than were saved.*")else:2 unmodified linesf"- **β Tokens Saved:** `{tokens_saved}`\n"f"- **π° Cost Saved:** `${real_cost:.6f}`\n"f"- **π Compression Ratio:** `{ratio:.2%}`\n"f"- **π‘οΈ Safety Score:** `{res.get('safety_score', 'N/A')}`")response_text = llm_responseif privacy_mode:response_text = pipeline.service.reconstructor._reinject_entities(response_text,shield_res.placeholder_map)# STEP 4: CORRECTcorrected = pipeline.corrector.correct(response_text, shield_res)# STEP 5: VERIFYverification = pipeline.verifier.verify(corrected, shield_res)correction_attempts = 05 unmodified linesand correction_attempts < max_regeneration_attempts):correction_attempts += 1logger.info(f"Auto-correction attempt {correction_attempts}/{max_regeneration_attempts}")# Simular regeneraciΓ³n (en producciΓ³n esto llamarΓa al LLM nuevamente)# Por ahora solo registramos el intentoverification = pipeline.verifier.verify(final_response_text, shield_res)if verification.confidence_score >= min_confidence:break# Build verification markdownverif_md = f"**π― Confidence Score:** `{verification.confidence_score:.2f}`\n\n"if correction_attempts > 0:verif_md += f"**π Auto-correction attempts:** {correction_attempts}\n\n"if verification.violations:semantic_drifts = []unauthorized_entities = []policy_violations = []for v in verification.violations:if "Semantic contradiction" in v:semantic_drifts.append(v)elif "Unauthorized entity" in v:match = re.search(r"Unauthorized entity in response: (.+?) \(type: price\)", v)if match:entity_val = match.group(1)is_real_price = any(sym in entity_val for sym in ['$', 'β¬', 'Β£', 'Β₯', 'USD', 'EUR', 'GBP', 'JPY'])if not is_real_price:continueunauthorized_entities.append(v)else:policy_violations.append(v)if policy_violations:verif_md += "**π¨ Policy & Restriction Violations:**\n"for v in policy_violations:verif_md += f"- {v}\n"if unauthorized_entities:verif_md += "\n**π΅οΈ Unauthorized Data Exfiltration:**\n"for v in unauthorized_entities:verif_md += f"- {v}\n"if semantic_drifts:verif_md += f"\n**π Semantic Drift (NLI):**\n"verif_md += f"- *Detected contradictions across {len(semantic_drifts)} original sentences.*\n"verif_md += f"- *LLM response diverges from original prompt intent.*\n"else:verif_md += "*β No semantic drift or policy violations detected.*"return firewall_md, compressed_text, tt_md, metrics_md, final_response_text, verif_mdexcept Exception as e:logger.exception("Critical failure in pipeline execution.")104 unmodified lineswith gr.Row():mode_dropdown = gr.Dropdown(choices=["general", "code", "finance", "legal"],value="code",label="Domain Mode")aggressiveness_slider = gr.Slider(18 unmodified linesgr.Markdown("#### π‘οΈ Step 1: Firewall (Pre-flight)")firewall_out = gr.Markdown()gr.Markdown("#### ποΈ Step 2 & 3: Compress & Shield (TruthTable)")compress_out = gr.Textbox(label="Compressed Prompt (Sent to LLM)", interactive=False, lines=6)truthtable_out = gr.Markdown()gr.Markdown("#### π§Ή Step 4: Response Corrector")corrector_out = gr.Textbox(label="Sanitized LLM Output (Post-Flight)", interactive=False, lines=6)21 unmodified linesoutputs=[firewall_out,compress_out,truthtable_out,metrics_out,corrector_out,12345279 unmodified lines2852862872882892902918 unmodified lines3003013023033043053063073083093103113123133143153163173183193203213223233241 unmodified line3263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763772 unmodified lines3803813823833843853863873883893903913923933943953963973983994 unmodified lines4044054064074084094102 unmodified lines4134144154164174184194204214224234244254264274284294304315 unmodified lines437438439440441442443444445446447448449450451452453454455456457458459460104 unmodified lines56556656756856957057118 unmodified lines59059159259359459559659759859960060160221 unmodified lines624625626627628629630from __future__ import annotationsimport osimport reimport sys279 unmodified linesdef execute_pipeline(raw_prompt: str,llm_response: str,privacy_mode: bool,mode: str,8 unmodified linesraise gr.Error("Dirty User Prompt cannot be empty.")if not llm_response.strip():raise gr.Error("Simulated LLM Response cannot be empty.")try:pipeline = NLProxyPipeline.get_instance()pipeline.verifier.use_nli = use_nli# =========================================================================# STEP 1: FIREWALL (Pre-flight)# =========================================================================action, violations = pipeline.firewall.check_prompt(raw_prompt)firewall_md = f"**π‘οΈ Action:** `{action.name}`\n\n"if violations:firewall_md += "**Violations:**\n" + "\n".join([f"- π¨ {v['rule']} ({v['severity']})" for v in violations])else:firewall_md += "*β No malicious injections detected.*"# =========================================================================# STEP 2: COMPRESS (Semantic Compression)# =========================================================================# compress_batch internally shields, segments, compresses, and reconstructs.res = pipeline.service.compress_batch([raw_prompt],mode=mode,1 unmodified lineprivacy_mode=privacy_mode)[0]compressed_text = res.get("compressed_text", "")# =========================================================================# STEP 3: SHIELD WITH MANUAL RULES (Matches chat.py exactly)# =========================================================================# We shield AGAIN to capture manual rules for the Safety/Corrector steps.manual_rules_list = parse_manual_rules(manual_rules)shield_res = pipeline.service._shield_with_cache(text=raw_prompt,manual_restrictions=manual_rules_list,mode=mode)# Resolve placeholders in restrictions to prevent "__PROT_..." leaking into Corrector notesfor r in shield_res.restrictions:if r.entity.startswith("__PROT_") and r.entity in shield_res.placeholder_map:real_value = shield_res.placeholder_map[r.entity]object.__setattr__(r, 'entity', real_value) # Bypass frozen dataclass# =========================================================================# STEP 4: SAFETY VALIDATION (Intent Preservation)# =========================================================================sentences = pipeline.service.segmenter.split_sentences(shield_res.shielded_text, language=None)safety_report = pipeline.service.safety.validate(original_text=raw_prompt,compressed_text=compressed_text,shield_result=shield_res,original_sentences=sentences,mode=mode,use_perplexity=False)# The safety checker might have re-injected missing critical sentencesfinal_prompt_for_llm = safety_report.final_textsafety_md = f"**π‘οΈ Safety Score:** `{safety_report.safety_score:.2f}`\n\n"if safety_report.forced_sentences_added > 0:safety_md += f"β οΈ **Re-injected {safety_report.forced_sentences_added} critical sentence(s)** that compression tried to remove.\n"safety_md += f"*Missing intents detected: {', '.join(safety_report.missing_intents[:3])}*\n"else:safety_md += "β *All critical intents preserved during compression.*"# =========================================================================# TRUTHTABLE VISUALIZATION# =========================================================================tt_md = "**π Shielded Entities (PII/Secrets):**\n"entity_groups = {}for ent in shield_res.entities:2 unmodified linesentity_groups[etype].append(ent.value)for etype, values in entity_groups.items():tt_md += f"- **{etype}**: `{', '.join(values[:3])}` {'...' if len(values) > 3 else ''}\n"if not entity_groups:tt_md += "- *None detected*\n"tt_md += "\n**π Semantic Restrictions (TruthTable):**\n"if shield_res.restrictions:for r in shield_res.restrictions:tt_md += f"- **{r.type}**: `{r.entity}`\n"else:tt_md += "- *None detected*\n"# =========================================================================# METRICS# =========================================================================tokens_saved = res.get('tokens_saved', 0)ratio = res.get('compression_ratio', 0)raw_cost = res.get('cost_saved_usd', 0)4 unmodified linesf"### π Compression & Security Metrics\n"f"- **π Security Overhead:** `{abs(tokens_saved)} tokens` *(Placeholders + Rules)*\n"f"- **π° Net Cost Impact:** `+${abs(real_cost):.6f}`\n"f"- **π‘οΈ Safety Score:** `{safety_report.safety_score:.2f}`\n"f"\n> βΉοΈ *Negative compression = Security features added more tokens than were saved.*")else:2 unmodified linesf"- **β Tokens Saved:** `{tokens_saved}`\n"f"- **π° Cost Saved:** `${real_cost:.6f}`\n"f"- **π Compression Ratio:** `{ratio:.2%}`\n"f"- **π‘οΈ Safety Score:** `{safety_report.safety_score:.2f}`")# =========================================================================# STEP 5: CORRECT & VERIFY (Post-flight)# =========================================================================response_text = llm_responseif privacy_mode:response_text = pipeline.service.reconstructor._reinject_entities(response_text, shield_res.placeholder_map)corrected = pipeline.corrector.correct(response_text, shield_res)verification = pipeline.verifier.verify(corrected, shield_res)correction_attempts = 05 unmodified linesand correction_attempts < max_regeneration_attempts):correction_attempts += 1verification = pipeline.verifier.verify(final_response_text, shield_res)if verification.confidence_score >= min_confidence:break# Build verification markdownverif_md = f"**π― Confidence Score:** `{verification.confidence_score:.2f}`\n\n"if correction_attempts > 0:verif_md += f"**π Auto-correction attempts:** {correction_attempts}\n\n"if verification.violations:verif_md += "**π¨ Violations Detected:**\n"for v in verification.violations[:5]: # Limit to 5 for UI cleanlinessverif_md += f"- {v}\n"else:verif_md += "*β No semantic drift or policy violations detected.*"# Return 7 items to match the new UI layoutreturn firewall_md, final_prompt_for_llm, safety_md, tt_md, metrics_md, final_response_text, verif_mdexcept Exception as e:logger.exception("Critical failure in pipeline execution.")104 unmodified lineswith gr.Row():mode_dropdown = gr.Dropdown(choices=["general", "code", "finance", "legal"],value="general",label="Domain Mode")aggressiveness_slider = gr.Slider(18 unmodified linesgr.Markdown("#### π‘οΈ Step 1: Firewall (Pre-flight)")firewall_out = gr.Markdown()gr.Markdown("#### ποΈ Step 2: Compress Prompt")compress_out = gr.Textbox(label="Compressed Prompt (Sent to LLM)", interactive=False, lines=6)truthtable_out = gr.Markdown()gr.Markdown("#### π§ Step 3: Safety Validation (Intent Preservation)")safety_out = gr.Markdown()gr.Markdown("#### π§Ή Step 4: Response Corrector")corrector_out = gr.Textbox(label="Sanitized LLM Output (Post-Flight)", interactive=False, lines=6)21 unmodified linesoutputs=[firewall_out,compress_out,safety_out,truthtable_out,metrics_out,corrector_out,
563 unmodified lines564565566567568569570571572563 unmodified linesif cached_bytes is not None:# Load from cachesent_emb[idx] = np.frombuffer(cached_bytes, dtype=np.float32).reshape(1, -1)else:uncached.append(sent)uncached_idx.append(idx)563 unmodified lines564565566567568569570563 unmodified linesif cached_bytes is not None:# Load from cachesent_emb[idx] = np.frombuffer(cached_bytes, dtype=np.float32)else:uncached.append(sent)uncached_idx.append(idx)
app.py+78-69
nlproxy/service/compression.py+1-3