Spaces:
Paused

miracle / agents /utils.py
dushyantsingh0
backend sprint
d050df5
Raw History Blame Contribute Delete
12.2 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, UserWorkspace.role).join(UserWorkspace).where(
UserWorkspace.workspace_id == workspace_id,
UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), # INTERNAL ONLY
User.global_role.is_distinct_from(UserRole.SUPERADMIN), # Exclude Global HQ from allocation
User.is_active == True,
User.deleted_at.is_(None),
UserWorkspace.is_active == True,
UserWorkspace.deleted_at.is_(None)
)
result = await db.execute(stmt)
verified_staff = []
for user, role in result.all():
user.role = role
verified_staff.append(user)
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: Optional[List[float]] = None,
threshold: float = 0.2,
limit: int = 5
) -> List[Dict[str, Any]]:
"""
Internal utility for hybrid search (FTS + Vector).
If query_embedding is None, it degrades to high-speed keyword FTS only.
"""
# 1. Semantic Chunk Search (Gated by vector presence)
semantic_results = []
if query_embedding:
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)
semantic_results = semantic_res.all()
# 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_results:
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),
UserWorkspace.is_active == True,
UserWorkspace.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),
UserWorkspace.is_active == True,
UserWorkspace.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: No Global HQ fallback per policy
return None
import json
class CustomEncoder(json.JSONEncoder):
"""JSON encoder that handles UUID objects by converting them to strings."""
def default(self, o):
if isinstance(o, UUID):
return str(o)
if isinstance(o, datetime):
return o.isoformat()
return super().default(o)
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, tuple, set)):
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 the input is already a valid UUID or UUID string, it returns it as-is to
prevent redundant hashing across system boundaries.
"""
# 1. Direct object check
if isinstance(val, UUID):
return val
# 2. String UUID check (crucial for API -> Worker synchronization)
parsed = safe_uuid(val)
if parsed:
return parsed
# 3. Deterministic Hash (Namespace v5)
# 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))
def parse_json_garbage(text: str) -> Dict[str, Any]:
"""
Robustly extract and parse JSON from a string that may contain markdown,
hallucinations, or descriptive garbage.
"""
import re
import json
if not text:
return {}
# 1. Strip Markdown Blocks
# Find everything between ```json and ``` or just ``` and ```
text = re.sub(r'```json\s*(.*?)\s*```', r'\1', text, flags=re.DOTALL)
text = re.sub(r'```\s*(.*?)\s*```', r'\1', text, flags=re.DOTALL)
# 2. Locate the first { and last }
start_idx = text.find('{')
end_idx = text.rfind('}')
if start_idx == -1 or end_idx == -1 or end_idx < start_idx:
# Check for single values or simple lists if needed, but here we expect objects
return {}
clean_json = text[start_idx:end_idx+1]
# 3. Repair common hallucinations
# - Trailing commas: {"a": 1,} -> {"a": 1}
clean_json = re.sub(r',\s*\}', '}', clean_json)
clean_json = re.sub(r',\s*\]', ']', clean_json)
# - Improper decimals: 123,45 -> 123.45 (European style)
clean_json = re.sub(r'(\d+),(\d+)', r'\1.\2', clean_json)
# 4. Attempt Parsing
try:
return json.loads(clean_json)
except json.JSONDecodeError:
# 5. Advanced Recovery: Strip descriptive garbage from numeric fields
# Look for "key": ... and try to fix values
# Specifically targeting "estimated_effort_hours" as seen in logs
def numeric_repair(match):
key_part = match.group(1)
val_part = match.group(2)
# Find first occurrence of a number (int or float) in the garbage
nums = re.findall(r'\d+\.?\d*', val_part)
if nums:
return f'{key_part}{nums[0]}'
return f'{key_part}1.0' # Default fallback for the field
# This regex looks for specific numeric keys and tries to isolate the number
clean_json = re.sub(r'("estimated_effort_hours"\s*:\s*)([^,}\]]+)', numeric_repair, clean_json)
clean_json = re.sub(r'("confidence"\s*:\s*)([^,}\]]+)', numeric_repair, clean_json)
try:
return json.loads(clean_json)
except Exception:
# Last ditch: remove all non-ASCII if LLM hallucinated Russian/Chinese in keys/values
# (risky but better than total failure in some cases)
# Actually, let's just log and fail for now to avoid side effects
return {}