标书生成与审查
This commit is contained in:
@@ -0,0 +1,587 @@
|
||||
"""Bounded, resumable analysis and outline planning for the authoring workspace.
|
||||
|
||||
Exact source spans are selected by ID. No textual source is silently dropped:
|
||||
unused spans are audited independently before analysis can be committed.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from pydantic import Field
|
||||
from typing import Literal
|
||||
from .bid_writing import (Strict, Part, COMMON, RULE_VERSION, _evidence,
|
||||
_review_response, _verify_extraction_completion, ExtractionCoverageError)
|
||||
from .bid_progress import current_progress
|
||||
from .bid_timing import STEP_SECONDS
|
||||
from .review_jobs import JobValidationBlocked
|
||||
|
||||
|
||||
class AnalyzedItem(Strict):
|
||||
part: Part
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
text: str = Field(min_length=1, max_length=1000)
|
||||
topic: str = Field(min_length=1, max_length=60)
|
||||
usage: str = Field(pattern='^(response|form|attachment|delivery|reference|clarify)$')
|
||||
uncertain: bool
|
||||
evidence_ids: list[str] = Field(min_length=1, max_length=5)
|
||||
|
||||
|
||||
class Analysis(Strict):
|
||||
requirements: list[AnalyzedItem] = Field(max_length=80)
|
||||
issues: list[str] = Field(max_length=12)
|
||||
|
||||
|
||||
class SourceGroup(Strict):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
part: Part
|
||||
usage: str = Field(pattern='^(response|form|attachment|delivery|reference|clarify)$')
|
||||
uncertain: bool
|
||||
evidence_ids: list[str] = Field(min_length=1, max_length=80)
|
||||
|
||||
|
||||
class SourceGroups(Strict):
|
||||
groups: list[SourceGroup] = Field(max_length=60)
|
||||
issues: list[str] = Field(max_length=12)
|
||||
|
||||
|
||||
def source_rows(raw, evidence):
|
||||
"""Verbatim requirements: the model groups spans, it never rewrites them."""
|
||||
parsed = SourceGroups.model_validate(raw)
|
||||
rows=[]; assigned=set()
|
||||
order={key:i for i,key in enumerate(evidence)}
|
||||
for group in parsed.groups:
|
||||
ids=list(dict.fromkeys(group.evidence_ids))
|
||||
if any(key not in evidence for key in ids) or assigned.intersection(ids):
|
||||
raise ValueError('原文归类编号无效或重复')
|
||||
assigned.update(ids);ids.sort(key=order.get)
|
||||
parts=[];length=0
|
||||
def append():
|
||||
if parts:
|
||||
basis=[evidence[key] for key in parts]
|
||||
rows.append(dict(part=group.part,title=group.title,topic=group.title,
|
||||
usage=group.usage,uncertain=group.uncertain or any(re.search(r'[□☐]|甲方\s*/\s*甲乙双方', ref['quote']) for ref in basis),
|
||||
text='\n'.join(ref['quote'] for ref in basis),basis=basis))
|
||||
for key in ids:
|
||||
size=len(evidence[key]['quote'])+1
|
||||
if parts and (len(parts)>=5 or length+size>1400):
|
||||
append();parts=[];length=0
|
||||
parts.append(key);length+=size
|
||||
append()
|
||||
return rows, assigned, parsed.issues
|
||||
|
||||
|
||||
class OutlineNode(Strict):
|
||||
title: str = Field(min_length=1, max_length=150)
|
||||
level: int = Field(ge=1, le=3)
|
||||
topics: list[str] = Field(max_length=150)
|
||||
objective: str = Field(min_length=1, max_length=400)
|
||||
|
||||
|
||||
class Outline(Strict):
|
||||
chapters: list[OutlineNode] = Field(min_length=1, max_length=120)
|
||||
|
||||
|
||||
class TopicPlacement(Strict):
|
||||
topic: str
|
||||
chapter: int = Field(ge=-1, le=119)
|
||||
title: str = Field(default='', max_length=150)
|
||||
objective: str = Field(default='', max_length=400)
|
||||
|
||||
|
||||
class TopicPlacements(Strict):
|
||||
assignments: list[TopicPlacement] = Field(min_length=1, max_length=50)
|
||||
|
||||
|
||||
class OutlineSection(Strict):
|
||||
title: str = Field(min_length=1, max_length=150)
|
||||
topics: list[str] = Field(min_length=1, max_length=8)
|
||||
objective: str = Field(min_length=1, max_length=400)
|
||||
|
||||
|
||||
class OutlineSections(Strict):
|
||||
chapters: list[OutlineSection] = Field(min_length=2, max_length=60)
|
||||
|
||||
|
||||
def _expand_outline(request, parsed, invoke, deadline):
|
||||
"""Large category headings are not usable authoring units: split by topic."""
|
||||
progress = current_progress.get()
|
||||
chapters = parsed.model_dump()['chapters']
|
||||
catalog = {item['key']: item for item in request.workbench['catalog']}
|
||||
for index in range(len(chapters) - 1, -1, -1):
|
||||
parent = chapters[index]
|
||||
if len(parent['topics']) <= 8:
|
||||
continue
|
||||
if parent['level'] >= 3:
|
||||
raise JobValidationBlocked('末级章节主题过多,请拆分为同级小节后继续。')
|
||||
targets = parent['topics']
|
||||
schema = OutlineSections.model_json_schema()
|
||||
schema['$defs']['OutlineSection']['properties']['topics']['items']['enum'] = targets
|
||||
feedback = ''
|
||||
for attempt in range(2):
|
||||
raw, commit = _review_response('workbench_outline_sections', invoke,
|
||||
COMMON + '\n把大章拆为可单独编写、预览和人工修改的小节。'
|
||||
'catalog每个主题编号恰好分配一次,每节最多8个相关主题。'
|
||||
'按实际内容组织,规定格式表格、具体技术方案及附件宜独立成节;'
|
||||
'不能仅用技术、商务等大类笼统合并。只返回本章的小节,不写正文。' + feedback,
|
||||
{'parent': parent, 'catalog': [catalog[key] for key in targets]},
|
||||
schema, deadline, max_tokens=4000)
|
||||
try:
|
||||
children = OutlineSections.model_validate(raw).chapters
|
||||
assigned = [key for node in children for key in node.topics]
|
||||
if set(assigned) - set(targets):
|
||||
raise ValueError('小节包含范围之外的主题')
|
||||
commit()
|
||||
scoped = request.model_copy(update={'workbench': dict(request.workbench, catalog=[catalog[key] for key in targets])})
|
||||
complete = _complete_outline(scoped, Outline(chapters=[OutlineNode(**node.model_dump(), level=1) for node in children]), invoke, deadline, checkpoint=False)
|
||||
children = complete.chapters
|
||||
if len(chapters) + len(children) > 120:
|
||||
raise ValueError('目录小节数量过多,请合并相关小节')
|
||||
commit()
|
||||
parent['topics'] = []
|
||||
chapters[index+1:index+1] = [dict(node.model_dump(), level=parent['level']+1) for node in children]
|
||||
if progress is not None:
|
||||
progress.state['workbench_outline_candidate'] = {'chapters': chapters}
|
||||
progress.persist(True)
|
||||
break
|
||||
except ValueError as exc:
|
||||
feedback = '\n上次拆分不完整:' + str(exc)[:1800]
|
||||
if attempt == 1:
|
||||
raise JobValidationBlocked('已保留目录,本次章节细分仍未通过覆盖检查。') from exc
|
||||
return Outline.model_validate({'chapters': chapters})
|
||||
|
||||
|
||||
def _complete_outline(request, parsed, invoke, deadline, *, checkpoint=True):
|
||||
"""Repair only missing/ambiguous topic mappings; retain the accepted tree."""
|
||||
progress = current_progress.get()
|
||||
chapters = [node.model_dump() for node in parsed.chapters]
|
||||
catalog = {item['key']: item for item in request.workbench['catalog']}
|
||||
counts = {key: sum(node['topics'].count(key) for node in chapters) for key in catalog}
|
||||
pending = [key for key, count in counts.items() if count != 1]
|
||||
for node in chapters:
|
||||
node['topics'] = [key for key in node['topics'] if key not in pending]
|
||||
while pending:
|
||||
targets = pending[:50]
|
||||
schema = TopicPlacements.model_json_schema()
|
||||
schema['$defs']['TopicPlacement']['properties']['topic']['enum'] = targets
|
||||
feedback = ''
|
||||
for attempt in range(2):
|
||||
raw, commit = _review_response('workbench_outline_mapping', invoke,
|
||||
COMMON + '\n只修复目录的主题分配。targets中的每个编号恰好分配一次。'
|
||||
'chapter为现有目录的零起始下标,按标题、层级和objective选择主响应位置。'
|
||||
'已有章节不适合时,chapter=-1并填写新一级章的title和objective;'
|
||||
'不要强行归入不相关的章节,不重写其他目录或已分配的主题。' + feedback,
|
||||
{'targets': [catalog[key] for key in targets], 'chapters': chapters},
|
||||
schema, deadline, max_tokens=2600)
|
||||
try:
|
||||
fixes = TopicPlacements.model_validate(raw).assignments
|
||||
keys = [fix.topic for fix in fixes]
|
||||
if len(keys) != len(set(keys)) or set(keys) != set(targets):
|
||||
raise ValueError('补充分配没有完整覆盖待处理主题')
|
||||
if any(fix.chapter >= len(chapters) or (fix.chapter == -1 and
|
||||
(not fix.title.strip() or not fix.objective.strip())) for fix in fixes):
|
||||
raise ValueError('补充分配的章节编号或新章内容无效')
|
||||
new_titles = {fix.title for fix in fixes if fix.chapter == -1}
|
||||
if len(chapters) + len(new_titles) > 120:
|
||||
raise ValueError('目录超过120节,请合并相关主题')
|
||||
commit()
|
||||
new_nodes = {}
|
||||
for fix in fixes:
|
||||
if fix.chapter == -1:
|
||||
if fix.title not in new_nodes:
|
||||
new_nodes[fix.title] = len(chapters)
|
||||
chapters.append(dict(title=fix.title, level=1, topics=[], objective=fix.objective))
|
||||
index = new_nodes[fix.title]
|
||||
else:
|
||||
index = fix.chapter
|
||||
chapters[index]['topics'].append(fix.topic)
|
||||
pending = pending[len(targets):]
|
||||
if progress is not None and checkpoint:
|
||||
progress.state['workbench_outline_candidate'] = {'chapters': chapters}
|
||||
progress.persist(True)
|
||||
break
|
||||
except ValueError as exc:
|
||||
feedback = '\n上次补充分配无效:' + str(exc)[:600]
|
||||
if attempt == 1:
|
||||
raise JobValidationBlocked('已保留目录,本次主题补充分配仍未通过校验。') from exc
|
||||
# A duplicate-only terminal node can become empty after reassignment.
|
||||
# Remove empty terminal nodes, while retaining meaningful parent headings.
|
||||
for index in range(len(chapters) - 1, -1, -1):
|
||||
node = chapters[index]
|
||||
if not node['topics'] and (index + 1 == len(chapters) or chapters[index+1]['level'] <= node['level']):
|
||||
chapters.pop(index)
|
||||
return Outline.model_validate({'chapters': chapters})
|
||||
|
||||
|
||||
def validate_context(request):
|
||||
wb = request.workbench
|
||||
allowed = {'version', 'title', 'path', 'target_words', 'segment', 'segments',
|
||||
'catalog', 'source_outline', 'guidance', 'previous', 'shared_context', 'writing_mode'}
|
||||
if set(wb) - allowed or wb.get('version') != 1:
|
||||
raise ValueError('编写工作台参数版本无效')
|
||||
if len(json.dumps(wb, ensure_ascii=False)) > 22000:
|
||||
raise ValueError('目录或章节上下文超过范围,请分批处理')
|
||||
if 'writing_mode' in wb and wb['writing_mode'] not in {'plan', 'response'}:
|
||||
raise ValueError('章节编写类型无效')
|
||||
if 'shared_context' in wb:
|
||||
shared = wb['shared_context']
|
||||
if (request.action not in {'generate', 'refine'} or not isinstance(shared, dict)
|
||||
or set(shared) != {'version', 'revision', 'items', 'omitted'}
|
||||
or shared.get('version') != 1 or not isinstance(shared.get('revision'), str)
|
||||
or not re.fullmatch(r'[a-f0-9-]{36}', shared['revision'])
|
||||
or type(shared.get('omitted')) is not int or shared['omitted'] < 0
|
||||
or not isinstance(shared.get('items'), list)
|
||||
or len(json.dumps(shared, ensure_ascii=False, separators=(',', ':'))) > 6500):
|
||||
raise ValueError('共用原文约束快照无效')
|
||||
for item in shared['items']:
|
||||
if (not isinstance(item, dict) or set(item) != {'id', 'title', 'part', 'text', 'uncertain', 'confirmation', 'source_ids'}
|
||||
or any(not isinstance(item.get(k), str) for k in ('id', 'title', 'part', 'text', 'confirmation'))
|
||||
or not item['id'] or not item['text'] or type(item.get('uncertain')) is not bool
|
||||
or not isinstance(item.get('source_ids'), list)
|
||||
or any(not isinstance(i, str) or not i for i in item['source_ids'])):
|
||||
raise ValueError('共用约束缺少原文与来源')
|
||||
if request.action == 'outline':
|
||||
catalog = wb.get('catalog', [])
|
||||
if not isinstance(catalog, list) or not 1 <= len(catalog) <= 150:
|
||||
raise ValueError('目录规划条目数量无效')
|
||||
keys = [item.get('key') for item in catalog if isinstance(item, dict)]
|
||||
if len(keys) != len(catalog) or not all(isinstance(key,str) and key for key in keys) or len(set(keys)) != len(keys):
|
||||
raise ValueError('目录主题编号重复或缺失')
|
||||
if request.action in {'generate', 'refine'}:
|
||||
if not isinstance(wb.get('title'), str) or not 1 <= len(wb['title']) <= 150:
|
||||
raise ValueError('缺少已确认的章节标题')
|
||||
words = wb.get('target_words')
|
||||
if type(words) is not int or not 100 <= words <= 6000:
|
||||
raise ValueError('本次续写的目标字数需为100至6000')
|
||||
|
||||
|
||||
def workbench_instruction(request):
|
||||
wb = request.workbench
|
||||
if not wb or request.action not in {'generate', 'refine'}:
|
||||
return ''
|
||||
from .bid_draft_quality import FACT_POLICY
|
||||
return ('\n已由人工确认的目录与写作说明见workbench。严格使用title作为章节标题,'
|
||||
'path为所属目录;不要自行另立同级章。target_words是本次目标篇幅,'
|
||||
'在完整响应与事实准确前提下尽量接近,不得复制段落凑字。'
|
||||
'正文应展开具体方法、执行步骤、责任分工、输入输出和交付标准,不能只给提纲或泛泛承诺。'
|
||||
'方案类章节充分写到目标篇幅;声明、证照、索引和固定表式按原文填写,不能为凑字添加无关内容或虚构事实。'
|
||||
'segment/segments表示同一章节的分批续写,previous为本章已完成内容,'
|
||||
'承接其术语与逻辑,不再重复开场、已写内容或另起全篇结论。'
|
||||
'guidance是人工确认的写作范围与待确认条件;未确认的选项保持条件性表述,'
|
||||
'不得写成确定承诺。目录中的其他章节不属于本次编写范围。'
|
||||
'shared_context是带版本与来源的跨章原文约束,用于核对项目名称、期限、范围与排除项,'
|
||||
'不是本章逐项写作清单。只使用与本节有关的信息,不另写全篇概况或材料清单;'
|
||||
'uncertain为true的条件没有确定适用,不能自行选定。与本章要求确有矛盾时保留待确认项,不擅自取舍。'
|
||||
'omitted大于0表示共用提示未容纳所有条款,仍以本章requirements和blocks的完整依据为准。'
|
||||
'技术方案应直接展开实施内容,不得习惯性追加资格证明、报价或“待补资料汇总”结尾;'
|
||||
'只有本章要求明确索要的真实资料尚缺时,才说明该具体缺项。' + FACT_POLICY)
|
||||
|
||||
|
||||
def normalize_known_fields(request, result):
|
||||
"""Fill app-owned fields only; unknown company facts remain explicit gaps."""
|
||||
pattern = re.compile(r'【待补[::]\s*(?:正式|实际|投标)?项目名称\s*】')
|
||||
def replace(value):
|
||||
if isinstance(value, str):
|
||||
return pattern.sub(lambda match: request.project, value)
|
||||
if isinstance(value, list):
|
||||
return [replace(item) for item in value]
|
||||
if isinstance(value, dict):
|
||||
return {key: replace(item) for key, item in value.items()}
|
||||
return value
|
||||
result['title'] = request.workbench['title']
|
||||
result['paragraphs'] = replace(result['paragraphs'])
|
||||
result['tables'] = replace(result.get('tables', []))
|
||||
result['missing_materials'] = [item for item in result['missing_materials']
|
||||
if item.strip() not in {'项目名称', '正式项目名称', '实际项目名称', '投标项目名称'}]
|
||||
|
||||
|
||||
class AuditFinding(Strict):
|
||||
index: int = Field(ge=0, le=9)
|
||||
kind: Literal['missing_text', 'incorrect_text', 'unsupported_fact']
|
||||
draft_quote: str = Field(max_length=1000)
|
||||
required_text: str = Field(max_length=700)
|
||||
explanation: str = Field(min_length=1, max_length=300)
|
||||
|
||||
|
||||
class AuditFindings(Strict):
|
||||
confirmed: list[AuditFinding] = Field(max_length=10)
|
||||
|
||||
|
||||
class SelectedAuditFinding(Strict):
|
||||
index: int = Field(ge=0, le=9)
|
||||
explanation: str = Field(min_length=1, max_length=300)
|
||||
|
||||
|
||||
class SelectedMissing(SelectedAuditFinding):
|
||||
kind: Literal['missing_text']
|
||||
draft_id: Literal['']
|
||||
source_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class SelectedIncorrect(SelectedAuditFinding):
|
||||
kind: Literal['incorrect_text']
|
||||
draft_id: str = Field(min_length=1)
|
||||
source_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class SelectedUnsupported(SelectedAuditFinding):
|
||||
kind: Literal['unsupported_fact']
|
||||
draft_id: str = Field(min_length=1)
|
||||
source_id: Literal['']
|
||||
|
||||
|
||||
class SelectedAuditFindings(Strict):
|
||||
confirmed: list[SelectedMissing | SelectedIncorrect | SelectedUnsupported] = Field(max_length=10)
|
||||
|
||||
|
||||
class AuditEvidenceError(ValueError):
|
||||
"""Retry the evidence check, not an already grounded candidate chapter."""
|
||||
|
||||
|
||||
def verify_audit_findings(request, result, issues, invoke, deadline):
|
||||
"""A literal omission claim must also survive a deterministic text check."""
|
||||
schema = AuditFindings.model_json_schema()
|
||||
schema['$defs']['AuditFinding']['properties']['index']['enum'] = list(range(len(issues)))
|
||||
progress=current_progress.get()
|
||||
feedback=progress.state.get('workbench_audit_feedback','') if progress else ''
|
||||
evidence_data = {}
|
||||
if feedback:
|
||||
# Reproducing PDF/table typography is an unreliable way to cite text.
|
||||
# On a bad quotation, constrain the decoder to exact supplied excerpts.
|
||||
# This changes citation transport, not the independent audit criteria.
|
||||
from types import SimpleNamespace
|
||||
def indexed(values, prefix):
|
||||
blocks = [SimpleNamespace(id=str(i), text=value) for i, value in enumerate(values)]
|
||||
return {prefix + key[1:]: value['quote'] for key, value in _evidence(blocks).items()}
|
||||
def text_values(value):
|
||||
if isinstance(value, str): return [value]
|
||||
if isinstance(value, list): return [s for v in value for s in text_values(v)]
|
||||
if isinstance(value, dict): return [s for v in value.values() for s in text_values(v)]
|
||||
return []
|
||||
source_ids = indexed([request.project] + [b.text for b in request.blocks + request.company]
|
||||
+ [r.text for r in request.requirements], 's')
|
||||
draft_ids = indexed(text_values(result.get('paragraphs', [])) + text_values(result.get('tables', [])), 'd')
|
||||
schema = SelectedAuditFindings.model_json_schema()
|
||||
for definition in schema['$defs'].values():
|
||||
fields = definition['properties']
|
||||
fields['index']['enum'] = list(range(len(issues)))
|
||||
if 'const' not in fields['draft_id']:
|
||||
fields['draft_id']['enum'] = list(draft_ids)
|
||||
if 'const' not in fields['source_id']:
|
||||
fields['source_id']['enum'] = list(source_ids)
|
||||
evidence_data = {'source_excerpts': source_ids, 'draft_excerpts': draft_ids}
|
||||
feedback += ('\n本轮使用编号引用:只返回index、kind、draft_id、source_id、explanation,不再抄写引用文字。'
|
||||
'missing_text须选source_excerpts里的source_id,draft_id为空;'
|
||||
'incorrect_text须同时选择实际错误稿件draft_id与正确原文source_id;'
|
||||
'unsupported_fact须选择实际稿件draft_id,source_id为空。编号由程序恢复逐字原文。')
|
||||
raw, save = _review_response('workbench_audit_evidence', invoke,
|
||||
COMMON + '\n逐项核对issues,只保留能由输入直接证明的写作错误。'
|
||||
'当前是待人工完善的初稿;未给出的公司名称、证书、真实签章、签署日期等以具体待补保留是正确行为,不要求模型编造。'
|
||||
'project是已知项目名称;已给出的金额、期限和实质条件不能省略。'
|
||||
'每项保留意见须提供index、kind、draft_quote、required_text及具体explanation。'
|
||||
'missing_text表示缺少某一明确条款,required_text必须是要求或依据中的完整连续短句,至少2字,表单字段名可简短;draft_quote可为空。'
|
||||
'先查找全部段落和表格(含表前后文字),required_text已经存在或已有同义表述时不应再报告缺失;不强求逐字复述。'
|
||||
'招标原文自身未明确的二选一(例如甲方/甲乙双方)不能要求模型按投标策略擅选,应交给人工确认;确认意见见guidance。'
|
||||
'incorrect_text表示写错,draft_quote逐字引用实际错误,required_text逐字引用正确依据。'
|
||||
'unsupported_fact表示编造事实,draft_quote逐字引用无依据的已发生事实,required_text为空;允许拟实施方案。'
|
||||
'无确证的推测、格式偏好、签章实物缺失、未知字段待补,不作为可自动修复错误。没有成立意见返回confirmed=[]。' + feedback,
|
||||
{'project': request.project, 'guidance': request.workbench.get('guidance',''), 'requirements': [r.model_dump() for r in request.requirements],
|
||||
'source': [b.model_dump() for b in request.blocks], 'company': [b.model_dump() for b in request.company],
|
||||
'draft': result, 'issues': [{'index': i, 'finding': issue} for i, issue in enumerate(issues)], **evidence_data},
|
||||
schema, deadline, max_tokens=2200)
|
||||
try:
|
||||
if feedback and evidence_data:
|
||||
selected = SelectedAuditFindings.model_validate(raw)
|
||||
restored = []
|
||||
for item in selected.confirmed:
|
||||
if ((item.draft_id and item.draft_id not in draft_ids)
|
||||
or (item.source_id and item.source_id not in source_ids)):
|
||||
raise ValueError('未知复核引用编号')
|
||||
restored.append(dict(index=item.index, kind=item.kind,
|
||||
draft_quote=draft_ids.get(item.draft_id, ''),
|
||||
required_text=source_ids.get(item.source_id, ''), explanation=item.explanation))
|
||||
parsed = AuditFindings.model_validate({'confirmed': restored})
|
||||
else:
|
||||
parsed = AuditFindings.model_validate(raw)
|
||||
except ValueError as exc:
|
||||
raise AuditEvidenceError('复核意见结构无效,请重新核对意见,不改写正文。') from exc
|
||||
def flatten(value):
|
||||
if isinstance(value, str): return [value]
|
||||
if isinstance(value, list): return [text for item in value for text in flatten(item)]
|
||||
if isinstance(value, dict): return [text for item in value.values() for text in flatten(item)]
|
||||
return []
|
||||
def norm(value): return re.sub(r'\s+', '', value)
|
||||
actual = norm('\n'.join(flatten(result.get('paragraphs', [])) + flatten(result.get('tables', []))))
|
||||
acknowledged = re.sub(r'我方(?:同意|确认|承诺)', '', actual)
|
||||
source = norm('\n'.join([request.project] + [b.text for b in request.blocks + request.company] + [r.text for r in request.requirements]))
|
||||
seen = set(); confirmed = []
|
||||
for item in parsed.confirmed:
|
||||
if item.index >= len(issues) or item.index in seen:
|
||||
raise AuditEvidenceError('章节复核意见编号重复或无效')
|
||||
seen.add(item.index)
|
||||
quote, required = norm(item.draft_quote), norm(item.required_text)
|
||||
if item.kind == 'missing_text':
|
||||
if len(required) < 2 or required not in source:
|
||||
raise AuditEvidenceError('遗漏意见 required_text 不在原文中:' + item.required_text[:180] + '。请逐字引用原文中的连续短句,不得概括或拼接。')
|
||||
if required in actual or required in acknowledged:
|
||||
continue
|
||||
# An omission is proved against the source and the whole draft.
|
||||
# Its optional draft_quote is not evidence: absent text cannot be
|
||||
# quoted from a draft. Only incorrect/unsupported facts require it.
|
||||
else:
|
||||
if not quote or quote not in actual:
|
||||
raise AuditEvidenceError('复核意见未引用实际稿件')
|
||||
if item.kind == 'incorrect_text' and (not required or required not in source):
|
||||
raise AuditEvidenceError('改写意见没有正确的原文依据')
|
||||
if item.kind == 'incorrect_text' and quote == required:
|
||||
continue
|
||||
confirmed.append(issues[item.index])
|
||||
save()
|
||||
if progress is not None:progress.state.pop('workbench_audit_feedback',None);progress.persist(True)
|
||||
return confirmed
|
||||
|
||||
|
||||
def workbench_step(request, *, invoke):
|
||||
deadline = time.monotonic() + STEP_SECONDS
|
||||
progress = current_progress.get()
|
||||
if progress is not None:
|
||||
progress.deadline = deadline
|
||||
if request.action == 'outline':
|
||||
schema = Outline.model_json_schema()
|
||||
keys = [item['key'] for item in request.workbench['catalog']]
|
||||
schema['$defs']['OutlineNode']['properties']['topics']['items']['enum'] = keys
|
||||
saved = progress.state.get('workbench_outline_candidate') if progress else None
|
||||
if saved:
|
||||
parsed = Outline.model_validate(saved)
|
||||
completed = _complete_outline(request, parsed, invoke, deadline)
|
||||
completed = _expand_outline(request, completed, invoke, deadline)
|
||||
return dict(rule_version=RULE_VERSION, **completed.model_dump())
|
||||
raw, save = _review_response('workbench_outline', invoke,
|
||||
COMMON + '\n规划投标文件多级目录,暂不写正文。catalog是需要编写的主题。'
|
||||
'优先遵循source_outline中明确的投标文件组成和规定格式;'
|
||||
'不要把招标文件自身的采购流程目录直接复制为投标目录。'
|
||||
'每个主题编号恰好分配一次,不漏项;可合并相关主题到同一节。'
|
||||
'每个可编写小节最多8个相关主题,不能把几十个主题合成一个技术或商务大章。'
|
||||
'容器章节topics可为空,叶子节topics非空。首项level=1,层级不能跳级,'
|
||||
'最多三级。objective说明该节具体写什么,标题精炼且有层次。'
|
||||
'只输出本次catalog对应目录,不编造无依据的资质或分册。',
|
||||
{'project': request.project, 'instructions': request.instructions, **request.workbench},
|
||||
schema, deadline, max_tokens=5000)
|
||||
parsed = Outline.model_validate(raw)
|
||||
assigned = [key for node in parsed.chapters for key in node.topics]
|
||||
if set(assigned) - set(keys):
|
||||
raise JobValidationBlocked('目录引用了本次范围之外的主题,请重试目录规划。')
|
||||
previous = 0
|
||||
for i, node in enumerate(parsed.chapters):
|
||||
if node.level > previous + 1:
|
||||
raise JobValidationBlocked('目录层级不连续,请重试目录规划。')
|
||||
if not node.topics and (i + 1 == len(parsed.chapters) or parsed.chapters[i+1].level <= node.level):
|
||||
raise JobValidationBlocked('目录存在没有内容的末级章节,请重试目录规划。')
|
||||
previous = node.level
|
||||
save()
|
||||
if progress is not None:
|
||||
progress.state['workbench_outline_candidate'] = parsed.model_dump()
|
||||
progress.persist(True)
|
||||
completed = _complete_outline(request, parsed, invoke, deadline)
|
||||
completed = _expand_outline(request, completed, invoke, deadline)
|
||||
return dict(rule_version=RULE_VERSION, **completed.model_dump())
|
||||
|
||||
evidence = _evidence(request.blocks)
|
||||
if not evidence:
|
||||
raise JobValidationBlocked('本批没有可解析的原文')
|
||||
schema = SourceGroups.model_json_schema()
|
||||
schema['$defs']['SourceGroup']['properties']['evidence_ids']['items']['enum'] = list(evidence)
|
||||
instruction = COMMON + '''
|
||||
按主题与用途归类招标原文,仅输出分组标题和evidence_ids,不改写或复述正文。程序将逐字保存原文作为要求。
|
||||
同一事项的条件与例外归入同组。尽量合并相同主题,不能按每段或每个证据编号新建一组。
|
||||
usage: response正文响应;form规定表式;attachment证明附件;delivery递交/签章检查;reference背景;clarify待澄清。
|
||||
title是写作主题(如测试方法、项目组织、技术响应表),不是每条要求独立章,也不是机械的技术标/商务标大类。
|
||||
未明确选中的“□无需”和“□需要”属于待确认选项,uncertain=true,保留全部备选条件。
|
||||
issues只列有原文依据的待确认事项,不据此停止其余要求的提取。不得把采购人职责写成投标人承诺。
|
||||
引用选择evidence_ids,程序恢复逐字原文,不必抄写引文。背景无需凑成要求。
|
||||
每个原文编号恰好归入一组,包括标题和背景。纯标题与背景集中归入reference,不当成应答要求。
|
||||
不要为了减少分组把资格、技术、评分、否决、否定条件或适用选项归为背景。程序仍独立检查遗漏编号。
|
||||
source是原文块的编号与位置索引;evidence按原文顺序提供完整内容,相同block_id属于同一原文块。
|
||||
'''
|
||||
if progress is not None and progress.state.get('workbench_repair'):
|
||||
return _repair_analysis(request, progress.state['workbench_repair'], evidence, invoke, deadline)
|
||||
feedback = progress.state.get('workbench_feedback', '') if progress else ''
|
||||
attempts = progress.state.get('workbench_attempts', 0) if progress else 0
|
||||
for attempt in range(attempts, 2):
|
||||
raw, save = _review_response('workbench_analysis', invoke, instruction + feedback,
|
||||
{'project': request.project, 'instructions': request.instructions,
|
||||
'source': [{'id': b.id, 'location': b.location} for b in request.blocks],
|
||||
'evidence': [{'id': key, **value} for key, value in evidence.items()]},
|
||||
schema, deadline, max_tokens=4000)
|
||||
try:
|
||||
if 'groups' in raw:
|
||||
rows, used, issues = source_rows(raw,evidence)
|
||||
else:
|
||||
# Read saved candidates from the initial workspace protocol.
|
||||
parsed=Analysis.model_validate(raw);rows=[];used=set();issues=parsed.issues
|
||||
for item in parsed.requirements:
|
||||
if any(key not in evidence for key in item.evidence_ids):raise ValueError('要求引用了本批之外的原文')
|
||||
used.update(item.evidence_ids);row=item.model_dump(exclude={'evidence_ids'});row['basis']=[evidence[key] for key in dict.fromkeys(item.evidence_ids)]
|
||||
if any('□' in ref['quote'] or '☐' in ref['quote'] for ref in row['basis']):row['uncertain']=True
|
||||
rows.append(row)
|
||||
result = dict(requirements=rows, conflicts=[], split_required=False)
|
||||
# Save the structurally grounded candidate before the independent
|
||||
# audit; a budget yield resumes the audit instead of regenerating.
|
||||
save()
|
||||
try:
|
||||
_verify_extraction_completion(request, result, [key for key in evidence if key not in used],
|
||||
evidence, invoke, deadline)
|
||||
except ExtractionCoverageError as exc:
|
||||
repair = dict(requirements=rows, issues=issues, missing=list(exc.ids), attempts=0)
|
||||
if progress is not None:
|
||||
progress.state['workbench_repair'] = repair
|
||||
progress.persist(True)
|
||||
return _repair_analysis(request, repair, evidence, invoke, deadline)
|
||||
save()
|
||||
return dict(rule_version=RULE_VERSION, requirements=rows, issues=issues, extraction_complete=True)
|
||||
except ValueError as exc:
|
||||
feedback = '\n上次解析需要修正:' + str(exc)[:1600]
|
||||
if progress is not None:
|
||||
progress.state['workbench_feedback'] = feedback
|
||||
progress.state['workbench_attempts'] = attempt + 1
|
||||
progress.persist(True)
|
||||
if len(request.blocks) > 1:
|
||||
return dict(rule_version=RULE_VERSION, job_status='split_required')
|
||||
raise JobValidationBlocked('本段解析尚未通过引用或覆盖校验,已保存其他完成结果:' + feedback)
|
||||
|
||||
|
||||
def _repair_analysis(request, repair, evidence, invoke, deadline):
|
||||
"""Only append independently confirmed gaps; never rewrite accepted rows."""
|
||||
progress = current_progress.get()
|
||||
while repair['missing']:
|
||||
targets = repair['missing'][:4]
|
||||
schema = Analysis.model_json_schema()
|
||||
schema['properties']['requirements']['maxItems'] = 12
|
||||
schema['$defs']['AnalyzedItem']['properties']['evidence_ids']['items']['enum'] = list(evidence)
|
||||
raw, save = _review_response('workbench_gap', invoke,
|
||||
COMMON + '\n仅补充targets中已确认遗漏的实质要求,已提取内容不得重写或重复。'
|
||||
'每条新增要求至少引用一个targets编号,保留适用条件、选项和数值。'
|
||||
'字段usage使用response/form/attachment/delivery/reference/clarify之一;'
|
||||
'topic为写作主题,uncertain表示需要人工确认。issues不要重复已有意见。',
|
||||
{'targets':[dict(id=key, **evidence[key]) for key in targets],
|
||||
'existing':[dict(title=r['title'],text=r['text']) for r in repair['requirements']],
|
||||
'context':[b.model_dump() for b in request.blocks]}, schema, deadline, max_tokens=2600)
|
||||
try:
|
||||
parsed=Analysis.model_validate(raw)
|
||||
used=set(); additions=[]
|
||||
for item in parsed.requirements:
|
||||
if not set(item.evidence_ids).intersection(targets) or any(key not in evidence for key in item.evidence_ids):
|
||||
raise ValueError('补充要求未引用目标原文')
|
||||
row=item.model_dump(exclude={'evidence_ids'})
|
||||
row['basis']=[evidence[key] for key in dict.fromkeys(item.evidence_ids)]
|
||||
if any('□' in ref['quote'] or '☐' in ref['quote'] for ref in row['basis']):row['uncertain']=True
|
||||
if any(r['text']==row['text'] for r in repair['requirements']):raise ValueError('补充结果重复既有要求')
|
||||
used.update(item.evidence_ids);additions.append(row)
|
||||
if not set(targets).issubset(used):raise ValueError('补充结果仍未覆盖已确认遗漏')
|
||||
save();repair['requirements'].extend(additions);repair['missing']=repair['missing'][len(targets):]
|
||||
repair['issues'].extend(parsed.issues);repair['attempts']=0
|
||||
if progress is not None:progress.persist(True)
|
||||
except ValueError as exc:
|
||||
repair['attempts']+=1
|
||||
if progress is not None:progress.persist(True)
|
||||
if repair['attempts']>=2:
|
||||
raise JobValidationBlocked('已保留解析结果,本次补漏仍未通过校验:'+str(exc)) from exc
|
||||
return dict(rule_version=RULE_VERSION, requirements=repair['requirements'], issues=repair['issues'], extraction_complete=True)
|
||||
Reference in New Issue
Block a user