Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
be01d40
1
Parent(s): 21080cb
backend stabilization
Browse filesFiles changed (16)
- agents/nexus_master.py+14-1
- agents/tools/nexus_tools.py+1
- alembic/versions/04e612a61bf9_add_persona_bifurcation_to_cache.pyAdded+38
- api/v1/messages.py+1
- api/v1/nexus.py+9-2
- api/v1/reports.py+30-9
- api/v1/tickets.py+2
- core/cache.py+10-4
- core/config.py+1-1
- frontend/apps/internal/src/App.tsx+1-1
- frontend/apps/internal/src/components/DashboardOverview.tsx+3-1
- frontend/apps/internal/src/components/KnowledgeBase.module.css+24-1
- frontend/packages/shared/src/hooks/useDashboard.ts+43-11
- models/nexus_semantic_cache.py+6-1
- models/ticket.py+2
- nexus_worker.py+2-2
364 unmodified lines36536636736836937037137237367 unmodified lines441442443444445446364 unmodified linesllm = get_llm().with_structured_output(ResponderOutput)sources = ", ".join(state.get("sources", []))# Build system prompt from Prompt Registry with runtime state variablessystem_prompt = get_prompt("responder").format(user_role=state['user_role'],is_agent=state['is_agent'],sources=sources,ticket_context=state.get('ticket_context', 'No ticket active.')67 unmodified lines# 2. Fire and Forget to Background Workertry:from core.config import get_redis_settingspool = await create_pool(get_redis_settings())await pool.enqueue_job(364 unmodified lines36536636736836937037137237337437537637737837938038138267 unmodified lines450451452453454455456457458459364 unmodified linesllm = get_llm().with_structured_output(ResponderOutput)sources = ", ".join(state.get("sources", []))# Human-readable mapping for UI/Persona consistencyrole_display = {"3sc_admin": "3SC Global Admin","3sc_lead": "3SC Infrastructure Lead","3sc_agent": "3SC Support Agent","customer_admin": "Customer Administrator","customer_user": "Customer User"}.get(state['user_role'], state['user_role'])# Build system prompt from Prompt Registry with runtime state variablessystem_prompt = get_prompt("responder").format(user_role=role_display,is_agent=state['is_agent'],sources=sources,ticket_context=state.get('ticket_context', 'No ticket active.')67 unmodified lines# 2. Fire and Forget to Background Workertry:from core.config import get_redis_settingsfrom arq import create_poolhistory_str = "\n".join([f"{m.type}: {m.content}" for m in pruned_messages])old_summary = state.get("internal_summary", "")pool = await create_pool(get_redis_settings())await pool.enqueue_job(
633 unmodified lines634635636637638639633 unmodified lines# We need to reach the arq_pool. In this tool context, we might lack the request object,# so we fallback to a manual pool creation or fetching from a singleton if available.from core.config import get_redis_settingspool = await create_pool(get_redis_settings())await pool.enqueue_job("generate_global_insight")633 unmodified lines634635636637638639640633 unmodified lines# We need to reach the arq_pool. In this tool context, we might lack the request object,# so we fallback to a manual pool creation or fetching from a singleton if available.from core.config import get_redis_settingsfrom arq import create_poolpool = await create_pool(get_redis_settings())await pool.enqueue_job("generate_global_insight")
1234567891011121314151617181920212223242526272829303132333435363738"""add_persona_bifurcation_to_cache
Revision ID: 04e612a61bf9Revises: 909517d9e971Create Date: 2026-04-08 12:15:32.090455
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = '04e612a61bf9'down_revision: Union[str, None] = '909517d9e971'branch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.add_column('nexus_semantic_cache', sa.Column('user_role', sa.Text(), server_default='customer_user', nullable=False)) op.add_column('nexus_semantic_cache', sa.Column('is_agent', sa.Boolean(), server_default='false', nullable=False)) op.create_index(op.f('ix_nexus_semantic_cache_is_agent'), 'nexus_semantic_cache', ['is_agent'], unique=False) op.create_index(op.f('ix_nexus_semantic_cache_user_role'), 'nexus_semantic_cache', ['user_role'], unique=False) op.create_index('idx_ticket_workspace_created', 'tickets', ['workspace_id', 'created_at'], unique=False) # ### end Alembic commands ###
def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_index('idx_ticket_workspace_created', table_name='tickets') op.drop_index(op.f('ix_nexus_semantic_cache_user_role'), table_name='nexus_semantic_cache') op.drop_index(op.f('ix_nexus_semantic_cache_is_agent'), table_name='nexus_semantic_cache') op.drop_column('nexus_semantic_cache', 'is_agent') op.drop_column('nexus_semantic_cache', 'user_role') # ### end Alembic commands ###130 unmodified lines131132133134135136130 unmodified linesif mentions:try:from core.config import get_redis_settingsredis = await create_pool(get_redis_settings())await redis.enqueue_job("notify_mentions", str(current_user.workspace_id), ticket.title, mentions, ticket_id=str(ticket.id))await redis.close()130 unmodified lines131132133134135136137130 unmodified linesif mentions:try:from core.config import get_redis_settingsfrom arq import create_poolredis = await create_pool(get_redis_settings())await redis.enqueue_job("notify_mentions", str(current_user.workspace_id), ticket.title, mentions, ticket_id=str(ticket.id))await redis.close()
44 unmodified lines4546474849505174 unmodified lines12612712812913013113244 unmodified linesis_agent = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN, UserRole.CUSTOMER_ADMIN]# 0. Semantic Cache Interception (Zero-Latency Bypassing)cache_hit = await SemanticCacheManager.check_cache(str(current_user.workspace_id), payload.query)if cache_hit:return NexusResponse(answer=cache_hit, sources=["Semantic Cache (Bypassed Computation)"])74 unmodified linesworkspace_id=str(current_user.workspace_id),user_id=str(current_user.id),query=payload.query,response_text=sanitized_msg))return NexusResponse(44 unmodified lines45464748495051525354555674 unmodified lines13113213313413513613713813944 unmodified linesis_agent = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN, UserRole.CUSTOMER_ADMIN]# 0. Semantic Cache Interception (Zero-Latency Bypassing)cache_hit = await SemanticCacheManager.check_cache(str(current_user.workspace_id),payload.query,is_agent=is_agent,user_role=current_user.role)if cache_hit:return NexusResponse(answer=cache_hit, sources=["Semantic Cache (Bypassed Computation)"])74 unmodified linesworkspace_id=str(current_user.workspace_id),user_id=str(current_user.id),query=payload.query,response_text=sanitized_msg,is_agent=is_agent,user_role=current_user.role))return NexusResponse(
160 unmodified lines16116216316416516616716816926 unmodified lines196197198199200201202203204205206207208209210211212213214215160 unmodified lines"duration_mins": round((now - t.created_at).total_seconds() / 60, 1)})# 3. Generate Narrativeinsight_text = await generate_service_insights(metrics, ticket_data)return {"insights": insight_text, "generated_at": now.isoformat()}@router.get("/daily-stats/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])async def get_daily_stats(26 unmodified linesresult = await db.execute(stmt)rows = result.all()# Format buckets for the last 30 daysbuckets = []for i in range(30):# bucket_date is i days agobucket_date = (now - timedelta(days=29 - i)).date()# Aggregate categories for this day from rowsday_total = 0categories = {}for row in rows:if row.day == bucket_date:cat = (row.category or "GENERAL").upper()categories[cat] = categories.get(cat, 0) + row.countday_total += row.countbuckets.append({"label": bucket_date.strftime("%m-%d"),160 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318426 unmodified lines211212213214215216217218219220221222223224225226227228229230231232233234235236160 unmodified lines"duration_mins": round((now - t.created_at).total_seconds() / 60, 1)})# --- CACHE CHECK: Prevent redundant LLM calls (15m TTL) ---from core.cache import get_redis_clientimport jsonredis = get_redis_client()cache_key = f"insights:narrative:{target_ws}"cached_val = await redis.get(cache_key)if cached_val:logger.info(f"⚡ Research Cache HIT [Narrative Insights]: {target_ws}")return json.loads(cached_val)# 3. Generate Narrativeinsight_text = await generate_service_insights(metrics, ticket_data)res_data = {"insights": insight_text, "generated_at": now.isoformat()}# Store with 15 minute TTLawait redis.set(cache_key, json.dumps(res_data), ex=900)return res_data@router.get("/daily-stats/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])async def get_daily_stats(26 unmodified linesresult = await db.execute(stmt)rows = result.all()# --- OPTIMIZED ACCUMULATION: O(M) instead of O(N*M) ---# 1. Pre-group rows by date for O(1) lookupfrom collections import defaultdictday_map = defaultdict(list)for row in rows:day_map[row.day].append(row)# 2. Sequential bucket assemblybuckets = []for i in range(30):bucket_date = (now - timedelta(days=29 - i)).date()day_total = 0categories = {}# O(1) Access to hits for this specific dayfor row in day_map.get(bucket_date, []):cat = (row.category or "GENERAL").upper()categories[cat] = categories.get(cat, 0) + row.countday_total += row.countbuckets.append({"label": bucket_date.strftime("%m-%d"),
93 unmodified lines9495969798996 unmodified lines10610710810911011193 unmodified lines# 5. Escalation Lead Lookup (Optimized)setattr(ticket, "escalated_to_name", lead_name)if ticket.is_escalated and not lead_name:from models.user_workspace import UserWorkspacestmt = select(User.full_name).join(UserWorkspace).where(6 unmodified lines# 6. Duplicate Title Lookup (Optimized)setattr(ticket, "duplicate_of_title", dup_title)if ticket.duplicate_of_id and not dup_title:dup_stmt = select(Ticket.title).where(Ticket.id == ticket.duplicate_of_id)dup_res = await db.execute(dup_stmt)93 unmodified lines9495969798991006 unmodified lines10710810911011111211393 unmodified lines# 5. Escalation Lead Lookup (Optimized)setattr(ticket, "escalated_to_name", lead_name)# Only hit DB if not pre-fetched (backward compatibility)if ticket.is_escalated and not lead_name:from models.user_workspace import UserWorkspacestmt = select(User.full_name).join(UserWorkspace).where(6 unmodified lines# 6. Duplicate Title Lookup (Optimized)setattr(ticket, "duplicate_of_title", dup_title)# Only hit DB if not pre-fetchedif ticket.duplicate_of_id and not dup_title:dup_stmt = select(Ticket.title).where(Ticket.id == ticket.duplicate_of_id)dup_res = await db.execute(dup_stmt)
55 unmodified lines5657585960616212 unmodified lines7576777879808118 unmodified lines10010110210310410510611 unmodified lines11811912012112212312455 unmodified lines"""@staticmethodasync def check_cache(workspace_id: str, query: str) -> Optional[str]:from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache12 unmodified linesNexusSemanticCache,NexusSemanticCache.query_embedding.cosine_distance(query_vector).label("distance")).where(NexusSemanticCache.workspace_id == workspace_id).order_by("distance").limit(1))18 unmodified linesreturn None@staticmethodasync def set_cache(workspace_id: str, user_id: str, query: str, response_text: str):from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache11 unmodified linesuser_id=user_id,query_text=query,query_embedding=query_vector,response_text=response_text)db.add(cache_entry)await db.commit()55 unmodified lines5657585960616212 unmodified lines757677787980818283848518 unmodified lines10410510610710810911011 unmodified lines12212312412512612712812913055 unmodified lines"""@staticmethodasync def check_cache(workspace_id: str, query: str, is_agent: bool, user_role: str) -> Optional[str]:from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache12 unmodified linesNexusSemanticCache,NexusSemanticCache.query_embedding.cosine_distance(query_vector).label("distance")).where(NexusSemanticCache.workspace_id == workspace_id,NexusSemanticCache.is_agent == is_agent,NexusSemanticCache.user_role == user_role).order_by("distance").limit(1))18 unmodified linesreturn None@staticmethodasync def set_cache(workspace_id: str, user_id: str, query: str, response_text: str, is_agent: bool, user_role: str):from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache11 unmodified linesuser_id=user_id,query_text=query,query_embedding=query_vector,response_text=response_text,is_agent=is_agent,user_role=user_role)db.add(cache_entry)await db.commit()
12 unmodified lines1314151617181912 unmodified lines"""Application settings from environment variables."""# AppAPP_NAME: str = "Customer Portal"APP_VERSION: str = "1.0.0"DEBUG: bool = FalseAPI_V1_STR: str = "/api/v1"12 unmodified lines1314151617181912 unmodified lines"""Application settings from environment variables."""# AppAPP_NAME: str = "Nexus Master Gateway"APP_VERSION: str = "1.0.0"DEBUG: bool = FalseAPI_V1_STR: str = "/api/v1"
99 unmodified lines10010110210310410510699 unmodified lines};const getPageInfo = () => {const openCount = stats?.by_status?.open || stats?.by_status?.OPEN || 0;const breachCount = stats?.performance?.sla_breached_count || 0;const pages: Record<TabId, { title: string; subtitle: string }> = {99 unmodified lines10010110210310410510699 unmodified lines};const getPageInfo = () => {const openCount = (stats?.by_status?.OPEN || 0) + (stats?.by_status?.ACKNOWLEDGED || 0) + (stats?.by_status?.IN_PROGRESS || 0);const breachCount = stats?.performance?.sla_breached_count || 0;const pages: Record<TabId, { title: string; subtitle: string }> = {
97 unmodified lines989910010110210310497 unmodified lines{isInitialQueueLoading ? (<div className={`${styles.skeleton} ${styles.sValue}`} />) : (<div className={styles.fValue}>{queueTickets.length}</div>)}<div className={styles.fSub}>Open Cases</div></div>97 unmodified lines989910010110210310410510697 unmodified lines{isInitialQueueLoading ? (<div className={`${styles.skeleton} ${styles.sValue}`} />) : (<div className={styles.fValue}>{queueTickets.filter(t => ['OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS'].includes(t.status)).length}</div>)}<div className={styles.fSub}>Open Cases</div></div>
180 unmodified lines181182183184185186329 unmodified lines51651751851952052152283 unmodified lines606607608609610611180 unmodified lines}/* Articles Grid */.articlesGrid {display: grid;grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));329 unmodified lines}/* Empty/Loading */.emptyState { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; background: white; border-radius: 20px; border: 2px dashed #E2E8F0; padding: 100px; text-align: center; }.loadingPulse { width: 40px; height: 40px; background: var(--primary); border-radius: 50%; animation: pulseS 2s infinite; }@keyframes pulseS { 0% { transform: scale(0.9); opacity: 0.6; } 50% { transform: scale(1.1); opacity: 0.2; } 100% { transform: scale(0.9); opacity: 0.6; } }83 unmodified linesdisplay: grid;grid-template-columns: repeat(auto-fill, minmax(450px, 1fr));gap: 32px;}.insightCard {180 unmodified lines181182183184185186187188189190191192329 unmodified lines52252352452552652752852953053153253353453553653753853954083 unmodified lines624625626627628629630631632633634180 unmodified lines}/* Articles Grid */.contentArea {flex: 1;display: flex;flex-direction: column;}.articlesGrid {display: grid;grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));329 unmodified lines}/* Empty/Loading */.emptyState {flex: 1;display: flex;flex-direction: column;align-items: center;justify-content: center;background: white;border-radius: 20px;border: 2px dashed #E2E8F0;padding: 60px;text-align: center;min-height: 500px;}.loadingPulse { width: 40px; height: 40px; background: var(--primary); border-radius: 50%; animation: pulseS 2s infinite; }@keyframes pulseS { 0% { transform: scale(0.9); opacity: 0.6; } 50% { transform: scale(1.1); opacity: 0.2; } 100% { transform: scale(0.9); opacity: 0.6; } }83 unmodified linesdisplay: grid;grid-template-columns: repeat(auto-fill, minmax(450px, 1fr));gap: 32px;flex: 1;}.growthGrid > .emptyState {grid-column: 1 / -1;}.insightCard {
33 unmodified lines343536373839404142434445464748495051525354555657585960616263646566676833 unmodified linescategories: Record<string, number>;}export const useDashboardStats = (workspaceId?: string) => {const [stats, setStats] = useState<DashboardStats | null>(null);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchStats = useCallback(async () => {setLoading(true);try {const url = workspaceId? `dashboard/stats/?workspace_id=${workspaceId}`: 'dashboard/stats/';const response = await api.get(url);setStats(response.data);setError(null);} catch (err: any) {setError(err.response?.data?.detail || 'Failed to fetch dashboard stats');} finally {setLoading(false);}}, [workspaceId]);useEffect(() => {const token = localStorage.getItem('token');if (token) {fetchStats();}}, [fetchStats]);return { stats, loading, error, refresh: fetchStats };};export const useReports = (workspaceId?: string) => {33 unmodified lines34353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910033 unmodified linescategories: Record<string, number>;}// Global singleton state for dashboard stats to ensure UI consistencylet globalStats: DashboardStats | null = null;let globalStatsLoading = false;let globalStatsError: string | null = null;const statsListeners = new Set<(s: DashboardStats | null, l: boolean, e: string | null) => void>();const notifyStats = () => {statsListeners.forEach(l => l(globalStats, globalStatsLoading, globalStatsError));};export const useDashboardStats = (workspaceId?: string) => {const [localStats, setLocalStats] = useState<DashboardStats | null>(globalStats);const [localLoading, setLocalLoading] = useState(globalStatsLoading);const [localError, setLocalError] = useState(globalStatsError);useEffect(() => {const listener = (s: DashboardStats | null, l: boolean, e: string | null) => {setLocalStats(s);setLocalLoading(l);setLocalError(e);};statsListeners.add(listener);return () => {statsListeners.delete(listener);};}, []);const fetchStats = useCallback(async () => {globalStatsLoading = true;notifyStats();try {const url = workspaceId? `dashboard/stats/?workspace_id=${workspaceId}`: 'dashboard/stats/';const response = await api.get(url);globalStats = response.data;globalStatsError = null;} catch (err: any) {globalStatsError = err.response?.data?.detail || 'Failed to fetch dashboard stats';} finally {globalStatsLoading = false;notifyStats();}}, [workspaceId]);useEffect(() => {const token = localStorage.getItem('token');if (token) {// If we already have stats for this workspace, don't re-fetch unless requestedif (!globalStats || globalStats.workspace_id !== workspaceId) {fetchStats();}}}, [fetchStats, workspaceId]);return {stats: localStats,loading: localLoading,error: localError,refresh: fetchStats};};export const useReports = (workspaceId?: string) => {
12347 unmodified lines121314151617from sqlalchemy import Column, Integer, Text, ForeignKey, DateTimefrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.sql import funcfrom pgvector.sqlalchemy import Vector7 unmodified linesworkspace_id = Column(UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), nullable=False, index=True)user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)query_text = Column(Text, nullable=False)query_embedding = Column(Vector(768), nullable=False)12347 unmodified lines1213141516171819202122from sqlalchemy import Column, Integer, Text, ForeignKey, DateTime, Booleanfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.sql import funcfrom pgvector.sqlalchemy import Vector7 unmodified linesworkspace_id = Column(UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), nullable=False, index=True)user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)# --- Persona Bifurcation Columns ---user_role = Column(Text, nullable=False, index=True, server_default='customer_user')is_agent = Column(Boolean, nullable=False, index=True, server_default='false')# -----------------------------------query_text = Column(Text, nullable=False)query_embedding = Column(Vector(768), nullable=False)
80 unmodified lines81828384858680 unmodified linespostgresql_with={'m': 16, 'ef_construction': 64},postgresql_ops={'embedding': 'vector_cosine_ops'}),)# Resolution Metadata80 unmodified lines818283848586878880 unmodified linespostgresql_with={'m': 16, 'ef_construction': 64},postgresql_ops={'embedding': 'vector_cosine_ops'}),# Optimizes range/reporting queries: select ... where workspace_id=X and created_at > YIndex('idx_ticket_workspace_created', "workspace_id", "created_at"),)# Resolution Metadata
67 unmodified lines686970717273743 unmodified lines7879808182838467 unmodified lines# Concurrency / Performancemax_jobs = 10job_timeout = 600 # 10 minutes max for complex AI taskspoll_delay = 30 # RE-OPTIMIZED: Reduced to 5s to prevent idle timeouts while maintaining balancekeep_result = 600 # Clear job results from Redis after 10 minutes# Retry Policy - Durable Backoff for AI/LLM 429 Errors3 unmodified lines# Periodic tasks (SLA Monitoring & Heartbeat)# Optimized for low-cost cloud Rediscron_jobs = [cron(monitor_sla_thresholds, minute={0, 30}), # Every 30 minutescron(record_system_heartbeat, hour={0, 12}, minute=0), # Twice a daycron(generate_global_insight, hour=3, minute=0), # Once a day at 3 AMcron(nexus_pulse_check, minute=set(range(0, 60, 15))) # Every 15 minutes67 unmodified lines686970717273743 unmodified lines7879808182838467 unmodified lines# Concurrency / Performancemax_jobs = 10job_timeout = 600 # 10 minutes max for complex AI taskspoll_delay = 30 # TUNED: Reduced to 5s for near real-time AI responsivenesskeep_result = 600 # Clear job results from Redis after 10 minutes# Retry Policy - Durable Backoff for AI/LLM 429 Errors3 unmodified lines# Periodic tasks (SLA Monitoring & Heartbeat)# Optimized for low-cost cloud Rediscron_jobs = [cron(monitor_sla_thresholds, minute={0, 20, 40}), # Every 10 minutes (Improved resolution)cron(record_system_heartbeat, hour={0, 12}, minute=0), # Twice a daycron(generate_global_insight, hour=3, minute=0), # Once a day at 3 AMcron(nexus_pulse_check, minute=set(range(0, 60, 15))) # Every 15 minutes
agents/nexus_master.py+14-1
agents/tools/nexus_tools.py+1
alembic/versions/04e612a61bf9_add_persona_bifurcation_to_cache.pyAdded+38
api/v1/messages.py+1
api/v1/nexus.py+9-2
api/v1/reports.py+30-9
api/v1/tickets.py+2
core/cache.py+10-4
core/config.py+1-1
frontend/apps/internal/src/App.tsx+1-1
frontend/apps/internal/src/components/DashboardOverview.tsx+3-1
frontend/apps/internal/src/components/KnowledgeBase.module.css+24-1
frontend/packages/shared/src/hooks/useDashboard.ts+43-11
models/nexus_semantic_cache.py+6-1
models/ticket.py+2
nexus_worker.py+2-2