File size: 8,486 Bytes
24f95f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Janus β€” LangGraph pipeline.

Deliberative graph topology:
  [switchboard]
       β”‚
       β”œβ”€ requires_simulation=true β†’ [mirofish] ┐
       β”œβ”€ requires_finance_data=true β†’ [finance] β”œβ†’ [research] β†’ [planner] β†’ [verifier]
       └─ (default) β†’ [research]               β”˜                        β”‚
                                                                        β”œβ”€ pass β†’ [synthesizer] β†’ [END]
                                                                        └─ fail once β†’ [repair] β†’ [planner]

Context from the context engine is injected into every LLM call.
"""

import uuid
import time
import logging
from typing import TypedDict, Dict, Any, Optional

from langgraph.graph import StateGraph, START, END

from app.agents import (
    planner,
    switchboard,
    research,
    synthesizer,
    verifier,
    mental_scratchpad,
)
from app.agents import mirofish_node, finance_node

logger = logging.getLogger(__name__)


class AgentState(TypedDict, total=False):
    user_input: str
    case_id: str
    route: dict
    simulation: dict
    finance: dict
    research: dict
    planner: dict
    verifier: dict
    final: dict
    errors: list
    context: dict
    replan_count: int
    scratchpad: dict


def switchboard_node(state: AgentState) -> dict:
    t0 = time.perf_counter()
    result = switchboard.run(state)
    elapsed = time.perf_counter() - t0
    logger.info(
        f"[{state.get('case_id', '?')[:8]}] switchboard: {elapsed:.2f}s β€” domain={result.get('route', {}).get('domain')}"
    )
    return result


async def mirofish_node_fn(state: AgentState) -> dict:
    t0 = time.perf_counter()
    result = await mirofish_node.run(state)
    elapsed = time.perf_counter() - t0
    logger.info(f"[{state.get('case_id', '?')[:8]}] mirofish: {elapsed:.2f}s")
    return result


async def finance_node_fn(state: AgentState) -> dict:
    t0 = time.perf_counter()
    result = await finance_node.run(state)
    elapsed = time.perf_counter() - t0
    logger.info(f"[{state.get('case_id', '?')[:8]}] finance: {elapsed:.2f}s")
    return result


def research_node(state: AgentState) -> dict:
    t0 = time.perf_counter()
    result = research.run(state)
    elapsed = time.perf_counter() - t0
    logger.info(f"[{state.get('case_id', '?')[:8]}] research: {elapsed:.2f}s")
    return result


def planner_node(state: AgentState) -> dict:
    t0 = time.perf_counter()
    result = planner.run(state)
    elapsed = time.perf_counter() - t0
    logger.info(f"[{state.get('case_id', '?')[:8]}] planner: {elapsed:.2f}s")
    return result


def verifier_node(state: AgentState) -> dict:
    t0 = time.perf_counter()
    result = verifier.run(state)
    elapsed = time.perf_counter() - t0
    verdict = result.get("verifier", {}).get("passed")
    logger.info(
        f"[{state.get('case_id', '?')[:8]}] verifier: {elapsed:.2f}s β€” passed={verdict}"
    )
    return result


def synthesizer_node(state: AgentState) -> dict:
    t0 = time.perf_counter()
    result = synthesizer.run(state)
    elapsed = time.perf_counter() - t0
    logger.info(f"[{state.get('case_id', '?')[:8]}] synthesizer: {elapsed:.2f}s")
    return result


def mental_scratchpad_node(state: AgentState) -> dict:
    t0 = time.perf_counter()
    result = mental_scratchpad.run(state)
    elapsed = time.perf_counter() - t0
    logger.info(f"[{state.get('case_id', '?')[:8]}] mental_scratchpad: {elapsed:.2f}s")
    return result


def repair_node(state: AgentState) -> dict:
    next_replan = state.get("replan_count", 0) + 1
    logger.info(
        "[%s] repair: incrementing replan_count to %s",
        state.get("case_id", "?")[:8],
        next_replan,
    )
    return {**state, "replan_count": next_replan}


def after_switchboard(state: AgentState) -> str:
    route = state.get("route", {})
    # Finance is cheap/structured and should run even if simulation is also needed.
    if route.get("requires_finance_data"):
        return "finance"
    if route.get("requires_simulation"):
        return "mirofish"
    if route.get("confidence", 0.5) < 0.45 and route.get(
        "complexity", "medium"
    ) in {"medium", "high", "very_high"}:
        logger.info(
            "[%s] switchboard triggered simulation due to low confidence",
            state.get("case_id", "?")[:8],
        )
    # High Complexity Deliberation: Go through Scratchpad
    if route.get("complexity") in {"high", "very_high"}:
        return "mental_scratchpad"

    return "research"


def after_finance(state: AgentState) -> str:
    route = state.get("route", {})
    if route.get("requires_simulation"):
        return "mirofish"
    if route.get("confidence", 0.5) < 0.45 and route.get(
        "complexity", "medium"
    ) in {"medium", "high", "very_high"}:
        return "mirofish"
    return "research"


def after_verifier(state: AgentState) -> str:
    verifier_result = state.get("verifier", {})
    route = state.get("route", {})
    complexity = route.get("complexity", "medium")
    
    # Allow 2 replans (3 attempts total) for high/very_high complexity, otherwise 1 replan.
    max_replans = 2 if complexity in {"high", "very_high"} else 1
    
    if not verifier_result.get("passed", True) and state.get("replan_count", 0) < max_replans:
        return "repair"
    return "synthesizer"


def build_graph():
    g = StateGraph(AgentState)

    g.add_node("switchboard", switchboard_node)
    g.add_node("research", research_node)
    g.add_node("mirofish", mirofish_node_fn)
    g.add_node("finance", finance_node_fn)
    g.add_node("planner", planner_node)
    g.add_node("verifier", verifier_node)
    g.add_node("repair", repair_node)
    g.add_node("synthesizer", synthesizer_node)
    g.add_node("mental_scratchpad", mental_scratchpad_node)

    g.set_entry_point("switchboard")

    g.add_conditional_edges(
        "switchboard",
        after_switchboard,
        {
            "mirofish": "mirofish",
            "finance": "finance",
            "research": "research",
            "synthesizer": "synthesizer",
            "mental_scratchpad": "mental_scratchpad",
        },
    )

    g.add_edge("mental_scratchpad", "research")

    g.add_edge("mirofish", "research")
    g.add_conditional_edges(
        "finance",
        after_finance,
        {"mirofish": "mirofish", "research": "research"},
    )
    g.add_edge("research", "planner")
    g.add_edge("planner", "verifier")
    g.add_conditional_edges(
        "verifier",
        after_verifier,
        {"repair": "repair", "synthesizer": "synthesizer"},
    )
    g.add_edge("repair", "planner")
    g.add_edge("synthesizer", END)
    return g.compile()


# Lazy graph compilation β€” prevents import-time crash if agents fail to load
_compiled_graph = None
_graph_build_error = None


def get_compiled_graph():
    """Lazy graph compilation with error handling. Call at runtime, not import."""
    global _compiled_graph, _graph_build_error
    if _compiled_graph is not None:
        return _compiled_graph
    if _graph_build_error is not None:
        raise RuntimeError(f"Graph compilation previously failed: {_graph_build_error}")
    try:
        _compiled_graph = build_graph()
        logger.info("LangGraph pipeline compiled successfully")
        return _compiled_graph
    except Exception as e:
        _graph_build_error = str(e)
        logger.error(f"LangGraph build failed: {e}")
        raise


def graph_status():
    """Return graph compilation status without triggering compilation."""
    if _compiled_graph is not None:
        return {"status": "ready"}
    if _graph_build_error:
        return {"status": "failed", "error": _graph_build_error}
    return {"status": "not_compiled"}


async def run_case(user_input: str, context: dict = None) -> dict:
    """Run the optimized agent pipeline on user input."""
    graph = get_compiled_graph()
    case_id = str(uuid.uuid4())
    t0 = time.perf_counter()
    logger.info("Starting case %s", case_id)

    initial_state = {
        "case_id": case_id,
        "user_input": user_input,
        "route": {},
        "research": {},
        "planner": {},
        "verifier": {},
        "final": {},
        "errors": [],
        "replan_count": 0,
    }
    if context:
        initial_state["context"] = context

    result = await graph.ainvoke(initial_state)

    elapsed = time.perf_counter() - t0
    logger.info("Case %s completed in %.2fs", case_id, elapsed)
    return result