Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit Β·
6bf2d17
1
Parent(s): 1aea11e
backend stabilisation
Browse files- agents/history.py +0 -24
- agents/nexus_checkpoint.py +3 -1
- agents/nexus_master.py +6 -5
- agents/workflow.py +24 -3
- core/llm.py +1 -2
- frontend/apps/customer/src/index.css +2 -2
- frontend/apps/internal/src/components/TicketDetails.tsx +2 -2
- tasks/ai.py +7 -2
agents/history.py
CHANGED
|
@@ -1,30 +1,6 @@
|
|
| 1 |
from typing import List, Any, Dict, Union
|
| 2 |
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage, ToolMessage
|
| 3 |
|
| 4 |
-
def reduce_messages(left: List[BaseMessage], right: List[BaseMessage] | Dict[str, Any]) -> List[BaseMessage]:
|
| 5 |
-
"""
|
| 6 |
-
Hardened state management for the Nexus Master Agent.
|
| 7 |
-
Strictly prevents history duplication and context window overflows.
|
| 8 |
-
"""
|
| 9 |
-
if not isinstance(right, list):
|
| 10 |
-
if isinstance(right, dict) and right.get("action") == "REPLACE":
|
| 11 |
-
return right["messages"]
|
| 12 |
-
return left
|
| 13 |
-
|
| 14 |
-
# Deduplication Logic:
|
| 15 |
-
# We only deduplicate based on EXPLICIT ID to avoid dropping intentional repeated content
|
| 16 |
-
# like "try again" or status checks that have identical text content.
|
| 17 |
-
existing_ids = {getattr(m, "id") for m in left if getattr(m, "id", None)}
|
| 18 |
-
|
| 19 |
-
new_messages = list(left)
|
| 20 |
-
for m in right:
|
| 21 |
-
m_id = getattr(m, "id", None)
|
| 22 |
-
if not m_id or m_id not in existing_ids:
|
| 23 |
-
new_messages.append(m)
|
| 24 |
-
if m_id:
|
| 25 |
-
existing_ids.add(m_id)
|
| 26 |
-
|
| 27 |
-
return new_messages
|
| 28 |
|
| 29 |
def get_role(msg: BaseMessage) -> str:
|
| 30 |
"""Maps LangChain message types to strict user/assistant roles."""
|
|
|
|
| 1 |
from typing import List, Any, Dict, Union
|
| 2 |
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage, ToolMessage
|
| 3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
def get_role(msg: BaseMessage) -> str:
|
| 6 |
"""Maps LangChain message types to strict user/assistant roles."""
|
agents/nexus_checkpoint.py
CHANGED
|
@@ -18,7 +18,9 @@ class SQLAlchemySaver(BaseCheckpointSaver):
|
|
| 18 |
"""
|
| 19 |
|
| 20 |
def __init__(self, serde: Optional[SerializerProtocol] = None):
|
| 21 |
-
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def _get_checkpoint_tuple(self, row: Any) -> CheckpointTuple:
|
| 24 |
return CheckpointTuple(
|
|
|
|
| 18 |
"""
|
| 19 |
|
| 20 |
def __init__(self, serde: Optional[SerializerProtocol] = None):
|
| 21 |
+
# New Paradigm: Explicitly define allowed object categories for serialization
|
| 22 |
+
# to suppress LangChainPendingDeprecationWarning and ensure security.
|
| 23 |
+
super().__init__(serde=serde or JsonPlusSerializer(allowed_objects=['messages', 'core']))
|
| 24 |
|
| 25 |
def _get_checkpoint_tuple(self, row: Any) -> CheckpointTuple:
|
| 26 |
return CheckpointTuple(
|
agents/nexus_master.py
CHANGED
|
@@ -13,7 +13,7 @@ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
|
| 13 |
from core.database import async_session_factory
|
| 14 |
from core.logging import get_logger
|
| 15 |
from core.llm import get_llm
|
| 16 |
-
from agents.history import standardize_history
|
| 17 |
from agents.prompts import get_prompt
|
| 18 |
from agents.tools.nexus_tools import (
|
| 19 |
create_ticket_tool, add_ticket_comment_tool, change_ticket_status_tool,
|
|
@@ -52,14 +52,15 @@ class ResponderOutput(BaseModel):
|
|
| 52 |
# --- GRAPH STATE ---
|
| 53 |
from typing import Annotated, TypedDict
|
| 54 |
from agents.state import merge_list, merge_dict
|
| 55 |
-
|
|
|
|
| 56 |
|
| 57 |
class NexusState(TypedDict):
|
| 58 |
"""
|
| 59 |
Production-grade State specifically for the Nexus Master Agent.
|
| 60 |
Uses Annotated reducers to ensure multi-node data accumulation.
|
| 61 |
"""
|
| 62 |
-
messages: Annotated[List[BaseMessage],
|
| 63 |
user_id: UUID
|
| 64 |
workspace_id: UUID
|
| 65 |
user_role: str
|
|
@@ -1073,7 +1074,7 @@ async def get_nexus_app(is_agent: bool = False):
|
|
| 1073 |
if cache_key in _GRAPH_CACHE:
|
| 1074 |
return _GRAPH_CACHE[cache_key]
|
| 1075 |
|
| 1076 |
-
from langgraph.graph import StateGraph, END
|
| 1077 |
|
| 1078 |
workflow = StateGraph(NexusState)
|
| 1079 |
|
|
@@ -1084,7 +1085,7 @@ async def get_nexus_app(is_agent: bool = False):
|
|
| 1084 |
workflow.add_node("responder", nexus_responder)
|
| 1085 |
|
| 1086 |
# 2. Add Edges & Control Flow
|
| 1087 |
-
workflow.
|
| 1088 |
|
| 1089 |
# Initializer -> End (if greeting) OR -> Router
|
| 1090 |
workflow.add_conditional_edges(
|
|
|
|
| 13 |
from core.database import async_session_factory
|
| 14 |
from core.logging import get_logger
|
| 15 |
from core.llm import get_llm
|
| 16 |
+
from agents.history import standardize_history
|
| 17 |
from agents.prompts import get_prompt
|
| 18 |
from agents.tools.nexus_tools import (
|
| 19 |
create_ticket_tool, add_ticket_comment_tool, change_ticket_status_tool,
|
|
|
|
| 52 |
# --- GRAPH STATE ---
|
| 53 |
from typing import Annotated, TypedDict
|
| 54 |
from agents.state import merge_list, merge_dict
|
| 55 |
+
|
| 56 |
+
from langgraph.graph.message import add_messages
|
| 57 |
|
| 58 |
class NexusState(TypedDict):
|
| 59 |
"""
|
| 60 |
Production-grade State specifically for the Nexus Master Agent.
|
| 61 |
Uses Annotated reducers to ensure multi-node data accumulation.
|
| 62 |
"""
|
| 63 |
+
messages: Annotated[List[BaseMessage], add_messages]
|
| 64 |
user_id: UUID
|
| 65 |
workspace_id: UUID
|
| 66 |
user_role: str
|
|
|
|
| 1074 |
if cache_key in _GRAPH_CACHE:
|
| 1075 |
return _GRAPH_CACHE[cache_key]
|
| 1076 |
|
| 1077 |
+
from langgraph.graph import StateGraph, START, END
|
| 1078 |
|
| 1079 |
workflow = StateGraph(NexusState)
|
| 1080 |
|
|
|
|
| 1085 |
workflow.add_node("responder", nexus_responder)
|
| 1086 |
|
| 1087 |
# 2. Add Edges & Control Flow
|
| 1088 |
+
workflow.add_edge(START, "initializer")
|
| 1089 |
|
| 1090 |
# Initializer -> End (if greeting) OR -> Router
|
| 1091 |
workflow.add_conditional_edges(
|
agents/workflow.py
CHANGED
|
@@ -137,6 +137,17 @@ async def run_ai_workflow(ctx: Any, ticket_id: Any, workspace_id: Any = None, **
|
|
| 137 |
ticket.resolved_at = datetime.utcnow()
|
| 138 |
ticket.resolution_text = f"Automated Workflow: Marked as fast-duplicate of #{str(fast_dup)[:8]}."
|
| 139 |
await db.commit()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
return {"is_duplicate": True, "duplicate_of_id": fast_dup}
|
| 141 |
|
| 142 |
app = await get_workflow_app()
|
|
@@ -321,9 +332,19 @@ async def run_ai_workflow(ctx: Any, ticket_id: Any, workspace_id: Any = None, **
|
|
| 321 |
|
| 322 |
# --- Step D: AI Metadata & Root Cause Analysis ---
|
| 323 |
final_meta = final_state.get("metadata", {})
|
|
|
|
|
|
|
| 324 |
internal_summary = final_state.get("internal_summary") or "Diagnostic analysis complete."
|
| 325 |
-
|
| 326 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
|
| 328 |
# ββ FORENSIC TRAIL FIX ββββββββββββββββββββββββββββββββββββββββββ
|
| 329 |
# processed_steps are accumulated in final_state by the merge_list reducer
|
|
@@ -477,12 +498,12 @@ async def run_ai_workflow(ctx: Any, ticket_id: Any, workspace_id: Any = None, **
|
|
| 477 |
except: pass
|
| 478 |
raise e
|
| 479 |
|
| 480 |
-
# 5. POST-WORKFLOW CHAINING (GAP-7 Fix)
|
| 481 |
try:
|
| 482 |
await enqueue_task(
|
| 483 |
ctx.get("redis") if isinstance(ctx, dict) else None,
|
| 484 |
'auto_summarize_ticket',
|
| 485 |
t_id,
|
|
|
|
| 486 |
_job_id=f"summarize_init_{t_id}"
|
| 487 |
)
|
| 488 |
except: pass
|
|
|
|
| 137 |
ticket.resolved_at = datetime.utcnow()
|
| 138 |
ticket.resolution_text = f"Automated Workflow: Marked as fast-duplicate of #{str(fast_dup)[:8]}."
|
| 139 |
await db.commit()
|
| 140 |
+
|
| 141 |
+
# TRIGGER: Immediate summarization for fast-duplicates (even with 0 messages)
|
| 142 |
+
from core.tasks import enqueue_task
|
| 143 |
+
await enqueue_task(
|
| 144 |
+
ctx.get("redis") if isinstance(ctx, dict) else None,
|
| 145 |
+
'auto_summarize_ticket',
|
| 146 |
+
t_id,
|
| 147 |
+
manual=True,
|
| 148 |
+
_job_id=f"summarize_init_{t_id}"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
return {"is_duplicate": True, "duplicate_of_id": fast_dup}
|
| 152 |
|
| 153 |
app = await get_workflow_app()
|
|
|
|
| 332 |
|
| 333 |
# --- Step D: AI Metadata & Root Cause Analysis ---
|
| 334 |
final_meta = final_state.get("metadata", {})
|
| 335 |
+
is_duplicate = final_state.get("is_duplicate")
|
| 336 |
+
|
| 337 |
internal_summary = final_state.get("internal_summary") or "Diagnostic analysis complete."
|
| 338 |
+
|
| 339 |
+
# For duplicates, we don't want to pollute with "Under investigation" placeholders
|
| 340 |
+
# The internal portal will hide the RCA section anyway, but the data should be clean.
|
| 341 |
+
rca = final_state.get("root_cause_analysis")
|
| 342 |
+
if not rca:
|
| 343 |
+
rca = "Marked as duplicate." if is_duplicate else "Under investigation."
|
| 344 |
+
|
| 345 |
+
tech_solution = final_state.get("proposed_technical_solution")
|
| 346 |
+
if not tech_solution:
|
| 347 |
+
tech_solution = "See original ticket." if is_duplicate else "Diagnostics in progress."
|
| 348 |
|
| 349 |
# ββ FORENSIC TRAIL FIX ββββββββββββββββββββββββββββββββββββββββββ
|
| 350 |
# processed_steps are accumulated in final_state by the merge_list reducer
|
|
|
|
| 498 |
except: pass
|
| 499 |
raise e
|
| 500 |
|
|
|
|
| 501 |
try:
|
| 502 |
await enqueue_task(
|
| 503 |
ctx.get("redis") if isinstance(ctx, dict) else None,
|
| 504 |
'auto_summarize_ticket',
|
| 505 |
t_id,
|
| 506 |
+
manual=True, # Ensure it runs even for immediate duplicates/resolutions
|
| 507 |
_job_id=f"summarize_init_{t_id}"
|
| 508 |
)
|
| 509 |
except: pass
|
core/llm.py
CHANGED
|
@@ -13,9 +13,8 @@ try:
|
|
| 13 |
except ImportError:
|
| 14 |
_lru_available = False
|
| 15 |
|
| 16 |
-
#
|
| 17 |
from langchain_core._api import LangChainDeprecationWarning
|
| 18 |
-
warnings.filterwarnings("ignore", category=LangChainDeprecationWarning)
|
| 19 |
logging.getLogger("transformers").setLevel(logging.ERROR)
|
| 20 |
|
| 21 |
settings = get_settings()
|
|
|
|
| 13 |
except ImportError:
|
| 14 |
_lru_available = False
|
| 15 |
|
| 16 |
+
# Logic-safe imports for LangChain
|
| 17 |
from langchain_core._api import LangChainDeprecationWarning
|
|
|
|
| 18 |
logging.getLogger("transformers").setLevel(logging.ERROR)
|
| 19 |
|
| 20 |
settings = get_settings()
|
frontend/apps/customer/src/index.css
CHANGED
|
@@ -153,11 +153,11 @@ select {
|
|
| 153 |
}
|
| 154 |
|
| 155 |
.theme-dark select {
|
| 156 |
-
background: var(--bg-card)
|
| 157 |
}
|
| 158 |
|
| 159 |
.theme-light select {
|
| 160 |
-
background: var(--bg-card)
|
| 161 |
}
|
| 162 |
|
| 163 |
option {
|
|
|
|
| 153 |
}
|
| 154 |
|
| 155 |
.theme-dark select {
|
| 156 |
+
background-color: var(--bg-card);
|
| 157 |
}
|
| 158 |
|
| 159 |
.theme-light select {
|
| 160 |
+
background-color: var(--bg-card);
|
| 161 |
}
|
| 162 |
|
| 163 |
option {
|
frontend/apps/internal/src/components/TicketDetails.tsx
CHANGED
|
@@ -1360,8 +1360,8 @@ export const TicketDetails: React.FC<TicketDetailsProps> = ({ initialTicket, onB
|
|
| 1360 |
</div>
|
| 1361 |
</section>
|
| 1362 |
|
| 1363 |
-
{/* RCA & Proposed Solution Section (
|
| 1364 |
-
{(ticket?.ai_metadata?.initial_analysis || ticket.rca_notes) && (
|
| 1365 |
<section className={styles.sectionBlock} style={{ marginTop: 24 }}>
|
| 1366 |
<div className={styles.dossierHeader} style={{ marginBottom: 12 }}>
|
| 1367 |
<div className={styles.sectionTitle}>ROOT CAUSE ANALYSIS & PROPOSED SOLUTION</div>
|
|
|
|
| 1360 |
</div>
|
| 1361 |
</section>
|
| 1362 |
|
| 1363 |
+
{/* RCA & Proposed Solution Section (Internal Gist) - Hidden for Duplicates */}
|
| 1364 |
+
{(ticket?.ai_metadata?.initial_analysis || ticket.rca_notes) && !ticket.duplicate_of_id && (
|
| 1365 |
<section className={styles.sectionBlock} style={{ marginTop: 24 }}>
|
| 1366 |
<div className={styles.dossierHeader} style={{ marginBottom: 12 }}>
|
| 1367 |
<div className={styles.sectionTitle}>ROOT CAUSE ANALYSIS & PROPOSED SOLUTION</div>
|
tasks/ai.py
CHANGED
|
@@ -54,10 +54,15 @@ async def auto_summarize_ticket(ctx, ticket_id: UUID, **kwargs):
|
|
| 54 |
msg_stmt = select(Message).where(Message.ticket_id == ticket_id, Message.deleted_at.is_(None)).order_by(Message.created_at.desc()).limit(limit)
|
| 55 |
messages = list(reversed((await db.execute(msg_stmt)).scalars().all()))
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
is_manual = kwargs.get('manual', False)
|
| 58 |
-
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
public_messages = [m for m in messages if not m.is_internal]
|
| 61 |
llm = get_llm(timeout=120, is_heavy_task=True)
|
| 62 |
|
| 63 |
res_text = f"\nResolution: {ticket.resolution_text}" if ticket.resolution_text else ""
|
|
|
|
| 54 |
msg_stmt = select(Message).where(Message.ticket_id == ticket_id, Message.deleted_at.is_(None)).order_by(Message.created_at.desc()).limit(limit)
|
| 55 |
messages = list(reversed((await db.execute(msg_stmt)).scalars().all()))
|
| 56 |
|
| 57 |
+
public_messages = [m for m in messages if not m.is_internal]
|
| 58 |
+
|
| 59 |
+
# RELAXATION: Allow summarization even with 0 messages if it's a manual trigger
|
| 60 |
+
# (e.g. from workflow engine) or if the ticket is terminal (duplicates).
|
| 61 |
is_manual = kwargs.get('manual', False)
|
| 62 |
+
is_terminal = ticket.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]
|
| 63 |
+
if not (is_manual or is_terminal) and len(messages) < 5:
|
| 64 |
+
return
|
| 65 |
|
|
|
|
| 66 |
llm = get_llm(timeout=120, is_heavy_task=True)
|
| 67 |
|
| 68 |
res_text = f"\nResolution: {ticket.resolution_text}" if ticket.resolution_text else ""
|