File size: 14,584 Bytes
89d813f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc8f5ff
 
 
 
 
 
89d813f
 
 
 
 
 
 
 
 
 
 
dc8f5ff
 
 
 
89d813f
 
dc8f5ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89d813f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
"""
main.py โ€” FastAPI ๅ…ฅๅฃ

ๆŽฅๅฃ๏ผš
  GET  /health              ๅฅๅบทๆฃ€ๆŸฅ๏ผˆๅซ้…็ฝฎๆ‘˜่ฆ๏ผ‰
  POST /api/overview        ็”Ÿๆˆๅˆๅง‹ๆ€ป่งˆ๏ผˆSSE ๆตๅผ๏ผ‰
  POST /api/followup        ่ฟฝ้—ฎๅ›ž็ญ”๏ผˆSSE ๆตๅผ๏ผ‰
  POST /api/decompose       ้—ฎ้ข˜ๆ‹†่งฃ๏ผˆ้žๆตๅผ๏ผŒ่ฟ”ๅ›ž QuestionPlan JSON๏ผ‰

SSE ๆตๅผๅ่ฎฎ๏ผˆไธŽๅ‰็ซฏ streamFromApi ๅ…ผๅฎน๏ผ‰๏ผš
  data: {"type": "chunk", "content": "..."}
  data: {"type": "metadata", "is_off_topic": false, "off_topic_hint": null}
  data: [DONE]

thread_id๏ผš
  ๆฏไธช่ฏทๆฑ‚ไปŽ่ฏทๆฑ‚ไฝ“็š„ thread_id ๅญ—ๆฎต่ฏปๅ–๏ผˆๅ‰็ซฏไผ  sessionId๏ผ‰
  ไฝœไธบ LangGraph config["configurable"]["thread_id"] ไผ ๅ…ฅ
"""

from __future__ import annotations

import json
import os
import uuid

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field

from agent.config import get_settings
from agent.graph import graph
from agent.state import AgentState, BubbleNode, LearningDocument
from agent.utils.security import sanitize_text, sanitize_document, check_query_safety

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# App ๅˆๅง‹ๅŒ–
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

app = FastAPI(
    title="LatentLearn Agent API",
    description="LangGraph-based AI agent backend for LatentLearn",
    version="0.1.0",
)

