Spaces:
Paused

nexus / api /v1 /nexus.py
dushyantsingh0
backend stabilization
ca7df66
Raw History Blame Contribute Delete
8.71 kB
from typing import Any, List, Dict, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from langchain_core.messages import HumanMessage, AIMessage
from core.deps import get_db, get_current_user
from models.user import User, UserRole
from agents.nexus_master import create_nexus_graph
from agents.nexus_customer import create_customer_graph
from models.nexus_interaction import NexusInteraction
from schemas.ai import NexusHistoryForensicResponse, AINodeInteraction, NexusInteractionResponse
from core.permissions import require_roles, ALL_SC_ROLES, WORKSPACE_ADMIN_ROLES
from core.cache import SemanticCacheManager
from sqlalchemy import select, desc
router = APIRouter()
class NexusQueryRequest(BaseModel):
query: str
chat_history: List[Dict[str, str]] = [] # [{"role": "user", "content": "..."}, ...]
thread_id: Optional[UUID] = None
workspace_id: Optional[UUID] = None
ticket_id: Optional[UUID] = None
action_approved: bool = False
class NexusResponse(BaseModel):
answer: str
sources: List[str] = []
@router.post("/query/", response_model=NexusResponse)
async def query_nexus_master(
payload: NexusQueryRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> Any:
"""
Unified entry point for natural language workspace interaction.
Orchestrates KB search, ticket management, and analytics with full RBAC isolation.
"""
from sqlalchemy import select
from models.nexus_interaction import NexusInteraction
# 1. Prepare Initial State & Identity Bifurcation
# Strictly isolate Staff (Master Agent) from Customers (Customer Agent)
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:
# Security Verification: Ensure user has access to the requested workspace
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}"
)
# Override role based on context (Crucial for 3SC Staff acting in Customer Workspaces)
target_role = active_link.role
# 0. Semantic Cache Interception (Zero-Latency Bypassing)
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) # Include user_id for strict identity isolation
)
if cache_hit:
return NexusResponse(answer=cache_hit, sources=["Semantic Cache (Bypassed Computation)"])
# Validation: If ticket_id provided, it MUST exist in this targeted workspace
if payload.ticket_id:
from models.ticket import Ticket
from sqlalchemy import select
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")
# 2. Fetch Long-Term Memory (Internal Summary) if thread exists
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 {}
}
# 2. Invoke the Correct Persona Graph
app = create_nexus_graph() if is_agent else create_customer_graph()
config = {"configurable": {"thread_id": str(payload.thread_id or "default_nexus_thread")}}
try:
final_state = await app.ainvoke(initial_state, config=config)
# 3. Extract final response
final_msg = final_state["messages"][-1].content
sources = final_state.get("sources", [])
# Sanitize response: Remove internal diagnostic markers or raw system paths
sanitized_msg = final_msg.replace("[INTERNAL_DIAGNOSTIC]", "").strip()
# 4. Fire-and-forget Cache Population
import asyncio
asyncio.create_task(SemanticCacheManager.set_cache(
workspace_id=str(target_workspace_id),
user_id=str(current_user.id),
query=payload.query,
response_text=sanitized_msg,
is_agent=is_agent,
user_role=str(target_role)
))
return NexusResponse(
answer=sanitized_msg,
sources=sources
)
except Exception as e:
import logging
logger = logging.getLogger(__name__)
logger.exception(f"Nexus Master Failure: {str(e)}")
# NEVER leak raw traceback or internal DB error to final output
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Nexus Master encountered an unexpected internal error. Please contact 3SC Support."
)
@router.get("/history/", response_model=NexusHistoryForensicResponse, dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def get_nexus_history(
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user)
) -> Any:
"""
Retrieve the last 50 Master Agent interactions for the current workspace.
"""
stmt = (
select(NexusInteraction)
.where(
NexusInteraction.workspace_id == current_user.workspace_id
)
.order_by(desc(NexusInteraction.created_at))
.limit(50)
)
result = await db.execute(stmt)
interactions = result.scalars().all()
return {
"interactions": interactions,
"count": len(interactions)
}
@router.get("/thread/{thread_id}/", response_model=List[NexusInteractionResponse], dependencies=[Depends(require_roles(ALL_SC_ROLES))])
async def get_nexus_thread_audit(
thread_id: UUID,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user)
) -> Any:
"""
Retrieve the full forensic audit trail for a specific conversational thread.
"""
stmt = (
select(NexusInteraction)
.where(
NexusInteraction.thread_id == thread_id,
NexusInteraction.workspace_id == current_user.workspace_id
)
.order_by(NexusInteraction.created_at.asc())
)
result = await db.execute(stmt)
interactions = result.scalars().all()
if not interactions:
raise HTTPException(status_code=404, detail="Thread not found or access denied")
return interactions