Adedoyinjames commited on
Commit
766d2af
·
verified ·
1 Parent(s): 88881c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -20
app.py CHANGED
@@ -5,6 +5,7 @@ import re
5
  from groq import Groq
6
  import google.generativeai as genai
7
  from typing import List, Dict, Any
 
8
 
9
  # Configuration
10
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
@@ -15,9 +16,9 @@ groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
15
  if GEMINI_API_KEY:
16
  genai.configure(api_key=GEMINI_API_KEY)
17
 
18
- # Model Mapping based on user availability
19
  MODELS = {
20
- "reasoning": "llama-3.3-70b-versatile", # Using Llama 3.3 70B as it's top tier on Groq
21
  "extraction": "llama-3.3-70b-versatile",
22
  "synthesis": "llama-3.3-70b-versatile"
23
  }
@@ -36,7 +37,6 @@ def call_llm(prompt: str, model_type: str = "reasoning") -> str:
36
  return completion.choices[0].message.content
37
  except Exception as e:
38
  print(f"Groq Error: {e}")
39
- # Fallback to Gemini if Groq fails
40
 
41
  if GEMINI_API_KEY:
42
  try:
@@ -48,8 +48,24 @@ def call_llm(prompt: str, model_type: str = "reasoning") -> str:
48
 
49
  return "Error: No active LLM provider configured or both failed."
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def verify_claim_pipeline(query: str):
52
- """The 12-agent verification pipeline"""
53
 
54
  # 1. Query Analyzer
55
  analysis_prompt = f"Analyze this query for verification intent: '{query}'. Return JSON with 'complexity', 'intent', 'isVerifiable' (bool)."
@@ -58,27 +74,48 @@ def verify_claim_pipeline(query: str):
58
  # 2. Claim Extractor
59
  claims_prompt = f"Extract distinct atomic claims from: '{query}'. Return JSON array 'claims' with 'text' fields."
60
  claims_data = json.loads(call_llm(claims_prompt, "extraction"))
61
- claims = claims_data.get("claims", [])
62
 
63
  # 3. Domain Classifier
64
- domains_prompt = f"Classify the domains for these claims: {claims}. Return JSON array 'domains'."
65
  domains = json.loads(call_llm(domains_prompt, "extraction"))
66
 
