Spaces:
Sleeping
Sleeping
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]
|