Spaces:
Paused
Paused
Download agents/utils.py from 3SCError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 9.03 kB
-
https://huggingface.co/spaces/3SCError404/nexus/resolve/main/agents/utils.py
- Command line
-
hf download hf://spaces/3SCError404/nexus/agents/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/3SCError404/nexus/resolve/main/agents/utils.py
9.03 kB
| from typing import Any, Dict, List, Optional | |
| import uuid | |
| from uuid import UUID | |
| from datetime import datetime | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select, func, desc | |
| from core.logging import get_logger | |
| from models.user import User, UserRole | |
| from models.user_workspace import UserWorkspace | |
| from models.kb_article import KBArticle | |
| from models.kb_article_chunk import KBArticleChunk | |
| logger = get_logger(__name__) | |
| async def get_available_agents(db: AsyncSession, workspace_id: UUID) -> List[User]: | |
| """ | |
| Fetch all active INTERNAL staff members for the given workspace context. | |
| Strictly restricted to users with a direct UserWorkspace relationship. | |
| """ | |
| # 1. Standard approach: Join with UserWorkspace and strictly whitelist staff roles | |
| stmt = select(User).join(UserWorkspace).where( | |
| UserWorkspace.workspace_id == workspace_id, | |
| UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), # INTERNAL ONLY | |
| User.is_active == True, | |
| User.deleted_at.is_(None) | |
| ) | |
| result = await db.execute(stmt) | |
| verified_staff = list(result.scalars().all()) | |
| logger.debug(f"Fetched {len(verified_staff)} verified staff agents for workspace {workspace_id}") | |
| return verified_staff | |
| async def update_ticket_ai_metadata(db: AsyncSession, ticket_id: UUID, metadata: Dict[str, Any]): | |
| """ | |
| Utility to update ticket AI metadata in the DB. | |
| """ | |
| from models.ticket import Ticket | |
| stmt = select(Ticket).where(Ticket.id == ticket_id) | |
| result = await db.execute(stmt) | |
| ticket = result.scalar_one_or_none() | |
| if ticket: | |
| # Merge new metadata | |
| existing = ticket.ai_metadata or {} | |
| existing.update(metadata) | |
| ticket.ai_metadata = existing | |
| db.add(ticket) | |
| async def semantic_search_kb(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]: | |
| """ | |
| Search KBArticles by embedding. | |
| """ | |
| from models.kb_article import KBArticle | |
| stmt = select(KBArticle).where( | |
| KBArticle.workspace_id == workspace_id, | |
| KBArticle.deleted_at.is_(None), | |
| KBArticle.duplicate_of_id.is_(None) | |
| ).order_by( | |
| KBArticle.embedding.cosine_distance(query_embedding) | |
| ).limit(limit) | |
| logger.info(f"AI: Semantic search KB for workspace {workspace_id}") | |
| result = await db.execute(stmt) | |
| return list(result.scalars().all()) | |
| async def semantic_search_past_tickets(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]: | |
| """ | |
| Search resolved Tickets by embedding. | |
| """ | |
| from models.ticket import Ticket, TicketStatus | |
| stmt = select(Ticket).where( | |
| Ticket.workspace_id == workspace_id, | |
| Ticket.status == TicketStatus.RESOLVED, | |
| Ticket.embedding.isnot(None), | |
| Ticket.deleted_at.is_(None) | |
| ).order_by( | |
| Ticket.embedding.cosine_distance(query_embedding) | |
| ).limit(limit) | |
| logger.info(f"AI: Semantic search past tickets for workspace {workspace_id}") | |
| result = await db.execute(stmt) | |
| return list(result.scalars().all()) | |
| async def hybrid_search_kb_internal( | |
| db: AsyncSession, | |
| workspace_id: UUID, | |
| query_text: str, | |
| query_embedding: List[float], | |
| threshold: float = 0.2, | |
| limit: int = 5 | |
| ) -> List[Dict[str, Any]]: | |
| """ | |
| Internal utility for hybrid search (FTS + Vector) to be used by AI nodes. | |
| Returns a list of dictionaries containing the article object and its hybrid score. | |
| """ | |
| # 1. Semantic Chunk Search | |
| semantic_stmt = ( | |
| select( | |
| KBArticle, | |
| (1 - KBArticleChunk.embedding.cosine_distance(query_embedding)).label("sim_score") | |
| ) | |
| .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id) | |
| .where( | |
| KBArticle.workspace_id == workspace_id, | |
| KBArticle.deleted_at.is_(None), | |
| KBArticle.is_published == True, | |
| KBArticle.duplicate_of_id.is_(None) | |
| ) | |
| .order_by(desc("sim_score")) | |
| .limit(20) | |
| ) | |
| semantic_res = await db.execute(semantic_stmt) | |
| # 2. Keyword FTS Search | |
| fts_stmt = ( | |
| select( | |
| KBArticle, | |
| func.ts_rank( | |
| func.to_tsvector('english', KBArticle.title + " " + KBArticle.content), | |
| func.plainto_tsquery('english', query_text) | |
| ).label("fts_rank") | |
| ) | |
| .where( | |
| KBArticle.workspace_id == workspace_id, | |
| KBArticle.deleted_at.is_(None), | |
| KBArticle.is_published == True, | |
| KBArticle.duplicate_of_id.is_(None), | |
| func.to_tsvector('english', KBArticle.title + " " + KBArticle.content).op("@@")(func.plainto_tsquery('english', query_text)) | |
| ) | |
| .order_by(desc("fts_rank")) | |
| .limit(20) | |
| ) | |
| fts_res = await db.execute(fts_stmt) | |
| # 3. Score Fusion | |
| article_scores = {} | |
| for article, sim in semantic_res.all(): | |
| if article.id not in article_scores: | |
| article_scores[article.id] = {"obj": article, "semantic": sim, "fts": 0.0} | |
| else: | |
| article_scores[article.id]["semantic"] = max(article_scores[article.id]["semantic"], sim) | |
| for article, rank in fts_res.all(): | |
| if article.id not in article_scores: | |
| article_scores[article.id] = {"obj": article, "semantic": 0.0, "fts": rank} | |
| else: | |
| article_scores[article.id]["fts"] = rank | |
| final_results = [] | |
| for art_id, data in article_scores.items(): | |
| score = (data["semantic"] * 0.7) + (min(data["fts"], 1.0) * 0.3) | |
| if score >= threshold: | |
| final_results.append({"article": data["obj"], "score": score}) | |
| final_results.sort(key=lambda x: x["score"], reverse=True) | |
| return final_results[:limit] | |
| async def get_workspace_manager(db: AsyncSession, workspace_id: UUID) -> Optional[User]: | |
| """Find the best person to notify in a workspace (Lead first, then Admin).""" | |
| # 1. Try to find a Lead within this workspace | |
| stmt = ( | |
| select(User) | |
| .join(UserWorkspace) | |
| .where( | |
| UserWorkspace.workspace_id == workspace_id, | |
| UserWorkspace.role == UserRole.SC_LEAD, | |
| User.is_active == True, | |
| User.deleted_at.is_(None) | |
| ) | |
| .limit(1) | |
| ) | |
| res = await db.execute(stmt) | |
| manager = res.scalar_one_or_none() | |
| if manager: | |
| return manager | |
| # 2. Fallback to an Admin associated with this workspace | |
| admin_stmt = ( | |
| select(User) | |
| .join(UserWorkspace) | |
| .where( | |
| UserWorkspace.workspace_id == workspace_id, | |
| UserWorkspace.role == UserRole.SC_ADMIN, | |
| User.is_active == True, | |
| User.deleted_at.is_(None) | |
| ) | |
| .limit(1) | |
| ) | |
| res = await db.execute(admin_stmt) | |
| manager = res.scalar_one_or_none() | |
| if manager: | |
| return manager | |
| # 3. Final Fallback: The Global Super Admin (Platform level) | |
| global_admin_stmt = ( | |
| select(User) | |
| .where( | |
| User.global_role == UserRole.SC_ADMIN, | |
| User.is_active == True, | |
| User.deleted_at.is_(None) | |
| ) | |
| .limit(1) | |
| ) | |
| res = await db.execute(global_admin_stmt) | |
| return res.scalar_one_or_none() | |
| import json | |
| class CustomEncoder(json.JSONEncoder): | |
| """JSON encoder that handles UUID objects by converting them to strings.""" | |
| def default(self, obj): | |
| if isinstance(obj, UUID): | |
| return str(obj) | |
| if isinstance(obj, datetime): | |
| return obj.isoformat() | |
| return super().default(obj) | |
| def sanitize_for_db(data: Any) -> Any: | |
| """Recursively converts UUIDs and datetimes to strings for DB storage.""" | |
| if isinstance(data, dict): | |
| return {k: sanitize_for_db(v) for k, v in data.items()} | |
| elif isinstance(data, list): | |
| return [sanitize_for_db(i) for i in data] | |
| elif isinstance(data, UUID): | |
| return str(data) | |
| elif isinstance(data, datetime): | |
| return data.isoformat() | |
| return data | |
| def safe_uuid(val: Any) -> Optional[UUID]: | |
| """Safely attempts to cast a value to UUID. Returns None on failure.""" | |
| if not val: | |
| return None | |
| if isinstance(val, UUID): | |
| return val | |
| try: | |
| # Check for common short-codes or hex strings that are not UUIDs | |
| s_val = str(val).strip() | |
| if len(s_val) < 32: | |
| return None | |
| return UUID(s_val) | |
| except (ValueError, TypeError, AttributeError): | |
| return None | |
| def get_deterministic_uuid(val: Any) -> UUID: | |
| """ | |
| Deterministically maps any input (string, int, etc) to a valid UUID v5. | |
| Ensures that arq string IDs (like cron tasks) can be stored in our UUID-based DB. | |
| """ | |
| if isinstance(val, UUID): | |
| return val | |
| # Use a dedicated namespace for Nexus Worker jobs | |
| NEXUS_NAMESPACE = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') # DNS Namespace as base | |
| return uuid.uuid5(NEXUS_NAMESPACE, str(val)) | |