Files
company-ai-platform/app/modules/work_assistant/bid_outline_planning.py
T
2026-11-27 14:43:37 +08:00

177 lines
9.9 KiB
Python

"""Bounded outline planning; full evidence stays available for section writing."""
import json
from pydantic import Field
from .bid_writing import Strict, _review_response
class PlanningTopic(Strict):
category: str
text: str = Field(min_length=1, max_length=650)
evidence_ids: list[str] = Field(max_length=150)
class PlanningDigest(Strict):
topics: list[PlanningTopic] = Field(min_length=1, max_length=45)
class ScoreBinding(Strict):
evidence_id: str
chapter_index: int = Field(ge=0)
class ScoreContext(Strict):
evidence_id: str
reason: str = Field(min_length=1, max_length=300)
class ScoreBindings(Strict):
matches: list[ScoreBinding] = Field(default_factory=list, max_length=12)
context_only: list[ScoreContext] = Field(default_factory=list, max_length=12)
def retain_unbound_scores(result, pending):
"""Keep real, unresolved requirements available to writing without blocking
an otherwise usable outline or falsely binding them to an unrelated chapter.
Source facts stay on the chapter; the title does not invent a requirement.
"""
if not pending:
return
chapter = next((c for c in result['chapters'] if c['title'] == '评审要求补充响应'
and len(c['evidence_ids']) + len(pending) <= 120
and len(c['sections']) < 15), None)
if chapter is None:
chapter = dict(title='评审要求补充响应', weight=1, evidence_ids=[], sections=[])
if len(result['chapters']) < 40:
result['chapters'].append(chapter)
else:
chapter = min(result['chapters'], key=lambda c:len(c['sections']))
for row in pending:
if row['id'] in chapter['evidence_ids']:
continue
chapter['evidence_ids'].append(row['id'])
if not chapter['sections'] or len(chapter['sections'][-1]['points']) >= 12:
chapter['sections'].append(dict(title='评审要求核对与响应', points=[]))
# The complete source text is retrieved by evidence_id during writing.
title = row['text'].strip().split('。', 1)[0][:120]
chapter['sections'][-1]['points'].append(title or '评审要求响应')
def bind_missing_scores(result, evidence, invoke, deadline, policy, progress):
from copy import deepcopy
context_ids = set(progress.state.get('studio_outline_context', {})) if progress else set()
while True:
assigned = {key for chapter in result['chapters'] for key in chapter['evidence_ids']}
pending = [row for row in evidence if row.get('category') == 'scoring' and row['id'] not in assigned | context_ids][:12]
if not pending: return
keys = {row['id'] for row in pending}
schema = ScoreBindings.model_json_schema()
schema['$defs']['ScoreBinding']['properties']['evidence_id']['enum'] = sorted(keys)
schema['$defs']['ScoreContext']['properties']['evidence_id']['enum'] = sorted(keys)
schema['$defs']['ScoreBinding']['properties']['chapter_index']['maximum'] = len(result['chapters'])-1
raw, commit = _review_response('studio_outline_score_bindings', invoke, policy + (
'核对目录尚未绑定的评分依据。将每条评分项绑定到实际编写对应方案或证明的章节,'
'不要绑定到仅解释评分规则的章节。chapter_index从0开始,每条missing须指定一个最适合的现有章。'
'scoring分类可能含评审背景,不能把所有条目都当作需要单独响应的评分项。'
'仅描述未提供评分细则、评审组织或采购方评标程序且没有供应商响应义务的条目,'
'放入context_only并说明reason,不要为这些背景信息虚构响应章节。'
'具体评分指标、需提交的方案或证明不能放入context_only。'
'若目录完全没有可承载实际响应项的章节,不能虚假绑定,允许不返回该项;系统会保留原依据补充响应节点。'
), {'missing':pending, 'chapters':[{'title':chapter['title'], 'sections':chapter['sections']}
for chapter in result['chapters']]}, schema, deadline, max_tokens=1800)
# One omitted/malformed mapping must not discard the whole directory.
# Preserve unmatched input evidence instead of repeatedly asking the same
# impossible all-items-to-chapters question.
bound = set()
for item in raw.get('matches', []) if isinstance(raw, dict) and isinstance(raw.get('matches'), list) else []:
try:
row = ScoreBinding.model_validate(item)
except (ValueError, TypeError):
continue
if row.evidence_id in keys and row.chapter_index < len(result['chapters']) and row.evidence_id not in bound:
result['chapters'][row.chapter_index]['evidence_ids'].append(row.evidence_id)
bound.add(row.evidence_id)
for item in raw.get('context_only', []) if isinstance(raw, dict) and isinstance(raw.get('context_only'), list) else []:
try:
row = ScoreContext.model_validate(item)
except (ValueError, TypeError):
continue
if row.evidence_id in keys and row.evidence_id not in bound:
context_ids.add(row.evidence_id)
if progress:
progress.state.setdefault('studio_outline_context', {})[row.evidence_id] = row.reason
retain_unbound_scores(result, [row for row in pending if row['id'] not in bound | context_ids])
if progress:
progress.state['studio_outline_base'] = deepcopy(result)
progress.state['studio_validation_failures'] = 0
progress.state.pop('studio_validation_feedback',None)
progress.persist(True)
# Cache only a well-formed binding answer. The normalized outline itself
# has already been checkpointed, including any retained missing items.
try:
ScoreBindings.model_validate(raw)
except (ValueError, TypeError):
pass
else:
commit()
def outline_payload(payload):
# The original paragraphs are used during writing, not duplicated in planning.
return {key:value for key,value in payload.items()
if key not in {'source', 'company', 'source_context', 'evidence'}} | {
'evidence':[{'id':row['id'], 'category':row.get('category','overview'), 'text':row['text']}
for row in payload.get('evidence', [])]}
def bounded_outline(invoke, instruction, payload, schema, deadline, policy):
payload = outline_payload(payload)
fits = invoke.fits
if fits(instruction, payload, schema, 10000):
return _review_response('studio_outline', invoke, instruction, payload, schema, deadline, max_tokens=10000)
# Read every confirmed analysis paragraph and every finding in bounded batches.
# IDs survive reduction so writing can retrieve the full original source later.
topics = [{'category':row['category'], 'text':row['text'], 'evidence_ids':[row['id']]}
for row in payload.pop('evidence')]
analysis = payload.pop('analysis', {})
for category,text in analysis.items():
for line in str(text).splitlines():
if line.strip():
for start in range(0,len(line),2500):
topics.append({'category':category, 'text':line[start:start+2500], 'evidence_ids':[]})
instruction += 'planning_topics是分批整理后的目录规划依据,保留了原始依据编号;确认分析的人工修改优先。'
for round_no in range(4):
reduced = []
batches, batch, size = [], [], 0
for topic in topics:
wire = invoke.wire(topic)
amount = len(json.dumps(wire,ensure_ascii=False).encode('utf8'))
if batch and size + amount > 12000:
batches.append(batch); batch=[]; size=0
batch.append(topic); size+=amount
if batch: batches.append(batch)
for index,batch in enumerate(batches):
ids = {key for row in batch for key in row['evidence_ids']}
digest_schema = PlanningDigest.model_json_schema()
digest_schema['$defs']['PlanningTopic']['properties']['evidence_ids']['items']['enum'] = sorted(ids) or ['']
raw,commit = _review_response(f'studio_outline_digest_{round_no}_{index}', invoke, policy + (
'将这批依据压缩为目录规划主题,不写正文。合并同主题,保留采购对象、必须响应的技术范围、'
'评分主题、规定格式、暗标约束和交付成果。不要重复项目背景或复述条款。'
'每个主题用简短中文,尽量不超过120字;全部evidence_ids必须保留在对应主题中,不能引用外部编号。'
'同一批的不同评分要求不能遗漏,人工确认分析与提取结果冲突时保留确认分析及冲突说明。'
'category保持输入类别,无法合并的主题分别列出。没有依据编号的确认分析也必须整理。'
), {'topics':batch}, digest_schema, deadline, max_tokens=5000)
digest = PlanningDigest.model_validate(raw).model_dump()['topics']
assigned = {key for row in digest for key in row['evidence_ids']}
if assigned - ids:
raise ValueError('目录规划引用了不存在的依据')
# Never silently drop a finding when a digest misses its reference.
digest.extend(row for row in batch if set(row['evidence_ids']) - assigned)
reduced.extend(digest)
commit()
topics = reduced
content = {**payload, 'planning_topics':topics}
if fits(instruction, content, schema, 10000):
return _review_response('studio_outline', invoke, instruction, content, schema, deadline, max_tokens=10000)
raise ValueError('目录规划资料分批整理后仍超出单次模型容量,已保留各批结果,请精简重复的人工补充说明后重试')