Spaces:
Paused

File size: 9,386 Bytes
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428a35c
ad4fe35
 
 
 
 
428a35c
 
 
 
b7980f7
 
 
 
ad4fe35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
ca7df66
 
 
b7980f7
 
 
 
 
 
e58f87e
b7980f7
 
 
 
 
 
 
 
 
ca7df66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
ca7df66
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
ca7df66
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca7df66
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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"
    )