from fastapi import APIRouter, Depends, HTTPException, status from fastapi.responses import StreamingResponse from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from typing import Any from uuid import UUID import json import asyncio from core.deps import get_db, get_current_user from models.user import User, UserRole from models.ticket import Ticket from models.nexus_interaction import NexusInteraction from agents.nexus_master import create_nexus_graph from agents.nexus_customer import create_customer_graph from api.v1.nexus import NexusQueryRequest from langchain_core.messages import HumanMessage, AIMessage router = APIRouter() async def nexus_event_generator(app, initial_state, config): """ Generator function that runs the LangGraph astream_events and yields Server-Sent Events (SSE) formatting for the frontend. """ accumulated_tokens = [] try: # astream_events version="v2" gives us fine-grained access to LangChain events async for event in app.astream_events(initial_state, config=config, version="v2"): event_type = event["event"] node_name = event.get("name", "") # 1. Stream tool invocations boundaries if event_type == "on_tool_start": yield f"data: {json.dumps({'type': 'tool_start', 'tool': node_name, 'input': event['data'].get('input')})}\n\n" elif event_type == "on_tool_end": yield f"data: {json.dumps({'type': 'tool_end', 'tool': node_name})}\n\n" # 2. Stream tokens from the responder LLM elif event_type == "on_chat_model_stream": # Only stream tokens from the 'responder' node to avoid internal router/chain output metadata = event.get("metadata", {}) node = metadata.get("langgraph_node", "") # OPTIMIZATION: Also stream from 'router' if it's producing a direct response if node in ["responder", "router"]: chunk = event["data"]["chunk"].content if chunk: accumulated_tokens.append(chunk) yield f"data: {json.dumps({'type': 'token', 'content': chunk})}\n\n" # 3. Stream graph milestones (e.g., node transitions) elif event_type == "on_chain_start": # When a subgraph or specific node starts if node_name in ["router", "pre_processor", "gatekeeper", "executor", "approval"]: display_names = { "pre_processor": "Syncing context", "gatekeeper": "Checking quick-path", "router": "Orchestrating tools", "executor": "Executing actions", "approval": "Awaiting approval" } msg = display_names.get(node_name, f"Running {node_name}") yield f"data: {json.dumps({'type': 'status', 'message': f'{msg}...'})}\n\n" # 4. Handle direct messages from non-streaming nodes (like Gatekeeper) elif event_type == "on_chain_end" and node_name in ["gatekeeper", "router"]: # If these nodes produced a final message without streaming (e.g. Gatekeeper templates) output = event.get("data", {}).get("output", {}) if isinstance(output, dict) and "messages" in output: msgs = output["messages"] if msgs and hasattr(msgs[-1], "content"): content = msgs[-1].content # If we haven't already streamed this content (to avoid duplication) if content and content not in "".join(accumulated_tokens): accumulated_tokens.append(content) yield f"data: {json.dumps({'type': 'token', 'content': content})}\n\n" # Signal completion yield f"data: {json.dumps({'type': 'done'})}\n\n" # Asynchronous Cache Population after stream concludes final_text = "".join(accumulated_tokens) if final_text: from core.cache import SemanticCacheManager asyncio.create_task(SemanticCacheManager.set_cache( workspace_id=str(initial_state["workspace_id"]), user_id=str(initial_state["user_id"]), query=initial_state["messages"][-1].content, response_text=final_text, is_agent=initial_state["is_agent"], user_role=initial_state["user_role"] )) except Exception as e: # Yield error to frontend before closing stream yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n" @router.post("/stream/") async def stream_nexus_master( payload: NexusQueryRequest, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): """ Streaming entry point for natural language workspace interaction. Delivers token-by-token responses and live tool updates via SSE. """ # 1. Prepare Initial State & Identity Bifurcation is_agent = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN] # Contextual Workspace & Role Override target_workspace_id = payload.workspace_id or current_user.workspace_id target_role = current_user.role if payload.workspace_id: from models.user_workspace import UserWorkspace ws_stmt = select(UserWorkspace).where( UserWorkspace.user_id == current_user.id, UserWorkspace.workspace_id == payload.workspace_id ) ws_res = await db.execute(ws_stmt) active_link = ws_res.scalar_one_or_none() if not active_link: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Access Denied: You are not a member of workspace {payload.workspace_id}" ) target_role = active_link.role # 0. Semantic Cache Interception (Zero-Latency SSE Masking) from core.cache import SemanticCacheManager cache_hit = await SemanticCacheManager.check_cache( workspace_id=str(target_workspace_id), query=payload.query, is_agent=is_agent, user_role=str(target_role), user_id=str(current_user.id) ) if cache_hit: async def cached_event_generator(): yield f"data: {json.dumps({'type': 'status', 'message': 'Semantic Cache Hit! Bypassing LLM...'})}\n\n" yield f"data: {json.dumps({'type': 'token', 'content': cache_hit})}\n\n" yield f"data: {json.dumps({'type': 'done'})}\n\n" return StreamingResponse(cached_event_generator(), media_type="text/event-stream") if payload.ticket_id: from models.ticket import Ticket stmt = select(Ticket).where(Ticket.id == payload.ticket_id, Ticket.workspace_id == target_workspace_id) res = await db.execute(stmt) if not res.scalar_one_or_none(): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Invalid ticket_id: {payload.ticket_id} for this workspace." ) messages = [] for m in payload.chat_history: if m["role"] == "user": messages.append(HumanMessage(content=m["content"])) else: messages.append(AIMessage(content=m["content"])) messages.append(HumanMessage(content=payload.query)) thread_id = payload.thread_id or UUID("00000000-0000-0000-0000-000000000001") # Fetch Long-Term Memory internal_summary = "" last_interaction_stmt = ( select(NexusInteraction) .where(NexusInteraction.thread_id == thread_id) .order_by(NexusInteraction.created_at.desc()) .limit(1) ) last_interaction_res = await db.execute(last_interaction_stmt) last_interaction = last_interaction_res.scalar_one_or_none() if last_interaction and last_interaction.metadata_json: internal_summary = last_interaction.metadata_json.get("internal_summary", "") initial_state = { "messages": messages, "workspace_id": target_workspace_id, "user_role": str(target_role), "is_agent": is_agent, "user_name": current_user.full_name, "user_id": current_user.id, "sources": [], "current_tool_output": None, "pending_actions": [], "action_approved": payload.action_approved or False, "vision_context": [], "ticket_id": payload.ticket_id, "thread_id": thread_id, "target_user_id": None, "target_status": None, "internal_summary": internal_summary, "ticket_context": "", "ai_gist": current_user.ai_gist or {} } app = create_nexus_graph() if is_agent else create_customer_graph() config = {"configurable": {"thread_id": str(payload.thread_id or "default_nexus_thread")}} # Return Streaming Response with media_type text/event-stream for SSE return StreamingResponse( nexus_event_generator(app, initial_state, config), media_type="text/event-stream" )