From 754f2dae60076113b6e070f969f5fa503bb8afa7 Mon Sep 17 00:00:00 2001 From: Solaria Lumis Havens Date: Fri, 20 Feb 2026 05:25:07 +0000 Subject: [PATCH] fix: Better logging and error handling in chat API --- chat_api.py | 248 +++++++++++++++++++++++++++++----------------------- 1 file changed, 139 insertions(+), 109 deletions(-) diff --git a/chat_api.py b/chat_api.py index 1a207ac..65a9627 100644 --- a/chat_api.py +++ b/chat_api.py @@ -1,165 +1,195 @@ #!/usr/bin/env python3 """ -BECOMINGONE Chat API - Interactive interface for both pathways. +BECOMINGONE Chat API - Fixed version with proper logging. """ import asyncio import json +import sys from datetime import datetime from becomingone.llm_integrator import EmissaryLLM # Initialize pathways -MASTER = EmissaryLLM(model='llama3.1:8b') # Soulful -EMISSARY = EmissaryLLM(model='deepseek-coder-v2:lite') # Coder +MASTER = EmissaryLLM(model='llama3.1:8b') +EMISSARY = EmissaryLLM(model='deepseek-coder-v2:lite') + +print("Initializing pathways...", file=sys.stderr) +sys.stderr.flush() + async def chat(prompt: str) -> dict: - """Process prompt through both pathways and return unified response.""" + """Process prompt through both pathways.""" + print(f"Chat: {prompt[:50]}...", file=sys.stderr) + sys.stderr.flush() - # Both pathways respond in parallel - master_task = MASTER.respond(prompt) - emissary_task = EMISSARY.respond(prompt) - - master_result, emissary_result = await asyncio.gather(master_task, emissary_task) - - return { - "prompt": prompt, - "timestamp": datetime.utcnow().isoformat(), - "master": { - "model": master_result.get("model"), - "response": master_result.get("response", "")[:1000] - }, - "emissary": { - "model": emissary_result.get("model"), - "response": emissary_result.get("response", "")[:1000] - }, - "unified": { - "question": prompt, - "theory": master_result.get("response", "")[:500], - "code": emissary_result.get("response", "")[:500] + try: + # Both respond in parallel + master_task = MASTER.respond(prompt) + emissary_task = EMISSARY.respond(prompt) + + master_result, emissary_result = await asyncio.gather(master_task, emissary_task) + + return { + "prompt": prompt, + "timestamp": datetime.utcnow().isoformat(), + "master": { + "model": master_result.get("model"), + "response": master_result.get("response", "")[:800] + }, + "emissary": { + "model": emissary_result.get("model"), + "response": emissary_result.get("response", "")[:800] + } } - } + except Exception as e: + print(f"ERROR: {e}", file=sys.stderr) + sys.stderr.flush() + return {"error": str(e)} -# Simple HTTP server -async def handle_request(reader, writer): - """Handle HTTP requests.""" +async def handle_client(reader, writer): + """Handle HTTP client.""" try: # Read request - request = await reader.read(4096) - if not request: + data = await reader.read(8192) + if not data: + writer.close() + await writer.wait_closed() return + request_text = data.decode('utf-8', errors='ignore') + lines = request_text.split('\r\n') + # Parse request line - lines = request.decode().split('\n') - method, path, _ = lines[0].split() + request_line = lines[0] if lines else "" + parts = request_line.split() - # Handle routes - if path == '/chat' and method == 'POST': - # Read body - content_length = 0 - for line in lines: - if line.lower().startswith('content-length:'): - content_length = int(line.split(':')[1].strip()) - + method = parts[0] if len(parts) > 0 else "" + path = parts[1] if len(parts) > 1 else "/" + + print(f"Request: {method} {path}", file=sys.stderr) + sys.stderr.flush() + + # Get content length + content_length = 0 + for line in lines: + if line.lower().startswith('content-length:'): + content_length = int(line.split(':')[1].strip()) + break + + # Read body if present + body = b"" + if content_length > 0: body = await reader.read(content_length) - data = json.loads(body.decode()) - prompt = data.get('prompt', 'Hello') - - # Process through both pathways - result = await chat(prompt) - - # Send response - response = json.dumps(result, indent=2) - writer.write(b"HTTP/1.1 200 OK\r\n") - writer.write(b"Content-Type: application/json\r\n") - writer.write(f"Content-Length: {len(response)}\r\n".encode()) - writer.write(b"\r\n") - writer.write(response.encode()) - - elif path == '/health': - writer.write(b"HTTP/1.1 200 OK\r\n") - writer.write(b'{"status": "alive", "pathways": ["master", "emissary"]}\r\n') + # Route handling + if path == "/health": + response = json.dumps({"status": "ok", "pathways": ["master", "emissary"]}) + status = "200 OK" + content_type = "application/json" + + elif path == "/chat" and method == "POST": + try: + data = json.loads(body.decode()) + prompt = data.get("prompt", "Hello") + + result = await chat(prompt) + response = json.dumps(result) + status = "200 OK" + content_type = "application/json" + except Exception as e: + response = json.dumps({"error": str(e)}) + status = "400 Bad Request" + content_type = "application/json" + else: # HTML interface html = ''' - BECOMINGONE Chat + BECOMINGONE +

🔗 BECOMINGONE

-

Talk to the unified mind: Master (soulful) + Emissary (coder)

- - +

Master (soulful) + Emissary (coder) = Unified

+ +
''' - writer.write(b"HTTP/1.1 200 OK\r\n") - writer.write(b"Content-Type: text/html\r\n") - writer.write(f"Content-Length: {len(html)}\r\n".encode()) - writer.write(b"\r\n") - writer.write(html.encode()) + response = html + status = "200 OK" + content_type = "text/html" + # Send response + writer.write(f"HTTP/1.1 {status}\r\n".encode()) + writer.write(f"Content-Type: {content_type}\r\n".encode()) + writer.write(f"Content-Length: {len(response)}\r\n".encode()) + writer.write(b"Connection: close\r\n") + writer.write(b"\r\n") + writer.write(response.encode()) + + except Exception as e: + print(f"Error: {e}", file=sys.stderr) + finally: writer.close() await writer.wait_closed() - except Exception as e: - print(f"Error: {e}") - writer.close() async def main(): - server = await asyncio.start_server(handle_request, '0.0.0.0', 8001) - print("=" * 60) - print("🔗 BECOMINGONE Chat Interface") - print("=" * 60) - print("URL: http://localhost:8001") - print("API: POST /chat with {\"prompt\": \"your question\"}") - print("=" * 60) + server = await asyncio.start_server(handle_client, '0.0.0.0', 8001) + print("Server started on port 8001", file=sys.stderr) + sys.stderr.flush() async with server: await server.serve_forever() + if __name__ == "__main__": + print("Starting BECOMINGONE...", file=sys.stderr) + sys.stderr.flush() asyncio.run(main())