acseresznye commited on
Commit
6f8a5dc
·
1 Parent(s): 395c9ad

rate limit added

Browse files
Files changed (3) hide show
  1. main.py +90 -69
  2. requirements.txt +2 -2
  3. ui/pages.py +37 -2
main.py CHANGED
@@ -15,12 +15,19 @@ os.environ["TOKENIZERS_PARALLELISM"] = "false"
15
 
16
  from datetime import datetime
17
 
18
- from fastapi import FastAPI, HTTPException
19
  from fastapi.middleware.cors import CORSMiddleware
20
  from fastapi.staticfiles import StaticFiles
21
  from loguru import logger
22
  from nicegui import ui
23
  from pydantic import BaseModel, Field
 
 
 
 
 
 
 
24
 
25
  # Configure loguru
26
  logger.remove()
@@ -133,6 +140,10 @@ async def lifespan(app: FastAPI):
133
  logger.critical(f"Failed to initialize application: {e}")
134
  # app.state.query_service is already None
135
 
 
 
 
 
136
  yield # Application runs here
137
 
138
  # --- SHUTDOWN LOGIC ---
@@ -151,12 +162,6 @@ async def lifespan(app: FastAPI):
151
 
152
  logger.info("Shutdown complete")
153
 
154
- logger.info("🛑 Shutting down: Closing services...")
155
- if hasattr(app.state, "query_service"):
156
- await app.state.query_service.close()
157
-
158
- logger.info("Shutdown complete")
159
-
160
 
