Skip to content
Human-in-the-Loop · Design

人在回路(Human-in-the-Loop)详细设计

适用范围:novelcraft/ 后端创作流程 + frontend/ 工作台交互 版本:v1.5(阶段确认门禁) 配套:docs/小说Agent需求文档_v1.4.md、docs/变更记录/

目录


1. 设计目标

把「AI 生成 → 作者被动接受」改成「AI 生成 → 作者决定是否放行」。具体目标:

目标 手段
生成前先对齐,避免生成后再推翻 阶段确认门禁(kind=confirm)
每个阶段产出都能被否决 人工审核(kind=review)
生成中能追问 提问 interrupt(kind=question)
讨论不污染创作上下文 旁路 sidecar(不写 checkpoint、不进 State)
挂起时长不受限(分钟 ~ 数天) checkpoint 落 TiDB
每个挂起点可回溯 每次 interrupt 都是一个 checkpoint

2. 底层机制

2.1 interrupt() / Command(resume=...) 语义

挂起:节点内调用 interrupt(payload),抛 LangGraph 内部异常 → 图在当前步骤前保存 checkpoint 到 TiDB → 停止。此时 state.next == ["gate"] 或 ["human_review"]。

恢复:API 用 Command(resume=decision) 重新驱动图。

核心语义(最易误解的一点):恢复时节点函数从头重新执行一遍,直到再次运行到 interrupt() 那一行——第二次调用直接返回注入的 decision,不再抛异常。

novelcraft/app/core/nodes.py:1911-1917
    decision = interrupt({
        "kind": "confirm",
        "stage": stage,
        "round": round_no,
        "discussion_id": discussion_id,
        "brief": brief,
    })

第一次执行:读 State → 重建 brief → 抛异常挂起,局部变量全部丢失。 resume 后:重新读 State → 重新从 sidecar 拉讨论日志 → 重建 brief → 这一行直接返回决策。

2.2 重放语义带来的约束

因为节点是重放的,跨轮状态只能存在两个地方:State 字段,或 resume 回传的数据。

novelcraft/app/core/nodes.py:1900-1927
    round_no = int(gate.get("round", 0)) + 1          # 轮次只能从 State 推算
    discussion_id = gate.get("discussion_id") or sidecar.new_discussion_id()
    ...
    echoed = decision.get("discussion_id")            # discussion_id 由前端原样回传
    if echoed and str(echoed) != str(discussion_id):
        discussion_id = str(echoed)
        gate = {**gate, "discussion_id": discussion_id}

同样地,brief 每次重放都会用最新的 State + 最新的讨论日志重建,因此作者讨论出来的内容能反映到新一轮门禁卡上。

2.3 命名约束

节点名 gate 与 State 字段 stage_gate 不同名,是因为 LangGraph 限制节点名不能与 State 键同名:

