File size: 2,060 Bytes
e130311
 
 
 
 
4468e16
e130311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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)}"