161
  app = FastAPI(
162
  title="Necthrall API",
@@ -165,6 +170,11 @@ app = FastAPI(
165
  lifespan=lifespan, # Register the lifespan handler here
166
  )
167
 
 
 
 
 
 
168
  # Mount static files
169
  app.mount("/static", StaticFiles(directory="static"), name="static")
170
 
@@ -193,78 +203,89 @@ class QueryRequest(BaseModel):
193
 
194
 
195
  @app.post("/query")
196
- async def query_endpoint(request: QueryRequest):
 
197
  """Process a research query."""
198
  if not hasattr(app.state, "query_service"):
199
  raise HTTPException(status_code=503, detail="Query service not initialized")
200
 
201
- try:
202
- result = await app.state.query_service.process_query(request.query)
203
-
204
- if not result.success:
205
- # Handle specific error cases
206
- if (
207
- result.error_message
208
- and "Semantic Scholar API is currently unavailable"
209
- in result.error_message
210
- ):
211
- raise HTTPException(
212
- status_code=503,
213
- detail=result.error_message,
 
 
 
 
 
 
 
 
 
 
 
214
  )
 
 
215
 
216
- # Include stage in error detail for debugging
217
- error_detail = (
218
- result.error_message or "Pipeline failed without error message"
219
- )
220
- if result.error_stage:
221
- error_detail = f"{error_detail} (Stage: {result.error_stage})"
222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  raise HTTPException(
224
- status_code=500,
225
- detail=error_detail,
226
  )
227
 
228
- # Format citations with IDs
229
- citations = []
230
- if result.passages:
231
- for idx, p in enumerate(result.passages, 1):
232
- # Handle both dict and object access
233
- text = p.get("text") if isinstance(p, dict) else getattr(p, "text", "")
234
- metadata = (
235
- p.get("metadata")
236
- if isinstance(p, dict)
237
- else getattr(p, "metadata", {})
238
- ).copy()
239
-
240
- # Ensure score is in metadata if available
241
- score = (
242
- p.get("score") if isinstance(p, dict) else getattr(p, "score", None)
243
- )
244
- if score is not None:
245
- metadata["score"] = score
246
-
247
- citations.append({"id": idx, "text": text, "metadata": metadata})
248
-
249
- return {
250
- "query": request.query,
251
- "answer": result.answer
252
- or "No answer could be generated from the available sources.",
253
- "citations": citations,
254
- "finalists": result.finalists,
255
- "execution_time": result.execution_time,
256
- "timing_breakdown": result.timing_breakdown,
257
- "optimized_queries": result.optimized_queries,
258
- "quality_gate": result.quality_gate,
259
- }
260
- except HTTPException:
261
- raise
262
- except Exception as e:
263
- logger.exception("Query processing failed")
264
- raise HTTPException(
265
- status_code=500, detail=f"An unexpected error occurred: {str(e)}"
266
- )
267
-
268
 
269
  # =============================================================================
270
  # NiceGUI Frontend
 
15
 
16
  from datetime import datetime
17
 
18
+ from fastapi import FastAPI, HTTPException, Request
19
  from fastapi.middleware.cors import CORSMiddleware
20
  from fastapi.staticfiles import StaticFiles
21
  from loguru import logger
22
  from nicegui import ui
23
  from pydantic import BaseModel, Field
24
+ from slowapi import Limiter, _rate_limit_exceeded_handler
25
+ from slowapi.errors import RateLimitExceeded
26
+ from slowapi.util import get_remote_address
27
+
28
+ # Global concurrency control
29
+ MAX_CONCURRENT_SEARCHES = 2
30
+ search_semaphore = asyncio.Semaphore(MAX_CONCURRENT_SEARCHES)
31
 
32
  # Configure loguru
33
  logger.remove()
 
140
  logger.critical(f"Failed to initialize application: {e}")
141
  # app.state.query_service is already None
142
 
143
+ # Expose concurrency controls to UI
144
+ app.state.search_semaphore = search_semaphore
145
+ app.state.max_concurrent_searches = MAX_CONCURRENT_SEARCHES
146
+
147
  yield # Application runs here
148
 
149
  # --- SHUTDOWN LOGIC ---
 
162
 
163
  logger.info("Shutdown complete")
164
 
 
 
 
 
 
 
165
 
166
  app = FastAPI(
167
  title="Necthrall API",
 
170
  lifespan=lifespan, # Register the lifespan handler here
171
  )
172
 
173
+ # Initialize Rate Limiter
174
+ limiter = Limiter(key_func=get_remote_address)
175
+ app.state.limiter = limiter
176
+ app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
177
+
178
  # Mount static files
179
  app.mount("/static", StaticFiles(directory="static"), name="static")
180
 
 
203
 
204
 
205
  @app.post("/query")
206
+ @limiter.limit("5/hour")
207
+ async def query_endpoint(query_request: QueryRequest, request: Request):
208
  """Process a research query."""
209
  if not hasattr(app.state, "query_service"):
210
  raise HTTPException(status_code=503, detail="Query service not initialized")
211
 
212
+ if search_semaphore.locked():
213
+ raise HTTPException(
214
+ status_code=503, detail="Server is busy. Please try again later."
215
+ )
216
+
217
+ async with search_semaphore:
218
+ try:
219
+ result = await app.state.query_service.process_query(query_request.query)
220
+
221
+ if not result.success:
222
+ # Handle specific error cases
223
+ if (
224
+ result.error_message
225
+ and "Semantic Scholar API is currently unavailable"
226
+ in result.error_message
227
+ ):
228
+ raise HTTPException(
229
+ status_code=503,
230
+ detail=result.error_message,
231
+ )
232
+
233
+ # Include stage in error detail for debugging
234
+ error_detail = (
235
+ result.error_message or "Pipeline failed without error message"
236
  )
237
+ if result.error_stage:
238
+ error_detail = f"{error_detail} (Stage: {result.error_stage})"
239
 
240
+ raise HTTPException(
241
+ status_code=500,
242
+ detail=error_detail,
243
+ )
 
 
244
 
245
+ # Format citations with IDs
246
+ citations = []
247
+ if result.passages:
248
+ for idx, p in enumerate(result.passages, 1):
249
+ # Handle both dict and object access
250
+ text = (
251
+ p.get("text") if isinstance(p, dict) else getattr(p, "text", "")
252
+ )
253
+ metadata = (
254
+ p.get("metadata")
255
+ if isinstance(p, dict)
256
+ else getattr(p, "metadata", {})
257
+ ).copy()
258
+
259
+ # Ensure score is in metadata if available
260
+ score = (
261
+ p.get("score")
262
+ if isinstance(p, dict)
263
+ else getattr(p, "score", None)
264
+ )
265
+ if score is not None:
266
+ metadata["score"] = score
267
+
268
+ citations.append({"id": idx, "text": text, "metadata": metadata})
269
+
270
+ return {
271
+ "query": query_request.query,
272
+ "answer": result.answer
273
+ or "No answer could be generated from the available sources.",
274
+ "citations": citations,
275
+ "finalists": result.finalists,
276
+ "execution_time": result.execution_time,
277
+ "timing_breakdown": result.timing_breakdown,
278
+ "optimized_queries": result.optimized_queries,
279
+ "quality_gate": result.quality_gate,
280
+ }
281
+ except HTTPException:
282
+ raise
283
+ except Exception as e:
284
+ logger.exception("Query processing failed")
285
  raise HTTPException(
286
+ status_code=500, detail=f"An unexpected error occurred: {str(e)}"
 
287
  )
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
 
290
  # =============================================================================
291
  # NiceGUI Frontend
requirements.txt CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:449ac3f9b72672955ffc2826ee3f224b04a9d9cb21ba54019784072919624f25
3
- size 463
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c889a8cb0d09efbfb6c11d395178120f0b7ce84258ae6f4b992e70656f31e09f
3
+ size 471
ui/pages.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  import asyncio
4
  import datetime
 
5
  from pathlib import Path
6
 
7
  import httpx
@@ -51,6 +52,8 @@ def init_ui(fastapi_app):
51
  # Get client reference for connection checking
52
  client = context.client
53
 
 
 
54
  # =====================================================================
55
  # DIALOG: HOW IT WORKS
56
  # =====================================================================
@@ -226,11 +229,30 @@ def init_ui(fastapi_app):
226
  # Only return False if explicitly disconnected, not transient issues
227
  return not getattr(client, "is_deleted", False)
228
  except Exception:
229
- # Assume connected on exception (avoid spurious errors)
230
  return True
231
 
232
  async def handle_search():
233
- nonlocal results_container
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  query_text = search_input.value.strip()
235
 
236
  if not query_text:
@@ -245,7 +267,17 @@ def init_ui(fastapi_app):
245
  )
