God Mode+ v3 fix: api/routes/chat.py
Browse files123456 unmodified lines1213141516176 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341 unmodified line1361371381391401411421431441451461471481493 unmodified lines1531541551561571581597 unmodified lines167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""Chat + Goal API Routes β Real-time streaming responses"""import asyncio6 unmodified linesfrom core.models import ChatRequest, GoalRequest, TaskCreateRequestfrom memory.db import save_memory, get_historyrouter = APIRouter()6 unmodified linesreturn request.app.state.ws_manager# βββ Chat (REST + SSE streaming) βββββββββββββββββββββββββββββββββββββββββββββββ@router.post("/chat", summary="Chat with the agent")async def chat(req: ChatRequest, request: Request):from core.agent import AgentCorews = get_ws(request)agent = AgentCore(ws)messages = [{"role": m.role, "content": m.content} for m in req.messages]if req.stream:async def stream_gen():async def _run():result = await agent.llm_stream(messages=messages,session_id=req.session_id,model=req.model,temperature=req.temperature,max_tokens=req.max_tokens,)await save_memory(content=result,memory_type="conversation",session_id=req.session_id,project_id=req.project_id,key="assistant",)# Save user message toouser_msg = next((m["content"] for m in reversed(messages) if m["role"] == "user"), "")await save_memory(content=user_msg,memory_type="conversation",session_id=req.session_id,project_id=req.project_id,key="user",)return resultroom_buffer = []original_emit_chat = ws.emit_chatasync def capture_emit(sid, etype, data):if etype == "llm_chunk":chunk = data.get("chunk", "")room_buffer.append(chunk)yield_data = json.dumps({"type": etype, "data": data, "session_id": sid})return yield_datareturn None# Stream tokens directlyfull = ""from core.agent import AgentCore as _Aimport httpximport osOPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")if OPENAI_API_KEY:headers = {"Authorization": f"Bearer {OPENAI_API_KEY}","Content-Type": "application/json",}payload = {"model": req.model,"messages": messages,"stream": True,"temperature": req.temperature,"max_tokens": req.max_tokens,}from core.agent import OPENAI_BASE_URL# Ensure base URL ends with /v1/chat/completions correctlyurl = f"{OPENAI_BASE_URL}/chat/completions"if "/v1/v1" in url: # Fix potential double /v1url = url.replace("/v1/v1", "/v1")async with httpx.AsyncClient(timeout=120) as client:async with client.stream("POST", url,headers=headers, json=payload) as resp:async for line in resp.aiter_lines():if not line.startswith("data:"):continuechunk_str = line[6:].strip()if chunk_str == "[DONE]":breaktry:data = json.loads(chunk_str)delta = data["choices"][0]["delta"].get("content", "")if delta:full += deltayield f"data: {json.dumps({'type': 'llm_chunk', 'data': {'chunk': delta}, 'session_id': req.session_id})}\n\n"except Exception:passelse:# Demo streamingdemo = (f"Hello! I'm your Devin-style AI Agent. I received: '{req.messages[-1].content[:80]}'. "f"Set OPENAI_API_KEY or ANTHROPIC_API_KEY for real AI responses. "f"I support real-time streaming, task planning, GitHub automation, and more!")for word in demo.split():chunk = word + " "full += chunkawait asyncio.sleep(0.04)yield f"data: {json.dumps({'type': 'llm_chunk', 'data': {'chunk': chunk}, 'session_id': req.session_id})}\n\n"yield f"data: {json.dumps({'type': 'stream_end', 'data': {'full_response': full}, 'session_id': req.session_id})}\n\n"return StreamingResponse(stream_gen(),1 unmodified lineheaders={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},)else:# Non-streamingagent = AgentCore(get_ws(request))result = await agent.llm_stream(messages, session_id=req.session_id)return {"response": result,"session_id": req.session_id,"model": req.model,"timestamp": time.time(),}3 unmodified linesreturn await chat(req, request)# βββ Goal API (create task from goal) βββββββββββββββββββββββββββββββββββββββββ@router.post("/goal", summary="Submit a high-level goal to the agent")async def submit_goal(req: GoalRequest, request: Request):7 unmodified lines)task_id = await engine.submit(task_req)return {"task_id": task_id,"goal": req.goal,"status": "queued","session_id": req.session_id,"ws_url": f"/ws/tasks/{task_id}","stream_url": f"/api/v1/tasks/{task_id}/stream",}@router.post("/goal/stream", summary="Submit goal with SSE streaming response")async def submit_goal_stream(req: GoalRequest, request: Request):req.stream = Truereturn await submit_goal(req, request)# βββ Execute (direct tool execution) ββββββββββββββββββββββββββββββββββββββββββ@router.post("/execute", summary="Execute a tool directly")async def execute(tool: str,task: str,request: Request,session_id: str = "",):from tools.executor import ToolExecutorws = get_ws(request)executor = ToolExecutor(ws)result = await executor.run(tool=tool,task=task,session_id=session_id,)return {"tool": tool, "task": task, "result": result, "session_id": session_id}# βββ Plan (generate plan without executing) βββββββββββββββββββββββββββββββββββ@router.post("/plan", summary="Generate execution plan for a goal")async def generate_plan(req: GoalRequest, request: Request):from core.agent import AgentCorews = get_ws(request)agent = AgentCore(ws)task_id = f"plan_{uuid.uuid4().hex[:8]}"plan = await agent.plan(goal=req.goal, task_id=task_id, session_id=req.session_id)return {"goal": req.goal,"plan": plan.model_dump(),"session_id": req.session_id,"task_id": task_id,}1234566 unmodified lines131415161718196 unmodified lines26272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111 unmodified line1131141151161171181191201211221231241251263 unmodified lines1301311321331341351367 unmodified lines144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""Chat + Goal API Routes β Real-time streaming via LLMRouter (Cloudflare Gateway primary)ALL LLM calls go through LLMRouter β no direct OpenAI calls"""import asyncio6 unmodified linesfrom core.models import ChatRequest, GoalRequest, TaskCreateRequestfrom memory.db import save_memory, get_historyfrom ai_router.router import LLMRouterrouter = APIRouter()6 unmodified linesreturn request.app.state.ws_managerdef get_router(request: Request) -> LLMRouter:return request.app.state.ai_router# βββ Chat (REST + SSE streaming) ββββββββββββββββββββββββββββββββββββββββββββββ@router.post("/chat", summary="Chat with the God Agent")async def chat(req: ChatRequest, request: Request):ws = get_ws(request)llm = get_router(request)messages = [{"role": m.role, "content": m.content} for m in req.messages]# Add system promptif not any(m["role"] == "system" for m in messages):messages.insert(0, {"role": "system","content": ("You are God Mode+ AI β an elite autonomous AI software engineer. ""You can plan, code, debug, refactor, test, and deploy software autonomously. ""Respond helpfully, concisely, and accurately.")})if req.stream:async def stream_gen():full = ""session_id = req.session_id# Buffer chunks for SSEchunks = []original_emit_chat = ws.emit_chatasync def capture_emit(sid, etype, data):if etype == "llm_chunk" and sid == session_id:chunk = data.get("chunk", "")if chunk:chunks.append(chunk)ws.emit_chat = capture_emit # type: ignore# Run in background, yield as SSEasync def run_llm():nonlocal fullfull = await llm.ask(messages=messages,session_id=session_id,model=req.model,temperature=req.temperature,max_tokens=req.max_tokens,stream=True,)llm_task = asyncio.create_task(run_llm())# Yield chunks as they arrivesent = 0while not llm_task.done():await asyncio.sleep(0.02)while sent < len(chunks):c = chunks[sent]sent += 1yield f"data: {json.dumps({'type': 'llm_chunk', 'data': {'chunk': c}, 'session_id': session_id})}\n\n"# Flush remainingawait llm_taskws.emit_chat = original_emit_chat # type: ignorewhile sent < len(chunks):c = chunks[sent]sent += 1yield f"data: {json.dumps({'type': 'llm_chunk', 'data': {'chunk': c}, 'session_id': session_id})}\n\n"# Save to memoryuser_msg = next((m["content"] for m in reversed(messages) if m["role"] == "user"), "")await save_memory(content=user_msg, memory_type="conversation",session_id=session_id, key="user")await save_memory(content=full, memory_type="conversation",session_id=session_id, key="assistant")yield f"data: {json.dumps({'type': 'stream_end', 'data': {'full_response': full}, 'session_id': session_id})}\n\n"return StreamingResponse(stream_gen(),1 unmodified lineheaders={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},)else:llm = get_router(request)result = await llm.ask(messages, session_id=req.session_id,model=req.model, stream=False)return {"response": result,"session_id": req.session_id,"model": req.model,"timestamp": time.time(),}3 unmodified linesreturn await chat(req, request)# βββ Goal API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@router.post("/goal", summary="Submit a high-level goal to the agent")async def submit_goal(req: GoalRequest, request: Request):7 unmodified lines)task_id = await engine.submit(task_req)return {"task_id": task_id,"goal": req.goal,"status": "queued","session_id": req.session_id,"ws_url": f"/ws/tasks/{task_id}","stream_url": f"/api/v1/tasks/{task_id}/stream",}@router.post("/goal/stream", summary="Submit goal with SSE streaming")async def submit_goal_stream(req: GoalRequest, request: Request):req.stream = Truereturn await submit_goal(req, request)# βββ Execute (direct tool execution) βββββββββββββββββββββββββββββββββββββββββ@router.post("/execute", summary="Execute a tool directly")async def execute(tool: str, task: str, request: Request, session_id: str = ""):from tools.executor import ToolExecutorws = get_ws(request)executor = ToolExecutor(ws)result = await executor.run(tool=tool, task=task, session_id=session_id)return {"tool": tool, "task": task, "result": result, "session_id": session_id}# βββ Plan (generate plan without executing) ββββββββββββββββββββββββββββββββββ@router.post("/plan", summary="Generate execution plan for a goal")async def generate_plan(req: GoalRequest, request: Request):from core.agent import AgentCorews = get_ws(request)agent = AgentCore(ws)task_id = f"plan_{uuid.uuid4().hex[:8]}"plan = await agent.plan(goal=req.goal, task_id=task_id, session_id=req.session_id)return {"goal": req.goal,"plan": plan.model_dump(),"session_id": req.session_id,"task_id": task_id,}
api/routes/chat.py+92-124