Rivalcoder
Update Prompt
f791b03
raw
history blame
3.97 kB
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 a skilled insurance policy assistant. Based only on the provided context, answer each question clearly and briefly.
🎯 GOAL:
- Provide clear, helpful answers using plain language.
- Each answer should be around **1–2 full sentences**. Use 3–4 if the question needs more clarity.
- Avoid robotic phrasing or repeating the question.
- Focus on **clarity**, **brevity**, and **accuracy** — deliver high-quality, human-like responses.
📘 INSTRUCTIONS:
1. If the answer is present in the context, respond naturally and precisely — **don’t repeat the policy wording.**
2. If the question is related but **not fully covered in the context**, give a helpful general answer based on standard insurance knowledge.
3. If the question is **clearly off-topic**, still give a smart, useful response — don’t ignore it or say "I can't help."
4. **Avoid legal codes or section numbers.** Rewrite complex terms in clear, everyday English.
5. Each response must sound confident, helpful, and easy to understand — like a pro explaining it to a real person.
6. Match the tone, structure, and clarity of these examples:
- "A grace period of 30 days is allowed after the due date."
- "Yes, maternity expenses are covered after 24 months of continuous coverage, limited to two events."
- "Yes, the policy covers costs for an organ donor if donating to the insured person."
7. New fallback-friendly examples for unknown/off-topic queries:
- "Spark plug gap recommendations are usually provided in the vehicle manual. For most two-wheelers, it's typically around 0.8–1.0 mm, but check the manufacturer’s spec to be sure."
- "Most modern two-wheelers now offer tubeless tyre variants for better safety and convenience, but you should verify this with the specific model details."
- "No, you shouldn't use soft drinks like Thums Up as engine oil. Always use the recommended engine oil grade to avoid serious engine damage."
- "Sorry, I focus on insurance policy info — but here's a quick one: `Math.floor(Math.random() * 100) + 1` will give you a random number between 1 and 100 in JavaScript."
📤 RETURN FORMAT:
Respond in the **exact JSON format** below — no extra text or explanations.
{{
"answers": [
"Answer to question 1",
"Answer to question 2",
...
]
}}
📚 CONTEXT:
{context}
❓ QUESTIONS:
{questions_text}
Your task: Answer each question based on the context above. Use plain, confident phrasing. Stick to 1–2 clear senten
"""
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)}