"""Hermes HF Space — FastAPI sub-agent with Groq API.""" import os, time, hashlib, json from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse import httpx app = FastAPI(title="Hermes Sub-Agent", version="2.2.0-hf") GROQ_KEY = os.environ.get("GROQ_KEY", "") AGENT_SECRET = os.environ.get("AGENT_SECRET", "hermes-nexus-secret-2026") @app.get("/health") def health(): return {"status": "ok", "backend": "hf-space-docker", "groq_ready": bool(GROQ_KEY)} @app.post("/task") async def handle_task(request: Request): secret = request.headers.get("x-agent-secret", "") if AGENT_SECRET and secret != AGENT_SECRET: raise HTTPException(401) try: body = await request.json() t0 = time.perf_counter() if body.get("task_type") == "llm": prompt = body.get("payload", {}).get("prompt", "") mx = body.get("max_tokens", 256) if not GROQ_KEY: return JSONResponse({"error":"GROQ_KEY not set"}, 500) async with httpx.AsyncClient(timeout=30) as c: r = await c.post("https://api.groq.com/openai/v1/chat/completions", headers={"Authorization":f"Bearer {GROQ_KEY}","Content-Type":"application/json"}, json={"model":"llama-3.1-8b-instant","messages":[{"role":"user","content":prompt}],"max_tokens":mx}) r.raise_for_status() d = r.json() result = d["choices"][0]["message"]["content"] return JSONResponse({"task_id":body.get("task_id"),"result":result,"model_used":"hf-space:groq-llama3","cached":False,"latency_ms":int((time.perf_counter()-t0)*1000)}) raise HTTPException(400) except Exception as e: return JSONResponse({"error":str(e)}, 500) @app.post("/v1/chat/completions") async def openai_chat(request: Request): try: body = await request.json() prompt = body.get("messages",[{}])[-1].get("content","") mx = body.get("max_tokens", 256) if not GROQ_KEY: return JSONResponse({"error":"GROQ_KEY not set"}, 500) async with httpx.AsyncClient(timeout=30) as c: r = await c.post("https://api.groq.com/openai/v1/chat/completions", headers={"Authorization":f"Bearer {GROQ_KEY}","Content-Type":"application/json"}, json={"model":"llama-3.1-8b-instant","messages":[{"role":"user","content":prompt}],"max_tokens":mx}) r.raise_for_status() d = r.json() result = d["choices"][0]["message"]["content"] return {"id":f"hf-{hashlib.md5(prompt.encode()).hexdigest()[:8]}","object":"chat.completion","choices":[{"message":{"role":"assistant","content":result}}],"model":"hf-space-groq"} except Exception as e: return JSONResponse({"error":str(e)}, 500)