misinformation-filter / llm_layer.py
harshbpathak's picture
Update llm_layer.py
4468e16 verified
import os
import requests
# Read the Gemini API key from Hugging Face "Repository secrets"
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"
def fact_check_with_llm(news_text: str) -> str:
"""
Sends the news text to Gemini API for a fact-checking style analysis.
Returns a label (Real or Fake) and explanation, or an error message.
"""
if not GEMINI_API_KEY:
return "Error: Gemini API key not found. Please set GEMINI_API_KEY in environment."
# Prompt design: Clear, constrained, and task-focused
prompt = f"""
You are an AI assistant that helps detect misinformation in news articles.
Here is a news claim:
\"{news_text.strip()}\"
Your task:
1. Decide if this claim is factually accurate or not.
2. Respond with **only one of** these labels: Real or Fake.
3. Then give a short explanation (2–3 lines) based on reasoning or likely credibility.
"""
# Gemini API request
headers = {
"Content-Type": "application/json"
}
params = {
"key": GEMINI_API_KEY
}
data = {
"contents": [
{
"parts": [
{"text": prompt}
]
}
]
}
try:
response = requests.post(
GEMINI_API_URL,
headers=headers,
params=params,
json=data,
timeout=30
)
response.raise_for_status()
result = response.json()
# Parse the Gemini response safely
message = result.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text", "")
return message.strip() or "No response from Gemini."
except requests.exceptions.Timeout:
return "Error: Gemini API request timed out."
except requests.exceptions.HTTPError as http_err:
return f"HTTP Error: {http_err}"
except Exception as e:
return f"Unexpected error during Gemini fact-check: {str(e)}"