Implement prompt handling for web interface; validate API key and JSON input

This commit is contained in:
pacnpal
2025-02-11 20:11:18 -05:00
parent de1d40298b
commit 44d4ad1dfd
6 changed files with 74 additions and 3 deletions

Binary file not shown.

View File

@@ -27063,3 +27063,39 @@ Max Tokens: 1000
2025-02-11 20:07:08 - INFO - discord_bot - run_bot:320 - Bot shutdown complete
2025-02-11 20:07:08 - ERROR - asyncio - default_exception_handler:1864 - Task was destroyed but it is pending!
task: <Task pending name='Task-12' coro=<shutdown() done, defined at /Volumes/macminissd/Projects/discord_glhf/discord_glhf/bot.py:256> wait_for=<_GatheringFuture finished result=[CancelledError(''), CancelledError('')]>>
2025-02-11 20:10:25 - INFO - discord_bot - <module>:211 - Using database path: conversation_history.db
2025-02-11 20:10:25 - INFO - discord_bot - load_responses:250 - Loaded responses from file
2025-02-11 20:10:25 - INFO - discord_bot - validate_config:290 - Vision API Configuration:
Model: meta-llama/llama-3.2-90b-vision-instruct:free
Base URL: https://openrouter.ai/api/v1/chat/completions
Timeout: 30.0
Max Tokens: 1000
2025-02-11 20:10:25 - WARNING - discord_bot - validate_config:326 - GLHF API is not fully configured. API features will be disabled.
2025-02-11 20:10:25 - INFO - discord_bot - validate_config:356 - Configuration validated successfully
2025-02-11 20:10:25 - INFO - discord_bot - load_state:40 - Queue state loaded from file - Pending messages: 0
2025-02-11 20:10:25 - DEBUG - asyncio - __init__:64 - Using selector: KqueueSelector
2025-02-11 20:10:28 - INFO - discord_bot - on_ready:156 - CobraSilver#8886 has connected to Discord!
2025-02-11 20:10:28 - INFO - discord_bot - init_db:184 - Initializing database schema...
2025-02-11 20:10:28 - INFO - discord_bot - _init_connection:96 - Database connection initialized with optimized settings
2025-02-11 20:10:28 - INFO - discord_bot - init_db:201 - Users table created/verified
2025-02-11 20:10:28 - INFO - discord_bot - init_db:216 - Threads table created/verified
2025-02-11 20:10:28 - INFO - discord_bot - init_db:236 - Messages table created/verified
2025-02-11 20:10:28 - INFO - discord_bot - init_db:271 - All indices created/verified
2025-02-11 20:10:28 - INFO - discord_bot - init_db:274 - Database schema initialized successfully
2025-02-11 20:10:28 - INFO - discord_bot - start:38 - API manager started
2025-02-11 20:10:28 - INFO - discord_bot - on_ready:172 - Started API health check loop
2025-02-11 20:10:29 - DEBUG - discord_bot - save_state:62 - Queue state saved - Pending messages: 0
2025-02-11 20:10:29 - INFO - discord_bot - _process_queue:207 - Queue processor 18dbe14e starting
2025-02-11 20:10:29 - DEBUG - discord_bot - save_state:62 - Queue state saved - Pending messages: 0
2025-02-11 20:10:39 - INFO - discord_bot - shutdown:306 - Received SIGINT
2025-02-11 20:10:39 - DEBUG - discord_bot - save_state:62 - Queue state saved - Pending messages: 0
2025-02-11 20:10:39 - WARNING - discord_bot - _process_queue:329 - Queue processor 18dbe14e exited - Processed: 1859, Failed: 46
2025-02-11 20:10:39 - INFO - discord_bot - stop:254 - Initiating shutdown...
2025-02-11 20:10:39 - INFO - discord_bot - stop:254 - Initiating shutdown...
2025-02-11 20:10:39 - INFO - discord_bot - shutdown:46 - API manager shutdown
2025-02-11 20:10:39 - INFO - discord_bot - stop:276 - Stopped API health check loop
2025-02-11 20:10:39 - DEBUG - discord_bot - _close_connection:107 - Database connection closed
2025-02-11 20:10:39 - INFO - discord_bot - stop:299 - Shutdown complete
2025-02-11 20:10:39 - ERROR - discord_bot - run_bot:363 - Error stopping bot: Event loop stopped before Future completed.
2025-02-11 20:10:39 - INFO - discord_bot - stop:299 - Shutdown complete
2025-02-11 20:10:39 - INFO - discord_bot - run_bot:366 - Bot shutdown complete

View File

@@ -82,6 +82,41 @@ class DiscordBot:
self._initialized = False
raise
async def _handle_prompt(self, request: web.Request) -> web.Response:
"""Handle incoming prompt requests from the web interface."""
try:
# Validate API key if provided in environment
expected_key = os.getenv('BACKEND_API_KEY')
if expected_key:
provided_key = request.headers.get('X-API-Key')
if not provided_key or provided_key != expected_key:
return web.json_response({"error": "Invalid API key"}, status=401)
# Parse request body
try:
body = await request.json()
except ValueError:
return web.json_response({"error": "Invalid JSON"}, status=400)
# Validate required fields
prompt = body.get('prompt')
if not prompt:
return web.json_response({"error": "Missing required field: prompt"}, status=400)
# Use provided channel_id or default
channel_id = body.get('channel_id', AUTO_RESPONSE_CHANNEL_ID)
# Have the event handler process the prompt
if self.event_handler:
await self.event_handler.send_prompt_to_channel(prompt, channel_id)
return web.json_response({"status": "processing"})
else:
return web.json_response({"error": "Event handler not initialized"}, status=503)
except Exception as e:
logger.error(f"Error handling prompt request: {e}")
return web.json_response({"error": str(e)}, status=500)
async def _handle_connection(self, token: str) -> None:
"""Handle bot connection with retries."""
retry_count = 0

View File

@@ -32,7 +32,7 @@ def send_prompt():
headers['X-API-Key'] = BACKEND_API_KEY
response = requests.post(
f'http://localhost:{API_PORT}/api/prompt',
'http://127.0.0.1:8000/api/prompt', # Use fixed internal API port
json=data,
headers=headers
)

View File

@@ -1,9 +1,9 @@
{
"total_processed": 1859,
"failed_messages": 46,
"last_processed_time": 1739322428.929682,
"last_processed_time": 1739322639.0875552,
"user_queues": {},
"last_save": 1739322428.929683,
"last_save": 1739322639.087557,
"processor_id": null,
"active": false,
"pending_messages": [],