File size: 1,758 Bytes
5a382ae |
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 |
import os
import google.generativeai as genai
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure Gemini API
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
# Model configuration
generation_config = {
"temperature": 0.7,
"top_p": 0.9,
"top_k": 40,
"max_output_tokens": 300,
"response_mime_type": "text/plain",
}
# Initialize the Gemini model
model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
generation_config=generation_config,
)
def generate_explanation(news, context, truth_score):
"""
Generate a concise explanation supporting the truth score.
Arguments:
- news (str): The news or claim being analyzed.
- context (str): Relevant context from external sources.
- truth_score (float): The score indicating the truthfulness of the news.
Returns:
- str: A simple explanation or an empty string if an error occurs.
"""
# Define the prompt for explanation
prompt = (
"Summarize the context below and explain why the given truth score was assigned to the news claim.\n\n"
f"News: {news}\n\n"
f"Context: {context[:3000]}...\n\n"
f"Truth Score: {truth_score:.2f}\n\n"
"Keep the explanation short, factual, and easy to understand."
)
# Generate explanation
try:
chat_session = model.start_chat(history=[]) # Start a new chat session
response = chat_session.send_message(prompt)
return response.text.strip() # Return only the explanation text
except Exception as e:
# Print error and return an empty string
print(f"Error generating explanation: {str(e)}")
return ""
|