Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -70,7 +70,7 @@ async def lifespan(app: FastAPI):
|
|
| 70 |
print("π Initializing models and prompt template...")
|
| 71 |
|
| 72 |
try:
|
| 73 |
-
GOOGLE_API_KEY = os.getenv("
|
| 74 |
print("π gemini_api_key:", "FOUND" if GOOGLE_API_KEY else "NOT FOUND")
|
| 75 |
|
| 76 |
if not GOOGLE_API_KEY:
|
|
@@ -105,23 +105,24 @@ async def lifespan(app: FastAPI):
|
|
| 105 |
max_output_tokens=300
|
| 106 |
)
|
| 107 |
ml_models["prompt_template"] = ChatPromptTemplate.from_template("""
|
| 108 |
-
**Role**: You are an expert assistant in insurance, legal compliance, human resources, and contract management.
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
| 113 |
**Tone & Style**:
|
| 114 |
-
-
|
| 115 |
-
-
|
| 116 |
-
-
|
| 117 |
-
|
| 118 |
-
- do not make it unnecessary lengthy.
|
| 119 |
-
|
| 120 |
-
**Context**:
|
| 121 |
{context}
|
| 122 |
-
|
| 123 |
-
**Query**:
|
| 124 |
-
|
|
|
|
| 125 |
**Response**:
|
| 126 |
"""
|
| 127 |
)
|
|
@@ -192,16 +193,15 @@ def parse_llm_response(content: str) -> str:
|
|
| 192 |
# --- 5. Main API Endpoint ---
|
| 193 |
@app.post("/api/v1/hackrx/run", response_model=RunResponse, dependencies=[Depends(verify_api_key)])
|
| 194 |
async def run_hackrx(req: RunRequest):
|
| 195 |
-
|
| 196 |
start_time = time.time()
|
| 197 |
-
|
|
|
|
| 198 |
end_time = time.time() - start_time
|
| 199 |
print(f"chunking done: {end_time}")
|
| 200 |
if not chunks:
|
| 201 |
return JSONResponse({"error": "No documents could be processed."}, status_code=400)
|
| 202 |
|
| 203 |
-
doc_url = str(req.documents) # Assuming it's a URL or unique path
|
| 204 |
-
|
| 205 |
|
| 206 |
start_time2 = time.time()
|
| 207 |
# β
Reuse vectorstore if already cached
|
|
@@ -210,9 +210,6 @@ async def run_hackrx(req: RunRequest):
|
|
| 210 |
vectorstore = vector_cache[doc_url]
|
| 211 |
else:
|
| 212 |
print(f"π Processing new document: {doc_url}")
|
| 213 |
-
if not chunks:
|
| 214 |
-
return JSONResponse({"error": "No documents could be processed."}, status_code=400)
|
| 215 |
-
|
| 216 |
# Build vectorstore & save to cache
|
| 217 |
vectorstore = await FAISS.afrom_documents(documents=chunks, embedding=ml_models["embedder"])
|
| 218 |
vector_cache[doc_url] = vectorstore # store in memory cache
|
|
@@ -235,15 +232,15 @@ async def run_hackrx(req: RunRequest):
|
|
| 235 |
keyword_retriever = BM25Retriever.from_documents(chunks)
|
| 236 |
keyword_retriever.k = 8
|
| 237 |
# dense_retriever = Chroma.from_documents(documents=chunks, embedding=ml_models["embedder"]).as_retriever()
|
| 238 |
-
ensemble_retriever = EnsembleRetriever(retrievers=[keyword_retriever, dense_retriever], weights=[0.35, 0.65],search_kwargs={"k":
|
| 239 |
### to make it faster we are now using our built reranker thats why commenting the code below
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
|
| 244 |
# Define the RAG chain using pre-loaded components
|
| 245 |
hybrid_rag_chain = (
|
| 246 |
-
{"context": itemgetter("full_query") |
|
| 247 |
| ml_models["prompt_template"]
|
| 248 |
| ml_models["llm"]
|
| 249 |
)
|
|
|
|
| 70 |
print("π Initializing models and prompt template...")
|
| 71 |
|
| 72 |
try:
|
| 73 |
+
GOOGLE_API_KEY = os.getenv("gemini_api_key")
|
| 74 |
print("π gemini_api_key:", "FOUND" if GOOGLE_API_KEY else "NOT FOUND")
|
| 75 |
|
| 76 |
if not GOOGLE_API_KEY:
|
|
|
|
| 105 |
max_output_tokens=300
|
| 106 |
)
|
| 107 |
ml_models["prompt_template"] = ChatPromptTemplate.from_template("""
|
| 108 |
+
**Role**: You are an expert assistant in insurance, legal compliance, human resources, and contract management.
|
| 109 |
+
**Instructions**:
|
| 110 |
+
- Answer using ONLY the provided context.
|
| 111 |
+
- Identify each distinct question in the query and give exactly one concise, complete sentence for each , Also do not use line breakers in between the sentence.
|
| 112 |
+
- Summarize the relevant part of the context without losing meaning.
|
| 113 |
+
- Do not copy large clauses verbatim unless absolutely necessary.
|
| 114 |
+
- If the answer is not in the context, respond: "Please ask query related to the Document only."
|
| 115 |
+
- Do not use unnecessary filler or legal jargon.
|
| 116 |
**Tone & Style**:
|
| 117 |
+
- Professional yet approachable.
|
| 118 |
+
- Clear and direct.
|
| 119 |
+
---
|
| 120 |
+
**Context**:
|
|
|
|
|
|
|
|
|
|
| 121 |
{context}
|
| 122 |
+
---
|
| 123 |
+
**Query**:
|
| 124 |
+
{full_query}
|
| 125 |
+
---
|
| 126 |
**Response**:
|
| 127 |
"""
|
| 128 |
)
|
|
|
|
| 193 |
# --- 5. Main API Endpoint ---
|
| 194 |
@app.post("/api/v1/hackrx/run", response_model=RunResponse, dependencies=[Depends(verify_api_key)])
|
| 195 |
async def run_hackrx(req: RunRequest):
|
| 196 |
+
doc_url = str(req.documents)
|
| 197 |
start_time = time.time()
|
| 198 |
+
if(doc_url not in vector_cache):
|
| 199 |
+
chunks = load_and_chunk(str(req.documents))
|
| 200 |
end_time = time.time() - start_time
|
| 201 |
print(f"chunking done: {end_time}")
|
| 202 |
if not chunks:
|
| 203 |
return JSONResponse({"error": "No documents could be processed."}, status_code=400)
|
| 204 |
|
|
|
|
|
|
|
| 205 |
|
| 206 |
start_time2 = time.time()
|
| 207 |
# β
Reuse vectorstore if already cached
|
|
|
|
| 210 |
vectorstore = vector_cache[doc_url]
|
| 211 |
else:
|
| 212 |
print(f"π Processing new document: {doc_url}")
|
|
|
|
|
|
|
|
|
|
| 213 |
# Build vectorstore & save to cache
|
| 214 |
vectorstore = await FAISS.afrom_documents(documents=chunks, embedding=ml_models["embedder"])
|
| 215 |
vector_cache[doc_url] = vectorstore # store in memory cache
|
|
|
|
| 232 |
keyword_retriever = BM25Retriever.from_documents(chunks)
|
| 233 |
keyword_retriever.k = 8
|
| 234 |
# dense_retriever = Chroma.from_documents(documents=chunks, embedding=ml_models["embedder"]).as_retriever()
|
| 235 |
+
ensemble_retriever = EnsembleRetriever(retrievers=[keyword_retriever, dense_retriever], weights=[0.35, 0.65],search_kwargs={"k": 20})
|
| 236 |
### to make it faster we are now using our built reranker thats why commenting the code below
|
| 237 |
+
compression_retriever = ContextualCompressionRetriever(
|
| 238 |
+
base_retriever=ensemble_retriever, base_compressor=ml_models["reranker_compressor"]
|
| 239 |
+
)
|
| 240 |
|
| 241 |
# Define the RAG chain using pre-loaded components
|
| 242 |
hybrid_rag_chain = (
|
| 243 |
+
{"context": itemgetter("full_query") | compression_retriever, "full_query": itemgetter("full_query")}
|
| 244 |
| ml_models["prompt_template"]
|
| 245 |
| ml_models["llm"]
|
| 246 |
)
|