Spaces:
Runtime error

PavanKumarD commited on
Commit
2bd46f3
Β·
verified Β·
1 Parent(s): f9b9553

Update app/backend.py

Browse files
Files changed (1) hide show
  1. app/backend.py +41 -21
app/backend.py CHANGED
@@ -5,22 +5,22 @@ import numpy as np
5
  import tempfile
6
  import requests
7
  from sentence_transformers import SentenceTransformer
8
- import google.generativeai as genai
9
  from dotenv import load_dotenv
10
 
11
- # Load environment variables
12
  load_dotenv()
13
- api_key = os.getenv("GEMINI_API_KEY")
14
- if api_key:
15
- genai.configure(api_key=api_key)
16
- else:
17
- raise ValueError("GEMINI_API_KEY not found in environment variables")
18
 
19
- # Load models
20
  embedding_model = SentenceTransformer("models/all-MiniLM-L6-v2")
21
- generation_model = genai.GenerativeModel("gemini-1.5-flash-002")
22
 
23
- # βœ… Extract text from PDF URL
 
 
 
 
 
 
24
  def extract_text_from_pdf_url(pdf_url):
25
  try:
26
  response = requests.get(pdf_url)
@@ -33,8 +33,8 @@ def extract_text_from_pdf_url(pdf_url):
33
  except Exception as e:
34
  return f"Error extracting PDF text: {str(e)}"
35
 
36
- # βœ… Build FAISS index with chunked text
37
- def build_faiss_index(text, chunk_size=500, overlap=100):
38
  chunks = []
39
  for i in range(0, len(text), chunk_size - overlap):
40
  chunks.append(text[i:i + chunk_size])
@@ -43,19 +43,21 @@ def build_faiss_index(text, chunk_size=500, overlap=100):
43
  index.add(np.array(embeddings))
44
  return index, chunks
45
 
46
- # βœ… Generate Gemini answer using top-K matched chunks
47
- def generate_answer(query, index, chunks, top_k=10):
48
  query_vec = embedding_model.encode([query])
49
  _, indices = index.search(np.array(query_vec), top_k)
50
  context = "\n".join([chunks[i] for i in indices[0] if i < len(chunks)])
51
 
52
  prompt = f"""
53
- You are an AI assistant specialized in insurance domain. Your job is to read the context and answer the question based on policy clauses.
54
 
55
  Instructions:
56
- - Be precise and fact-based.
57
- - If multiple conditions apply, list them clearly.
58
- - If answer is not in context, say \"Sorry, I couldn't find that information.\"
 
 
59
 
60
  <context>
61
  {context}
@@ -64,9 +66,27 @@ Instructions:
64
  <question>
65
  {query}
66
  </question>
 
 
 
 
 
67
  """
 
 
68
  try:
69
- response = generation_model.generate_content(prompt)
70
- return response.text.strip()
 
 
 
 
 
 
 
 
 
 
 
71
  except Exception as e:
72
- return f"Error generating answer: {str(e)}"
 
5
  import tempfile
6
  import requests
7
  from sentence_transformers import SentenceTransformer
8
+ from openai import OpenAI # βœ… Ensure you installed openai>=1.0.0 for OpenRouter
9
  from dotenv import load_dotenv
10
 
11
+ # βœ… Load environment variables (optional but recommended)
12
  load_dotenv()
 
 
 
 
 
13
 
14
+ # βœ… Set up embedding model
15
  embedding_model = SentenceTransformer("models/all-MiniLM-L6-v2")
 
16
 
17
+ # βœ… Model name for OpenRouter (DeepSeek)
18
+ MODEL_NAME = "deepseek/deepseek-r1-0528:free"
19
+
20
+ # βœ… API key (you can load from environment for safety)
21
+ OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "sk-or-...") # fallback
22
+
23
+ # βœ… Extract text from a PDF URL
24
  def extract_text_from_pdf_url(pdf_url):
25
  try:
26
  response = requests.get(pdf_url)
 
33
  except Exception as e:
34
  return f"Error extracting PDF text: {str(e)}"
35
 
36
+ # βœ… Chunk the text and build FAISS index
37
+ def build_faiss_index(text, chunk_size=700, overlap=150):
38
  chunks = []
39
  for i in range(0, len(text), chunk_size - overlap):
40
  chunks.append(text[i:i + chunk_size])
 
43
  index.add(np.array(embeddings))
44
  return index, chunks
45
 
46
+ # βœ… Generate answer using OpenRouter's DeepSeek
47
+ def generate_answer(query, index, chunks, top_k=20):
48
  query_vec = embedding_model.encode([query])
49
  _, indices = index.search(np.array(query_vec), top_k)
50
  context = "\n".join([chunks[i] for i in indices[0] if i < len(chunks)])
51
 
52
  prompt = f"""
53
+ You are an expert insurance assistant. Your job is to answer user questions based strictly on the provided policy document.
54
 
55
  Instructions:
56
+ - Use only the information in <context> to answer the <question>.
57
+ - Always restate the relevant clause clearly and completely.
58
+ - Provide full context (e.g., duration, limits, eligibility, exclusions).
59
+ - Use domain-specific language and proper structure (as in insurance policy).
60
+ - If the information is not found, respond with: "Sorry, I couldn't find that information."
61
 
62
  <context>
63
  {context}
 
66
  <question>
67
  {query}
68
  </question>
69
+
70
+ Your answer must be:
71
+ - Factual and detailed (avoid vague or generic answers).
72
+ - Clearly structured in proper English.
73
+ - Written in 2–4 sentences like a policy explainer.
74
  """
75
+
76
+
77
  try:
78
+ client = OpenAI(
79
+ base_url="https://openrouter.ai/api/v1",
80
+ api_key=OPENROUTER_API_KEY
81
+ )
82
+ completion = client.chat.completions.create(
83
+ model=MODEL_NAME,
84
+ messages=[{"role": "user", "content": prompt}],
85
+ extra_headers={
86
+ "HTTP-Referer": "https://hackrx.yourproject.com",
87
+ "X-Title": "HackRx-PolicyQA"
88
+ }
89
+ )
90
+ return completion.choices[0].message.content.strip()
91
  except Exception as e:
92
+ return f"❌ Error generating answer: {str(e)}"