246
  return
247
 
 
 
 
 
248
  # Clear previous results
 
 
 
 
 
 
249
  if results_container:
250
  try:
251
  results_container.clear()
@@ -391,6 +423,9 @@ def init_ui(fastapi_app):
391
  # Client was deleted, silently ignore
392
  pass
393
 
 
 
 
394
  # =====================================================================
395
  # HEADER
396
  # =====================================================================
 
2
 
3
  import asyncio
4
  import datetime
5
+ import time
6
  from pathlib import Path
7
 
8
  import httpx
 
52
  # Get client reference for connection checking
53
  client = context.client
54
 
55
+ state = {"is_searching": False, "last_search_time": 0}
56
+
57
  # =====================================================================
58
  # DIALOG: HOW IT WORKS
59
  # =====================================================================
 
229
  # Only return False if explicitly disconnected, not transient issues
230
  return not getattr(client, "is_deleted", False)
231
  except Exception:
 
232
  return True
233
 
234
  async def handle_search():
235
+ # Client Spam Check
236
+ if state["is_searching"]:
237
+ ui.notify("Search in progress", type="warning")
238
+ return
239
+
240
+ # Rate Limit Check
241
+ if time.time() - state["last_search_time"] < 10:
242
+ ui.notify(
243
+ "Please wait a moment before searching again.", type="warning"
244
+ )
245
+ return
246
+
247
+ # Server Load Check
248
+ if fastapi_app.state.search_semaphore.locked():
249
+ limit = fastapi_app.state.max_concurrent_searches
250
+ ui.notify(
251
+ f"Server is at capacity ({limit}/{limit}). Please try again later.",
252
+ type="warning",
253
+ )
254
+ return
255
+
256
  query_text = search_input.value.strip()
257
 
258
  if not query_text:
 
267
  )
268
  return
269
 
270
+ # Update State
271
+ state["is_searching"] = True
272
+ state["last_search_time"] = time.time()
273
+
274
  # Clear previous results
275
+ if results_container:
276
+ try:
277
+ results_container.clear()
278
+ except RuntimeError:
279
+ # Client deleted, exit gracefully
280
+ state["is_searching"] = False
281
  if results_container:
282
  try:
283
  results_container.clear()
 
423
  # Client was deleted, silently ignore
424
  pass
425
 
426
+ finally:
427
+ state["is_searching"] = False
428
+
429
  # =====================================================================
430
  # HEADER
431
  # =====================================================================