File size: 11,538 Bytes
159f5a5
 
 
 
 
 
 
 
 
 
 
 
 
 
68af3c5
159f5a5
 
68af3c5
825e852
159f5a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8e67fc
 
 
 
 
159f5a5
 
 
 
 
 
 
 
 
 
 
 
 
 
8900d0e
159f5a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8900d0e
159f5a5
 
 
 
68af3c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159f5a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8900d0e
159f5a5
 
 
 
825e852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159f5a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8900d0e
 
159f5a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68af3c5
 
159f5a5
825e852
159f5a5
 
 
 
 
 
 
 
 
 
 
 
68af3c5
 
159f5a5
825e852
159f5a5
 
 
 
 
 
 
 
 
68af3c5
 
159f5a5
825e852
159f5a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""LangGraph graph definition — nodes, edges, and parallel execution."""

from __future__ import annotations

import asyncio
import logging
from typing import Any

from langgraph.graph import END, StateGraph

from agent.agents.guardrail import run_guardrail
from agent.agents.planner import run_planner
from agent.agents.synthesiser import stream_synthesis
from agent.models import AgentResult, KnowledgeGraphState, RetrievedChunk
from agent.tools.confluence_search import run_confluence_search
from agent.tools.doc_search import compute_retrieval_confidence, run_doc_search
from agent.tools.live_docs import run_live_docs
from agent.tools.slack_search import run_slack_search
from agent.tools.sql_query import run_sql_query
from agent.tools.ticket_lookup import run_ticket_lookup

logger = logging.getLogger(__name__)


async def _push_event(queue: asyncio.Queue, event: str, data: Any) -> None:
    if queue is not None:
        await queue.put({"event": event, "data": data})


async def planner_node(state: KnowledgeGraphState) -> dict:
    queue = state.sse_queue
    plan = await run_planner(state.query_input)
    await _push_event(
        queue,
        "plan_ready",
        {
            "tasks": [t.model_dump() for t in plan.tasks],
            "reasoning": plan.reasoning,
        },
    )
    return {"execution_plan": plan}


async def doc_search_node(state: KnowledgeGraphState) -> dict:
    queue = state.sse_queue
    await _push_event(queue, "agent_started", {"agent": "doc_search"})

    task_input = _find_task_input(state, "doc_search") or state.query_input.query
    chunks: list[RetrievedChunk] = []
    error: str | None = None

    try:
        chunks = await run_doc_search(
            task_input,
            state.query_input.team_id,
            state.query_input.allowed_channel_ids or None,
        )
    except Exception as exc:
        logger.exception("doc_search_node error")
        error = str(exc)

    confidence = compute_retrieval_confidence(chunks)
    result = AgentResult(
        agent="doc_search",
        chunks=chunks,
        retrieval_confidence=confidence,
        error=error,
    )
    await _push_event(
        queue,
        "agent_done",
        {"agent": "doc_search", "retrieval_confidence": confidence},
    )
    return {"agent_results": {**state.agent_results, "doc_search": result}}


async def ticket_lookup_node(state: KnowledgeGraphState) -> dict:
    queue = state.sse_queue
    await _push_event(queue, "agent_started", {"agent": "ticket_lookup"})

    task_input = _find_task_input(state, "ticket_lookup") or state.query_input.query
    chunks: list[RetrievedChunk] = []
    error: str | None = None

    try:
        chunks = await run_ticket_lookup(task_input, state.query_input.team_id)
    except Exception as exc:
        logger.exception("ticket_lookup_node error")
        error = str(exc)

    confidence = compute_retrieval_confidence(chunks)
    result = AgentResult(
        agent="ticket_lookup",
        chunks=chunks,
        retrieval_confidence=confidence,
        error=error,
    )
    await _push_event(
        queue,
        "agent_done",
        {"agent": "ticket_lookup", "retrieval_confidence": confidence},
    )
    return {"agent_results": {**state.agent_results, "ticket_lookup": result}}


async def confluence_search_node(state: KnowledgeGraphState) -> dict:
    queue = state.sse_queue
    await _push_event(queue, "agent_started", {"agent": "confluence_search"})

    task_input = _find_task_input(state, "confluence_search") or state.query_input.query
    chunks: list[RetrievedChunk] = []
    error: str | None = None

    try:
        chunks = await run_confluence_search(task_input, state.query_input.team_id)
    except Exception as exc:
        logger.exception("confluence_search_node error")
        error = str(exc)

    confidence = compute_retrieval_confidence(chunks)
    result = AgentResult(
        agent="confluence_search",
        chunks=chunks,
        retrieval_confidence=confidence,
        error=error,
    )
    await _push_event(queue, "agent_done", {"agent": "confluence_search", "retrieval_confidence": confidence})
    return {"agent_results": {**state.agent_results, "confluence_search": result}}


async def slack_search_node(state: KnowledgeGraphState) -> dict:
    queue = state.sse_queue
    await _push_event(queue, "agent_started", {"agent": "slack_search"})

    task_input = _find_task_input(state, "slack_search") or state.query_input.query
    chunks: list[RetrievedChunk] = []
    error: str | None = None

    try:
        chunks = await run_slack_search(task_input, state.query_input.team_id)
    except Exception as exc:
        logger.exception("slack_search_node error")
        error = str(exc)

    confidence = compute_retrieval_confidence(chunks)
    result = AgentResult(
        agent="slack_search",
        chunks=chunks,
        retrieval_confidence=confidence,
        error=error,
    )
    await _push_event(queue, "agent_done", {"agent": "slack_search", "retrieval_confidence": confidence})
    return {"agent_results": {**state.agent_results, "slack_search": result}}


async def live_docs_node(state: KnowledgeGraphState) -> dict:
    queue = state.sse_queue
    await _push_event(queue, "agent_started", {"agent": "live_docs"})

    task_input = _find_task_input(state, "live_docs") or state.query_input.query
    chunks: list[RetrievedChunk] = []
    error: str | None = None

    try:
        chunks = await run_live_docs(task_input, state.query_input.team_id)
    except Exception as exc:
        logger.exception("live_docs_node error")
        error = str(exc)

    confidence = compute_retrieval_confidence(chunks)
    result = AgentResult(
        agent="live_docs",
        chunks=chunks,
        retrieval_confidence=confidence,
        error=error,
    )
    await _push_event(
        queue,
        "agent_done",
        {"agent": "live_docs", "retrieval_confidence": confidence},
    )
    return {"agent_results": {**state.agent_results, "live_docs": result}}


async def sql_query_node(state: KnowledgeGraphState) -> dict:
    queue = state.sse_queue
    await _push_event(queue, "agent_started", {"agent": "sql_query"})

    task_input = _find_task_input(state, "sql_query") or state.query_input.query
    chunks: list[RetrievedChunk] = []
    error: str | None = None

    try:
        chunks = await run_sql_query(task_input, state.query_input.team_id)
    except Exception as exc:
        logger.exception("sql_query_node error")
        error = str(exc)

    confidence = compute_retrieval_confidence(chunks)
    result = AgentResult(
        agent="sql_query",
        chunks=chunks,
        retrieval_confidence=confidence,
        error=error,
    )
    await _push_event(
        queue,
        "agent_done",
        {"agent": "sql_query", "retrieval_confidence": confidence},
    )
    return {"agent_results": {**state.agent_results, "sql_query": result}}


async def synthesiser_node(state: KnowledgeGraphState) -> dict:
    queue = state.sse_queue
    await _push_event(queue, "synthesis_started", {})

    full_answer_parts: list[str] = []
    async for token in stream_synthesis(state.query_input.query, state.agent_results):
        full_answer_parts.append(token)
        await _push_event(queue, "answer_chunk", {"chunk": token})

    final_answer = "".join(full_answer_parts)

    all_chunks: list[RetrievedChunk] = []
    seen: set[str] = set()
    for result in state.agent_results.values():
        for chunk in result.chunks:
            if chunk.chunk_id not in seen:
                seen.add(chunk.chunk_id)
                all_chunks.append(chunk)

    await _push_event(queue, "citations", {"chunks": [c.model_dump() for c in all_chunks]})

    return {"final_answer": final_answer, "citations": all_chunks}


async def join_node(state: KnowledgeGraphState) -> dict:
    """Fan-in synchronisation point — waits for all retrieval nodes, then hands off to synthesiser."""
    await _push_event(state.sse_queue, "agent_started", {"agent": "synthesiser"})
    return {}


async def guardrail_node(state: KnowledgeGraphState) -> dict:
    queue = state.sse_queue
    score, escalate = await run_guardrail(
        state.final_answer or "",
        state.citations,
    )
    await _push_event(
        queue,
        "guardrail_result",
        {"score": score, "escalate": escalate},
    )
    return {
        "guardrail_passed": not escalate,
        "guardrail_score": score,
        "escalate": escalate,
    }


def _find_task_input(state: KnowledgeGraphState, agent: str) -> str | None:
    if state.execution_plan is None:
        return None
    for task in state.execution_plan.tasks:
        if task.agent == agent:
            return task.input
    return None


def _plan_includes(state: KnowledgeGraphState, agent: str) -> bool:
    if state.execution_plan is None:
        return False
    return any(t.agent == agent for t in state.execution_plan.tasks)


def _route_after_planner(state: KnowledgeGraphState) -> list[str]:
    if state.execution_plan is None:
        return ["synthesiser_node"]

    plan = state.execution_plan
    immediate: list[str] = []
    for task in plan.tasks:
        if not task.depends_on:
            immediate.append(f"{task.agent}_node")

    # If nothing is immediate (shouldn't happen), fall back to synthesiser
    return immediate or ["synthesiser_node"]


def _route_after_guardrail(state: KnowledgeGraphState) -> str:
    return "escalate" if state.escalate else END


def build_graph() -> Any:
    builder = StateGraph(KnowledgeGraphState)

    builder.add_node("planner_node", planner_node)
    builder.add_node("doc_search_node", doc_search_node)
    builder.add_node("ticket_lookup_node", ticket_lookup_node)
    builder.add_node("confluence_search_node", confluence_search_node)
    builder.add_node("slack_search_node", slack_search_node)
    builder.add_node("live_docs_node", live_docs_node)
    builder.add_node("sql_query_node", sql_query_node)
    builder.add_node("join_node", join_node)
    builder.add_node("synthesiser_node", synthesiser_node)
    builder.add_node("guardrail_node", guardrail_node)

    builder.set_entry_point("planner_node")

    builder.add_conditional_edges(
        "planner_node",
        _route_after_planner,
        {
            "doc_search_node": "doc_search_node",
            "ticket_lookup_node": "ticket_lookup_node",
            "confluence_search_node": "confluence_search_node",
            "slack_search_node": "slack_search_node",
            "live_docs_node": "live_docs_node",
            "sql_query_node": "sql_query_node",
            "summariser_node": "synthesiser_node",
            "synthesiser_node": "synthesiser_node",
        },
    )

    # Retrieval nodes all converge on join_node — LangGraph waits for every
    # incoming edge to fire before executing join_node (fan-in).
    builder.add_edge("doc_search_node", "join_node")
    builder.add_edge("ticket_lookup_node", "join_node")
    builder.add_edge("confluence_search_node", "join_node")
    builder.add_edge("slack_search_node", "join_node")
    builder.add_edge("live_docs_node", "join_node")
    builder.add_edge("sql_query_node", "join_node")

    builder.add_edge("join_node", "synthesiser_node")

    builder.add_edge("synthesiser_node", "guardrail_node")

    builder.add_conditional_edges(
        "guardrail_node",
        _route_after_guardrail,
        {END: END, "escalate": END},
    )

    return builder.compile()


graph = build_graph()