Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,172 +0,0 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import os
|
| 3 |
-
import json
|
| 4 |
-
import time
|
| 5 |
-
from groq import Groq
|
| 6 |
-
import google.generativeai as genai
|
| 7 |
-
from typing import List, Dict, Any
|
| 8 |
-
from duckduckgo_search import DDGS
|
| 9 |
-
|
| 10 |
-
# Configuration
|
| 11 |
-
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 12 |
-
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 13 |
-
|
| 14 |
-
# Simple Rate Limiter
|
| 15 |
-
rate_limit_store = {}
|
| 16 |
-
RATE_LIMIT_WINDOW = 60 # 1 minute
|
| 17 |
-
MAX_REQUESTS = 5
|
| 18 |
-
|
| 19 |
-
def is_rate_limited(client_ip: str) -> bool:
|
| 20 |
-
now = time.time()
|
| 21 |
-
if client_ip not in rate_limit_store:
|
| 22 |
-
rate_limit_store[client_ip] = []
|
| 23 |
-
|
| 24 |
-
# Filter out old requests
|
| 25 |
-
rate_limit_store[client_ip] = [t for t in rate_limit_store[client_ip] if now - t < RATE_LIMIT_WINDOW]
|
| 26 |
-
|
| 27 |
-
if len(rate_limit_store[client_ip]) >= MAX_REQUESTS:
|
| 28 |
-
return True
|
| 29 |
-
|
| 30 |
-
rate_limit_store[client_ip].append(now)
|
| 31 |
-
return False
|
| 32 |
-
|
| 33 |
-
# Initialize Clients
|
| 34 |
-
groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
|
| 35 |
-
if GEMINI_API_KEY:
|
| 36 |
-
genai.configure(api_key=GEMINI_API_KEY)
|
| 37 |
-
|
| 38 |
-
# Model Mapping
|
| 39 |
-
MODELS = {
|
| 40 |
-
"reasoning": "llama-3.3-70b-versatile",
|
| 41 |
-
"extraction": "llama-3.3-70b-versatile",
|
| 42 |
-
"synthesis": "llama-3.3-70b-versatile"
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
def call_llm(prompt: str, model_type: str = "reasoning") -> str:
|
| 46 |
-
"""Helper to call available LLM (Groq with Gemini fallback)"""
|
| 47 |
-
model_name = MODELS.get(model_type, "llama-3.3-70b-versatile")
|
| 48 |
-
|
| 49 |
-
if groq_client:
|
| 50 |
-
try:
|
| 51 |
-
completion = groq_client.chat.completions.create(
|
| 52 |
-
messages=[{"role": "user", "content": prompt}],
|
| 53 |
-
model=model_name,
|
| 54 |
-
response_format={"type": "json_object"} if "JSON" in prompt else None
|
| 55 |
-
)
|
| 56 |
-
return completion.choices[0].message.content
|
| 57 |
-
except Exception as e:
|
| 58 |
-
print(f"Groq Error: {e}")
|
| 59 |
-
|
| 60 |
-
if GEMINI_API_KEY:
|
| 61 |
-
try:
|
| 62 |
-
model = genai.GenerativeModel("gemini-1.5-flash")
|
| 63 |
-
response = model.generate_content(prompt)
|
| 64 |
-
return response.text
|
| 65 |
-
except Exception as e:
|
| 66 |
-
print(f"Gemini Error: {e}")
|
| 67 |
-
|
| 68 |
-
return "Error: No active LLM provider configured or both failed."
|
| 69 |
-
|
| 70 |
-
def web_search(query: str, max_results: int = 5) -> List[Dict[str, str]]:
|
| 71 |
-
"""Real-time search using DuckDuckGo"""
|
| 72 |
-
results = []
|
| 73 |
-
try:
|
| 74 |
-
with DDGS() as ddgs:
|
| 75 |
-
ddgs_gen = ddgs.text(query, max_results=max_results)
|
| 76 |
-
for r in ddgs_gen:
|
| 77 |
-
results.append({
|
| 78 |
-
"title": r.get("title", ""),
|
| 79 |
-
"body": r.get("body", ""),
|
| 80 |
-
"href": r.get("href", "")
|
| 81 |
-
})
|
| 82 |
-
except Exception as e:
|
| 83 |
-
print(f"Search Error: {e}")
|
| 84 |
-
return results
|
| 85 |
-
|
| 86 |
-
def verify_claim_pipeline(query: str, request: gr.Request = None):
|
| 87 |
-
"""The full 12-agent verification pipeline with real search"""
|
| 88 |
-
|
| 89 |
-
# Check rate limit
|
| 90 |
-
client_ip = request.client.host if request else "unknown"
|
| 91 |
-
if is_rate_limited(client_ip):
|
| 92 |
-
return {
|
| 93 |
-
"answer": "Rate limit exceeded",
|
| 94 |
-
"confidence": 0.0,
|
| 95 |
-
"reasoningSummary": f"Too many requests from {client_ip}. Please wait a minute.",
|
| 96 |
-
"supportingEvidence": [],
|
| 97 |
-
"sources": []
|
| 98 |
-
}
|
| 99 |
-
|
| 100 |
-
# 1. Query Analyzer
|
| 101 |
-
analysis_prompt = f"Analyze this query for verification intent: '{query}'. Return JSON with 'complexity', 'intent', 'isVerifiable' (bool)."
|
| 102 |
-
analysis = json.loads(call_llm(analysis_prompt, "extraction"))
|
| 103 |
-
|
| 104 |
-
# 2. Claim Extractor
|
| 105 |
-
claims_prompt = f"Extract distinct atomic claims from: '{query}'. Return JSON array 'claims' with 'text' fields."
|
| 106 |
-
claims_data = json.loads(call_llm(claims_prompt, "extraction"))
|
| 107 |
-
claims = claims_data.get("claims", [query])
|
| 108 |
-
|
| 109 |
-
# 3. Domain Classifier
|
| 110 |
-
domains_prompt = f"Classify the domains (e.g. Science, Tech, Politics) for these claims: {claims}. Return JSON array 'domains'."
|
| 111 |
-
domains = json.loads(call_llm(domains_prompt, "extraction"))
|
| 112 |
-
|
| 113 |
-
# 4. Source Selector (Search Query Generator)
|
| 114 |
-
search_queries_prompt = f"Generate 3 optimized search queries to verify these claims: {claims}. Return JSON array 'queries'."
|
| 115 |
-
search_queries = json.loads(call_llm(search_queries_prompt, "extraction")).get("queries", [query])
|
| 116 |
-
|
| 117 |
-
# 5. Retrieval Engine (Real-time Search)
|
| 118 |
-
all_search_results = []
|
| 119 |
-
for sq in search_queries:
|
| 120 |
-
all_search_results.extend(web_search(sq))
|
| 121 |
-
|
| 122 |
-
# 6. Evidence Extractor
|
| 123 |
-
extraction_prompt = f"Extract the most relevant factual snippets for claims {claims} from these search results: {all_search_results[:10]}. Return JSON array 'snippets' with 'fact' and 'source' (url)."
|
| 124 |
-
evidence_data = json.loads(call_llm(extraction_prompt, "reasoning"))
|
| 125 |
-
evidence = evidence_data.get("snippets", [])
|
| 126 |
-
|
| 127 |
-
# 7. Evidence Scorer
|
| 128 |
-
scoring_prompt = f"Score the relevance and reliability (0.0-1.0) of this evidence {evidence} for claims {claims}. Return JSON array 'scored_evidence' with 'fact', 'source', 'score'."
|
| 129 |
-
scored_evidence = json.loads(call_llm(scoring_prompt, "reasoning")).get("scored_evidence", evidence)
|
| 130 |
-
|
| 131 |
-
# 8. Verification Engine
|
| 132 |
-
verification_prompt = f"Verify claims {claims} against scored evidence {scored_evidence}. Identify specific confirmations or contradictions. Return JSON 'verdict' (Verified/Debunked/Uncertain) and 'detailed_analysis'."
|
| 133 |
-
verification = json.loads(call_llm(verification_prompt, "reasoning"))
|
| 134 |
-
|
| 135 |
-
# 9. Conflict Resolver
|
| 136 |
-
conflict_prompt = f"Are there any contradictions in the retrieved evidence or verification results? {verification}. Resolve conflicts and return JSON 'resolved_verdict', 'conflict_notes'."
|
| 137 |
-
resolved = json.loads(call_llm(conflict_prompt, "reasoning"))
|
| 138 |
-
|
| 139 |
-
# 10. Truth Policy Engine
|
| 140 |
-
policy_prompt = f"Check the resolved verdict {resolved} against safety and factual accuracy policies. Is this output helpful and harmless? Return JSON 'is_safe' (bool), 'adjustment_needed' (string)."
|
| 141 |
-
policy = json.loads(call_llm(policy_prompt, "reasoning"))
|
| 142 |
-
|
| 143 |
-
# 11. Knowledge Graph Preparation (Simulated)
|
| 144 |
-
graph_prompt = f"Structure the following verified info for graph database entry: {resolved}. Return JSON array 'triplets' (subject, predicate, object)."
|
| 145 |
-
graph_data = json.loads(call_llm(graph_prompt, "extraction"))
|
| 146 |
-
|
| 147 |
-
# 12. Response Generator
|
| 148 |
-
synthesis_prompt = f"Synthesize a final authoritative report for: '{query}'. Use evidence: {scored_evidence} and verdict: {resolved}. Safety check: {policy}. Return JSON with 'answer', 'confidence' (float 0-1), 'reasoningSummary', 'supportingEvidence' (array of {{'fact', 'source'}}), 'sources' (array of urls)."
|
| 149 |
-
final_response = json.loads(call_llm(synthesis_prompt, "synthesis"))
|
| 150 |
-
|
| 151 |
-
return final_response
|
| 152 |
-
|
| 153 |
-
# Gradio Interface
|
| 154 |
-
with gr.Blocks(title="Truth API Backend") as demo:
|
| 155 |
-
gr.Markdown("# Truth Verification Pipeline API")
|
| 156 |
-
gr.Markdown("Full 12-Agent distributed verification pipeline with real-time web search.")
|
| 157 |
-
|
| 158 |
-
with gr.Row():
|
| 159 |
-
query_input = gr.Textbox(label="Claim to Verify", placeholder="Enter a claim...", lines=3)
|
| 160 |
-
verify_btn = gr.Button("Verify", variant="primary")
|
| 161 |
-
|
| 162 |
-
output_json = gr.JSON(label="Verification Result")
|
| 163 |
-
|
| 164 |
-
verify_btn.click(
|
| 165 |
-
fn=verify_claim_pipeline,
|
| 166 |
-
inputs=query_input,
|
| 167 |
-
outputs=output_json,
|
| 168 |
-
api_name="verify"
|
| 169 |
-
)
|
| 170 |
-
|
| 171 |
-
if __name__ == "__main__":
|
| 172 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|