This commit is contained in:
zyp
2026-11-25 17:25:46 +08:00
parent c27f84cf91
commit 066a5023b7
11 changed files with 767 additions and 53 deletions
+130 -8
View File
@@ -13,6 +13,7 @@ from app.modules.work_assistant.review_jobs import JobDeferred
from app.modules.work_assistant.personnel_recovery import (row_fingerprint, raw_handles, failure_units, shape_feedback,
apply_repair, reassess_findings, accept_generation_part)
from app.modules.work_assistant.personnel_workflow import GROUPS, BEHAVIOR_CONTRACT, accept_group, migrate_parts, normalize_presentation
from app.modules.work_assistant import personnel_context as context
RULE_VERSION = "personnel-profile-v6"
REVIEW_SECONDS = 150
@@ -23,6 +24,7 @@ MAX_RESULT_TOKENS = 10000
GROUNDING_REVISION = 18
REPAIR_REVISION = 34
REVIEW_CACHE_RULE = f'{RULE_VERSION}:grounding-{GROUNDING_REVISION}:repair-{REPAIR_REVISION}'
REVIEW_POLICY = f'{REVIEW_CACHE_RULE}:context-{context.CONTEXT_REVISION}:recovery-1'
KEYS = ("recent", "fit", "attitude", "development", "assignment")
@@ -571,6 +573,63 @@ def validate(entry,raw):
return {**result.model_dump(),"analysis_version":RULE_VERSION,"heading_review_version":3,"detail_review_version":1,"assessment_scope":"duties" if any(e.kind=="duty" for e in entry.evidence) else "tasks"}
def verified_partial_profile(entry, checkpoint):
"""Publish verifiable work records when some analysis cannot pass validation."""
evidence = [source for source in entry.evidence if source.content.strip()]
duties = [source for source in evidence if source.kind == 'duty']
actual = sorted((source for source in evidence if source.kind in {'log', 'feedback'} and source.relation == 'self'),
key=lambda source: source.at, reverse=True)
checks = sorted((source for source in evidence if source.kind == 'review' and source.relation == 'reviewer'),
key=lambda source: source.at, reverse=True)
bodies = [source for source in evidence if source.kind == 'deliverable' and source.read_state in {'text', 'text_partial'}]
tasks = [source for source in evidence if source.kind == 'task']
def basis(sources):
return [{'evidence_id': source.id, 'quote': source.content.strip()[:180]} for source in sources]
def finding(key, heading, summary, sources, status='insufficient'):
return dict(key=key, headline=heading, finding=summary, action='', status=status, basis=basis(sources))
records = actual[:3]+checks[:1]+bodies[:1]
submitted = [label for label, source in (('本人工作记录', actual), ('检查评价', checks), ('成果正文', bodies)) if source]
facts = '已核读'+'、'.join(submitted)+',主要事项可查看所附原文。' if submitted else '当前材料可用于核对任务要求及安排,实际交付还需查看对应工作记录。'
result = {section: [] for section in DETAIL_SECTIONS}
result['findings'] = [
finding('recent', '本期工作记录', facts, records or tasks[:3]),
finding('fit', '工作结果待逐项核实', '可查看已有工作、交付和检查记录,具体完成程度及交付质量待按对应事项核实。', checks[:2]+bodies[:1]+tasks[:2]+duties[:1]),
finding('attitude', '查看本期履责事例', '可核对所附记录中记载的实际动作,综合履责判断待补核。', actual[:2]+checks[:1]),
finding('development', '后续适配方向待核实', '结合已有工作和对应要求复核后,可进一步确定适合侧重的工作。', actual[:2]+duties[:1]),
finding('assignment', '下一阶段分工待核实', '待主管结合原有工作及岗位要求复核,再确认下一阶段分工。', duties[:1]+(records or tasks or evidence)[:2], 'review_required'),
]
checked = validate(entry, result)
try:
_, excerpts = material(entry)
candidate = attach_task_basis(resolve(checkpoint.get('candidate'), excerpts), entry, excerpts)
candidate = Decision.model_validate(candidate).model_dump()
except (ValueError, TypeError, AttributeError, KeyError):
candidate = {}
cache = (checkpoint.get('grounding_cache') or {}) if checkpoint.get('grounding_revision') == GROUNDING_REVISION else {}
for section in ('findings',)+DETAIL_SECTIONS:
for index, row in enumerate(candidate.get(section, [])):
fingerprint = row_fingerprint(section, row)
if fingerprint not in cache or cache[fingerprint]:
continue
rows = result[section].copy()
if section == 'findings':
rows[index] = row
else:
rows.append(row)
updated = {**result, section: rows}
# Factual summaries still need a way to open the known work, even
# when the surviving model findings cite a narrower set of records.
try:
checked = validate(entry, updated)
except ValueError:
continue
result = updated
return {**checked, 'assessment_status': 'partial', 'work_record_basis': basis(records or tasks[:3])}
def generation_schema(schema, actual_count, work_count=None, has_material=False, insufficient_keys=()):
"""Constrain status and reference cardinality while the model generates, not after display."""
output=deepcopy(schema);finding=output['$defs']['Finding'];allowed=finding['properties']['key']['enum'];variants=[]
@@ -1110,6 +1169,10 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
split_generation=bool(resume.get('split_generation',False))
generation_parts=deepcopy(resume.get('generation_parts',{}))
if staged:generation_parts=migrate_parts(generation_parts,KEYS)
scans=deepcopy(resume.get('context_scans',{})) if resume.get('context_revision')==context.CONTEXT_REVISION else {}
context_limits=deepcopy(resume.get('context_limits',{})) if resume.get('context_revision')==context.CONTEXT_REVISION else {}
scan_plan=None
original_handles={(ref['evidence_id'],ref['quote']):key for key,ref in excerpts.items()}
workflow_steps=int(resume.get('workflow_steps',0))
workflow_phase=resume.get('workflow_phase','generating')
calls_in_slice=0
@@ -1124,6 +1187,8 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
'grounding_cache':deepcopy(grounding_cache),'grounding_revision':GROUNDING_REVISION,'repair_revision':REPAIR_REVISION}
saved.update(workflow_steps=workflow_steps,workflow_phase=workflow_phase,operation_truncations=dict(operation_truncations))
saved['verification_batch_size']=verification_batch_size
if staged:
saved.update(context_revision=context.CONTEXT_REVISION,context_scans=deepcopy(scans),context_limits=dict(context_limits))
saved['verified_current']=0
if staged and isinstance(candidate,dict):
try:
@@ -1135,17 +1200,58 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
if save_checkpoint is not None:
save_checkpoint(saved)
def budgeted(instruction,payload,request_schema,**kwargs):
nonlocal truncations,format_failures,split_generation,calls_in_slice,workflow_steps,workflow_phase,verification_batch_size
nonlocal truncations,format_failures,split_generation,calls_in_slice,workflow_steps,workflow_phase,verification_batch_size,scan_plan
if staged and calls_in_slice:
remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections),last_checkpoint.get('validation_feedback'))
raise JobDeferred()
request_schema=future_role_contract(request_schema,data['duty_refs'],data['behavior_refs']+data['readable_refs'])
stage='verify' if 'issues' in request_schema.get('properties',{}) else 'repair' if 'repair_keys' in payload else 'generate'
operation='adjudicate' if payload.get('adjudication') else stage+':'+(payload.get('generation_part') or ','.join(payload.get('repair_keys',[])+payload.get('repair_sections',[])))
stage=('scan' if 'evidence_batch' in payload else 'verify' if 'issues' in request_schema.get('properties',{})
else 'repair' if 'repair_keys' in payload or 'validation_feedback' in payload else 'generate')
operation=('adjudicate' if payload.get('adjudication') else stage+':'+(payload.get('evidence_batch') or payload.get('generation_part')
or ','.join(payload.get('repair_keys',[])+payload.get('repair_sections',[]))))
transform=kwargs.pop('transform',lambda value:value)
budget_key=operation if staged else stage
tokens=max(kwargs['max_tokens'],budgets.get(budget_key,0));kwargs['max_tokens']=tokens
kwargs['prompt_schema']=prompt_contract(request_schema)
kwargs['prompt_schema']=request_schema if stage=='scan' else prompt_contract(request_schema)
visible=None
if staged and stage!='scan':
limit=min(context.input_budget(tokens),context_limits.get(operation,context.input_budget(tokens)))
count=lambda value:context.prompt_bytes(instruction,value,kwargs['prompt_schema'])
if count(payload)>limit:
# Verification is already local to cited rows. Split the pending
# assertions before narrowing a single row's reference context.
if stage=='verify' and not payload.get('adjudication') and verification_batch_size>1:
verification_batch_size=max(1,verification_batch_size//2)
remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections))
raise JobDeferred()
nested='material' in payload and 'evidence_columns' in payload['material']
base=payload['material'] if nested else payload
make_payload=lambda value:{**payload,'material':value} if nested else value
if 'evidence_columns' in base:
ranked=[]
if stage!='verify':
if scan_plan is None:scan_plan=[(context.scan_key(rows),rows) for rows in context.scan_pages(data)]
for key,rows in scan_plan:
if key in scans:continue
scans[key]=budgeted(context.SCAN_PROMPT,{'evidence_batch':key,'columns':['excerpt_id','kind','source_role','subject','date','text'],'rows':rows},
context.scan_schema(rows),timeout_seconds=60,max_tokens=480,transform=lambda value:context.accept_scan(value,rows))
remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections))
raise JobDeferred()
# Read one chosen passage from each batch before taking additional passages from older batches.
ranked=[scans[key][i] for i in range(12) for key,_ in scan_plan if i<len(scans[key])]
anchors=list(context.handles([payload.get('previous_rows'),payload.get('items')]))
if stage=='verify':
rows=(row for group in payload.get('candidate',{}).values() for row in group)
if payload.get('adjudication'):rows=(item['candidate'] for item in payload['items'])
anchors.extend(original_handles.get((basis['evidence_id'],basis['quote'])) for row in rows for basis in row.get('basis',[]))
elif stage=='generate' and payload.get('generation_part')=='work':
anchors.extend(ref for row in base.get('task_contexts',[]) for ref in [row['task'],*row['behavior'][:1]])
anchors.extend(ref for row in base.get('review_contexts',[]) for ref in [row['review'],*row['responses'][:1]])
scoped,visible=context.narrow(base,ranked,anchors,lambda value:count(make_payload(value))<=limit,trim_shared_text)
payload=make_payload(scoped)
request_schema=context.restrict_schema(request_schema,visible)
if count(payload)>limit:
raise ModelUnavailable('profile_context_limit')
# The deployed model can repeat a completed object inside a new Markdown
# fence. Stop there; JSON parsing and all evidence checks still apply.
kwargs['stop']=['\n```']
@@ -1154,12 +1260,15 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
# With a single upstream call per slice, waiting for admission must not
# acquire a model slot and immediately release it without doing work.
kwargs['minimum_execution_seconds']=0 if staged else 90 if stage=='generate' else 60
if staged:kwargs['timeout_seconds']=min(140,REVIEW_SECONDS-(time.monotonic()-started)-5)
workflow_phase={'generate':'generating','verify':'grounding','repair':'repairing'}[stage]
if staged:kwargs['timeout_seconds']=min(60 if stage=='scan' else 140,REVIEW_SECONDS-(time.monotonic()-started)-5)
workflow_phase={'scan':'scanning','generate':'generating','verify':'grounding','repair':'repairing'}[stage]
remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections),last_checkpoint.get('validation_feedback'))
calls_in_slice+=1
try:
value=transform(invoke(instruction,payload,request_schema,**kwargs))
response=invoke(instruction,payload,request_schema,**kwargs)
if visible is not None and stage!='verify' and any(ref not in visible for ref in context.handles(response)):
raise ModelOutputInvalid('personnel output cited material absent from this step')
value=transform(response)
workflow_steps+=1
format_attempts[operation]=0
return value
@@ -1180,12 +1289,25 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No
raise JobDeferred()
except ModelUnavailable as exc:
if exc.reason=='review_continuation':raise JobDeferred() from exc
if staged and stage=='verify' and not payload.get('adjudication') and verification_batch_size>1 and exc.reason in {'direct_output_truncated','gateway_output_truncated','direct_timeout'}:
if staged and stage=='scan' and exc.reason in {'model_context_full','context_capacity'}:
# These pages are already below the bounded input limit. A
# different upstream capacity must not reopen the same page forever.
raise ModelUnavailable('profile_context_limit') from exc
if staged and stage=='verify' and not payload.get('adjudication') and verification_batch_size>1 and exc.reason in {'direct_output_truncated','gateway_output_truncated','direct_timeout','model_context_full','context_capacity'}:
# A long verification response is a unit-size problem. Keep all
# accepted rows and automatically retry a smaller pending batch.
verification_batch_size=max(1,verification_batch_size//2)
remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections),last_checkpoint.get('validation_feedback'))
raise JobDeferred() from exc
if staged and stage!='scan' and exc.reason in {'model_context_full','context_capacity'}:
size=context.prompt_bytes(instruction,payload,kwargs['prompt_schema'])
previous=context_limits.get(operation,context.input_budget(tokens))
smaller=min(previous-2048,size-2048)
if smaller>=11000:
context_limits[operation]=smaller
remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections))
raise JobDeferred() from exc
raise ModelUnavailable('profile_context_limit') from exc
if stage=='generate' and not payload.get('generation_part') and not split_generation and exc.reason in {'model_context_full','direct_output_truncated','gateway_output_truncated'}:
split_generation=True
remember(raw,corrections)