67
- # 4. Source Selector
68
- sources_prompt = f"Select 3-5 authoritative source types for these domains: {domains}. Return JSON array 'sources'."
69
- sources = json.loads(call_llm(sources_prompt, "extraction"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- # 5. Retrieval (Simulated Knowledge Retrieval)
72
- retrieval_prompt = f"Provide factual evidence and common knowledge points for these claims: {claims}. Cite general authoritative sources. Return JSON array 'evidence' with 'fact' and 'source'."
73
- retrieval = json.loads(call_llm(retrieval_prompt, "reasoning"))
74
- evidence = retrieval.get("evidence", [])
75
 
76
- # 6. Fact Check
77
- fact_check_prompt = f"Cross-reference these claims {claims} against retrieved evidence {evidence}. Identify confirmations and contradictions. Return JSON 'verdict' (Verified/Debunked/Uncertain) and 'reasoning'."
78
- verdict_data = json.loads(call_llm(fact_check_prompt, "reasoning"))
79
 
80
- # 7. Synthesis & Final Response
81
- synthesis_prompt = f"Synthesize a final report for: '{query}'. Based on verdict: {verdict_data} and evidence: {evidence}. Return JSON with 'answer', 'confidence' (0-1), 'reasoningSummary', 'supportingEvidence' (array), 'sources' (array)."
82
  final_response = json.loads(call_llm(synthesis_prompt, "synthesis"))
83
 
84
  return final_response
@@ -86,10 +123,10 @@ def verify_claim_pipeline(query: str):
86
  # Gradio Interface
87
  with gr.Blocks(title="Truth API Backend") as demo:
88
  gr.Markdown("# Truth Verification Pipeline API")
89
- gr.Markdown("This space serves as the backend for the Truth application. It uses a multi-agent pipeline powered by Llama 3.3 70B (Groq) and Gemini.")
90
 
91
  with gr.Row():
92
- query_input = gr.Textbox(label="Claim to Verify", placeholder="e.g. The moon is made of green cheese")
93
  verify_btn = gr.Button("Verify", variant="primary")
94
 
95
  output_json = gr.JSON(label="Verification Result")
 
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")
 
16
  if GEMINI_API_KEY:
17
  genai.configure(api_key=GEMINI_API_KEY)
18
 
19
+ # Model Mapping
20
  MODELS = {
21
+ "reasoning": "llama-3.3-70b-versatile",
22
  "extraction": "llama-3.3-70b-versatile",
23
  "synthesis": "llama-3.3-70b-versatile"
24
  }
 
37
  return completion.choices[0].message.content
38
  except Exception as e:
39
  print(f"Groq Error: {e}")
 
40
 
41
  if GEMINI_API_KEY:
42
  try:
 
48
 
49
  return "Error: No active LLM provider configured or both failed."
50
 
51
+ def web_search(query: str, max_results: int = 5) -> List[Dict[str, str]]:
52
+ """Real-time search using DuckDuckGo"""
53
+ results = []
54
+ try:
55
+ with DDGS() as ddgs:
56
+ ddgs_gen = ddgs.text(query, max_results=max_results)
57
+ for r in ddgs_gen:
58
+ results.append({
59
+ "title": r.get("title", ""),
60
+ "body": r.get("body", ""),
61
+ "href": r.get("href", "")
62
+ })
63
+ except Exception as e:
64
+ print(f"Search Error: {e}")
65
+ return results
66
+
67
  def verify_claim_pipeline(query: str):
68
+ """The full 12-agent verification pipeline with real search"""
69
 
70
  # 1. Query Analyzer
71
  analysis_prompt = f"Analyze this query for verification intent: '{query}'. Return JSON with 'complexity', 'intent', 'isVerifiable' (bool)."
 
74
  # 2. Claim Extractor
75
  claims_prompt = f"Extract distinct atomic claims from: '{query}'. Return JSON array 'claims' with 'text' fields."
76
  claims_data = json.loads(call_llm(claims_prompt, "extraction"))
77
+ claims = claims_data.get("claims", [query])
78
 
79
  # 3. Domain Classifier
80
+ domains_prompt = f"Classify the domains (e.g. Science, Tech, Politics) for these claims: {claims}. Return JSON array 'domains'."
81
  domains = json.loads(call_llm(domains_prompt, "extraction"))
82
 
83
+ # 4. Source Selector (Search Query Generator)
84
+ search_queries_prompt = f"Generate 3 optimized search queries to verify these claims: {claims}. Return JSON array 'queries'."
85
+ search_queries = json.loads(call_llm(search_queries_prompt, "extraction")).get("queries", [query])
86
+
87
+ # 5. Retrieval Engine (Real-time Search)
88
+ all_search_results = []
89
+ for sq in search_queries:
90
+ all_search_results.extend(web_search(sq))
91
+
92
+ # 6. Evidence Extractor
93
+ 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)."
94
+ evidence_data = json.loads(call_llm(extraction_prompt, "reasoning"))
95
+ evidence = evidence_data.get("snippets", [])
96
+
97
+ # 7. Evidence Scorer
98
+ 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'."
99
+ scored_evidence = json.loads(call_llm(scoring_prompt, "reasoning")).get("scored_evidence", evidence)
100
+
101
+ # 8. Verification Engine
102
+ 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'."
103
+ verification = json.loads(call_llm(verification_prompt, "reasoning"))
104
+
105
+ # 9. Conflict Resolver
106
+ conflict_prompt = f"Are there any contradictions in the retrieved evidence or verification results? {verification}. Resolve conflicts and return JSON 'resolved_verdict', 'conflict_notes'."
107
+ resolved = json.loads(call_llm(conflict_prompt, "reasoning"))
108
 
109
+ # 10. Truth Policy Engine
110
+ 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)."
111
+ policy = json.loads(call_llm(policy_prompt, "reasoning"))
 
112
 
113
+ # 11. Knowledge Graph Preparation (Simulated)
114
+ graph_prompt = f"Structure the following verified info for graph database entry: {resolved}. Return JSON array 'triplets' (subject, predicate, object)."
115
+ graph_data = json.loads(call_llm(graph_prompt, "extraction"))
116
 
117
+ # 12. Response Generator
118
+ 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)."
119
  final_response = json.loads(call_llm(synthesis_prompt, "synthesis"))
120
 
121
  return final_response
 
123
  # Gradio Interface
124
  with gr.Blocks(title="Truth API Backend") as demo:
125
  gr.Markdown("# Truth Verification Pipeline API")
126
+ gr.Markdown("Full 12-Agent distributed verification pipeline with real-time web search.")
127
 
128
  with gr.Row():
129
+ query_input = gr.Textbox(label="Claim to Verify", placeholder="Enter a claim...", lines=3)
130
  verify_btn = gr.Button("Verify", variant="primary")
131
 
132
  output_json = gr.JSON(label="Verification Result")