cors_origins = os.environ.get("AGENT_CORS_ORIGINS", "http://localhost:3000").split(",")
app.add_middleware(
    CORSMiddleware,
    allow_origins=[o.strip() for o in cors_origins],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Request / Response ๆจกๅž‹
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class OverviewRequest(BaseModel):
    thread_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    document: dict
    language: str = "en"


class FollowUpRequest(BaseModel):
    thread_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    document: dict
    conversation_path: list[dict] = []
    user_query: str
    anchor_text: str | None = None
    language: str = "en"
    skip_decomposition: bool = False


class DecomposeRequest(BaseModel):
    thread_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    document: dict
    query: str
    language: str = "en"


class TreeWriterRequest(BaseModel):
    thread_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    nodes: list[dict]
    questions: list[dict]
    current_node_id: str | None = None
    quote_refs: list[dict] = []
    language: str = "en"


class SummarizePathRequest(BaseModel):
    thread_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    conversation_path: list[dict] = []
    language: str = "en"


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ๅทฅๅ…ทๅ‡ฝๆ•ฐ
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

def _sse(data: str) -> str:
    return f"data: {data}\n\n"


def _make_config(thread_id: str) -> dict:
    """็”Ÿๆˆ LangGraph ่ฐƒ็”จ้…็ฝฎ๏ผŒthread_id ไฝœไธบ checkpointer key"""
    return {"configurable": {"thread_id": thread_id}}


async def _stream_graph_response(initial_state: AgentState, thread_id: str):
    """
    ้€š่ฟ‡ graph.astream_events() ็›‘ๅฌ LLM ๆตๅผ token๏ผŒ
    ไปฅ SSE ๆ ผๅผ้€ๅ—ๆŽจ้€็ป™ๅ‰็ซฏใ€‚
    ๆœ€็ปˆๅ‘้€ metadata ไบ‹ไปถ๏ผˆis_off_topic ็ญ‰๏ผ‰๏ผŒ็„ถๅŽ [DONE]ใ€‚
    """
    config = _make_config(thread_id)
    final_state: dict = {}

    # ๆตๅผๆ€่€ƒๅ— (Thinking Block) ๅฎžๆ—ถ่ฟ‡ๆปคๅ™จ็š„็Šถๆ€ๅ˜้‡
    accumulated = ""
    has_thought = False
    thought_ended = False
    yielded_length = 0

    async for event in graph.astream_events(initial_state, config=config, version="v2"):
        kind = event.get("event", "")

        # LLM ๆตๅผ token๏ผšๅชๅ…่ฎธ tutor ่Š‚็‚น็š„ๅ›ž็ญ”่ฟ›ๅ…ฅๅ‰็ซฏๆญฃๆ–‡ใ€‚
        # decomposer / tree-writer ็ญ‰็ป“ๆž„ๅŒ– JSON ่Š‚็‚น็š„ token ๅฟ…้กป่ฟ‡ๆปคๆމ๏ผŒ
        # ๅฆๅˆ™ไผšๆŠŠ {"decomposed": ...} ไน‹็ฑปๅ†…ๅฎนๆ˜พ็คบๆˆๅ›ž็ญ”ใ€‚
        if kind == "on_chat_model_stream":
            metadata = event.get("metadata", {}) or {}
            node_name = metadata.get("langgraph_node")
            if node_name != "tutor":
                continue
            # ่ฟ‡ๆปคๆމๆ€ป็ป“่ฐƒ็”จ็š„ stream๏ผŒ้˜ฒๆญขๅฎƒๆฑกๆŸ“ๅ‰็ซฏ็š„ๆ€ป่งˆๆฐ”ๆณก
            tags = event.get("tags", []) or []
            if "document_summary" in tags:
                continue
            chunk = event.get("data", {}).get("chunk")
            if chunk and hasattr(chunk, "content") and chunk.content:
                accumulated += chunk.content

                # A. ็กฎๅฎšๆ˜ฏๅฆๅŒ…ๅซๆ€่€ƒๆ ‡็ญพ
                if not has_thought and not thought_ended:
                    if "<thought>" in accumulated or "<think>" in accumulated:
                        has_thought = True
                    elif len(accumulated) >= 30:
                        # ็งฏ็ดฏไบ† 30 ไธชๅญ—ไปๆ— ๆ€่€ƒๆ ‡็ญพๅ‰็ผ€๏ผŒ่ฏดๆ˜Žๆจกๅž‹ๆฒกๆœ‰่ฟ›ๅ…ฅ Thinking ๆจกๅผ๏ผŒ็›ดๆŽฅๆ”พ่กŒ
                        thought_ended = True

                # B. ๅฆ‚ๆžœๅœจๆ€่€ƒๆจกๅผไธญ๏ผŒๆฃ€ๆต‹็ป“ๆŸๆ ‡็ญพๅนถๅšๅˆ†ๅ‰ฒ
                if has_thought and not thought_ended:
                    if "</thought>" in accumulated:
                        thought_ended = True
                        start_idx = accumulated.find("</thought>") + len("</thought>")
                        to_yield = accumulated[start_idx:]
                        if to_yield:
                            yield _sse(json.dumps({"type": "chunk", "content": to_yield}))
                        yielded_length = len(accumulated)
                    elif "</think>" in accumulated:
                        thought_ended = True
                        start_idx = accumulated.find("</think>") + len("</think>")
                        to_yield = accumulated[start_idx:]
                        if to_yield:
                            yield _sse(json.dumps({"type": "chunk", "content": to_yield}))
                        yielded_length = len(accumulated)

                # C. ๅฆ‚ๆžœๅทฒ็ป้€€ๅ‡บๆ€่€ƒๆจกๅผ๏ผŒๆญฃๅธธๆตๅผ่พ“ๅ‡บ
                if thought_ended:
                    if len(accumulated) > yielded_length:
                        to_yield = accumulated[yielded_length:]
                        yield _sse(json.dumps({"type": "chunk", "content": to_yield}))
                        yielded_length = len(accumulated)

        # ๅ›พๆ‰ง่กŒๅฎŒๆฏ•๏ผŒๅ–ๆœ€็ปˆ state
        elif kind == "on_chain_end" and event.get("name") == "LangGraph":
            output = event.get("data", {}).get("output", {})
            if isinstance(output, dict):
                final_state = output

    # ๅ‘้€ metadata
    yield _sse(json.dumps({
        "type": "metadata",
        "is_off_topic": final_state.get("is_off_topic", False),
        "off_topic_hint": final_state.get("off_topic_hint"),
    }))
    yield _sse("[DONE]")


async def _stream_safety_warning(warning_text: str):
    """ๅฝ“่งฆๅ‘่พ“ๅ…ฅๅฎ‰ๅ…จๆ‹ฆๆˆชๆ—ถ๏ผŒไผ˜้›…่ฟ”ๅ›ž SSE ๆต๏ผŒๅ‘Š็Ÿฅ่ญฆๅ‘Šไฟกๆฏๅนถไธๅดฉๆบƒๅ‰็ซฏใ€‚"""
    yield _sse(json.dumps({"type": "chunk", "content": warning_text}))
    yield _sse(json.dumps({
        "type": "metadata",
        "is_off_topic": True,
        "off_topic_hint": "safety-alert",
    }))
    yield _sse("[DONE]")


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Routes
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@app.get("/health")
async def health():
    settings = get_settings()
    return {"status": "ok", **settings}


@app.post("/api/overview")
async def overview(req: OverviewRequest):
    # ้˜ฒๅพกๆธ…ๆด—ๆ–‡ๆกฃ๏ผŒๅฝปๅบ•ๅ‰ฅ็ฆป HTML ๆณจๅ…ฅๅ’Œ XSS ่„šๆœฌ
    safe_doc = sanitize_document(req.document)

    initial_state = AgentState(
        thread_id=req.thread_id,
        document=safe_doc,  # type: ignore[arg-type]
        conversation_path=[],
        user_query="",
        anchor_text=None,
        language=req.language,  # type: ignore[arg-type]
        mode="overview",
        skip_decomposition=True,
        decomposed_questions=[],
        needs_decomposition=False,
        answer="",
        is_off_topic=False,
        off_topic_hint=None,
    )
    return StreamingResponse(
        _stream_graph_response(initial_state, req.thread_id),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )


@app.post("/api/followup")
async def followup(req: FollowUpRequest):
    # 1. ๅ‡€ๅŒ–็”จๆˆทๆ้—ฎๅŠๅˆ’่ฏ
    clean_query = sanitize_text(req.user_query)
    clean_anchor = sanitize_text(req.anchor_text)

    # 2. ๆฃ€ๆŸฅ่พ“ๅ…ฅๅฎ‰ๅ…จๅˆ่ง„ๆ€ง๏ผˆ้•ฟๅบฆใ€ๆ็คบ่ฏๆณจๅ…ฅใ€่ฟ่ง„ๆœ‰ๆฏ’ๅ†…ๅฎน๏ผ‰
    is_safe, warning_msg = check_query_safety(clean_query)
    if not is_safe and warning_msg:
        return StreamingResponse(
            _stream_safety_warning(warning_msg),
            media_type="text/event-stream",
            headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
        )

    # 3. ้˜ฒๅพกๆธ…ๆด—ๆ–‡ๆกฃ
    safe_doc = sanitize_document(req.document)

    initial_state = AgentState(
        thread_id=req.thread_id,
        document=safe_doc,  # type: ignore[arg-type]
        conversation_path=req.conversation_path,  # type: ignore[arg-type]
        user_query=clean_query or "",
        anchor_text=clean_anchor,
        language=req.language,  # type: ignore[arg-type]
        mode="followup",
        skip_decomposition=req.skip_decomposition,
        decomposed_questions=[],
        needs_decomposition=False,
        answer="",
        is_off_topic=False,
        off_topic_hint=None,
    )
    return StreamingResponse(
        _stream_graph_response(initial_state, req.thread_id),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )


@app.post("/api/tree-writer")
async def tree_writer(req: TreeWriterRequest):
    initial_state = AgentState(
        thread_id=req.thread_id,
        document={"type": "topic", "title": "", "content": "", "structure": []},  # type: ignore[arg-type]
        conversation_path=[],
        user_query="",
        anchor_text=None,
        language=req.language,  # type: ignore[arg-type]
        mode="tree_writer",
        skip_decomposition=True,
        decomposed_questions=[],
        needs_decomposition=False,
        tree_nodes=req.nodes,  # type: ignore[typeddict-item]
        tree_questions=req.questions,  # type: ignore[typeddict-item]
        current_node_id=req.current_node_id,
        quote_refs=req.quote_refs,  # type: ignore[typeddict-item]
        tree_mounts=[],
        answer="",
        is_off_topic=False,
        off_topic_hint=None,
    )
    config = _make_config(req.thread_id)
    final_state = await graph.ainvoke(initial_state, config=config)
    return {"mounts": final_state.get("tree_mounts", [])}


@app.post("/api/decompose")
async def decompose(req: DecomposeRequest):
    """
    ้žๆตๅผ๏ผš่ฟ่กŒ decomposer node๏ผŒ่ฟ”ๅ›ž QuestionPlan JSONใ€‚
    ไธŽๅ‰็ซฏ decomposeQuery() ๅ‡ฝๆ•ฐๆœŸๆœ›็š„ๆ ผๅผๅฎŒๅ…จๅ…ผๅฎนใ€‚
    """
    # 1. ๅ‡€ๅŒ–ๆ้—ฎๅนถๆ ก้ชŒๅฎ‰ๅ…จๅˆ่ง„
    clean_query = sanitize_text(req.query)
    is_safe, warning_msg = check_query_safety(clean_query)
    if not is_safe and warning_msg:
        return {
            "summary": warning_msg,
            "questions": [],
        }

    # 2. ้˜ฒๅพกๅ‡€ๅŒ–ๆ–‡ๆกฃ
    safe_doc = sanitize_document(req.document)

    initial_state = AgentState(
        thread_id=req.thread_id,
        document=safe_doc,  # type: ignore[arg-type]
        conversation_path=[],
        user_query=clean_query or "",
        anchor_text=None,
        language=req.language,  # type: ignore[arg-type]
        mode="decompose",
        skip_decomposition=False,
        decomposed_questions=[],
        needs_decomposition=False,
        answer="",
        is_off_topic=False,
        off_topic_hint=None,
    )

    config = _make_config(req.thread_id)
    final_state = await graph.ainvoke(initial_state, config=config)

    questions = final_state.get("decomposed_questions", [])
    needs = final_state.get("needs_decomposition", False)

    if not needs or len(questions) < 2:
        lang = req.language
        return {
            "summary": "This is a single question, better to answer directly." if lang == "en"
                       else "่ฟ™ๆ˜ฏไธ€ไธชๅ•ไธ€้—ฎ้ข˜๏ผŒ็›ดๆŽฅๅ›ž็ญ”ๆ›ดๅˆ้€‚ใ€‚",
            "questions": [],
        }

    return {
        "summary": (
            f"I identified {len(questions)} points of confusion to explain sequentially."
            if req.language == "en"
            else f"ๆˆ‘่ฏ†ๅˆซๅˆฐ {len(questions)} ไธชๅฏไปฅ้กบๅบ่ฎฒ่งฃ็š„็–‘ๆƒ‘็‚นใ€‚"
        ),
        "questions": questions,
    }


@app.post("/api/summarize-path")
async def summarize_path_route(req: SummarizePathRequest):
    """
    ๅฎšๆœŸๅฏนๅฏน่ฏ่ทฏๅพ„่ฟ›่กŒๆๅ–ๆฑ‡ๆ€ป๏ผŒๆไพ›ๅทฒๆŽŒๆกใ€ๆœชๅ†ณ้—ฎ้ข˜ๅ’Œๆ€ป็ป“ๅปบ่ฎฎ
    """
    from agent.nodes.memory_summarizer import summarize_path
    return await summarize_path(req.conversation_path, req.language) # type: ignore[arg-type]