Spaces:
Runtime error
Runtime error
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) | |
# Create a numbered list of questions | |
questions_text = "\n".join([f"{i+1}. {q}" for i, q in enumerate(questions)]) | |
prompt = f"""You are an insurance policy assistant. Based on the below document snippets, answer the following questions precisely. | |
IMPORTANT INSTRUCTIONS: | |
1. Only respond based on the context provided. If information is not found in the context, respond with "Not Found". | |
2. Provide clear, concise answers that directly address each question. | |
3. Return your response in the exact JSON format shown below. | |
4. Give complete, informative responses based on the provided context. | |
5. Answer each question in the order provided. | |
Context: | |
{context} | |
Questions: | |
{questions_text} | |
Response Should Good And Refined And Details But also Not So Large For Small Things and Too small Also Not Recommended With One Informative Line. | |
Below I Provided For Current Context Coming How I Can need The Sentences Phrases And Words like is Given For Understanding and Reference: | |
-Old_Ai_Response_Format | |
{{ | |
"answers": [ | |
"The grace period for premium payment is thirty days.", | |
"Expenses related to the treatment of a Pre-Existing Disease (PED) and its direct complications shall be excluded until the expiry of thirty six (36) months of continuous coverage after the date of inception of the first policy.", | |
"Yes, the company shall indemnify Maternity Expenses as described in section 3.1.14 for any female Insured Person, and also Pre-Natal and Post-Natal Hospitalisation expenses per delivery, including expenses for necessary vaccination for New Born Baby, subject to the limit as shown in the Table of Benefits. The female Insured Person should have been continuously covered for at least 24 months before availing this benefit.", | |
"Cataract surgery has a waiting period of two years.", | |
"Yes, the Company shall indemnify the Medical Expenses incurred in respect of an organ donor’s Hospitalisation during the Policy Period for harvesting of the organ donated to an Insured Person, provided that certain conditions are met as outlined in section 3.1.7.", | |
"On renewal of policies with a term of one year, a NCD of flat 5% shall be allowed on the * base premium, provided claims are not reported in the expiring Policy.\nOn renewal of policies with a term exceeding one year, the NCD amount with respect to each claim free policy year shall be aggregated and allowed on renewal. Aggregate amount of NCD allowed shall not exceed flat 5% of the total base premium for the term of the policy.", | |
"Yes, expenses of health check up shall be reimbursed (irrespective of past claims) at the end of a block of two continuous policy years, provided the Policy has been continuously renewed with the Company without a break. Expenses payable are subject to the limit stated in the Table of Benefits.", | |
"Hospital means any institution established for in-patient care and day care treatment of disease/ injuries and which has been registered as a hospital with the local authorities under the Clinical Establishments (Registration and Regulation) Act, 2010 or under the enactments specified under Schedule of Section 56(1) of the said Act, OR complies with all minimum criteria as under:\ni. has qualified nursing staff under its employment round the clock;\nii. has at least ten inpatient beds, in those towns having a population of less than ten lacs and fifteen inpatient beds in all other places;\niii. has qualified medical practitioner (s) in charge round the clock;\niv. has a fully equipped operation theatre of its own where surgical procedures are carried out \nv. maintains daily records of patients and shall make these accessible to the Company’s authorized personnel.", | |
"The Company shall indemnify Medical Expenses incurred for Inpatient Care treatment under Ayurveda, Yoga and Naturopathy, Unani, Siddha and Homeopathy systems of medicines during each Policy Period up to the limit of Sum Insured as specified in the Policy Schedule in any AYUSH Hospital.", | |
"For Plan A, Room Charges are limited to Up to 1% of SI or actual, whichever is lower and ICU Charges are limited to Up to 2% of SI or actual, whichever is lower, per day per insured person." | |
] | |
}} | |
-New_Ai_Response_Format_And Wordings Given Like | |
{{ | |
"answers": [ | |
"A grace period of thirty days is provided for premium payment after the due date to renew or continue the policy without losing continuity benefits.", | |
"There is a waiting period of thirty-six (36) months of continuous coverage from the first policy inception for pre-existing diseases and their direct complications to be covered.", | |
"Yes, the policy covers maternity expenses, including childbirth and lawful medical termination of pregnancy. To be eligible, the female insured person must have been continuously covered for at least 24 months. The benefit is limited to two deliveries or terminations during the policy period.", | |
"The policy has a specific waiting period of two (2) years for cataract surgery.", | |
"Yes, the policy indemnifies the medical expenses for the organ donor's hospitalization for the purpose of harvesting the organ, provided the organ is for an insured person and the donation complies with the Transplantation of Human Organs Act, 1994.", | |
"A No Claim Discount of 5% on the base premium is offered on renewal for a one-year policy term if no claims were made in the preceding year. The maximum aggregate NCD is capped at 5% of the total base premium.", | |
"Yes, the policy reimburses expenses for health check-ups at the end of every block of two continuous policy years, provided the policy has been renewed without a break. The amount is subject to the limits specified in the Table of Benefits.", | |
"A hospital is defined as an institution with at least 10 inpatient beds (in towns with a population below ten lakhs) or 15 beds (in all other places), with qualified nursing staff and medical practitioners available 24/7, a fully equipped operation theatre, and which maintains daily records of patients.", | |
"The policy covers medical expenses for inpatient treatment under Ayurveda, Yoga, Naturopathy, Unani, Siddha, and Homeopathy systems up to the Sum Insured limit, provided the treatment is taken in an AYUSH Hospital.", | |
"Yes, for Plan A, the daily room rent is capped at 1% of the Sum Insured, and ICU charges are capped at 2% of the Sum Insured. These limits do not apply if the treatment is for a listed procedure in a Preferred Provider Network (PPN)." | |
] | |
}} | |
## The Above Is Reference How Can Give Output Wordings Back To The Question is Given For References | |
Return your response in this exact JSON format: | |
{{ | |
"answers": [ | |
"Answer to question 1", | |
"Answer to question 2", | |
"Answer to question 3", | |
... | |
] | |
}} | |
Ensure each answer is comprehensive and directly addresses the corresponding question. If information is not found in the context for any question, respond with "Not Found" for that question.""" | |
model = genai.GenerativeModel('gemini-2.0-flash-exp') | |
response = model.generate_content(prompt) | |
response_text = response.text.strip() | |
# Try to parse the response as JSON | |
try: | |
# Remove any markdown code blocks if present | |
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: | |
# If JSON parsing fails, return a structured response | |
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)} | |