112 lines
4.9 KiB
Python
112 lines
4.9 KiB
Python
"""Bounded hierarchical organization; source and completed chunks survive failures."""
|
||
import re
|
||
import time
|
||
|
||
|
||
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):
|
||
if budget < 256:
|
||
raise ValueError('模型上下文预算不足,请调大上下文或减少输出长度')
|
||
chunks, current = [], ''
|
||
blocks = re.split(r'(?m)(?=^#{1,6} )', text)
|
||
for block in blocks:
|
||
while block:
|
||
if token_bound(current + block) <= budget:
|
||
current += block
|
||
break
|
||
if current:
|
||
chunks.append(current); current = ''
|
||
if token_bound(block) <= budget:
|
||
current = block
|
||
break
|
||
lo, hi = 1, min(len(block), budget)
|
||
while lo < hi:
|
||
mid = (lo + hi + 1) // 2
|
||
if token_bound(block[:mid]) <= budget:
|
||
lo = mid
|
||
else:
|
||
hi = mid - 1
|
||
end = lo
|
||
newline = block.rfind('\n', 0, end)
|
||
if newline > end // 2:
|
||
end = newline + 1
|
||
# 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 organize(markdown, prompt, invoke, *, context_tokens=32768, output_tokens=4096,
|
||
safety_tokens=1024, progress=None, checkpoint=None):
|
||
budget = context_tokens - output_tokens - safety_tokens - token_bound(prompt) - 512
|
||
chunks = split_markdown(markdown, budget)
|
||
if len(chunks) > 128:
|
||
raise ValueError('文档分块过多,请调大模型上下文或拆分文档')
|
||
calls = 0
|
||
|
||
def call(content, instruction):
|
||
nonlocal calls
|
||
calls += 1
|
||
if calls > 160:
|
||
raise ValueError('整理批次过多,请拆分文档')
|
||
if token_bound(content) + token_bound(instruction) > context_tokens - output_tokens - safety_tokens:
|
||
raise ValueError('模型输入超过上下文预算')
|
||
for attempt in range(3):
|
||
try:
|
||
response = invoke(instruction, content)
|
||
break
|
||
except Exception as exc:
|
||
if attempt == 2:
|
||
raise ValueError('模型调用失败,已保留原稿和完成的分块,请稍后重试') from exc
|
||
time.sleep(attempt + 1)
|
||
metadata = getattr(response, 'response_metadata', {})
|
||
if isinstance(metadata, dict) and metadata.get('finish_reason') in ('length', 'max_tokens'):
|
||
raise ValueError('模型输出被截断,请到模型管理调大该模型的输出上限,或减少整理内容')
|
||
result = getattr(response, 'content', response)
|
||
if isinstance(result, list):
|
||
result = ''.join(item.get('text', '') for item in result if isinstance(item, dict))
|
||
if not isinstance(result, str) or not result.strip():
|
||
raise ValueError('模型未返回有效整理内容')
|
||
return result.strip()
|
||
|
||
outputs = []
|
||
chunk_prompt = prompt + '\n这是文档的一个分块,保留事实及标题关系,精简重复内容。'
|
||
for index, chunk in enumerate(chunks, 1):
|
||
if progress:
|
||
progress({'stage': f'智能整理分块 {index}/{len(chunks)}', 'percent': (index - 1) * 70 // len(chunks)})
|
||
outputs.append(call(chunk, prompt if len(chunks) == 1 else chunk_prompt))
|
||
if checkpoint:
|
||
checkpoint(list(outputs))
|
||
if len(outputs) == 1:
|
||
return outputs[0]
|
||
merge_prompt = prompt + '\n合并以下局部大纲,统一标题层级,压缩重复内容;保留事实、数字和图片占位符。'
|
||
previous_size = None
|
||
for round_index in range(4):
|
||
joined = '\n\n'.join(outputs)
|
||
groups = split_markdown(joined, budget)
|
||
if previous_size is not None and token_bound(joined) >= previous_size and len(groups) > 1:
|
||
raise ValueError('合并结果未收敛,已保留完成的分块,请缩小文档或调整提示词')
|
||
previous_size = token_bound(joined)
|
||
merged = []
|
||
for index, group in enumerate(groups, 1):
|
||
if progress:
|
||
progress({'stage': f'合并大纲 {round_index + 1}:{index}/{len(groups)}', 'percent': 70 + round_index * 6})
|
||
merged.append(call(group, merge_prompt))
|
||
if checkpoint:
|
||
checkpoint(merged)
|
||
if len(merged) == 1:
|
||
return merged[0]
|
||
outputs = merged
|
||
raise ValueError('合并批次超过限制,已保留完成的分块')
|