webscout 8.3.3__py3-none-any.whl → 8.3.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of webscout might be problematic. Click here for more details.
- webscout/AIutel.py +53 -800
- webscout/Bard.py +2 -22
- webscout/Provider/AISEARCH/__init__.py +11 -10
- webscout/Provider/AISEARCH/felo_search.py +7 -3
- webscout/Provider/AISEARCH/scira_search.py +26 -11
- webscout/Provider/AISEARCH/stellar_search.py +53 -8
- webscout/Provider/Deepinfra.py +81 -57
- webscout/Provider/ExaChat.py +9 -5
- webscout/Provider/Flowith.py +1 -1
- webscout/Provider/FreeGemini.py +2 -2
- webscout/Provider/Gemini.py +3 -10
- webscout/Provider/GeminiProxy.py +31 -5
- webscout/Provider/LambdaChat.py +39 -31
- webscout/Provider/Netwrck.py +5 -8
- webscout/Provider/OLLAMA.py +8 -9
- webscout/Provider/OPENAI/README.md +1 -1
- webscout/Provider/OPENAI/TogetherAI.py +57 -48
- webscout/Provider/OPENAI/TwoAI.py +94 -1
- webscout/Provider/OPENAI/__init__.py +1 -3
- webscout/Provider/OPENAI/autoproxy.py +1 -1
- webscout/Provider/OPENAI/copilot.py +73 -26
- webscout/Provider/OPENAI/deepinfra.py +60 -24
- webscout/Provider/OPENAI/exachat.py +9 -5
- webscout/Provider/OPENAI/monochat.py +3 -3
- webscout/Provider/OPENAI/netwrck.py +4 -7
- webscout/Provider/OPENAI/qodo.py +630 -0
- webscout/Provider/OPENAI/scirachat.py +86 -49
- webscout/Provider/OPENAI/textpollinations.py +19 -14
- webscout/Provider/OPENAI/venice.py +1 -0
- webscout/Provider/Perplexitylabs.py +163 -147
- webscout/Provider/Qodo.py +478 -0
- webscout/Provider/TTI/__init__.py +1 -0
- webscout/Provider/TTI/monochat.py +3 -3
- webscout/Provider/TTI/together.py +7 -6
- webscout/Provider/TTI/venice.py +368 -0
- webscout/Provider/TextPollinationsAI.py +19 -14
- webscout/Provider/TogetherAI.py +57 -44
- webscout/Provider/TwoAI.py +96 -2
- webscout/Provider/TypliAI.py +33 -27
- webscout/Provider/UNFINISHED/PERPLEXED_search.py +254 -0
- webscout/Provider/UNFINISHED/fetch_together_models.py +6 -11
- webscout/Provider/Venice.py +1 -0
- webscout/Provider/WiseCat.py +18 -20
- webscout/Provider/__init__.py +4 -10
- webscout/Provider/copilot.py +58 -61
- webscout/Provider/freeaichat.py +64 -55
- webscout/Provider/monochat.py +275 -0
- webscout/Provider/scira_chat.py +115 -21
- webscout/Provider/toolbaz.py +5 -10
- webscout/Provider/typefully.py +1 -11
- webscout/Provider/x0gpt.py +325 -315
- webscout/__init__.py +4 -11
- webscout/auth/__init__.py +19 -4
- webscout/auth/api_key_manager.py +189 -189
- webscout/auth/auth_system.py +25 -40
- webscout/auth/config.py +105 -6
- webscout/auth/database.py +377 -22
- webscout/auth/models.py +185 -130
- webscout/auth/request_processing.py +175 -11
- webscout/auth/routes.py +119 -5
- webscout/auth/server.py +9 -2
- webscout/auth/simple_logger.py +236 -0
- webscout/sanitize.py +1074 -0
- webscout/version.py +1 -1
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/METADATA +9 -150
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/RECORD +70 -72
- webscout/Provider/AI21.py +0 -177
- webscout/Provider/HuggingFaceChat.py +0 -469
- webscout/Provider/OPENAI/README_AUTOPROXY.md +0 -238
- webscout/Provider/OPENAI/freeaichat.py +0 -363
- webscout/Provider/OPENAI/typegpt.py +0 -368
- webscout/Provider/OPENAI/uncovrAI.py +0 -477
- webscout/Provider/WritingMate.py +0 -273
- webscout/Provider/typegpt.py +0 -284
- webscout/Provider/uncovr.py +0 -333
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/WHEEL +0 -0
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/entry_points.txt +0 -0
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/licenses/LICENSE.md +0 -0
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/top_level.txt +0 -0
webscout/auth/routes.py
CHANGED
|
@@ -41,9 +41,11 @@ from .request_processing import (
|
|
|
41
41
|
handle_streaming_response, handle_non_streaming_response
|
|
42
42
|
)
|
|
43
43
|
from .auth_system import get_auth_components
|
|
44
|
+
from .simple_logger import request_logger
|
|
44
45
|
from webscout.DWEBS import GoogleSearch
|
|
45
46
|
from webscout.yep_search import YepSearch
|
|
46
47
|
from webscout.webscout_search import WEBS
|
|
48
|
+
from webscout.Bing_search import BingSearch
|
|
47
49
|
|
|
48
50
|
# Setup logger
|
|
49
51
|
logger = Logger(
|
|
@@ -164,6 +166,7 @@ class Api:
|
|
|
164
166
|
self._register_chat_routes()
|
|
165
167
|
self._register_auth_routes()
|
|
166
168
|
self._register_websearch_routes()
|
|
169
|
+
self._register_monitoring_routes()
|
|
167
170
|
|
|
168
171
|
def _register_model_routes(self):
|
|
169
172
|
"""Register model listing routes."""
|
|
@@ -240,6 +243,7 @@ class Api:
|
|
|
240
243
|
}
|
|
241
244
|
)
|
|
242
245
|
async def chat_completions(
|
|
246
|
+
request: Request,
|
|
243
247
|
chat_request: ChatCompletionRequest = Body(...)
|
|
244
248
|
):
|
|
245
249
|
"""Handle chat completion requests with comprehensive error handling."""
|
|
@@ -270,11 +274,39 @@ class Api:
|
|
|
270
274
|
# Prepare parameters for provider
|
|
271
275
|
params = prepare_provider_params(chat_request, model_name, processed_messages)
|
|
272
276
|
|
|
277
|
+
# Extract client IP address
|
|
278
|
+
client_ip = request.client.host if request.client else "unknown"
|
|
279
|
+
if "x-forwarded-for" in request.headers:
|
|
280
|
+
client_ip = request.headers["x-forwarded-for"].split(",")[0].strip()
|
|
281
|
+
elif "x-real-ip" in request.headers:
|
|
282
|
+
client_ip = request.headers["x-real-ip"]
|
|
283
|
+
|
|
284
|
+
# Extract question from messages (last user message)
|
|
285
|
+
question = ""
|
|
286
|
+
for msg in reversed(processed_messages):
|
|
287
|
+
if msg.get("role") == "user":
|
|
288
|
+
content = msg.get("content", "")
|
|
289
|
+
if isinstance(content, str):
|
|
290
|
+
question = content
|
|
291
|
+
elif isinstance(content, list) and content:
|
|
292
|
+
# Handle content with multiple parts (text, images, etc.)
|
|
293
|
+
for part in content:
|
|
294
|
+
if isinstance(part, dict) and part.get("type") == "text":
|
|
295
|
+
question = part.get("text", "")
|
|
296
|
+
break
|
|
297
|
+
break
|
|
298
|
+
|
|
273
299
|
# Handle streaming vs non-streaming
|
|
274
300
|
if chat_request.stream:
|
|
275
|
-
return await handle_streaming_response(
|
|
301
|
+
return await handle_streaming_response(
|
|
302
|
+
provider, params, request_id, client_ip, question, model_name, start_time,
|
|
303
|
+
provider_class.__name__, request
|
|
304
|
+
)
|
|
276
305
|
else:
|
|
277
|
-
return await handle_non_streaming_response(
|
|
306
|
+
return await handle_non_streaming_response(
|
|
307
|
+
provider, params, request_id, start_time, client_ip, question, model_name,
|
|
308
|
+
provider_class.__name__, request
|
|
309
|
+
)
|
|
278
310
|
|
|
279
311
|
except APIError:
|
|
280
312
|
# Re-raise API errors as-is
|
|
@@ -483,11 +515,11 @@ class Api:
|
|
|
483
515
|
@self.app.get(
|
|
484
516
|
"/search",
|
|
485
517
|
tags=["Web search"],
|
|
486
|
-
description="Unified web search endpoint supporting Google, Yep, and
|
|
518
|
+
description="Unified web search endpoint supporting Google, Yep, DuckDuckGo, and Bing with text, news, images, and suggestions search types."
|
|
487
519
|
)
|
|
488
520
|
async def websearch(
|
|
489
521
|
q: str = Query(..., description="Search query"),
|
|
490
|
-
engine: str = Query("google", description="Search engine: google, yep, duckduckgo"),
|
|
522
|
+
engine: str = Query("google", description="Search engine: google, yep, duckduckgo, bing"),
|
|
491
523
|
max_results: int = Query(10, description="Maximum number of results"),
|
|
492
524
|
region: str = Query("all", description="Region code (optional)"),
|
|
493
525
|
safesearch: str = Query("moderate", description="Safe search: on, moderate, off"),
|
|
@@ -532,8 +564,24 @@ class Api:
|
|
|
532
564
|
return {"engine": "duckduckgo", "type": "suggestions", "results": results}
|
|
533
565
|
else:
|
|
534
566
|
return {"error": "DuckDuckGo only supports text and suggestions in this API.", "footer": github_footer}
|
|
567
|
+
elif engine == "bing":
|
|
568
|
+
bs = BingSearch()
|
|
569
|
+
if type == "text":
|
|
570
|
+
results = bs.text(keywords=q, region=region, safesearch=safesearch, max_results=max_results)
|
|
571
|
+
return {"engine": "bing", "type": "text", "results": [r.__dict__ for r in results]}
|
|
572
|
+
elif type == "news":
|
|
573
|
+
results = bs.news(keywords=q, region=region, safesearch=safesearch, max_results=max_results)
|
|
574
|
+
return {"engine": "bing", "type": "news", "results": [r.__dict__ for r in results]}
|
|
575
|
+
elif type == "images":
|
|
576
|
+
results = bs.images(keywords=q, region=region, safesearch=safesearch, max_results=max_results)
|
|
577
|
+
return {"engine": "bing", "type": "images", "results": [r.__dict__ for r in results]}
|
|
578
|
+
elif type == "suggestions":
|
|
579
|
+
results = bs.suggestions(q, region=region)
|
|
580
|
+
return {"engine": "bing", "type": "suggestions", "results": results}
|
|
581
|
+
else:
|
|
582
|
+
return {"error": "Bing only supports text, news, images, and suggestions in this API.", "footer": github_footer}
|
|
535
583
|
else:
|
|
536
|
-
return {"error": "Unknown engine. Use one of: google, yep, duckduckgo.", "footer": github_footer}
|
|
584
|
+
return {"error": "Unknown engine. Use one of: google, yep, duckduckgo, bing.", "footer": github_footer}
|
|
537
585
|
except Exception as e:
|
|
538
586
|
# Special handling for rate limit errors
|
|
539
587
|
msg = str(e)
|
|
@@ -548,3 +596,69 @@ class Api:
|
|
|
548
596
|
"error": f"Search request failed: {msg}",
|
|
549
597
|
"footer": github_footer
|
|
550
598
|
}
|
|
599
|
+
|
|
600
|
+
def _register_monitoring_routes(self):
|
|
601
|
+
"""Register monitoring and analytics routes for no-auth mode."""
|
|
602
|
+
|
|
603
|
+
@self.app.get(
|
|
604
|
+
"/monitor/requests",
|
|
605
|
+
tags=["Monitoring"],
|
|
606
|
+
description="Get recent API requests (no-auth mode only)"
|
|
607
|
+
)
|
|
608
|
+
async def get_recent_requests(limit: int = Query(10, description="Number of recent requests to fetch")):
|
|
609
|
+
"""Get recent API requests for monitoring."""
|
|
610
|
+
if AppConfig.auth_required:
|
|
611
|
+
return {"error": "Monitoring is only available in no-auth mode"}
|
|
612
|
+
|
|
613
|
+
try:
|
|
614
|
+
return await request_logger.get_recent_requests(limit)
|
|
615
|
+
except Exception as e:
|
|
616
|
+
return {"error": f"Failed to fetch requests: {str(e)}"}
|
|
617
|
+
|
|
618
|
+
@self.app.get(
|
|
619
|
+
"/monitor/stats",
|
|
620
|
+
tags=["Monitoring"],
|
|
621
|
+
description="Get API usage statistics (no-auth mode only)"
|
|
622
|
+
)
|
|
623
|
+
async def get_api_stats():
|
|
624
|
+
"""Get API usage statistics."""
|
|
625
|
+
if AppConfig.auth_required:
|
|
626
|
+
return {"error": "Monitoring is only available in no-auth mode"}
|
|
627
|
+
|
|
628
|
+
try:
|
|
629
|
+
return await request_logger.get_stats()
|
|
630
|
+
except Exception as e:
|
|
631
|
+
return {"error": f"Failed to fetch stats: {str(e)}"}
|
|
632
|
+
|
|
633
|
+
@self.app.get(
|
|
634
|
+
"/monitor/health",
|
|
635
|
+
tags=["Monitoring"],
|
|
636
|
+
description="Health check with database status"
|
|
637
|
+
)
|
|
638
|
+
async def enhanced_health_check():
|
|
639
|
+
"""Enhanced health check including database connectivity."""
|
|
640
|
+
try:
|
|
641
|
+
# Check database connectivity
|
|
642
|
+
db_status = "disconnected"
|
|
643
|
+
if request_logger.supabase_client:
|
|
644
|
+
try:
|
|
645
|
+
# Try a simple query to check connectivity
|
|
646
|
+
result = request_logger.supabase_client.table("api_requests").select("id").limit(1).execute()
|
|
647
|
+
db_status = "connected"
|
|
648
|
+
except Exception as e:
|
|
649
|
+
db_status = f"error: {str(e)[:100]}"
|
|
650
|
+
|
|
651
|
+
return {
|
|
652
|
+
"status": "healthy",
|
|
653
|
+
"database": db_status,
|
|
654
|
+
"auth_required": AppConfig.auth_required,
|
|
655
|
+
"rate_limit_enabled": AppConfig.rate_limit_enabled,
|
|
656
|
+
"request_logging_enabled": AppConfig.request_logging_enabled,
|
|
657
|
+
"timestamp": datetime.now(timezone.utc).isoformat()
|
|
658
|
+
}
|
|
659
|
+
except Exception as e:
|
|
660
|
+
return {
|
|
661
|
+
"status": "unhealthy",
|
|
662
|
+
"error": str(e),
|
|
663
|
+
"timestamp": datetime.now(timezone.utc).isoformat()
|
|
664
|
+
}
|
webscout/auth/server.py
CHANGED
|
@@ -40,8 +40,15 @@ logger = Logger(
|
|
|
40
40
|
fmt=LogFormat.DEFAULT
|
|
41
41
|
)
|
|
42
42
|
|
|
43
|
-
# Global configuration instance
|
|
44
|
-
config =
|
|
43
|
+
# Global configuration instance - lazy initialization
|
|
44
|
+
config = None
|
|
45
|
+
|
|
46
|
+
def get_config() -> ServerConfig:
|
|
47
|
+
"""Get or create the global configuration instance."""
|
|
48
|
+
global config
|
|
49
|
+
if config is None:
|
|
50
|
+
config = ServerConfig()
|
|
51
|
+
return config
|
|
45
52
|
|
|
46
53
|
|
|
47
54
|
def create_app():
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Simple database logging for no-auth mode.
|
|
3
|
+
Logs API requests directly to Supabase without authentication.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import uuid
|
|
8
|
+
import asyncio
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from typing import Optional, Dict, Any
|
|
11
|
+
import json
|
|
12
|
+
|
|
13
|
+
from webscout.Litlogger import Logger, LogLevel, LogFormat, ConsoleHandler
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
# Setup logger
|
|
17
|
+
logger = Logger(
|
|
18
|
+
name="webscout.api.simple_db",
|
|
19
|
+
level=LogLevel.INFO,
|
|
20
|
+
handlers=[ConsoleHandler(stream=sys.stdout)],
|
|
21
|
+
fmt=LogFormat.DEFAULT
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
from supabase import create_client, Client
|
|
26
|
+
SUPABASE_AVAILABLE = True
|
|
27
|
+
except ImportError:
|
|
28
|
+
logger.warning("Supabase not available. Install with: pip install supabase")
|
|
29
|
+
SUPABASE_AVAILABLE = False
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SimpleRequestLogger:
|
|
33
|
+
"""Simple request logger for no-auth mode."""
|
|
34
|
+
|
|
35
|
+
def __init__(self):
|
|
36
|
+
self.supabase_client: Optional[Client] = None
|
|
37
|
+
self.initialize_supabase()
|
|
38
|
+
|
|
39
|
+
def initialize_supabase(self):
|
|
40
|
+
"""Initialize Supabase client if credentials are available."""
|
|
41
|
+
if not SUPABASE_AVAILABLE:
|
|
42
|
+
logger.warning("Supabase package not installed. Request logging disabled.")
|
|
43
|
+
return
|
|
44
|
+
|
|
45
|
+
supabase_url = os.getenv("SUPABASE_URL")
|
|
46
|
+
supabase_key = os.getenv("SUPABASE_ANON_KEY")
|
|
47
|
+
|
|
48
|
+
if supabase_url and supabase_key:
|
|
49
|
+
try:
|
|
50
|
+
self.supabase_client = create_client(supabase_url, supabase_key)
|
|
51
|
+
logger.info("Supabase client initialized for request logging")
|
|
52
|
+
|
|
53
|
+
except Exception as e:
|
|
54
|
+
logger.error(f"Failed to initialize Supabase client: {e}")
|
|
55
|
+
self.supabase_client = None
|
|
56
|
+
else:
|
|
57
|
+
logger.info("Supabase credentials not found. Request logging disabled.")
|
|
58
|
+
|
|
59
|
+
async def log_request(
|
|
60
|
+
self,
|
|
61
|
+
request_id: str,
|
|
62
|
+
ip_address: str,
|
|
63
|
+
model: str,
|
|
64
|
+
question: str,
|
|
65
|
+
answer: str,
|
|
66
|
+
provider: Optional[str] = None,
|
|
67
|
+
request_time: Optional[datetime] = None,
|
|
68
|
+
response_time: Optional[datetime] = None,
|
|
69
|
+
processing_time_ms: Optional[float] = None,
|
|
70
|
+
tokens_used: Optional[int] = None,
|
|
71
|
+
error: Optional[str] = None,
|
|
72
|
+
user_agent: Optional[str] = None
|
|
73
|
+
) -> bool:
|
|
74
|
+
"""
|
|
75
|
+
Log API request details to Supabase.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
request_id: Unique identifier for the request
|
|
79
|
+
ip_address: Client IP address
|
|
80
|
+
model: Model used for the request
|
|
81
|
+
question: User's question/prompt
|
|
82
|
+
answer: AI's response
|
|
83
|
+
provider: Provider used (e.g., ChatGPT, Claude, etc.)
|
|
84
|
+
request_time: When the request was received
|
|
85
|
+
response_time: When the response was sent
|
|
86
|
+
processing_time_ms: Processing time in milliseconds
|
|
87
|
+
tokens_used: Number of tokens consumed
|
|
88
|
+
error: Error message if any
|
|
89
|
+
user_agent: User agent string
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
bool: True if logged successfully, False otherwise
|
|
93
|
+
"""
|
|
94
|
+
if not self.supabase_client:
|
|
95
|
+
# Still log to console for debugging
|
|
96
|
+
logger.info(f"Request {request_id}: {model} - {question[:100]}...")
|
|
97
|
+
return False
|
|
98
|
+
|
|
99
|
+
if not request_time:
|
|
100
|
+
request_time = datetime.now(timezone.utc)
|
|
101
|
+
|
|
102
|
+
if not response_time:
|
|
103
|
+
response_time = datetime.now(timezone.utc)
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
data = {
|
|
107
|
+
"request_id": request_id,
|
|
108
|
+
"ip_address": ip_address,
|
|
109
|
+
"model": model,
|
|
110
|
+
"provider": provider or "unknown",
|
|
111
|
+
"question": question[:2000] if question else "", # Truncate long questions
|
|
112
|
+
"answer": answer[:5000] if answer else "", # Truncate long answers
|
|
113
|
+
"request_time": request_time.isoformat(),
|
|
114
|
+
"response_time": response_time.isoformat(),
|
|
115
|
+
"processing_time_ms": processing_time_ms,
|
|
116
|
+
"tokens_used": tokens_used,
|
|
117
|
+
"error": error[:1000] if error else None, # Truncate long errors
|
|
118
|
+
"user_agent": user_agent[:500] if user_agent else None,
|
|
119
|
+
"created_at": datetime.now(timezone.utc).isoformat()
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
result = self.supabase_client.table("api_requests").insert(data).execute()
|
|
123
|
+
|
|
124
|
+
if result.data:
|
|
125
|
+
logger.info(f"✅ Request {request_id} logged to database")
|
|
126
|
+
return True
|
|
127
|
+
else:
|
|
128
|
+
logger.error(f"❌ Failed to log request {request_id}: No data returned")
|
|
129
|
+
return False
|
|
130
|
+
|
|
131
|
+
except Exception as e:
|
|
132
|
+
logger.error(f"❌ Failed to log request {request_id}: {e}")
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
async def get_recent_requests(self, limit: int = 10) -> Dict[str, Any]:
|
|
136
|
+
"""Get recent API requests for monitoring."""
|
|
137
|
+
if not self.supabase_client:
|
|
138
|
+
return {"error": "Database not available", "requests": []}
|
|
139
|
+
|
|
140
|
+
try:
|
|
141
|
+
result = self.supabase_client.table("api_requests")\
|
|
142
|
+
.select("request_id, ip_address, model, provider, created_at, processing_time_ms, error")\
|
|
143
|
+
.order("created_at", desc=True)\
|
|
144
|
+
.limit(limit)\
|
|
145
|
+
.execute()
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
"requests": result.data if result.data else [],
|
|
149
|
+
"count": len(result.data) if result.data else 0
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
except Exception as e:
|
|
153
|
+
logger.error(f"Failed to get recent requests: {e}")
|
|
154
|
+
return {"error": str(e), "requests": []}
|
|
155
|
+
|
|
156
|
+
async def get_stats(self) -> Dict[str, Any]:
|
|
157
|
+
"""Get basic statistics about API usage."""
|
|
158
|
+
if not self.supabase_client:
|
|
159
|
+
return {"error": "Database not available"}
|
|
160
|
+
|
|
161
|
+
try:
|
|
162
|
+
# Get total requests today
|
|
163
|
+
today = datetime.now(timezone.utc).date().isoformat()
|
|
164
|
+
|
|
165
|
+
today_requests = self.supabase_client.table("api_requests")\
|
|
166
|
+
.select("request_id", count="exact")\
|
|
167
|
+
.gte("created_at", f"{today}T00:00:00Z")\
|
|
168
|
+
.execute()
|
|
169
|
+
|
|
170
|
+
# Get requests by model (last 100)
|
|
171
|
+
model_requests = self.supabase_client.table("api_requests")\
|
|
172
|
+
.select("model")\
|
|
173
|
+
.order("created_at", desc=True)\
|
|
174
|
+
.limit(100)\
|
|
175
|
+
.execute()
|
|
176
|
+
|
|
177
|
+
model_counts = {}
|
|
178
|
+
if model_requests.data:
|
|
179
|
+
for req in model_requests.data:
|
|
180
|
+
model = req.get("model", "unknown")
|
|
181
|
+
model_counts[model] = model_counts.get(model, 0) + 1
|
|
182
|
+
|
|
183
|
+
return {
|
|
184
|
+
"today_requests": today_requests.count if hasattr(today_requests, 'count') else 0,
|
|
185
|
+
"model_usage": model_counts,
|
|
186
|
+
"available": True
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
except Exception as e:
|
|
190
|
+
logger.error(f"Failed to get stats: {e}")
|
|
191
|
+
return {"error": str(e), "available": False}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# Global instance
|
|
195
|
+
request_logger = SimpleRequestLogger()
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
async def log_api_request(
|
|
199
|
+
request_id: str,
|
|
200
|
+
ip_address: str,
|
|
201
|
+
model: str,
|
|
202
|
+
question: str,
|
|
203
|
+
answer: str,
|
|
204
|
+
**kwargs
|
|
205
|
+
) -> bool:
|
|
206
|
+
"""Convenience function to log API requests."""
|
|
207
|
+
return await request_logger.log_request(
|
|
208
|
+
request_id=request_id,
|
|
209
|
+
ip_address=ip_address,
|
|
210
|
+
model=model,
|
|
211
|
+
question=question,
|
|
212
|
+
answer=answer,
|
|
213
|
+
**kwargs
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def get_client_ip(request) -> str:
|
|
218
|
+
"""Extract client IP address from request."""
|
|
219
|
+
# Check for X-Forwarded-For header (common with proxies/load balancers)
|
|
220
|
+
forwarded_for = request.headers.get("X-Forwarded-For")
|
|
221
|
+
if forwarded_for:
|
|
222
|
+
# Take the first IP in the chain
|
|
223
|
+
return forwarded_for.split(",")[0].strip()
|
|
224
|
+
|
|
225
|
+
# Check for X-Real-IP header
|
|
226
|
+
real_ip = request.headers.get("X-Real-IP")
|
|
227
|
+
if real_ip:
|
|
228
|
+
return real_ip.strip()
|
|
229
|
+
|
|
230
|
+
# Fall back to direct client IP
|
|
231
|
+
return getattr(request.client, "host", "unknown")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def generate_request_id() -> str:
|
|
235
|
+
"""Generate a unique request ID."""
|
|
236
|
+
return str(uuid.uuid4())
|