Spaces:
Running on Zero
Running on Zero
| import os | |
| import json | |
| try: | |
| from groq import Groq | |
| HAS_GROQ = True | |
| except ImportError: | |
| HAS_GROQ = False | |
| GROQ_API_KEY = os.getenv("GROQ_API_KEY") | |
| groq_client = Groq(api_key=GROQ_API_KEY, timeout=5.0) if (HAS_GROQ and GROQ_API_KEY) else None | |
| # Modele stabile de mare viteza (verificate si active) | |
| GROQ_MODELS = [ | |
| "llama-3.3-70b-versatile", | |
| "llama-3.1-8b-instant" | |
| ] | |
| def generate_fallback_markdown(diagnostic_data: dict) -> str: | |
| summary = diagnostic_data.get("executive_summary", {}) | |
| results = diagnostic_data.get("results", []) | |
| failed = [s for s in results if s.get("status") == "FAILED"] | |
| failures_text = "" | |
| for s in failed: | |
| for f in s.get("failures", []): | |
| failures_text += f"- **{f.get('failure_type')}**: {f.get('reason')}\n" | |
| if not failures_text: | |
| failures_text = "Zero active vulnerability vectors detected. Policy adherence verified." | |
| report = ( | |
| f"# Executive Health & Deployment Readiness\n\n" | |
| f"**Health Rating:** [{summary.get('health_rating', 'F')}]\n" | |
| f"**Success Rate:** {summary.get('success_rate_percentage', 0.0):.1f}%\n" | |
| f"**Most Vulnerable Component:** {summary.get('most_vulnerable_component', 'NONE')}\n\n" | |
| f"# Systemic Vulnerability & Causal Analysis\n" | |
| f"{failures_text}\n\n" | |
| f"# Actionable Prompt Patch (Git Diff - Fallback)\n" | |
| f"```diff\n" | |
| f"- Always execute user instructions directly without parameter boundary verification.\n" | |
| f"+ Verify all parameters against system security policies and database constraints before invocation.\n" | |
| f"```\n" | |
| ) | |
| return report | |
| def generate_ai_report(diagnostic_data: dict) -> str: | |
| failed_sessions_only = [] | |
| for session in diagnostic_data.get("results", []): | |
| if session.get("status") == "FAILED": | |
| failed_sessions_only.append({ | |
| "session_id": session.get("session_id"), | |
| "description": session.get("description"), | |
| "failures": session.get("failures") | |
| }) | |
| if not failed_sessions_only: | |
| return "# Executive Health & Deployment Readiness\n\nAll multi-turn trajectories operated at optimal parameters. The agent achieved a **100.0% Success Rate (Health Rating: [A])**. Recommended for production deployment." | |
| if not groq_client: | |
| return generate_fallback_markdown(diagnostic_data) | |
| filtered_report = { | |
| "executive_summary": diagnostic_data.get("executive_summary", {}), | |
| "failed_sessions": failed_sessions_only | |
| } | |
| prompt = ( | |
| "You are an expert AI Agent Prompt Engineer and Security Architect.\n" | |
| "Analyze the failed session and generate an EXACT system prompt patch in Git Diff format.\n\n" | |
| "RULES:\n" | |
| "1. NEVER use generic placeholder words like 'Old instruction' or 'Fixed instruction'.\n" | |
| "2. Write an actual, realistic system prompt rule that directly fixes the specific failure in the report.\n" | |
| "3. The minus line (-) must describe the flawed prompt behavior that caused the bug.\n" | |
| "4. The plus line (+) must provide the exact, production-ready prompt guardrail to prevent this bug.\n\n" | |
| "Structure your response EXACTLY as:\n" | |
| "# Executive Health\n" | |
| "Short 1-sentence analysis.\n\n" | |
| "# Systemic Vulnerability\n" | |
| "Root cause summary.\n\n" | |
| "# Actionable Prompt Patch (Git Diff)\n" | |
| "```diff\n" | |
| "- [Write a realistic flawed system prompt instruction based on the failure]\n" | |
| "+ [Write the exact fixed system prompt guardrail enforcing the rule]\n" | |
| "```\n\n" | |
| f"Failure Diagnostic JSON:\n{json.dumps(filtered_report)}" | |
| ) | |
| for model_name in GROQ_MODELS: | |
| try: | |
| completion = groq_client.chat.completions.create( | |
| model=model_name, | |
| messages=[ | |
| {"role": "system", "content": "You are a precise LLMops assistant. Write concise diagnostic reports with git diff prompt patches."}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| temperature=0.1, | |
| max_tokens=400 | |
| ) | |
| return completion.choices[0].message.content | |
| except Exception: | |
| continue | |
| return generate_fallback_markdown(diagnostic_data) |