feat: add ai writing imitation mode
This commit is contained in:
1 parent
9268c73776
commit
bb6b9bd84b
22 files changed
+714
-30
No files matched your search
+7
-4
@@ -7,12 +7,13 @@ from langchain_core.runnables import RunnableConfig
|
||||
from langgraph.graph import END, StateGraph
|
||||
from langgraph.types import interrupt
|
||||
|
||||
from .state import AIWritingState
|
||||
from .nodes.editor import editor_node
|
||||
from .nodes.intent_parser import intent_parser_node
|
||||
from .nodes.researcher import researcher_node
|
||||
from .nodes.writer_outline import writer_outline_node
|
||||
from .nodes.sample_analyzer import sample_analyzer_node
|
||||
from .nodes.writer_draft import writer_draft_node
|
||||
from .nodes.editor import editor_node
|
||||
from .nodes.writer_outline import writer_outline_node
|
||||
from .state import AIWritingState
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -414,6 +415,7 @@ def make_ai_writing_graph(config=None):
|
||||
"""
|
||||
g = StateGraph(AIWritingState)
|
||||
|
||||
g.add_node("sample_analyzer", sample_analyzer_node)
|
||||
g.add_node("intent_parser", intent_parser_node)
|
||||
g.add_node("researcher", researcher_node)
|
||||
g.add_node("pause_material", pause_material_confirm)
|
||||
@@ -425,7 +427,8 @@ def make_ai_writing_graph(config=None):
|
||||
g.add_node("editor", editor_node)
|
||||
g.add_node("pause_review", pause_review_confirm)
|
||||
|
||||
g.set_entry_point("intent_parser")
|
||||
g.set_entry_point("sample_analyzer")
|
||||
g.add_edge("sample_analyzer", "intent_parser")
|
||||
g.add_edge("intent_parser", "researcher")
|
||||
g.add_conditional_edges("researcher", after_researcher,
|
||||
{"pause_material": "pause_material", "writer_draft": "writer_draft", "writer_outline": "writer_outline"})
|
||||
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
"""样文仿写:分析用户上传/粘贴的样文,提取可复用的文风画像。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
|
||||
from ..state import AIWritingState, SampleStyleProfile
|
||||
from ._utils import count_words, llm_json
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MAX_SAMPLE_ANALYSIS_CHARS = 12000
|
||||
|
||||
SAMPLE_ANALYZE_SYSTEM = """你是一名资深中文编辑和文风分析师。
|
||||
你的任务:阅读用户提供的样文,提取「可用于仿写的文风画像」,供后续写作模型模仿其结构、语气和表达节奏。
|
||||
|
||||
【重要边界】
|
||||
- 你不是改写样文本身,而是分析它的写作风格。
|
||||
- 不要复述样文的具体事实、数字、人名、机构名,除非用于概括文章结构。
|
||||
- 后续写作必须避免直接照抄样文,因此你要明确指出哪些表达方式可以学、哪些原文内容不能复制。
|
||||
|
||||
【输出要求】
|
||||
- 只输出一个 JSON 对象,不要解释文字,不要 markdown 代码块。
|
||||
- 必须使用英文双引号。
|
||||
- 字段结构:
|
||||
{
|
||||
"summary": "一句话概括样文风格",
|
||||
"article_type_guess": "推测文章类型",
|
||||
"tone": "语气/立场/情绪特征",
|
||||
"structure": ["篇章结构特征1", "篇章结构特征2"],
|
||||
"language_features": ["遣词造句特征1", "修辞/表达特征2"],
|
||||
"sentence_style": "句式、长短句、节奏特征",
|
||||
"opening_style": "开头方式",
|
||||
"ending_style": "结尾方式",
|
||||
"imitation_guidance": ["后续仿写应遵守的建议1", "建议2"],
|
||||
"avoid_copying": ["不得复制的内容/风险1", "风险2"],
|
||||
"sample_outline": ["样文结构骨架1", "样文结构骨架2"]
|
||||
}"""
|
||||
|
||||
SAMPLE_ANALYZE_USER = """样文文件名:{filename}
|
||||
样文字数:约 {word_count} 字
|
||||
|
||||
样文内容(可能已截断):
|
||||
{sample_text}
|
||||
|
||||
请提取可用于后续仿写的文风画像,只输出 JSON。"""
|
||||
|
||||
|
||||
def _is_imitate_mode(state: AIWritingState) -> bool:
|
||||
mode = (state.get("writing_mode_type") or "").strip().lower()
|
||||
return mode == "imitate"
|
||||
|
||||
|
||||
def _compact_list(values: object, limit: int = 6) -> list[str]:
|
||||
if not isinstance(values, list):
|
||||
return []
|
||||
out: list[str] = []
|
||||
for item in values:
|
||||
text = str(item or "").strip()
|
||||
if text:
|
||||
out.append(text[:120])
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _normalize_profile(raw: dict, sample_text: str) -> SampleStyleProfile:
|
||||
"""规整 LLM 输出,避免缺字段影响后续提示词。"""
|
||||
first_lines = [ln.strip() for ln in sample_text.splitlines() if ln.strip()][:5]
|
||||
fallback_outline = first_lines or ["起承转合清晰", "围绕主题分段展开"]
|
||||
profile: SampleStyleProfile = {
|
||||
"summary": str(raw.get("summary") or "样文表达较为完整,结构清晰,适合提取篇章节奏与措辞习惯。")[:200],
|
||||
"article_type_guess": str(raw.get("article_type_guess") or raw.get("articleTypeGuess") or "")[:80],
|
||||
"tone": str(raw.get("tone") or "稳健、清晰")[:120],
|
||||
"structure": _compact_list(raw.get("structure"), 8) or ["先交代背景或问题,再分层展开,最后收束观点。"],
|
||||
"language_features": _compact_list(raw.get("language_features") or raw.get("languageFeatures"), 8) or ["表达相对凝练,注重段落之间的衔接。"],
|
||||
"sentence_style": str(raw.get("sentence_style") or raw.get("sentenceStyle") or "长短句结合,段落节奏平稳。")[:160],
|
||||
"opening_style": str(raw.get("opening_style") or raw.get("openingStyle") or "开头直接引入主题。")[:160],
|
||||
"ending_style": str(raw.get("ending_style") or raw.get("endingStyle") or "结尾总结全文并给出判断或展望。")[:160],
|
||||
"imitation_guidance": _compact_list(raw.get("imitation_guidance") or raw.get("imitationGuidance"), 8) or ["模仿篇章结构、语气和句式节奏,不搬运样文事实。"],
|
||||
"avoid_copying": _compact_list(raw.get("avoid_copying") or raw.get("avoidCopying"), 8) or ["不得连续照抄样文原句或复用样文中的专有事实。"],
|
||||
"sample_outline": _compact_list(raw.get("sample_outline") or raw.get("sampleOutline"), 10) or fallback_outline,
|
||||
}
|
||||
return profile
|
||||
|
||||
|
||||
def _fallback_profile(sample_text: str) -> SampleStyleProfile:
|
||||
"""模型失败时的确定性兜底画像。"""
|
||||
paragraphs = [p.strip() for p in re.split(r"\n\s*\n+", sample_text) if p.strip()]
|
||||
avg_len = round(sum(len(p) for p in paragraphs) / max(len(paragraphs), 1))
|
||||
return {
|
||||
"summary": "已根据样文段落和篇幅提取基础仿写约束。",
|
||||
"article_type_guess": "",
|
||||
"tone": "保持样文的正式程度和表达密度。",
|
||||
"structure": [
|
||||
f"样文约 {len(paragraphs)} 个自然段,平均每段约 {avg_len} 字。",
|
||||
"仿写时保留相近的段落推进节奏。",
|
||||
],
|
||||
"language_features": ["保留样文的用词正式程度、连接方式和论述密度。"],
|
||||
"sentence_style": "参照样文长短句比例,避免明显口语化或突兀转换。",
|
||||
"opening_style": "参照样文开头的切入方式,但改写为新主题。",
|
||||
"ending_style": "参照样文结尾的收束方式,形成新主题下的总结。",
|
||||
"imitation_guidance": ["学习样文结构和语气,所有事实内容以用户新要求为准。"],
|
||||
"avoid_copying": ["不要连续复用样文原句,不要照搬样文专有事实、案例和数据。"],
|
||||
"sample_outline": [p[:80] for p in paragraphs[:8]] or ["围绕主题分层展开"],
|
||||
}
|
||||
|
||||
|
||||
def render_sample_style_section(state: AIWritingState) -> str:
|
||||
"""把文风画像渲染成可注入大纲/写作提示词的约束片段。"""
|
||||
if not _is_imitate_mode(state):
|
||||
return ""
|
||||
profile = state.get("sample_style_profile") or {}
|
||||
if not profile:
|
||||
return ""
|
||||
strength = (state.get("imitate_strength") or "medium").strip().lower()
|
||||
strength_label = {
|
||||
"light": "轻度:只参考语气和部分表达节奏,结构可按新主题调整。",
|
||||
"medium": "中度:同时参考语气、段落节奏和篇章推进方式。",
|
||||
"strong": "高度:尽量贴近样文结构骨架、标题组织和表达密度,但仍不得照抄原文。",
|
||||
}.get(strength, "中度:同时参考语气、段落节奏和篇章推进方式。")
|
||||
preserve = "是" if state.get("preserve_sample_structure") else "否"
|
||||
compact = {
|
||||
"summary": profile.get("summary", ""),
|
||||
"tone": profile.get("tone", ""),
|
||||
"structure": profile.get("structure", []),
|
||||
"language_features": profile.get("language_features", []),
|
||||
"sentence_style": profile.get("sentence_style", ""),
|
||||
"opening_style": profile.get("opening_style", ""),
|
||||
"ending_style": profile.get("ending_style", ""),
|
||||
"imitation_guidance": profile.get("imitation_guidance", []),
|
||||
"avoid_copying": profile.get("avoid_copying", []),
|
||||
"sample_outline": profile.get("sample_outline", []),
|
||||
}
|
||||
return (
|
||||
"\n\n【样文仿写要求】\n"
|
||||
f"- 仿写强度:{strength_label}\n"
|
||||
f"- 是否尽量沿用样文结构:{preserve}\n"
|
||||
"- 仿写目标:学习样文的篇章结构、语气、段落节奏、句式和表达密度;新文章主题、事实与论点必须服务用户的新要求。\n"
|
||||
"- 严禁:不得连续照抄样文原句,不得搬运样文中的专有事实、数据、人物、机构或案例。\n"
|
||||
"文风画像 JSON:\n"
|
||||
f"{json.dumps(compact, ensure_ascii=False)}"
|
||||
)
|
||||
|
||||
|
||||
async def sample_analyzer_node(state: AIWritingState, config: RunnableConfig) -> dict:
|
||||
if not _is_imitate_mode(state):
|
||||
return {}
|
||||
|
||||
sample_text = (state.get("sample_text") or "").strip()
|
||||
filename = (state.get("sample_filename") or "粘贴文本").strip()
|
||||
if not sample_text:
|
||||
return {
|
||||
"writing_mode_type": "normal",
|
||||
"status": "researching",
|
||||
"progress_events": [{
|
||||
"type": "notice",
|
||||
"agent_name": "系统",
|
||||
"title": "样文为空",
|
||||
"detail": "未收到可分析的样文内容,已按普通写作继续。",
|
||||
}],
|
||||
}
|
||||
|
||||
clipped = sample_text[:_MAX_SAMPLE_ANALYSIS_CHARS]
|
||||
fallback = _fallback_profile(clipped)
|
||||
configurable = (config or {}).get("configurable", {}) or {}
|
||||
model_name = (state.get("model_name") or configurable.get("model_name") or "").strip() or None
|
||||
raw = await llm_json(
|
||||
SAMPLE_ANALYZE_SYSTEM,
|
||||
SAMPLE_ANALYZE_USER.format(
|
||||
filename=filename,
|
||||
word_count=count_words(sample_text),
|
||||
sample_text=clipped,
|
||||
),
|
||||
fallback,
|
||||
config,
|
||||
model_name=model_name,
|
||||
disable_thinking=True,
|
||||
)
|
||||
profile = _normalize_profile(raw, clipped)
|
||||
events = [
|
||||
{"type": "step_start", "agent_name": "样文分析师", "message": "正在分析样文风格"},
|
||||
{
|
||||
"type": "sample_profile_ready",
|
||||
"agent_name": "样文分析师",
|
||||
"message": profile.get("summary") or "样文风格分析完成",
|
||||
"sample_style_profile": profile,
|
||||
},
|
||||
]
|
||||
if raw.get("_llm_error"):
|
||||
events.append({
|
||||
"type": "notice",
|
||||
"agent_name": "样文分析师",
|
||||
"title": "样文分析模型异常",
|
||||
"detail": f"已使用基础画像兜底。原因:{raw['_llm_error']}",
|
||||
})
|
||||
return {
|
||||
"sample_style_profile": profile,
|
||||
"status": "researching",
|
||||
"progress_events": events,
|
||||
}
|
||||
+32
-12
@@ -8,19 +8,21 @@ import re
|
||||
from langchain_core.messages import HumanMessage, SystemMessage
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
|
||||
from ..state import AIWritingState, DraftArticle
|
||||
from ..prompts.writer_prompts import (
|
||||
DRAFT_SECTION_SYSTEM, DRAFT_SECTION_USER, DRAFT_EXPAND_USER, DRAFT_COMPRESS_USER,
|
||||
DRAFT_REVISE_SCOPE_SYSTEM, DRAFT_REVISE_SCOPE_USER, DRAFT_REVISE_SECTION_USER,
|
||||
OUTLINE_REVISE_SYSTEM, OUTLINE_REVISE_USER,
|
||||
WRITER_MODE_LOOSE, WRITER_MODE_STRICT, SECTION_BLOCKED_MARKER,
|
||||
)
|
||||
# 复用大纲节点的解析/素材摘要:修订模式下先据意见更新大纲(含标题),再重写正文。
|
||||
# writer_outline 不反向 import 本模块,无循环。
|
||||
from .writer_outline import (
|
||||
_parse_outline as _revise_parse_outline,
|
||||
_materials_summary as _revise_materials_summary,
|
||||
DRAFT_COMPRESS_USER,
|
||||
DRAFT_EXPAND_USER,
|
||||
DRAFT_REVISE_SCOPE_SYSTEM,
|
||||
DRAFT_REVISE_SCOPE_USER,
|
||||
DRAFT_REVISE_SECTION_USER,
|
||||
DRAFT_SECTION_SYSTEM,
|
||||
DRAFT_SECTION_USER,
|
||||
OUTLINE_REVISE_SYSTEM,
|
||||
OUTLINE_REVISE_USER,
|
||||
SECTION_BLOCKED_MARKER,
|
||||
WRITER_MODE_LOOSE,
|
||||
WRITER_MODE_STRICT,
|
||||
)
|
||||
from ..state import AIWritingState, DraftArticle
|
||||
from ._agent_runner import (
|
||||
WRITER_AGENT_ID,
|
||||
WritingAgentUnavailable,
|
||||
@@ -36,7 +38,22 @@ from ._model_fallback import (
|
||||
emit_model_switch_event,
|
||||
fallback_chain,
|
||||
)
|
||||
from ._utils import resolve_writing_model_name, _content_to_text, count_words, llm_json, reasoning_delta, ThinkTagParser, safe_get_stream_writer
|
||||
from ._utils import (
|
||||
ThinkTagParser,
|
||||
_content_to_text,
|
||||
count_words,
|
||||
llm_json,
|
||||
reasoning_delta,
|
||||
resolve_writing_model_name,
|
||||
safe_get_stream_writer,
|
||||
)
|
||||
from .sample_analyzer import render_sample_style_section
|
||||
from .writer_outline import (
|
||||
_materials_summary as _revise_materials_summary,
|
||||
)
|
||||
from .writer_outline import (
|
||||
_parse_outline as _revise_parse_outline,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -480,6 +497,7 @@ async def _stream_revise_section(
|
||||
existing_text=existing_text,
|
||||
note=note,
|
||||
)
|
||||
msg += render_sample_style_section(state)
|
||||
if add_references:
|
||||
msg += "\n\n注意:保留原文中已有的引用角标(形如 [1]、[2]),不要删除或改动它们。"
|
||||
|
||||
@@ -807,6 +825,7 @@ async def writer_draft_node(state: AIWritingState, config: RunnableConfig) -> di
|
||||
min_words=sec_min_words,
|
||||
max_words=sec_max_words,
|
||||
)
|
||||
user_msg += render_sample_style_section(state)
|
||||
# 开启参考文献时,追加角标引用要求(两条路径——内置 agent 与旧路径——共用 user_msg)。
|
||||
if add_references:
|
||||
user_msg += _CITATION_DIRECTIVE
|
||||
@@ -987,6 +1006,7 @@ async def writer_draft_node(state: AIWritingState, config: RunnableConfig) -> di
|
||||
existing_text=section_bufs[idx],
|
||||
target_words=sec_target,
|
||||
)
|
||||
msg += render_sample_style_section(state)
|
||||
# 扩写/压缩时保留正文里已有的引用角标 [n],避免重排后文献缺失。
|
||||
if add_references:
|
||||
msg += "\n\n注意:保留原文中已有的引用角标(形如 [1]、[2]),不要删除或改动它们。"
|
||||
|
||||
+6
-4
@@ -35,6 +35,7 @@ from ._model_fallback import (
|
||||
fallback_chain,
|
||||
)
|
||||
from ._utils import ThinkTagParser, _content_to_text, parse_json, reasoning_delta, resolve_writing_model_name, safe_get_stream_writer
|
||||
from .sample_analyzer import render_sample_style_section
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -362,6 +363,7 @@ async def writer_outline_node(state: AIWritingState, config: RunnableConfig) ->
|
||||
word_count_target=state.get("word_count_target", 800),
|
||||
materials_summary=_materials_summary(pkg),
|
||||
)
|
||||
sample_style_section = render_sample_style_section(state)
|
||||
if is_revise:
|
||||
system_prompt = OUTLINE_REVISE_SYSTEM
|
||||
revise_args = dict(
|
||||
@@ -369,14 +371,14 @@ async def writer_outline_node(state: AIWritingState, config: RunnableConfig) ->
|
||||
current_outline=json.dumps(current_outline, ensure_ascii=False, indent=2),
|
||||
feedback=feedback,
|
||||
)
|
||||
user_prompt = OUTLINE_REVISE_USER.format(**revise_args)
|
||||
agent_payload = _AGENT_OUTLINE_REVISE_USER.format(**revise_args)
|
||||
user_prompt = OUTLINE_REVISE_USER.format(**revise_args) + sample_style_section
|
||||
agent_payload = _AGENT_OUTLINE_REVISE_USER.format(**revise_args) + sample_style_section
|
||||
else:
|
||||
system_prompt = OUTLINE_SYSTEM
|
||||
feedback_section = f"\n重新规划要求:{feedback}" if feedback else ""
|
||||
gen_args = dict(fmt_args, feedback_section=feedback_section)
|
||||
user_prompt = OUTLINE_USER.format(**gen_args)
|
||||
agent_payload = _AGENT_OUTLINE_USER.format(**gen_args)
|
||||
user_prompt = OUTLINE_USER.format(**gen_args) + sample_style_section
|
||||
agent_payload = _AGENT_OUTLINE_USER.format(**gen_args) + sample_style_section
|
||||
|
||||
# 流式推送:阶段 2 起统一走 LangGraph 原生 custom 通道(get_stream_writer)。
|
||||
writer = safe_get_stream_writer()
|
||||
|
||||
+27
-1
@@ -1,5 +1,5 @@
|
||||
from typing import Annotated, List, Literal, Optional, TypedDict
|
||||
import operator
|
||||
from typing import Annotated, List, Literal, Optional, TypedDict
|
||||
|
||||
# ── 素材 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -74,6 +74,23 @@ class DraftArticle(TypedDict):
|
||||
word_count: int
|
||||
revision_count: int
|
||||
|
||||
|
||||
# ── 样文仿写 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
class SampleStyleProfile(TypedDict, total=False):
|
||||
summary: str
|
||||
article_type_guess: str
|
||||
tone: str
|
||||
structure: List[str]
|
||||
language_features: List[str]
|
||||
sentence_style: str
|
||||
opening_style: str
|
||||
ending_style: str
|
||||
imitation_guidance: List[str]
|
||||
avoid_copying: List[str]
|
||||
sample_outline: List[str]
|
||||
|
||||
|
||||
# ── 编辑审核 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
class ReviewIssue(TypedDict):
|
||||
@@ -109,6 +126,7 @@ class UserInterventionPayload(TypedDict, total=False):
|
||||
# ── 主状态 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
WritingStatus = Literal[
|
||||
"analyzing_sample",
|
||||
"researching", "awaiting_material_confirm",
|
||||
"writing_outline", "awaiting_outline_confirm",
|
||||
"writing_draft", "awaiting_section_help", "awaiting_draft_confirm",
|
||||
@@ -128,6 +146,14 @@ class AIWritingState(TypedDict):
|
||||
# 用户在写作表单粘贴的「已有大纲」原文(可选)。非空时 writer_outline 跳过 LLM 规划,
|
||||
# 直接解析这份大纲并按用户结构生成,做到「完全按我的大纲写」。留空走正常自动规划。
|
||||
user_outline_raw: str
|
||||
# 写作入口模式:normal=普通写作 / imitate=样文仿写。仿写模式下先分析 sample_text,
|
||||
# 得到 sample_style_profile,再将其注入大纲与草稿提示词。
|
||||
writing_mode_type: str
|
||||
sample_text: str
|
||||
sample_filename: str
|
||||
sample_style_profile: Optional[SampleStyleProfile]
|
||||
imitate_strength: str
|
||||
preserve_sample_structure: bool
|
||||
article_type: str
|
||||
# 当 article_type 是「已有类型库里没有」的新类型时,配置助手识别出的一句话特征说明。
|
||||
# 仅本次写作临时使用(不入库):在大纲生成时作为 hint 附在类型后,影响全文结构与侧重。
|
||||
|
||||
Reference in new issue
Block a user