Spaces:
Sleeping
Sleeping
Download main.py from howcloudy/latentlearn-agent: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/howcloudy/latentlearn-agent/resolve/main/main.py
- Command line
-
hf download hf://spaces/howcloudy/latentlearn-agent/main.py
-
curl -L -o main.py https://huggingface.co/spaces/howcloudy/latentlearn-agent/resolve/main/main.py
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 | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| async def health(): | |
| settings = get_settings() | |
| return {"status": "ok", **settings} | |
| 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"}, | |
| ) | |
| 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"}, | |
| ) | |
| 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", [])} | |
| 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, | |
| } | |
| 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] | |