novelcraft/app/core/nodes.py:1993-1996
NODES = {
    "router": router_node,
    # 注意:节点名不能与 State 键同名(LangGraph 限制),故节点叫 gate,State 字段叫 stage_gate
    "gate": stage_gate_node,

3. 三个挂起点

3.1 总览

kind 节点 时机 恢复 API 恢复入口校验
confirmstage_gate_node 进入 worldbuilding / character / outline / writing 前POST /projects/{id}/resume{"human_review","gate"} & state.next
reviewhuman_review_node 每个阶段产出后POST /projects/{id}/review"human_review" in state.next
question保留兼容代码:事件构造函数(interrupt_question_event)与 /resume 的 action=answer 分支都还在,但 没有任何节点发出 kind=question——当前图只有 confirm 与 review 两个挂起点。 同上
novelcraft/app/core/nodes.py:1847-1848 · novelcraft/app/core/prompts.py:322-323
# nodes.py:1848 —— 需要「先对齐再创作」的阶段;reviewing / polishing 是对产物的加工,不设门禁
STAGE_GATES = {"worldbuilding", "character", "outline", "writing"}
# prompts.py:323 —— 门禁轮次软上限:超过后仍要求确认,只在 tips 中提示可直接确认
GATE_MAX_ROUNDS = 5

3.2 kind=confirm:阶段确认门禁

触发:router 判定当前阶段在 STAGE_GATES 内且门禁未对当前作用域放行。

novelcraft/app/core/graph.py:54-64
    gate = state.get("stage_gate") or {}
    # 已放行且仍适用于当前章/卷(v1.5 J2):写作按章、大纲按卷确认,避免每章重复询问
    if NODES.gate_applies_to_current_scope(gate, stage, state):
        return _node_for(stage)                    # 已放行(§9.5.6)
    if stage in STAGE_GATES:
        # J18:写作前先定章纲——当前章章纲未生成时先走「章纲生成」节点,
        # 随后进门禁由作者就章纲探讨确认,确认后才撰写正文
        if stage == "writing" and state.get("outline") and not NODES.has_chapter_outline(state):
            return "chapter_outline"
        return "gate"                              # 先与作者对齐,再创作

payload(下发前端):

{
  "kind": "confirm",
  "stage": "writing",
  "round": 1,
  "discussion_id": "d_xxxxxxxxxx",
  "brief": {
    "title": "第 5 章《玉佩》",
    "goal": "请先确认本章章纲……(已按章纲预取 3 条写作资料)",
    "questions": [{"id": "pov", "label": "本章视角 / 时态", "placeholder": "第三人称限知 · 过去时", "required": false}],
    "checklist": ["已确认结局走向"],
    "tips": ["本章要回收 / 埋下哪些伏笔,现在说最有效"],
    "chapter_outline": {"title": "...", "summary": "...", "target_word_count": 3000},
    "foreshadow_plan": {"plant": ["..."], "payoff": ["..."]},
    "new_characters": [{"name": "..."}]
  }
}

brief 由 build_gate_brief() 构造,只读 State 与 sidecar,不产出正文。问题模板在 STAGE_GATE_TEMPLATE(nodes.py:1874-1915)。

decision(前端回传):

字段 说明
actionconfirm(放行)/ revise(自环,round+1 重新下发卡片)
feedback / notes 作者意见;notes 为 dict 时落盘(J37)
discussion_id 原样回传,保持同一轮对话连续性
foreshadow{plant:[], payoff:[]} 勾选的伏笔(J21)
characters 勾选的新角色名列表(J22)

恢复后的行为:

novelcraft/app/core/nodes.py:1941-1953
    updates: Dict[str, Any] = {
        "stage_gate": {
            **gate, "stage": stage, "round": round_no,
            "confirmed": confirmed, "brief": brief,
            "notes": decision.get("notes") if isinstance(decision.get("notes"), dict) else {},
        },
        "human_decision_pending": not confirmed,
    }

确认时按勾选结果登记伏笔与新角色,并清空临时计划字段:

novelcraft/app/core/nodes.py:1966-1988
            updates["foreshadow"] = _apply_foreshadow_plan(state, eff, co, cur_idx)
        updates["chapter_foreshadow_plan"] = {}
        ...
            updates["character_settings"] = _apply_new_characters(state, eff_nc, cur_idx)
        updates["chapter_new_characters"] = []

未回传 foreshadow / characters(旧客户端)时视为全选,保持兼容。

3.3 kind=review:人工审核

payload:

novelcraft/app/core/nodes.py:1567-1576
    payload = {
        "kind": "review",
        "stage": stage,
        "project_id": state["project_id"],
        "chapter_id": chapter_id,
        "chapter_index": idx,
        "issues": findings,
        # 单独下发,按"你上一轮提的要求"的口径展示
        "rejected_feedback": rejected_feedback,
    }

issues 是 ReviewIssue{kind: ooc|foreshadow|conflict|logic, severity, description, chapter_id, paragraph_index, suggestion}。已剔除 rejected=True 的条目(见 §10.4)。

decision 与三种动作:

action 行为
approve 推进 current_stage、清空 review_issues、同步章节 status;仅 reviewing / polishing 阶段通过才定稿入库(writing 阶段只是确认草稿,不索引)
modify 只写白名单字段(world_setting/character_settings/outline/chapters/foreshadow/project_meta/llm_config),同样推进阶段
reject 写入一条 rejected=True 的 ReviewIssue,route_after_human_review 直连当前阶段节点重跑
novelcraft/app/core/nodes.py:1626-1634
        # v1.5(J2):通过时推进 current_stage,交回 router 统一分发(含阶段门禁)
        nxt = STAGE_FLOW.get(stage)
        # J16:润色是**可选工序** —— 审核通过时未明确要求润色(decision.polish)就跳过
        if stage == "reviewing" and not decision.get("polish"):
            nxt = STAGE_FLOW.get("polishing")      # 跳过润色 → "_next_chapter"
        if nxt:
            updates["current_stage"] = nxt

状态推进与定稿入库:

novelcraft/app/core/nodes.py:1651-1663
        if stage in ("writing", "reviewing", "polishing") and chapter_id and idx < len(chapters) and not polish_applied:
            new_status = {"writing": "draft", "reviewing": "reviewed", "polishing": "reviewed"}[stage]
            ...
        if stage in ("reviewing", "polishing"):
            _index_approved_chapter(state, polished_chapter)

润色候选(J15):polishing 阶段只产出候选,不改正文。作者在「左原文 / 右润色」对比视图确认后才落盘;discard_polish=true 则保留原文。

3.4 kind=question:生成中追问(当前无调用点)

事件构造函数 interrupt_question_event() 与恢复走 /resume 的 action=answer 分支都还在, 但 nodes.py 全文只有两处 interrupt()(kind=review 与 kind=confirm),没有任何节点发出 kind=question:

novelcraft/app/api/routers/creation.py:414-417
    action = request.action or ("answer" if request.answer is not None else "confirm")
    if action == "answer":
        # kind=question 的 interrupt 恢复需返回 {"data": ...}
        resume_data: Dict[str, Any] = {"data": request.answer or ""}

4. 状态机与路由

4.1 阶段流转

novelcraft/app/core/nodes.py:1838-1845
STAGE_FLOW = {
    "worldbuilding": "character",
    "character": "outline",
    "outline": "writing",
    "writing": "reviewing",
    "reviewing": "polishing",
    "polishing": "_next_chapter",
}

4.2 router 是唯一分发点

覆盖四条路径:首次进入 / 阶段推进 / 下一章 / 完成态恢复。这样门禁才能无遗漏地覆盖每个创作阶段(J2)。human_review 与 next_chapter 都改为设好 current_stage 后回 router,不再直连阶段节点。

图接线见 novelcraft/app/core/graph.py:89-143。

4.3 门禁作用域:按章 / 按卷

novelcraft/app/core/nodes.py:1854-1867
def _gate_scope_changed(gate, stage, state) -> bool:
    """写作按章、大纲按卷确认:章/卷推进后,已确认的门禁不再适用(需重新确认)。"""
    if stage == "writing":
        return gate.get("chapter_index") != state.get("current_chapter_index", 0)
    if stage == "outline":
        return gate.get("volume_index") != len(state.get("outline", []) or [])
    return False
def gate_applies_to_current_scope(gate, stage, state) -> bool:
    if not gate or gate.get("stage") != stage or not gate.get("confirmed"):
        return False
    return not _gate_scope_changed(gate, stage, state)

第 5 章确认过不影响第 6 章重新确认;同一章内反复「继续」不再被拦。

4.4 驳回不重复门禁

novelcraft/app/core/graph.py:78-86
    if any(i.get("rejected") for i in review_issues):
        return _node_for(current_stage)      # 直连阶段节点重跑(不重复门禁)
    if current_stage == "_next_chapter":
        return "next_chapter"
    return "router"

已对齐过的事不该再问一遍。


5. 完整时序

以「撰写第 N 章」为例:

 1. 前端 POST /projects/{id}/run
 2. router ── writing 有门禁 ──→ gate
 3. router 发现无章纲 → chapter_outline(生成章纲 + 预取资料)→ 回 gate
 4. gate: interrupt(brief) 挂起 ── 下发 interrupt/confirm 卡
 5. 作者:右栏会话多轮讨论(POST /discuss,旁路,不写 checkpoint)
 6. 作者点「确认」→ POST /resume {action:"confirm", discussion_id, foreshadow, characters, notes}
 7. gate 重放 → 按勾选登记伏笔/新角色 → stage_gate.confirmed=True
 8. route_after_gate ──→ writing
      ├─ retrieved 事件:引用卡(章纲 + 未回收伏笔 + 角色名,k=8)
      └─ delta 事件:正文 token 流式进中间栏编辑器
 9. human_review: interrupt(review 卡) 挂起
10. 作者 approve → POST /review
      ├─ current_stage: writing → reviewing
      ├─ 章节 status: draft(注意:此时**不**入库)
      └─ 回到 router
11. reviewing(AI 审核,产出 issues)→ human_review 再次挂起
12. 作者 approve 且 polish=true → polishing(产出候选,不改正文)
      → human_review 下发「左原文 / 右润色」对比 → 采用才落盘
13. 定稿(reviewing 通过)→ 正文写进向量库
14. next_chapter → router → 下一章门禁

若审核通过时 polish=false,直接跳到 _next_chapter(润色不强制,可随时用 /polish/start 补做)。


6. 交互契约

6.1 事件帧(NDJSON)

Content-Type: application/x-ndjson,每帧一行。定义见 novelcraft/app/api/stream_events.py。

type 用途
stage 阶段切换
delta LLM token 增量,target 决定落在哪个面板:editor / review / polish / artifact / chat
retrieved 引用卡(hits 为结构化 {type,id,label,snippet,score})
interrupt 挂起卡,kind = confirm / review(question 的构造函数存在但无调用点,见 §3.4)
revised / applied 低成本修改通道(/revise-field、/revise-chapter)的产出 / 写回确认,见 §8
sources / suggestion / discuss 旁路讨论(/discuss)的引用卡、建议卡与会话帧
done / metrics / error 收尾 / 统计 / 错误

interrupt 帧:

{"type":"interrupt","kind":"confirm","payload":{"stage":"writing","round":1,"discussion_id":"d_x","brief":{...}}}
{"type":"interrupt","kind":"review","payload":{"stage":"reviewing","chapter_id":"ch_0004","issues":[...],"content":{...},"polish_candidate":{...}}}

6.2 payload 必须从 interrupt 任务里取

首轮 interrupt 的 payload 不落 checkpoint,所以不能只读 state.values:

novelcraft/app/api/routers/creation.py:220-233
            intr_payload: Dict[str, Any] = {}
            for t in (getattr(state, "tasks", None) or []):
                for i in (getattr(t, "interrupts", None) or []):
                    if isinstance(getattr(i, "value", None), dict):
                        intr_payload = i.value
                        break
            ...
            yield se.interrupt_confirm_event(
                intr_payload.get("stage") or gate.get("stage") or values.get("current_stage", ""),
                intr_payload.get("round") or gate.get("round", 1),
                intr_payload.get("discussion_id") or gate.get("discussion_id", ""),
                intr_payload.get("brief") or gate.get("brief") or {},
            )

6.3 API 入口

接口 请求 说明
POST /run{input?, llm_config?, force?} 启动/继续创作
POST /resume{action?, answer?, feedback?, notes?, discussion_id?, foreshadow?, characters?} 门禁决策 / 回答问题
POST /review{action, reason?, modifications?, discard_polish?, polish?} 人审决策
POST /discuss{message, scope?, target_id?, refs?, discussion_id?, checkpoint_id?, command?} 旁路讨论(不写 checkpoint)
POST /revise-field{field, instruction, target_ids?, discussion_id?, apply?} 局部改字段
POST /revise-chapter{instruction, chapter_id?} 按意见修订正文

force=true(J27)用于「重新生成本章」,只对本次 run 的首次写作有效,走进程内信号,不落 State。


7. 旁路讨论:门禁的多轮对话

作者在门禁卡上可以来回讨论 N 轮,但这些对话不进图。

novelcraft/app/core/sidecar.py:1-7
讨论是图**之外**的独立服务(§9.4.2「图挂起 ≠ 对话挂起」):
- **不推进图、不写 checkpoint**:可来回 N 轮,图上毫无痕迹。
- **会话历史只落 sidecar,绝不进 State**:避免重蹈 P0-5(State 膨胀)/ H7。
- **复用 H4 检索器**:RAG 能力从生成流程内扩展到旁路,回答附 `sources`。
- **AI 给「建议」不直接改稿**:落地走既有 PUT /state 或 POST /review{modify},不开后门。

存储:TiDB sidecar_events 表,append-only。

log_key 用途
{project_id} 统一会话流(run + discuss 事件),用于回放
{project_id}::{discussion_id} 单轮讨论明细

为什么要旁路:每次 interrupt 都是一个 checkpoint,若多轮讨论也走 interrupt,checkpoint 会随讨论轮次堆积;且讨论内容进入创作 State 会污染后续生成。旁路后,门禁只承载「最终确认」这一个动作。

门禁如何读到讨论内容:stage_gate_node 重放时从 sidecar 拉最近 20 条重建 brief:

novelcraft/app/core/nodes.py:1903-1909
    recent: List[Dict[str, Any]] = []
    try:
        recent = sidecar.discussion_log(pid, discussion_id).read(limit=20)
    except Exception:
        recent = []
    brief = build_gate_brief(stage, state, recent)

8. 低成本修改通道

驳回 = 一次完整阶段重跑(整章重写),成本高。真正低成本的修改路径不经过 interrupt:

接口 行为
POST /revise-field 局部改世界观 / 人设 / 大纲。提示词强约束「未提及部分逐字保留」,产出完整字段值草稿。apply=false 只出草稿;apply=true 按产出节点归属写回 State,不推进图、不触发重生成
POST /revise-chapter 按意见整章修订,流式输出到中间栏编辑器
PUT /chapters/{id}/paragraph/{i} 段落级直接编辑

apply=true 时挂起在门禁的节点归属处理:

novelcraft/app/api/routers/creation.py:508-513
            at_gate = "gate" in next_nodes
            writer = N.FIELD_WRITER_NODE.get(request.field, "router")
            # 挂起在门禁时以 router 身份写:router 仍会返回 gate,门禁不丢
            as_node = "router" if at_gate else writer
            await graph.aupdate_state(config, {request.field: merged}, as_node=as_node)

9. 持久化、并发与错误恢复

9.1 每次 interrupt 都是一个 checkpoint

checkpoint 落 TiDB(自研 TiDBSaver,因为官方 mysql saver 依赖 JSON_TABLE(),TiDB 不支持)。因此:

  • 挂起时长不受限,进程重启后可恢复
  • 每个挂起点天然可回溯(见 retention.py:里程碑永久保留 + 最近 20 步级,取值来自 settings.checkpoint_keep_recent)

9.2 并发纪律

novelcraft/app/api/in_flight.py:1-5
核心:只有「/run 流式响应正在进行」才算"图运行中"。
图停在 human_review 中断(流已结束、前端已收到 interrupt)属于静止态,允许裸 PUT /state。
  • track_run 在流式响应期间标记 thread 为运行中
  • 重复触发返回 409
  • 挂起态不算运行中,因此作者在审核卡上可以直接改 State

9.3 停在未知节点 = 异常

停在既非 gate 也非 human_review 的节点(最常见:LLM 连接失败导致节点抛错、图原地等待重试)没有任何卡片可操作:

novelcraft/app/api/routers/creation.py:251-262
        else:
            # J30:停在**其他**节点既没有人审/门禁卡片可操作,也不是正常结束。
            # 最常见的是节点执行失败后图原地暂停(例如 LLM 连接错误 APIConnectionError:
            # 节点抛错 → 图停在那个节点等待重试)。此前这里什么都不发,前端 phase 会
            # **永久停在 generating** —— 按钮显示「停止」,再点等于停止,观感就是
            # 「点击生成没有反应,也没有任何正文输出」。必须补发错误帧让前端能恢复。

必须补发 NODE_STALLED 错误帧,否则前端 UI 永久卡死。


10. 关键设计决策记录

10.1 J1 门禁:从「先生成后审核」到「先对齐后生成」

问题:POST /run 经 router 直接进阶段节点,先生成、后审核。作者在世界观/人设/大纲/撰写前收不到任何提示,不满意只能驳回重跑——每轮都是一次完整生成,成本高且不一定命中意图。

处理:新增 stage_gate 节点,进入四个创作阶段前先挂起对齐。

10.2 J2 router 唯一分发点

问题:human_review 与 next_chapter 的条件边直连阶段节点,绕过 router,门禁无处插入;STAGE_FLOW 判定逻辑散落在各路由函数。

处理:两条路径都改为「设好 current_stage 后回 router」。

10.3 J18 写作前先出章纲

问题:章纲与正文同时生成,作者没有单独审视章纲的机会。

处理:chapter_outline 节点前置,章纲生成后先进门禁由作者确认,确认后才撰写正文。

10.4 CR-59 作者的驳回理由 ≠ AI 审核结论

问题:驳回时写入的 ReviewIssue 会混进下一轮下发的 issues,前端把作者自己的话回显成「AI 发现的严重问题」,作者看到「1 个问题:角色数量不变…」以为根本没改。

处理:

novelcraft/app/core/nodes.py:1562-1565
    findings = [
        i for i in all_issues if not (isinstance(i, dict) and i.get("rejected"))
    ]
    rejected_feedback = _rejected_feedbacks(state)

rejected=True 的条目留在 State 里供重跑时读取,但单独以 rejected_feedback 字段下发。

10.5 J37 门禁卡上的答案必须能进 prompt

问题:作者填的「本卷计划章数」只写进了讨论日志,阶段节点读不到,卷纲仍按 prompt 示例输出(每卷都是 10 章)。

处理:stage_gate.notes 落盘,节点从 State 读取。这是典型的"回路断线"——UI 有输入、数据也存了,但节点读不到。读得到才算闭环。

10.6 CR-64 定稿才入库

问题:正文写完就进向量库,作者还没「通过」就已被检索到。

处理:只有 reviewing / polishing 通过才 _index_approved_chapter。

10.7 J15/J16 润色是可选工序且只产候选

润色节点不直接改正文,产出候选版本供左右对比;审核通过时未明确要求润色则跳过。

10.8 J25 完成态恢复

current_stage == "completed" 时,判定「还能继续写」的逻辑是纯函数,改不了 State,必须经 recover 节点把目标阶段写回,否则门禁与后续路由全部错位(表现为「继续创作」毫无反应)。


11. 已知边界

边界 说明
并发标记是进程内的in_flight 用进程内 Set,多副本部署会失效,需换成分布式锁
一致性是软检测reviewing 的 issues 是 LLM 自查产物,没有规则引擎 / NLI 硬校验。回路只保证「作者有机会看到并否决」,不保证问题被找全
AI 看不到讨论过程 多轮讨论只以 notes 和最终 brief 的形式进入生成,中间推理链不传给阶段节点
reject 成本高 一次驳回 = 一次完整阶段重跑。低成本修改应走 /revise-field、/revise-chapter
GATE_MAX_ROUNDS 是软上限 超过 5 轮仍要求确认,只在 tips 里提示可直接确认
kind=question 无调用点 事件构造函数与 /resume 的 action=answer 分支都还在,但没有任何节点发出 kind=question——挂起点实际只有 confirm 与 review

基于 VitePress 搭建 · 资料持续整理中