Spaces:
Sleeping
Sleeping
File size: 19,057 Bytes
b378103 095c98b b378103 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 | from fastapi import FastAPI, UploadFile, File, HTTPException, Form
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Optional
import shutil
import os
from pathlib import Path
import sys
from openai import OpenAI
import json
sys.path.insert(0, str(Path(__file__).parent))
from src.rag_system import IncrementalRAGSystem
from src.database import get_db_session, DocumentVersion, DocumentChunk
client = OpenAI(
api_key=os.getenv("GROQ_API_KEY"), base_url="https://api.groq.com/openai/v1"
)
app = FastAPI(
title="Incremental RAG API",
description="API for document Q&A RAG System",
version="1.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=[
"https://document-qa-rag-system.vercel.app",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
rag_system = None
@app.on_event("startup")
def startup():
global rag_system
rag_system = IncrementalRAGSystem()
TEMP_UPLOAD_DIR = "./temp_uploads"
Path(TEMP_UPLOAD_DIR).mkdir(exist_ok=True)
class QueryRequest(BaseModel):
question: str
version_id: Optional[int] = None
k: int = 5
class ComparisonRequest(BaseModel):
question: str
version_id_1: int
version_id_2: int
k: int = 3
@app.get("/")
async def root():
return {
"status": "online",
"message": "Document Q&A RAG API is running",
}
@app.post("/api/documents/upload")
async def upload_document(
file: UploadFile = File(...), doc_name: Optional[str] = Form(None)
):
temp_file_path = None
try:
allowed_extensions = {".pdf", ".txt", ".docx"}
file_ext = Path(file.filename).suffix.lower()
if file_ext not in allowed_extensions:
raise HTTPException(
status_code=400, detail=f"File type {file_ext} not supported"
)
temp_file_path = Path(TEMP_UPLOAD_DIR) / file.filename
with open(temp_file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
if not doc_name:
doc_name = Path(file.filename).stem
result = rag_system.add_document(
file_path=str(temp_file_path), doc_name=doc_name
)
temp_file_path.unlink()
return JSONResponse(
content={
"success": True,
"message": f"Document uploaded as version {result['version_number']}",
"data": result,
}
)
except Exception as e:
if temp_file_path and temp_file_path.exists():
temp_file_path.unlink()
raise HTTPException(status_code=500, detail=str(e))
def build_source_context(results):
parts = []
for i, r in enumerate(results, start=1):
excerpt = r["content"]
if len(excerpt) > 2000:
excerpt = excerpt[:2000] + "..."
parts.append(f"[Source {i}]\n{excerpt}")
return "\n\n".join(parts)
def extract_document_topics(chunks: list, max_topics: int = 5) -> list:
sample_text = "\n".join([c["content"] for c in chunks[:3]])
try:
prompt = f"""
Extract the main topics covered in this document.
Document sample:
{sample_text[:1000]}
Return JSON with main topics/sections:
{{
"topics": ["Topic 1", "Topic 2", "Topic 3"]
}}
Keep topics concise (2-4 words each). Maximum {max_topics} topics.
"""
resp = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[{"role": "user", "content": prompt}],
temperature=0.3,
max_tokens=200,
response_format={"type": "json_object"},
)
result = json.loads(resp.choices[0].message.content)
return result.get("topics", [])[:max_topics]
except Exception as e:
words = sample_text.lower().split()
fallback_topics = []
policy_keywords = [
"policy",
"work",
"remote",
"vacation",
"benefits",
"security",
"equipment",
"eligibility",
]
for keyword in policy_keywords:
if keyword in words:
fallback_topics.append(keyword.title())
return (
fallback_topics[:max_topics] if fallback_topics else ["General Information"]
)
@app.post("/api/query/generate")
async def query_with_llm(query_request: QueryRequest):
question = query_request.question.strip()
if len(question) < 3:
return {
"question": question,
"not_found": True,
"answer": "",
"message": "Question too short (minimum 3 characters)",
"sources": [],
}
results = rag_system.query(
question=question,
version_id=query_request.version_id,
k=query_request.k,
)
if not results:
return {
"question": question,
"not_found": True,
"answer": "",
"message": "No content found in this document version",
"suggestion": "Check if you selected the correct version or try searching all versions",
"sources": [],
}
top_score = results[0]["similarity_score"]
if top_score < 0.35:
topics = extract_document_topics(results)
return {
"question": question,
"not_found": True,
"answer": "",
"message": "No direct match for your question",
"topics": topics,
"suggestions": [
"Try asking about specific topics listed above",
"Use keywords from the document",
(
f"Example: 'What is the {topics[0].lower()}?'"
if topics
else "Be more specific"
),
],
"top_score": round(top_score, 3),
"sources": [],
}
force_low_confidence = False
if top_score < 0.4:
filtered = results[:3]
force_low_confidence = True
elif top_score > 0.6:
filtered = [r for r in results if r["similarity_score"] > 0.5][:3]
elif top_score > 0.45:
filtered = [r for r in results if r["similarity_score"] > 0.4][:2]
else:
filtered = results[:1]
context = build_source_context(filtered)
avg_sim = sum(r["similarity_score"] for r in filtered) / len(filtered)
system_msg = """You are a helpful document Q&A assistant.
IMPORTANT RULES:
1. Answer using ONLY the provided context
2. If context is relevant, provide an answer even if partial
3. Only return not_found=true if context is COMPLETELY unrelated
4. For general questions (like "policy" or "document"), summarize key points
You must return valid JSON in this format:
{
"not_found": false,
"answer": "Your answer here",
"confidence": "high|medium|low"
}
Only use not_found=true if truly nothing relevant exists."""
user_prompt = f"""
Context (avg similarity: {avg_sim:.2f}):
{context}
Question: {question}
Provide a helpful answer based on the context. If the question is general, summarize the main points."""
try:
resp = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": system_msg},
{"role": "user", "content": user_prompt},
],
temperature=0.1,
max_tokens=800,
response_format={"type": "json_object"},
)
text = resp.choices[0].message.content.strip()
except Exception as e:
raise HTTPException(status_code=500, detail=f"LLM API error: {str(e)}")
try:
j = json.loads(text)
except json.JSONDecodeError:
start = text.find("{")
end = text.rfind("}")
if start != -1 and end != -1:
try:
j = json.loads(text[start : end + 1])
except json.JSONDecodeError:
j = {
"not_found": False,
"answer": text,
"confidence": "low",
"note": "Response format was non-standard",
}
else:
raise HTTPException(
status_code=500, detail="Failed to parse LLM response as JSON"
)
j["sources"] = filtered
j["question"] = question
j["avg_similarity"] = round(avg_sim, 3)
if "confidence" not in j:
if avg_sim > 0.6:
j["confidence"] = "high"
elif avg_sim > 0.45:
j["confidence"] = "medium"
else:
j["confidence"] = "low"
if force_low_confidence:
j["confidence"] = "low"
j["warning"] = "Answer based on limited context relevance"
return j
@app.get("/api/documents")
async def list_documents():
try:
documents = rag_system.get_all_documents()
return documents
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/documents/{doc_name}/versions")
async def get_document_versions(doc_name: str):
try:
versions = rag_system.get_document_versions(doc_name)
if not versions:
raise HTTPException(
status_code=404, detail=f"Document '{doc_name}' not found"
)
return versions
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/documents/{doc_name}/versions/{version_id}/diff")
async def get_version_diff(doc_name: str, version_id: int):
try:
session = get_db_session()
try:
current_version = (
session.query(DocumentVersion).filter_by(id=version_id).first()
)
if not current_version:
raise HTTPException(status_code=404, detail="Version not found")
prev_version = (
session.query(DocumentVersion)
.filter_by(
document_id=current_version.document_id,
version_number=current_version.version_number - 1,
)
.first()
)
if not prev_version:
return {
"success": True,
"message": "This is the first version",
"is_first_version": True,
"current_version": current_version.version_number,
}
current_chunks = [chunk.content for chunk in current_version.chunks]
prev_chunks = [chunk.content for chunk in prev_version.chunks]
current_text = "\n\n".join(current_chunks)
prev_text = "\n\n".join(prev_chunks)
stats = {
"chunks_added": len(current_chunks) - len(prev_chunks),
"current_chunks": len(current_chunks),
"previous_chunks": len(prev_chunks),
"current_version": current_version.version_number,
"previous_version": prev_version.version_number,
}
system_msg = """You are analyzing document changes.
Identify what changed between two versions.
Be specific and concise.
You must respond with valid JSON only."""
user_prompt = f"""
Previous Version:
{prev_text[:3000]}...
Current Version:
{current_text[:3000]}...
Analyze the changes and return valid JSON in this format:
{{
"summary": "Brief overview of changes",
"key_changes": [
{{"type": "added|modified|removed", "description": "what changed"}},
],
"impact": "low|medium|high"
}}
"""
try:
resp = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": system_msg},
{"role": "user", "content": user_prompt},
],
temperature=0.1,
max_tokens=500,
response_format={"type": "json_object"}, # Now this works
)
llm_response = resp.choices[0].message.content.strip()
try:
diff_analysis = json.loads(llm_response)
except json.JSONDecodeError as e:
print(f"Failed to parse LLM response: {llm_response}")
diff_analysis = {
"summary": f"Version {current_version.version_number} has {len(current_chunks) - len(prev_chunks)} more chunks than version {prev_version.version_number}",
"key_changes": [
{
"type": "modified",
"description": f"Content updated with {abs(len(current_chunks) - len(prev_chunks))} chunk difference",
}
],
"impact": "medium",
}
except Exception as llm_error:
print(f"LLM API error: {llm_error}")
diff_analysis = {
"summary": "Unable to generate detailed analysis",
"key_changes": [
{
"type": "modified",
"description": f"{len(current_chunks)} chunks in current version vs {len(prev_chunks)} in previous",
}
],
"impact": "unknown",
}
return {
"success": True,
"is_first_version": False,
"stats": stats,
"analysis": diff_analysis,
"version_info": {
"current": {
"id": current_version.id,
"number": current_version.version_number,
"date": current_version.upload_date.isoformat(),
},
"previous": {
"id": prev_version.id,
"number": prev_version.version_number,
"date": prev_version.upload_date.isoformat(),
},
},
}
finally:
session.close()
except HTTPException:
raise
except json.JSONDecodeError as e:
raise HTTPException(
status_code=500, detail=f"Failed to parse LLM response: {str(e)}"
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/compare/detailed")
async def compare_versions_detailed(comparison: ComparisonRequest):
try:
session = get_db_session()
try:
v1 = (
session.query(DocumentVersion)
.filter_by(id=comparison.version_id_1)
.first()
)
v2 = (
session.query(DocumentVersion)
.filter_by(id=comparison.version_id_2)
.first()
)
if not v1 or not v2:
raise HTTPException(status_code=404, detail="Version not found")
v1_chunks = [chunk.content for chunk in v1.chunks]
v2_chunks = [chunk.content for chunk in v2.chunks]
v1_text = "\n\n".join(v1_chunks)
v2_text = "\n\n".join(v2_chunks)
if comparison.question:
results_v1 = rag_system.query(
question=comparison.question,
version_id=comparison.version_id_1,
k=comparison.k,
)
results_v2 = rag_system.query(
question=comparison.question,
version_id=comparison.version_id_2,
k=comparison.k,
)
context_v1 = "\n".join([r["content"] for r in results_v1[:2]])
context_v2 = "\n".join([r["content"] for r in results_v2[:2]])
system_msg = """Compare how two document versions answer the same question.
Identify specific differences."""
user_prompt = f"""
Question: {comparison.question}
Version {v1.version_number} says:
{context_v1}
Version {v2.version_number} says:
{context_v2}
Return JSON:
{{
"answer_v1": "Answer from version 1",
"answer_v2": "Answer from version 2",
"changed": true/false,
"differences": [
{{"aspect": "what changed", "v1": "old value", "v2": "new value"}}
],
"summary": "Overall comparison"
}}
"""
else:
system_msg = """Compare two document versions.
Identify all significant changes."""
user_prompt = f"""
Version {v1.version_number}:
{v1_text[:4000]}...
Version {v2.version_number}:
{v2_text[:4000]}...
Return JSON:
{{
"overall_change": "high|medium|low",
"summary": "What changed overall",
"sections_changed": ["section 1", "section 2"],
"key_differences": [
{{"category": "category", "description": "what changed", "type": "added|modified|removed"}}
],
"recommendations": "Who should review these changes"
}}
"""
resp = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": system_msg},
{"role": "user", "content": user_prompt},
],
temperature=0.1,
max_tokens=1000,
)
analysis = json.loads(resp.choices[0].message.content)
return {
"success": True,
"question": comparison.question if comparison.question else None,
"version_info": {
"version_1": {
"id": v1.id,
"number": v1.version_number,
"date": v1.upload_date.isoformat(),
"chunks": len(v1_chunks),
},
"version_2": {
"id": v2.id,
"number": v2.version_number,
"date": v2.upload_date.isoformat(),
"chunks": len(v2_chunks),
},
},
"analysis": analysis,
"stats": {
"chunks_difference": len(v2_chunks) - len(v1_chunks),
"text_length_v1": len(v1_text),
"text_length_v2": len(v2_text),
},
}
finally:
session.close()
except HTTPException:
raise
except json.JSONDecodeError:
raise HTTPException(status_code=500, detail="Failed to parse LLM response")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run("server_app:app", host="0.0.0.0", port=8000, reload=True)
|