|
import os |
|
import requests |
|
|
|
|
|
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 = 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. |
|
""" |
|
|
|
|
|
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() |
|
|
|
|
|
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)}" |
|
|