Spaces:
Sleeping
Sleeping
File size: 11,478 Bytes
f75cf19 e3e3a84 c4b28eb e3e3a84 c4b28eb e3e3a84 c4b28eb 7793bb6 ffa0f3d aff5d04 ffa0f3d 89aa2b4 ffa0f3d 7793bb6 aff5d04 a3dfc07 ffa0f3d a3dfc07 aff5d04 a3dfc07 ffa0f3d 7793bb6 aff5d04 7793bb6 aff5d04 a3dfc07 aff5d04 a3dfc07 aff5d04 57abf2f aff5d04 7793bb6 ffa0f3d 7793bb6 ffa0f3d 500761d c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 e3e3a84 |
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 |
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route("/")
def index():
"""
Renders the main page.
"""
return render_template("index.html")
@app.route("/health")
def health():
"""
Health check endpoint.
"""
return jsonify({"status": "ok"}), 200
@app.route("/ingest", methods=["POST"])
def ingest():
"""Endpoint to trigger document ingestion with embeddings"""
try:
from src.config import (
CORPUS_DIRECTORY,
DEFAULT_CHUNK_SIZE,
DEFAULT_OVERLAP,
RANDOM_SEED,
)
from src.ingestion.ingestion_pipeline import IngestionPipeline
# Get optional parameters from request
data = request.get_json() if request.is_json else {}
store_embeddings = data.get("store_embeddings", True)
pipeline = IngestionPipeline(
chunk_size=DEFAULT_CHUNK_SIZE,
overlap=DEFAULT_OVERLAP,
seed=RANDOM_SEED,
store_embeddings=store_embeddings,
)
result = pipeline.process_directory_with_embeddings(CORPUS_DIRECTORY)
# Create response with enhanced information
response = {
"status": result["status"],
"chunks_processed": result["chunks_processed"],
"files_processed": result["files_processed"],
"embeddings_stored": result["embeddings_stored"],
"store_embeddings": result["store_embeddings"],
"message": (
f"Successfully processed {result['chunks_processed']} chunks "
f"from {result['files_processed']} files"
),
}
# Include failed files info if any
if result["failed_files"]:
response["failed_files"] = result["failed_files"]
failed_count = len(result["failed_files"])
response["warnings"] = f"{failed_count} files failed to process"
return jsonify(response)
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
@app.route("/search", methods=["POST"])
def search():
"""
Endpoint to perform semantic search on ingested documents.
Accepts JSON requests with query text and optional parameters.
Returns semantically similar document chunks.
"""
try:
# Validate request contains JSON data
if not request.is_json:
return (
jsonify(
{
"status": "error",
"message": "Content-Type must be application/json",
}
),
400,
)
data = request.get_json()
# Validate required query parameter
query = data.get("query")
if query is None:
return (
jsonify({"status": "error", "message": "Query parameter is required"}),
400,
)
if not isinstance(query, str) or not query.strip():
return (
jsonify(
{"status": "error", "message": "Query must be a non-empty string"}
),
400,
)
# Extract optional parameters with defaults
top_k = data.get("top_k", 5)
threshold = data.get("threshold", 0.3)
# Validate parameters
if not isinstance(top_k, int) or top_k <= 0:
return (
jsonify(
{"status": "error", "message": "top_k must be a positive integer"}
),
400,
)
if not isinstance(threshold, (int, float)) or not (0.0 <= threshold <= 1.0):
return (
jsonify(
{
"status": "error",
"message": "threshold must be a number between 0 and 1",
}
),
400,
)
# Initialize search components
from src.config import COLLECTION_NAME, VECTOR_DB_PERSIST_PATH
from src.embedding.embedding_service import EmbeddingService
from src.search.search_service import SearchService
from src.vector_store.vector_db import VectorDatabase
vector_db = VectorDatabase(VECTOR_DB_PERSIST_PATH, COLLECTION_NAME)
embedding_service = EmbeddingService()
search_service = SearchService(vector_db, embedding_service)
# Perform search
results = search_service.search(
query=query.strip(), top_k=top_k, threshold=threshold
)
# Format response
response = {
"status": "success",
"query": query.strip(),
"results_count": len(results),
"results": results,
}
return jsonify(response)
except ValueError as e:
return jsonify({"status": "error", "message": str(e)}), 400
except Exception as e:
return jsonify({"status": "error", "message": f"Search failed: {str(e)}"}), 500
@app.route("/chat", methods=["POST"])
def chat():
"""
Endpoint for conversational RAG interactions.
Accepts JSON requests with user messages and returns AI-generated
responses based on corporate policy documents.
"""
try:
# Validate request contains JSON data
if not request.is_json:
return (
jsonify(
{
"status": "error",
"message": "Content-Type must be application/json",
}
),
400,
)
data = request.get_json()
# Validate required message parameter
message = data.get("message")
if message is None:
return (
jsonify(
{"status": "error", "message": "message parameter is required"}
),
400,
)
if not isinstance(message, str) or not message.strip():
return (
jsonify(
{"status": "error", "message": "message must be a non-empty string"}
),
400,
)
# Extract optional parameters
conversation_id = data.get("conversation_id")
include_sources = data.get("include_sources", True)
include_debug = data.get("include_debug", False)
# Initialize RAG pipeline components
try:
from src.config import COLLECTION_NAME, VECTOR_DB_PERSIST_PATH
from src.embedding.embedding_service import EmbeddingService
from src.llm.llm_service import LLMService
from src.rag.rag_pipeline import RAGPipeline
from src.rag.response_formatter import ResponseFormatter
from src.search.search_service import SearchService
from src.vector_store.vector_db import VectorDatabase
# Initialize services
vector_db = VectorDatabase(VECTOR_DB_PERSIST_PATH, COLLECTION_NAME)
embedding_service = EmbeddingService()
search_service = SearchService(vector_db, embedding_service)
# Initialize LLM service from environment
llm_service = LLMService.from_environment()
# Initialize RAG pipeline
rag_pipeline = RAGPipeline(search_service, llm_service)
# Initialize response formatter
formatter = ResponseFormatter()
except ValueError as e:
return (
jsonify(
{
"status": "error",
"message": f"LLM service configuration error: {str(e)}",
"details": (
"Please ensure OPENROUTER_API_KEY or GROQ_API_KEY "
"environment variables are set"
),
}
),
503,
)
except Exception as e:
return (
jsonify(
{
"status": "error",
"message": f"Service initialization failed: {str(e)}",
}
),
500,
)
# Generate RAG response
rag_response = rag_pipeline.generate_answer(message.strip())
# Format response for API
if include_sources:
formatted_response = formatter.format_api_response(
rag_response, include_debug
)
else:
formatted_response = formatter.format_chat_response(
rag_response, conversation_id, include_sources=False
)
return jsonify(formatted_response)
except Exception as e:
return (
jsonify({"status": "error", "message": f"Chat request failed: {str(e)}"}),
500,
)
@app.route("/chat/health", methods=["GET"])
def chat_health():
"""
Health check endpoint for RAG chat functionality.
Returns the status of all RAG pipeline components.
"""
try:
from src.config import COLLECTION_NAME, VECTOR_DB_PERSIST_PATH
from src.embedding.embedding_service import EmbeddingService
from src.llm.llm_service import LLMService
from src.rag.rag_pipeline import RAGPipeline
from src.rag.response_formatter import ResponseFormatter
from src.search.search_service import SearchService
from src.vector_store.vector_db import VectorDatabase
# Initialize services for health check
vector_db = VectorDatabase(VECTOR_DB_PERSIST_PATH, COLLECTION_NAME)
embedding_service = EmbeddingService()
search_service = SearchService(vector_db, embedding_service)
try:
llm_service = LLMService.from_environment()
rag_pipeline = RAGPipeline(search_service, llm_service)
formatter = ResponseFormatter()
# Perform health check
health_data = rag_pipeline.health_check()
health_response = formatter.create_health_response(health_data)
# Determine HTTP status based on health
if health_data.get("pipeline") == "healthy":
return jsonify(health_response), 200
elif health_data.get("pipeline") == "degraded":
return jsonify(health_response), 200 # Still functional
else:
return jsonify(health_response), 503 # Service unavailable
except ValueError as e:
return (
jsonify(
{
"status": "error",
"message": f"LLM configuration error: {str(e)}",
"health": {
"pipeline_status": "unhealthy",
"components": {
"llm_service": {
"status": "unconfigured",
"error": str(e),
}
},
},
}
),
503,
)
except Exception as e:
return (
jsonify({"status": "error", "message": f"Health check failed: {str(e)}"}),
500,
)
if __name__ == "__main__":
app.run(debug=True)
|