文章类型添加
This commit is contained in:
1 parent
918e65d8d3
commit
a0a6227368
14 files changed
+1089
-57
No files matched your search
@@ -126,6 +126,10 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
|
||||
app.state.ai_writing_session_store = make_ai_writing_session_store(sf)
|
||||
|
||||
from deerflow.persistence.article_types import make_article_type_store
|
||||
|
||||
app.state.article_type_store = make_article_type_store(sf)
|
||||
|
||||
# Run event store (has its own factory with config-driven backend selection)
|
||||
run_events_config = getattr(config, "run_events", None)
|
||||
app.state.run_event_store = make_run_event_store(run_events_config)
|
||||
@@ -231,6 +235,11 @@ def get_ai_writing_session_store(request: Request):
|
||||
return getattr(request.app.state, "ai_writing_session_store", None)
|
||||
|
||||
|
||||
def get_article_type_store(request: Request):
|
||||
"""Return the article type store, or None when not configured."""
|
||||
return getattr(request.app.state, "article_type_store", None)
|
||||
|
||||
|
||||
def get_run_context(request: Request) -> RunContext:
|
||||
"""Build a :class:`RunContext` from ``app.state`` singletons.
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
"""AI 写作路由 —— 独立于原有路由,前缀 /api/ai-writing/
|
||||
|
||||
POST /api/ai-writing/start 启动写作流程,返回 session_id
|
||||
GET /api/ai-writing/{id}/stream SSE 流(进度/干预/草稿事件)
|
||||
POST /api/ai-writing/{id}/resume 用户干预响应,恢复流程
|
||||
GET /api/ai-writing/{id}/state 查询当前流程状态
|
||||
GET /api/ai-writing/sessions 列出用户的会话历史
|
||||
GET /api/ai-writing/sessions/{id} 获取单个历史会话
|
||||
PATCH /api/ai-writing/sessions/{id} 重命名会话标题
|
||||
DELETE /api/ai-writing/sessions/{id} 删除会话
|
||||
POST /api/ai-writing/start 启动写作流程,返回 session_id
|
||||
GET /api/ai-writing/{id}/stream SSE 流(进度/干预/草稿事件)
|
||||
POST /api/ai-writing/{id}/resume 用户干预响应,恢复流程
|
||||
GET /api/ai-writing/{id}/state 查询当前流程状态
|
||||
GET /api/ai-writing/sessions 列出用户的会话历史
|
||||
GET /api/ai-writing/sessions/{id} 获取单个历史会话
|
||||
PATCH /api/ai-writing/sessions/{id} 重命名会话标题
|
||||
DELETE /api/ai-writing/sessions/{id} 删除会话
|
||||
GET /api/ai-writing/article-types 列出所有文章类型
|
||||
POST /api/ai-writing/article-types 新增文章类型
|
||||
PATCH /api/ai-writing/article-types/{id} 更新文章类型
|
||||
DELETE /api/ai-writing/article-types/{id} 删除文章类型
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -59,6 +63,36 @@ class RenameSessionRequest(BaseModel):
|
||||
title: str
|
||||
|
||||
|
||||
class ArticleTypeRequest(BaseModel):
|
||||
key: str
|
||||
label: str
|
||||
description: Optional[str] = None
|
||||
prompt_hint: Optional[str] = None
|
||||
default_word_count: int = 800
|
||||
sort_order: int = 0
|
||||
|
||||
|
||||
class UpdateArticleTypeRequest(BaseModel):
|
||||
key: Optional[str] = None
|
||||
label: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
prompt_hint: Optional[str] = None
|
||||
default_word_count: Optional[int] = None
|
||||
sort_order: Optional[int] = None
|
||||
|
||||
|
||||
class ArticleTypeResponse(BaseModel):
|
||||
id: str
|
||||
key: str
|
||||
label: str
|
||||
description: Optional[str] = None
|
||||
prompt_hint: Optional[str] = None
|
||||
default_word_count: int
|
||||
sort_order: int
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
id: str
|
||||
user_id: Optional[str] = None
|
||||
@@ -93,6 +127,9 @@ _session_interventions: dict[str, list] = {}
|
||||
# session_id → True if session ended with error
|
||||
_session_error_flags: dict[str, bool] = {}
|
||||
|
||||
# session_id → valid_article_types(list[dict] with key/label)
|
||||
_session_article_types: dict[str, list[dict]] = {}
|
||||
|
||||
|
||||
# ── 工具函数 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -100,7 +137,7 @@ def _sse(event: str, data: dict) -> str:
|
||||
return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def _make_config(session_id: str, model_name: str = "") -> dict:
|
||||
def _make_config(session_id: str, model_name: str = "", valid_article_types: list[dict] | None = None) -> dict:
|
||||
return {
|
||||
"configurable": {
|
||||
"thread_id": session_id,
|
||||
@@ -109,6 +146,8 @@ def _make_config(session_id: str, model_name: str = "") -> dict:
|
||||
# 把 SSE 队列注入,供草稿/大纲节点直接推流式 chunk
|
||||
"sse_queue": _event_queues.get(session_id),
|
||||
"sse_session_id": session_id,
|
||||
# 动态文章类型列表,intent_parser 从此处读取有效枚举
|
||||
"valid_article_types": valid_article_types or _session_article_types.get(session_id),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,7 +163,7 @@ def _truncate_title(text: str, max_len: int = 50) -> str:
|
||||
async def start_writing(body: StartWritingRequest, request: Request):
|
||||
"""启动写作流程,返回 session_id。"""
|
||||
from deerflow.agents.ai_writing.graph import AI_WRITING_GRAPH
|
||||
from app.gateway.deps import get_ai_writing_session_store, get_current_user
|
||||
from app.gateway.deps import get_ai_writing_session_store, get_article_type_store, get_current_user
|
||||
|
||||
session_id = str(uuid.uuid4())
|
||||
queue: asyncio.Queue = asyncio.Queue()
|
||||
@@ -132,6 +171,18 @@ async def start_writing(body: StartWritingRequest, request: Request):
|
||||
_session_model_names[session_id] = body.model_name
|
||||
_session_interventions[session_id] = []
|
||||
|
||||
# 加载动态文章类型列表,注入给 intent_parser 节点
|
||||
article_type_store = get_article_type_store(request)
|
||||
valid_article_types: list[dict] | None = None
|
||||
if article_type_store is not None:
|
||||
try:
|
||||
records = await article_type_store.list()
|
||||
if records:
|
||||
valid_article_types = [{"key": r["key"], "label": r["label"]} for r in records]
|
||||
except Exception:
|
||||
logger.exception("ai_writing: failed to load article types for session=%s", session_id)
|
||||
_session_article_types[session_id] = valid_article_types or []
|
||||
|
||||
# 持久化会话记录(DB 可能未配置,则跳过)
|
||||
repo = get_ai_writing_session_store(request)
|
||||
user_id = await get_current_user(request)
|
||||
@@ -165,7 +216,7 @@ async def start_writing(body: StartWritingRequest, request: Request):
|
||||
"review_result": None,
|
||||
"last_user_intervention": None,
|
||||
}
|
||||
config = _make_config(session_id, body.model_name)
|
||||
config = _make_config(session_id, body.model_name, valid_article_types=valid_article_types)
|
||||
|
||||
asyncio.create_task(_stream_graph_segment(session_id, initial_state, config, AI_WRITING_GRAPH))
|
||||
return StartWritingResponse(session_id=session_id)
|
||||
@@ -228,6 +279,79 @@ async def delete_session(session_id: str, request: Request):
|
||||
return {"success": True}
|
||||
|
||||
|
||||
@router.get("/article-types", response_model=list[ArticleTypeResponse])
|
||||
async def list_article_types(request: Request):
|
||||
"""列出所有文章类型,按 sort_order 升序排列。"""
|
||||
from app.gateway.deps import get_article_type_store
|
||||
|
||||
store = get_article_type_store(request)
|
||||
if store is None:
|
||||
return []
|
||||
return await store.list()
|
||||
|
||||
|
||||
@router.post("/article-types", response_model=ArticleTypeResponse, status_code=201)
|
||||
async def create_article_type(body: ArticleTypeRequest, request: Request):
|
||||
"""新增文章类型。key 必须全局唯一。"""
|
||||
from app.gateway.deps import get_article_type_store
|
||||
|
||||
store = get_article_type_store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Article type store not available")
|
||||
existing = await store.get_by_key(body.key)
|
||||
if existing is not None:
|
||||
raise HTTPException(status_code=409, detail=f"Article type key '{body.key}' already exists")
|
||||
return await store.create(
|
||||
key=body.key,
|
||||
label=body.label,
|
||||
description=body.description,
|
||||
prompt_hint=body.prompt_hint,
|
||||
default_word_count=body.default_word_count,
|
||||
sort_order=body.sort_order,
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/article-types/{article_type_id}", response_model=ArticleTypeResponse)
|
||||
async def update_article_type(article_type_id: str, body: UpdateArticleTypeRequest, request: Request):
|
||||
"""更新文章类型字段(只传需要修改的字段)。"""
|
||||
from app.gateway.deps import get_article_type_store
|
||||
|
||||
store = get_article_type_store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Article type store not available")
|
||||
# 如果修改了 key,检查唯一性
|
||||
if body.key is not None:
|
||||
existing = await store.get_by_key(body.key)
|
||||
if existing is not None and existing["id"] != article_type_id:
|
||||
raise HTTPException(status_code=409, detail=f"Article type key '{body.key}' already exists")
|
||||
|
||||
_UNSET = object.__new__(object)
|
||||
kwargs = {}
|
||||
for field in ("key", "label", "description", "prompt_hint", "default_word_count", "sort_order"):
|
||||
val = getattr(body, field)
|
||||
if val is not None:
|
||||
kwargs[field] = val
|
||||
|
||||
updated = await store.update(article_type_id, **kwargs)
|
||||
if updated is None:
|
||||
raise HTTPException(status_code=404, detail="Article type not found")
|
||||
return updated
|
||||
|
||||
|
||||
@router.delete("/article-types/{article_type_id}")
|
||||
async def delete_article_type(article_type_id: str, request: Request):
|
||||
"""删除文章类型。"""
|
||||
from app.gateway.deps import get_article_type_store
|
||||
|
||||
store = get_article_type_store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Article type store not available")
|
||||
deleted = await store.delete(article_type_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="Article type not found")
|
||||
return {"success": True}
|
||||
|
||||
|
||||
@router.get("/{session_id}/stream")
|
||||
async def stream_progress(session_id: str):
|
||||
"""SSE 流:推送进度事件、干预请求、草稿内容。"""
|
||||
@@ -427,6 +551,7 @@ async def _stream_graph_segment(
|
||||
_session_user_ids.pop(session_id, None)
|
||||
_session_interventions.pop(session_id, None)
|
||||
_session_error_flags.pop(session_id, None)
|
||||
_session_article_types.pop(session_id, None)
|
||||
|
||||
|
||||
def _event_type(evt: dict) -> str:
|
||||
|
||||
Reference in new issue
Block a user