396 lines
23 KiB
Python
396 lines
23 KiB
Python
"""Bounded hierarchical organization; source and completed chunks survive failures."""
|
||
import re
|
||
import time
|
||
import hashlib
|
||
import json
|
||
import threading
|
||
from models_provider.context_policy import DEFAULT_CONTEXT_TOKENS, summary_defaults
|
||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||
from system_manage.summary_plan import LOCAL_PARAMETERS, prompt_rules, output_estimate, source_language, language_rule, language_matches, boundaries_match
|
||
|
||
ORGANIZER_PARAMETERS = LOCAL_PARAMETERS
|
||
|
||
|
||
def resolve_settings(defaults, params):
|
||
"""Workflow overrides win; model-management fields configure the organizer locally."""
|
||
defaults = summary_defaults(defaults)
|
||
def number(name, value, low, high):
|
||
if isinstance(value, str) and value.isdigit():
|
||
value = int(value)
|
||
if type(value) is not int or not low <= value <= high:
|
||
raise ValueError(f'总结参数 {name} 无效,请填写 {low} 至 {high} 的整数')
|
||
return value
|
||
context = number('context_tokens', params.get('context_tokens', defaults['context_tokens']), 1024, 2000000)
|
||
if context > int(defaults['context_tokens']):
|
||
raise ValueError('上下文超过模型配置上限,请先在模型管理中配置能力参数')
|
||
output = number('output_tokens', params.get('max_tokens', params.get('output_tokens',
|
||
defaults['output_tokens'])), 1, 524288)
|
||
safety = number('safety_tokens', params.get('safety_tokens', defaults['safety_tokens']), 0, 200000)
|
||
if output + safety >= context:
|
||
raise ValueError('总结输出与预留长度不能超过上下文长度')
|
||
for key, value in [('context_tokens', context), ('max_input_tokens', params.get('max_input_tokens')),
|
||
('max_output_tokens', max(output, params.get('max_output_tokens') or 0))]:
|
||
limit = defaults.get(key)
|
||
if limit is not None and value is not None and int(value) > int(limit):
|
||
raise ValueError(f'总结参数超过模型配置的 {key} 上限')
|
||
if params.get('max_output_tokens') is not None and output > params['max_output_tokens']:
|
||
raise ValueError('本次输出长度超过模型最大输出长度')
|
||
return {'context_tokens': context, 'output_tokens': output, 'safety_tokens': safety}
|
||
|
||
|
||
def token_bound(text):
|
||
# A conservative UTF-8 byte bound avoids assuming one tokenizer for all providers.
|
||
return len(text.encode('utf-8'))
|
||
|
||
|
||
def split_markdown(text, budget, count=None):
|
||
count = count or token_bound
|
||
if budget < 256:
|
||
raise ValueError('模型上下文预算不足,请调大上下文或减少输出长度')
|
||
chunks, current = [], ''
|
||
# Do not mistake headings inside fenced examples for document sections.
|
||
protected = list(re.finditer(r'(?ms)^```[^\n]*\n.*?^```[^\n]*(?:\n|$)|^~~~[^\n]*\n.*?^~~~[^\n]*(?:\n|$)', text))
|
||
boundaries = [m.start() for m in re.finditer(r'(?m)^#{1,6} ', text)
|
||
if not any(span.start() <= m.start() < span.end() for span in protected)]
|
||
boundaries = sorted(set([0, *boundaries, len(text)]))
|
||
blocks = [text[a:b] for a, b in zip(boundaries, boundaries[1:])]
|
||
for block in blocks:
|
||
while block:
|
||
if count(current + block) <= budget:
|
||
current += block
|
||
break
|
||
if current:
|
||
chunks.append(current); current = ''
|
||
if count(block) <= budget:
|
||
current = block
|
||
break
|
||
lo, hi = 1, len(block)
|
||
while lo < hi:
|
||
mid = (lo + hi + 1) // 2
|
||
if count(block[:mid]) <= budget:
|
||
lo = mid
|
||
else:
|
||
hi = mid - 1
|
||
end = lo
|
||
newline = block.rfind('\n', 0, end)
|
||
if newline > end // 2:
|
||
end = newline + 1
|
||
# Keep a table, fenced example, or consecutive list together when
|
||
# the whole block fits; oversized blocks may still be continued.
|
||
spans = re.finditer(r'(?ms)^```[^\n]*\n.*?^```[^\n]*(?:\n|$)|^~~~[^\n]*\n.*?^~~~[^\n]*(?:\n|$)|(?:^\|[^\n]*\n?)+|(?:^[ \t]*(?:[-*+] |\d+[.)] )[^\n]*\n?)+', block)
|
||
for span in spans:
|
||
if span.start() < end < span.end() and count(span[0]) <= budget:
|
||
end = span.start() if span.start() else span.end()
|
||
break
|
||
# Never split an image placeholder between requests.
|
||
for match in re.finditer(r'AIHUBIMAGE\s*\d+\s*TOKEN', block[:end + 64]):
|
||
if match.start() < end < match.end():
|
||
end = match.start()
|
||
break
|
||
if not end:
|
||
raise ValueError('图片占位符超过模型输入预算')
|
||
chunks.append(block[:end]); block = block[end:]
|
||
if current:
|
||
chunks.append(current)
|
||
return chunks
|
||
|
||
|
||
def plan_document(markdown, prompt, settings, options, count=token_bound):
|
||
context_tokens, output_tokens, safety_tokens = (settings[key] for key in ('context_tokens', 'output_tokens', 'safety_tokens'))
|
||
instruction = prompt_rules(prompt, options, source_language(markdown, prompt))
|
||
# Includes bounded batch context, retry guidance, and message framing.
|
||
input_limit = min(context_tokens - output_tokens - safety_tokens,
|
||
options.get('max_input_tokens') or context_tokens)
|
||
budget = input_limit - count(instruction) - 2048
|
||
if budget < 256:
|
||
raise ValueError('模型上下文预算不足,请减少提示词或输出预留')
|
||
ratio = max(.05, output_estimate(markdown, count, options) / max(1, count(markdown)))
|
||
# Output risk can require splitting even when input fits. Never constrain
|
||
# every map result to a fraction of the final merge's output allowance.
|
||
output_budget = max(256, int(output_tokens * .8 / ratio))
|
||
chunk_budget = min(budget, output_budget)
|
||
chunks = split_markdown(markdown, chunk_budget, count)
|
||
if len(chunks) > 128:
|
||
raise ValueError('文档分块过多,请调大模型预算或拆分文档')
|
||
if len(chunks) > 1 and not options.get('auto_split', True):
|
||
raise ValueError('文档超过输入或输出预算,请开启自动拆分')
|
||
return instruction, input_limit, budget, chunk_budget, chunks
|
||
|
||
|
||
def organize(markdown, prompt, invoke, *, context_tokens=DEFAULT_CONTEXT_TOKENS, output_tokens=None,
|
||
safety_tokens=None, progress=None, checkpoint=None, metrics=None,
|
||
options=None, count=None, count_method='conservative_bytes', resume=None,
|
||
state_checkpoint=None, fingerprint_context=None):
|
||
options = options or {}
|
||
count = count or token_bound
|
||
inherited = summary_defaults({'context_tokens': context_tokens})
|
||
output_tokens = inherited['output_tokens'] if output_tokens is None else output_tokens
|
||
safety_tokens = inherited['safety_tokens'] if safety_tokens is None else safety_tokens
|
||
settings = {'context_tokens': context_tokens, 'output_tokens': output_tokens, 'safety_tokens': safety_tokens}
|
||
instruction, input_limit, budget, chunk_budget, chunks = plan_document(markdown, prompt, settings, options, count)
|
||
merge = len(chunks) > 1 and options.get('structure_mode', 'preserve') == 'reorganize'
|
||
concurrency = min(len(chunks), options.get('concurrency', 1)) if options.get('parallel', True) else 1
|
||
stats = metrics if metrics is not None else {}
|
||
stats.update(context_tokens=context_tokens, output_tokens=output_tokens, safety_tokens=safety_tokens,
|
||
input_bytes=token_bound(markdown), input_tokens_estimate=count(markdown), token_count_method=count_method,
|
||
input_budget=budget, chunk_budget=chunk_budget, map_chunks=len(chunks), concurrency=concurrency,
|
||
needs_merge=merge, expected_calls=len(chunks) + int(merge), model_calls=0,
|
||
compression_retries=0, language_retries=0, structure_retries=0, fact_retries=0, language_splits=0, split_retries=0, reused_chunks=0,
|
||
estimated_output_tokens=output_estimate(markdown, count, options))
|
||
fingerprint = hashlib.sha256(json.dumps([markdown, instruction, context_tokens, output_tokens,
|
||
safety_tokens, chunk_budget, options, fingerprint_context, 'summary-v4'],
|
||
ensure_ascii=False, sort_keys=True).encode()).hexdigest()
|
||
previous = (resume or {}).get('outputs', {}) if (resume or {}).get('fingerprint') == fingerprint else {}
|
||
saved = {key: value for key, value in previous.items() if isinstance(value, str) and value.strip()}
|
||
lock = threading.RLock()
|
||
last_saved = None
|
||
|
||
def persist():
|
||
nonlocal last_saved
|
||
with lock:
|
||
if checkpoint and saved != last_saved:
|
||
checkpoint(list(saved.values()))
|
||
last_saved = dict(saved)
|
||
if state_checkpoint:
|
||
state_checkpoint({'fingerprint': fingerprint, 'outputs': dict(saved), 'metrics': dict(stats)})
|
||
|
||
def report(stage, percent):
|
||
if progress:
|
||
progress({'stage': stage, 'percent': percent, 'plan': dict(stats)})
|
||
|
||
def call(content, guidance):
|
||
if count(content) + count(guidance) + 512 > input_limit:
|
||
raise ValueError('模型输入超过上下文预算')
|
||
for attempt in range(options.get('retries', 2) + 1):
|
||
with lock:
|
||
stats['model_calls'] += 1
|
||
if stats['model_calls'] > 160:
|
||
raise ValueError('总结调用超过限制,已保留完成分块')
|
||
try:
|
||
response = invoke(guidance, content)
|
||
break
|
||
except Exception as exc:
|
||
if attempt == options.get('retries', 2):
|
||
raise ValueError('模型调用失败,已保留原稿和完成的分块,请稍后重试') from exc
|
||
time.sleep(attempt + 1)
|
||
metadata = getattr(response, 'response_metadata', {}) or {}
|
||
truncated = (metadata.get('finish_reason') or metadata.get('done_reason')) in ('length', 'max_tokens', 'max_output_tokens')
|
||
value = getattr(response, 'content', response)
|
||
if isinstance(value, list):
|
||
value = ''.join(item.get('text', '') for item in value if isinstance(item, dict))
|
||
if not truncated and (not isinstance(value, str) or not value.strip()):
|
||
raise ValueError('模型未返回有效整理内容')
|
||
value = value.strip() if isinstance(value, str) else ''
|
||
if value.startswith('```'):
|
||
lines = value.splitlines()
|
||
closing = next((i for i, line in enumerate(lines[1:], 1) if re.fullmatch(r'```\s*', line)), len(lines))
|
||
value = '\n'.join(lines[1:closing]).strip()
|
||
elif '```' not in content:
|
||
closing = re.search(r'(?m)^```\s*$', value)
|
||
if closing:
|
||
value = value[:closing.start()].strip()
|
||
usage = getattr(response, 'usage_metadata', {}) or metadata.get('token_usage', {}) or {}
|
||
actual_output = usage.get('output_tokens', usage.get('completion_tokens', metadata.get('eval_count')))
|
||
return value, truncated, actual_output
|
||
|
||
def summarize(content, key, guidance, depth=0):
|
||
with lock:
|
||
if key in saved:
|
||
stats['reused_chunks'] += 1
|
||
return saved[key]
|
||
original = content
|
||
language = source_language(original, prompt)
|
||
language_failed = False
|
||
outline_source = re.sub(r'(?ms)^```[^\n]*\n.*?^```[^\n]*(?:\n|$)|^~~~[^\n]*\n.*?^~~~[^\n]*(?:\n|$)', '', original)
|
||
required_headings = re.findall(r'(?m)^(#{1,6}) (.+)$', outline_source) if options.get('structure_mode') == 'preserve' else []
|
||
outline = '\n'.join(hashes + ' ' + title for hashes, title in required_headings)
|
||
# An exceptionally large TOC would defeat the body budget; it is already
|
||
# present in the source. Include only bounded, exact outline guidance.
|
||
outline_hint = ('\nREQUIRED OUTPUT OUTLINE. Copy these headings EXACTLY and add summary bullets beneath each:\n' + outline
|
||
if outline and count(outline) <= 400 else '')
|
||
structure_failed = False
|
||
facts_failed = False
|
||
for attempt in range(2):
|
||
hint = guidance + f'\nOutput at most {output_tokens} tokens. Summarize concisely, do not repeat the full source.'
|
||
if attempt:
|
||
hint += '\nPrevious result failed validation. Return a concise, complete summary in the required language.'
|
||
with lock:
|
||
stats['language_retries' if language_failed else 'structure_retries' if structure_failed else 'fact_retries' if facts_failed else 'compression_retries'] += 1
|
||
hint += '\n' + language_rule(language)
|
||
hint += outline_hint
|
||
if language_failed or structure_failed:
|
||
hint += '\nVALIDATION FAILED. Keep ALL original section headings in order. Fill EACH section using its source language.'
|
||
if facts_failed:
|
||
hint += '\nNUMERIC CONDITION VALIDATION FAILED. Preserve all explicit comparison operators and conditions EXACTLY. Above/exceeds means >, not >= or reaches. Do not weaken or reverse a threshold.'
|
||
value, truncated, actual_output = call(content, hint)
|
||
source_sections = list(re.finditer(r'(?m)^(#{1,6}) (.+)$', outline_source)) if required_headings else []
|
||
target_sections = list(re.finditer(r'(?m)^(#{1,6}) (.+)$', value))
|
||
bodies = [outline_source[src.end():source_sections[j+1].start() if j+1 < len(source_sections) else len(outline_source)].strip()
|
||
for j, src in enumerate(source_sections)]
|
||
# A heading-only ancestor chain has one unambiguous body owner.
|
||
# Restore that skeleton in code instead of paying for a relabel call.
|
||
if (source_sections and sum(bool(body) for body in bodies) == 1 and bodies[-1] and target_sections and
|
||
all(not value[dst.end():target_sections[j+1].start()].strip() for j, dst in enumerate(target_sections[:-1]))):
|
||
last_body = value[target_sections[-1].end():].strip()
|
||
if (len(target_sections) <= len(source_sections) and
|
||
language_matches(last_body, source_language(bodies[-1], prompt)) and
|
||
set(re.findall(r'\d+(?:\.\d+)?', bodies[-1])) <= set(re.findall(r'\d+(?:\.\d+)?', last_body))):
|
||
value = '\n'.join(src[1] + ' ' + src[2] for src in source_sections) + '\n' + last_body
|
||
target_sections = list(re.finditer(r'(?m)^(#{1,6}) (.+)$', value))
|
||
aligned = bool(source_sections) and len(source_sections) == len(target_sections)
|
||
section_language_failed = False
|
||
if aligned:
|
||
# Headings are owned by the document. Restore harmless translated
|
||
# or reformatted labels only when section order, body languages,
|
||
# and numeric anchors agree; do not ask the model to relabel them.
|
||
for j, (src, dst) in enumerate(zip(source_sections, target_sections)):
|
||
body = outline_source[src.end():source_sections[j+1].start() if j+1 < len(source_sections) else len(outline_source)].strip()
|
||
summary = value[dst.end():target_sections[j+1].start() if j+1 < len(target_sections) else len(value)].strip()
|
||
anchors = set(re.findall(r'\d+(?:\.\d+)?', body))
|
||
if body and not language_matches(summary, source_language(body, prompt)):
|
||
section_language_failed = True
|
||
aligned = False
|
||
if not anchors <= set(re.findall(r'\d+(?:\.\d+)?', summary)):
|
||
aligned = False
|
||
if aligned:
|
||
for src, dst in reversed(list(zip(source_sections, target_sections))):
|
||
value = value[:dst.start()] + src[1] + ' ' + src[2] + value[dst.end():]
|
||
# With no model tokenizer use the conservative estimator, explicitly
|
||
# recorded in the plan. Provider finish_reason remains authoritative.
|
||
language_failed = section_language_failed or not language_matches(value, language)
|
||
facts_failed = not boundaries_match(original, value)
|
||
actual_headings = re.findall(r'(?m)^#{1,6} (.+)$', value)
|
||
remaining = iter(actual_headings)
|
||
heading_key = lambda title: re.sub(r'[*_`]', '', title).strip()
|
||
structure_failed = any(not any(heading_key(candidate) == heading_key(title) for candidate in remaining) for _, title in required_headings)
|
||
# Some small models translate mixed-language documents despite valid
|
||
# instructions. Retry only language-local sections, with no global
|
||
# rewrite. Models that succeed initially still use a single call.
|
||
body_languages = {source_language(body, prompt) for body in bodies if body}
|
||
if (attempt == 0 and depth < 2 and language == 'mixed' and (language_failed or structure_failed)
|
||
and len(body_languages) > 1 and body_languages <= {'english', 'chinese'}):
|
||
with lock:
|
||
stats['language_splits'] += 1
|
||
stats['expected_calls'] += sum(bool(body) for body in bodies)
|
||
parts = []
|
||
for j, (section, body) in enumerate(zip(source_sections, bodies)):
|
||
heading = section[1] + ' ' + section[2]
|
||
if not body:
|
||
parts.append(heading)
|
||
continue
|
||
section_language = source_language(body, prompt)
|
||
parts.append(summarize(heading + '\n' + body, key + '/language' + str(j),
|
||
prompt_rules(prompt, options, section_language) +
|
||
f'\nLanguage-local recovery section {j+1}/{len(source_sections)}. Only summarize this section.', depth+1))
|
||
value = '\n\n'.join(parts)
|
||
with lock:
|
||
saved[key] = value
|
||
return value
|
||
if not truncated and not language_failed and not structure_failed and not facts_failed and (actual_output if isinstance(actual_output, int) else count(value)) <= output_tokens:
|
||
# Restore original levels by ordered occurrence, including duplicate titles.
|
||
pending_headings = list(required_headings)
|
||
def restore_level(match):
|
||
if pending_headings and heading_key(match[2]) == heading_key(pending_headings[0][1]):
|
||
hashes, title = pending_headings.pop(0)
|
||
return hashes + ' ' + title
|
||
return match[0]
|
||
value = re.sub(r'(?m)^(#{1,6}) (.+)$', restore_level, value)
|
||
with lock:
|
||
saved[key] = value
|
||
return value
|
||
if language_failed or structure_failed or facts_failed:
|
||
content = original
|
||
elif not truncated and count(value) <= budget:
|
||
content = value
|
||
if language_failed:
|
||
raise ValueError('总结未保持原文语言,已保留完成分块;请调整提示词或更换模型后重试')
|
||
if structure_failed:
|
||
raise ValueError('总结未保留原文标题,已保留完成分块;请调整提示词或更换模型后重试')
|
||
if facts_failed:
|
||
raise ValueError('总结改变了数值边界条件,已保留原稿和完成分块;请调整提示词或更换模型后重试')
|
||
if depth >= 3 or count(original) <= 512:
|
||
raise ValueError('模型总结截断或长度校验未通过,已保留完成的分块,请提高输出上限或减少细节')
|
||
with lock:
|
||
stats['split_retries'] += 1
|
||
parts = split_markdown(original, max(256, (count(original) + 1) // 2), count)
|
||
values = [summarize(part, key + '/' + str(i), guidance +
|
||
f'\n本批继续拆分为 {len(parts)} 段,当前第 {i+1} 段,只总结当前正文。', depth + 1)
|
||
for i, part in enumerate(parts)]
|
||
value = '\n\n'.join(values)
|
||
with lock:
|
||
saved[key] = value
|
||
return value
|
||
|
||
report(f'预计 {len(chunks)} 批,并发 {concurrency},' + ('完成后汇总' if merge else '完成后组装'), 0)
|
||
outputs = [None] * len(chunks)
|
||
offset = 0
|
||
jobs = []
|
||
for i, chunk in enumerate(chunks):
|
||
prefix = markdown[:offset]
|
||
path = []
|
||
for match in re.finditer(r'(?m)^(#{1,6}) (.+)$', prefix):
|
||
level, title = len(match[1]), match[2]
|
||
path = [(n, t) for n, t in path if n < level] + [(level, title)]
|
||
headings = re.findall(r'(?m)^#{1,6} (.+)$', chunk)
|
||
opening_heading = re.match(r'^(#{1,6}) ', chunk)
|
||
if opening_heading:
|
||
path = [(level, title) for level, title in path if level < len(opening_heading[1])]
|
||
metadata = ('\nStage: full document.' if len(chunks) == 1 else
|
||
f'\nCONTEXT ONLY, NEVER INCLUDE IN OUTPUT: batch {i+1}/{len(chunks)}; '
|
||
f'ancestor path: {" > ".join(t for _, t in path)[-80:] or "document start"}; '
|
||
f'headings: {" > ".join(headings[:3])[:80] or "continued body"}; '
|
||
f'source character range {offset+1}-{offset+len(chunk)} of {len(markdown)}; '
|
||
f'previous/next batch: {i or "none"}/{i+2 if i+1 < len(chunks) else "none"}. '
|
||
'Summarize ONLY the current source, never infer other batches.'
|
||
+ (f'\nPrevious source excerpt for context only, do not summarize it again: {prefix[-80:]}'
|
||
if prefix and not opening_heading else ''))
|
||
jobs.append((chunk, f'part{i}', instruction + metadata))
|
||
offset += len(chunk)
|
||
error = None
|
||
if concurrency == 1:
|
||
for i, job in enumerate(jobs):
|
||
try:
|
||
outputs[i] = summarize(*job)
|
||
finally:
|
||
persist()
|
||
report(f'总结分块 {i+1}/{len(chunks)}', (i+1)*85//len(chunks))
|
||
else:
|
||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||
futures = {pool.submit(summarize, *job): i for i, job in enumerate(jobs)}
|
||
done = 0
|
||
for future in as_completed(futures):
|
||
try:
|
||
outputs[futures[future]] = future.result()
|
||
except Exception as exc:
|
||
error = error or exc
|
||
for pending in futures:
|
||
pending.cancel()
|
||
done += 1
|
||
persist()
|
||
report(f'总结分块 {done}/{len(chunks)}', done*85//len(chunks))
|
||
if error:
|
||
raise error
|
||
if merge:
|
||
for round_index in range(4):
|
||
joined = '\n\n'.join(outputs)
|
||
groups = split_markdown(joined, chunk_budget, count)
|
||
report(f'合并大纲 {round_index+1},共 {len(groups)} 批', 88 + round_index*2)
|
||
merged = []
|
||
for i, group in enumerate(groups):
|
||
try:
|
||
merged.append(summarize(group, f'merge{round_index}/{i}', instruction +
|
||
f'\n全局汇总阶段,当前第 {i+1}/{len(groups)} 组章节摘要。统一主题、去重,保持原文语言及不同条件。'))
|
||
finally:
|
||
persist()
|
||
if len(merged) == 1:
|
||
outputs = merged
|
||
break
|
||
if count('\n\n'.join(merged)) >= count(joined):
|
||
raise ValueError('合并结果未收敛,已保留完成的分块')
|
||
outputs = merged
|
||
else:
|
||
raise ValueError('合并批次超过限制,已保留完成的分块')
|
||
report('总结完成', 100)
|
||
persist()
|
||
return '\n\n'.join(outputs)
|