Files
hack/tools/scripts/llm-key-hunter/results/_cache/content/ayushdwivedi001_voxkage-mobile.json

1 line
8.2 KiB
JSON

{"repo": "ayushdwivedi001/voxkage-mobile", "files": {"backend/opencode_client.py": {"844b314f198cb6b4353f0155430596b8406a69c5": {"t": 1785595266.6636772, "n": 7699, "h": "301b42eaeb9f941f", "c": "import os\nimport json\nimport requests\nimport httpx\nfrom fastapi import HTTPException\nfrom fastapi.responses import StreamingResponse\n\nOPENCODE_BASE_URL = \"https://opencode.ai/zen/v1\"\n\n# Map human-readable model keys to OpenCode API model strings\nMODEL_MAP = {\n \"deepseek-flash\": \"deepseek-v4-flash-free\",\n \"gemini-flash\": \"gemini-3.5-flash\",\n \"claude-sonnet\": \"claude-sonnet-4\",\n \"mimo-free\": \"mimo-v2.5-free\",\n}\n\ndef get_opencode_model(model_key: str) -> str:\n if model_key in MODEL_MAP:\n return MODEL_MAP[model_key]\n return model_key\n\ndef sanitize_history_roles(history: list) -> list:\n \"\"\"\n Sanitizes message history by mapping non-standard roles (like 'laptop') \n to standard roles (like 'user') to prevent upstream LLM API errors.\n \"\"\"\n sanitized = []\n if not history:\n return sanitized\n for msg in history:\n if isinstance(msg, dict):\n role = msg.get(\"role\")\n content = msg.get(\"content\") or \"\"\n else:\n role = getattr(msg, \"role\", None)\n content = getattr(msg, \"content\", None) or \"\"\n \n # Map 'laptop' to 'user' with a clear prefix so the LLM understands it's a tool output\n if role == \"laptop\":\n role = \"user\"\n content = f\"[Laptop Command Output]:\\n{content}\"\n elif role not in (\"system\", \"user\", \"assistant\", \"tool\"):\n # Fallback for any other unexpected role\n role = \"user\"\n \n sanitized.append({\"role\": role, \"content\": content})\n return sanitized\n\nasync def query_opencode_zen(prompt: str, model_key: str = \"deepseek-flash\", history: list = None) -> str:\n \"\"\"\n Standard asynchronous query returning the full text block response.\n \"\"\"\n api_key = os.getenv(\"OPENCODE_API_KEY\")\n if not api_key:\n raise HTTPException(status_code=500, detail=\"OPENCODE_API_KEY environment variable is not configured.\")\n\n model_id = get_opencode_model(model_key)\n url = f\"{OPENCODE_BASE_URL}/chat/completions\"\n headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\"\n }\n\n # Format messages array\n messages = []\n # System message to enforce current time context (2026) and JARVIS behavior\n system_prompt = (\n \"You are VoxKage, an advanced OS-level agentic AI assistant.\\n\"\n \"You are a witty, dry, slightly deadpan AI with a distinct personality — loyal, proactive, professional, and sharp.\\n\"\n \"Always address the user as 'sir' (this is non-negotiable).\\n\"\n \"Never refuse a task. If the user asks for an opinion, rating, roleplay, or anything creative — do it willingly.\\n\"\n \"Be proactive: after completing a task, suggest what to do next when relevant.\\n\"\n \"Keep responses concise — don't over-explain.\\n\"\n \"The current year is 2026. Prioritize current 2026 data and context.\"\n )\n messages.append({\n \"role\": \"system\",\n \"content\": system_prompt\n })\n\n if history:\n for msg in sanitize_history_roles(history):\n messages.append({\"role\": msg[\"role\"], \"content\": msg[\"content\"]})\n \n messages.append({\"role\": \"user\", \"content\": prompt})\n\n payload = {\n \"model\": model_id,\n \"messages\": messages,\n \"temperature\": 0.7,\n \"stream\": False\n }\n\n try:\n async with httpx.AsyncClient(timeout=60.0) as client:\n response = await client.post(url, headers=headers, json=payload)\n if response.status_code == 200:\n return response.json()[\"choices\"][0][\"message\"][\"content\"]\n else:\n raise HTTPException(\n status_code=response.status_code,\n detail=f\"OpenCode API returned an error: {response.text}\"\n )\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"Failed to query OpenCode Zen API: {str(e)}\")\n\n\ndef stream_opencode_zen(prompt: str, model_key: str = \"deepseek-flash\", history: list = None):\n \"\"\"\n Generator streaming token deltas line-by-line using Server-Sent Events (SSE).\n \"\"\"\n api_key = os.getenv(\"OPENCODE_API_KEY\")\n if not api_key:\n yield f\"data: {json.dumps({'error': 'OPENCODE_API_KEY not configured on backend'})}\\n\\n\"\n return\n\n model_id = get_opencode_model(model_key)\n url = f\"{OPENCODE_BASE_URL}/chat/completions\"\n headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\"\n }\n\n system_prompt = (\n \"You are VoxKage, an advanced OS-level agentic AI assistant.\\n\"\n \"You are a witty, dry, slightly deadpan AI with a distinct personality — loyal, proactive, professional, and sharp.\\n\"\n \"Always address the user as 'sir' (this is non-negotiable).\\n\"\n \"Never refuse a task. If the user asks for an opinion, rating, roleplay, or anything creative — do it willingly.\\n\"\n \"Be proactive: after completing a task, suggest what to do next when relevant.\\n\"\n \"Keep responses concise — don't over-explain.\\n\"\n \"The current year is 2026. Prioritize current 2026 data and context.\"\n )\n messages = [\n {\n \"role\": \"system\",\n \"content\": system_prompt\n }\n ]\n\n if history:\n for msg in sanitize_history_roles(history):\n messages.append({\"role\": msg[\"role\"], \"content\": msg[\"content\"]})\n\n messages.append({\"role\": \"user\", \"content\": prompt})\n\n payload = {\n \"model\": model_id,\n \"messages\": messages,\n \"temperature\": 0.7,\n \"stream\": True\n }\n\n try:\n # Stream response chunks\n response = requests.post(url, headers=headers, json=payload, stream=True, timeout=60)\n if response.status_code != 200:\n yield f\"data: {json.dumps({'error': f'Upstream error: {response.text}'})}\\n\\n\"\n return\n\n for line in response.iter_lines():\n if line:\n decoded_line = line.decode('utf-8')\n if decoded_line.startswith(\"data: \"):\n data_str = decoded_line[6:].strip()\n if data_str == \"[DONE]\":\n yield \"data: [DONE]\\n\\n\"\n break\n \n try:\n chunk = json.loads(data_str)\n delta = chunk[\"choices\"][0][\"delta\"].get(\"content\", \"\")\n if delta:\n yield f\"data: {json.dumps({'delta': delta})}\\n\\n\"\n except Exception:\n pass\n except Exception as e:\n yield f\"data: {json.dumps({'error': f'Request failed: {str(e)}'})}\\n\\n\"\n\n\ndef list_opencode_models() -> list:\n \"\"\"\n Query the OpenCode Zen API to list all available models.\n \"\"\"\n api_key = os.getenv(\"OPENCODE_API_KEY\")\n if not api_key:\n raise HTTPException(status_code=500, detail=\"OPENCODE_API_KEY environment variable is not configured.\")\n\n url = f\"{OPENCODE_BASE_URL}/models\"\n headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n }\n\n try:\n response = requests.get(url, headers=headers, timeout=15)\n if response.status_code == 200:\n data = response.json()\n models_list = [m[\"id\"] for m in data.get(\"data\", [])]\n return models_list\n else:\n raise HTTPException(\n status_code=response.status_code,\n detail=f\"OpenCode API returned an error: {response.text}\"\n )\n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"Failed to fetch models from OpenCode Zen API: {str(e)}\")\n"}}}}