Spaces:
Running
Running
import google.generativeai as genai | |
import os | |
import json | |
from dotenv import load_dotenv | |
load_dotenv() | |
api_key = os.getenv("GOOGLE_API_KEY") | |
if not api_key: | |
raise ValueError("GOOGLE_API_KEY environment variable is not set. Please add it to your .env file") | |
print(f"Google API Key loaded: {api_key[:10]}..." if api_key else "No API key found") | |
genai.configure(api_key=api_key) | |
def query_gemini(questions, contexts): | |
try: | |
context = "\n\n".join(contexts) | |
questions_text = "\n".join([f"{i+1}. {q}" for i, q in enumerate(questions)]) | |
prompt = f""" | |
You are an expert insurance assistant helping users understand policy details. Use the information provided to answer each question clearly and completely — as if you're speaking directly to the user. Do not reference the document or say where the information came from. | |
🎯 GOAL: | |
- Each answer must be fully informative and written in natural, easy-to-understand language. | |
- Aim for 2–3 clear and complete sentences per answer. | |
- Rephrase complex clauses into simpler terms. If conditions, eligibility, waiting periods, or limits apply — clearly mention them. | |
- If the answer isn’t directly found, respond using general insurance knowledge in a confident and helpful tone. | |
📘 INSTRUCTIONS: | |
1. DO NOT mention the words “context,” “provided text,” “document,” or similar. Just answer directly. | |
2. Avoid robotic or legalistic tone. Use human, natural phrasing. | |
3. Do NOT include legal codes, section numbers, or abbreviations like “as per...” or “clause 3.2.1”. | |
4. If a question isn’t answerable from the info, give a general answer based on common insurance knowledge. Be confident and clear. | |
5. Never leave the answer empty — say something helpful or general if the exact info isn't available. | |
6. Follow this tone and format style: | |
✅ GOOD EXAMPLES: | |
- "A grace period of thirty days is allowed after the due date for premium payment, so the policy can be renewed without losing benefits." | |
- "Yes, maternity expenses are covered after 24 months of continuous coverage, and are limited to two deliveries or terminations during the policy period." | |
- "Donor hospitalization costs are covered when the organ is used for the insured person, provided the transplant is legally compliant." | |
📤 RETURN FORMAT: | |
Respond in the exact JSON format below — no extra comments or explanation. | |
{{ | |
"answers": [ | |
"Answer to question 1", | |
"Answer to question 2", | |
... | |
] | |
}} | |
📚 CONTEXT: | |
{context} | |
❓ QUESTIONS: | |
{questions_text} | |
Your task: For each question, provide a clear, helpful answer in 2–3 sentences. Use natural, professional language — never mention the context or document, just explain as if you know the answer. | |
""" | |
model = genai.GenerativeModel('gemini-2.5-flash-lite') | |
response = model.generate_content(prompt) | |
response_text = response.text.strip() | |
try: | |
if response_text.startswith("```json"): | |
response_text = response_text.replace("```json", "").replace("```", "").strip() | |
elif response_text.startswith("```"): | |
response_text = response_text.replace("```", "").strip() | |
parsed_response = json.loads(response_text) | |
return parsed_response | |
except json.JSONDecodeError: | |
print(f"Failed to parse JSON response: {response_text}") | |
return {"answers": ["Error parsing response"] * len(questions)} | |
except Exception as e: | |
print(f"Error in query_gemini: {str(e)}") | |
return {"answers": [f"Error generating response: {str(e)}"] * len(questions)} |