howcloudy's picture
deploy: sync agent updates to Hugging Face Space
dc8f5ff
Raw History Blame Contribute Delete
14.6 kB
"""
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]