webscout 8.3.4__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.

Files changed (55) hide show
  1. webscout/AIutel.py +52 -1016
  2. webscout/Provider/AISEARCH/__init__.py +11 -10
  3. webscout/Provider/AISEARCH/felo_search.py +7 -3
  4. webscout/Provider/AISEARCH/scira_search.py +2 -0
  5. webscout/Provider/AISEARCH/stellar_search.py +53 -8
  6. webscout/Provider/Deepinfra.py +7 -1
  7. webscout/Provider/OPENAI/TogetherAI.py +57 -48
  8. webscout/Provider/OPENAI/TwoAI.py +94 -1
  9. webscout/Provider/OPENAI/__init__.py +0 -2
  10. webscout/Provider/OPENAI/deepinfra.py +6 -0
  11. webscout/Provider/OPENAI/scirachat.py +4 -0
  12. webscout/Provider/OPENAI/textpollinations.py +11 -7
  13. webscout/Provider/OPENAI/venice.py +1 -0
  14. webscout/Provider/Perplexitylabs.py +163 -147
  15. webscout/Provider/Qodo.py +30 -6
  16. webscout/Provider/TTI/__init__.py +1 -0
  17. webscout/Provider/TTI/together.py +7 -6
  18. webscout/Provider/TTI/venice.py +368 -0
  19. webscout/Provider/TextPollinationsAI.py +11 -7
  20. webscout/Provider/TogetherAI.py +57 -44
  21. webscout/Provider/TwoAI.py +96 -2
  22. webscout/Provider/TypliAI.py +33 -27
  23. webscout/Provider/UNFINISHED/PERPLEXED_search.py +254 -0
  24. webscout/Provider/UNFINISHED/fetch_together_models.py +6 -11
  25. webscout/Provider/Venice.py +1 -0
  26. webscout/Provider/WiseCat.py +18 -20
  27. webscout/Provider/__init__.py +0 -6
  28. webscout/Provider/scira_chat.py +4 -0
  29. webscout/Provider/toolbaz.py +5 -10
  30. webscout/Provider/typefully.py +1 -11
  31. webscout/__init__.py +3 -15
  32. webscout/auth/__init__.py +19 -4
  33. webscout/auth/api_key_manager.py +189 -189
  34. webscout/auth/auth_system.py +25 -40
  35. webscout/auth/config.py +105 -6
  36. webscout/auth/database.py +377 -22
  37. webscout/auth/models.py +185 -130
  38. webscout/auth/request_processing.py +175 -11
  39. webscout/auth/routes.py +99 -2
  40. webscout/auth/server.py +9 -2
  41. webscout/auth/simple_logger.py +236 -0
  42. webscout/sanitize.py +1074 -0
  43. webscout/version.py +1 -1
  44. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/METADATA +9 -149
  45. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/RECORD +49 -51
  46. webscout/Provider/OPENAI/README_AUTOPROXY.md +0 -238
  47. webscout/Provider/OPENAI/typegpt.py +0 -368
  48. webscout/Provider/OPENAI/uncovrAI.py +0 -477
  49. webscout/Provider/WritingMate.py +0 -273
  50. webscout/Provider/typegpt.py +0 -284
  51. webscout/Provider/uncovr.py +0 -333
  52. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/WHEEL +0 -0
  53. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/entry_points.txt +0 -0
  54. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/licenses/LICENSE.md +0 -0
  55. {webscout-8.3.4.dist-info → webscout-8.3.5.dist-info}/top_level.txt +0 -0
webscout/auth/routes.py CHANGED
@@ -41,6 +41,7 @@ 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
@@ -165,6 +166,7 @@ class Api:
165
166
  self._register_chat_routes()
166
167
  self._register_auth_routes()
167
168
  self._register_websearch_routes()
169
+ self._register_monitoring_routes()
168
170
 
169
171
  def _register_model_routes(self):
170
172
  """Register model listing routes."""
@@ -241,6 +243,7 @@ class Api:
241
243
  }
242
244
  )
243
245
  async def chat_completions(
246
+ request: Request,
244
247
  chat_request: ChatCompletionRequest = Body(...)
245
248
  ):
246
249
  """Handle chat completion requests with comprehensive error handling."""
@@ -271,11 +274,39 @@ class Api:
271
274
  # Prepare parameters for provider
272
275
  params = prepare_provider_params(chat_request, model_name, processed_messages)
273
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
+
274
299
  # Handle streaming vs non-streaming
275
300
  if chat_request.stream:
276
- return await handle_streaming_response(provider, params, request_id)
301
+ return await handle_streaming_response(
302
+ provider, params, request_id, client_ip, question, model_name, start_time,
303
+ provider_class.__name__, request
304
+ )
277
305
  else:
278
- return await handle_non_streaming_response(provider, params, request_id, start_time)
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
+ )
279
310
 
280
311
  except APIError:
281
312
  # Re-raise API errors as-is
@@ -565,3 +596,69 @@ class Api:
565
596
  "error": f"Search request failed: {msg}",
566
597
  "footer": github_footer
567
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 = ServerConfig()
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())