Skip to content

Commit 4641dfe

Browse files
committed
Reduce summary integration stalls
1 parent 5c65d0d commit 4641dfe

3 files changed

Lines changed: 100 additions & 15 deletions

File tree

‎README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,15 @@ copy config.json config.local.json
323323

324324
`CODEX_USE_PROXY` 默认为 `false`,总结接口不会继承系统 `HTTP_PROXY` / `HTTPS_PROXY`。如果你的接口必须走代理,再改成 `true`。
325325

326+
如果总结阶段长时间停在“整合方法、结果和分析”,通常是大模型接口长时间没有返回。默认单次接口超时为 120 秒,默认重试 2 次;确实需要更慢接口时可以在 `config.local.json` 中调整:
327+
328+
```json
329+
{
330+
"CODEX_TIMEOUT_SECONDS": "180",
331+
"CODEX_CHAT_ATTEMPTS": "2"
332+
}
333+
```
334+
326335
`config.local.json` 已加入 `.gitignore`,不会提交到 GitHub。你当前机器上的真实配置保存在该文件中,本地启动时直接指定它即可。
327336

328337
## 启动命令

‎paper_agent/paper_summary.py‎

Lines changed: 78 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2866,7 +2866,7 @@ def _summarize_chunks_with_codex(
28662866
prompt_patches: list[PromptPatch] | None = None,
28672867
) -> list[str]:
28682868
chunks = _chunk_text(paper_text, 16000)
2869-
asset_context = _asset_context(assets)
2869+
asset_context = _asset_context(assets, text_preview_chars=700, latex_preview_chars=800)
28702870
memories = correction_memories or []
28712871
patches = prompt_patches or _build_prompt_patches(memories)
28722872
memory_context = _correction_memory_context(memories)
@@ -2910,13 +2910,13 @@ def _integrate_summary_with_codex(
29102910
correction_memories: list[CorrectionMemory] | None = None,
29112911
prompt_patches: list[PromptPatch] | None = None,
29122912
) -> str:
2913-
asset_context = _asset_context(assets)
2913+
asset_context = _asset_context(assets, text_preview_chars=500, latex_preview_chars=800)
29142914
formula_context = _formula_context(formulas)
29152915
memories = correction_memories or []
29162916
patches = prompt_patches or _build_prompt_patches(memories)
29172917
memory_context = _correction_memory_context(memories)
29182918
summarization_patch = _prompt_patch_context(patches, "summarization")
2919-
final_input = "\n\n".join(f"[Chunk {i + 1}]\n{note}" for i, note in enumerate(chunk_notes))
2919+
final_input = _compact_chunk_notes_for_final(chunk_notes)
29202920
return _chat(
29212921
client,
29222922
model,
@@ -2938,6 +2938,40 @@ def _integrate_summary_with_codex(
29382938
)
29392939

29402940

2941+
def _compact_chunk_notes_for_final(chunk_notes: list[str], max_total_chars: int = 36000) -> str:
2942+
if not chunk_notes:
2943+
return ""
2944+
2945+
per_chunk_limit = max(3000, max_total_chars // max(1, len(chunk_notes)))
2946+
compacted = []
2947+
total = 0
2948+
for idx, note in enumerate(chunk_notes, 1):
2949+
cleaned = _postprocess_summary(note)
2950+
remaining = max_total_chars - total
2951+
if remaining <= 0:
2952+
break
2953+
limit = min(per_chunk_limit, remaining)
2954+
chunk_text = _truncate_middle(cleaned, limit)
2955+
compacted.append(f"[Chunk {idx}]\n{chunk_text}")
2956+
total += len(chunk_text)
2957+
return "\n\n".join(compacted)
2958+
2959+
2960+
def _truncate_middle(text: str, max_chars: int) -> str:
2961+
text = text.strip()
2962+
if max_chars <= 0 or len(text) <= max_chars:
2963+
return text
2964+
if max_chars < 200:
2965+
return text[:max_chars].rstrip()
2966+
head = max_chars // 2
2967+
tail = max_chars - head - 80
2968+
return (
2969+
text[:head].rstrip()
2970+
+ "\n\n...[中间内容已压缩以避免最终整合请求过大]...\n\n"
2971+
+ text[-tail:].lstrip()
2972+
)
2973+
2974+
29412975
def _verify_summary_claims(
29422976
summary: str,
29432977
paper_text: str,
@@ -4095,25 +4129,44 @@ def _extract_json_object(text: str) -> str:
40954129

40964130

40974131
def _create_codex_client(config: CodexConfig) -> openai.OpenAI:
4132+
timeout_seconds = _codex_timeout_seconds()
40984133
http_client = httpx.Client(
40994134
trust_env=config.use_proxy,
4100-
timeout=httpx.Timeout(600.0, connect=30.0),
4135+
timeout=httpx.Timeout(timeout_seconds, connect=min(20.0, timeout_seconds)),
41014136
)
41024137
return openai.OpenAI(
41034138
base_url=config.base_url,
41044139
api_key=config.api_key,
41054140
http_client=http_client,
4106-
max_retries=2,
4141+
max_retries=0,
41074142
)
41084143

41094144

4145+
def _codex_timeout_seconds() -> float:
4146+
raw_value = _first_value({}, "CODEX_TIMEOUT_SECONDS", "CODEX_TIMEOUT")
4147+
try:
4148+
value = float(raw_value) if raw_value else 120.0
4149+
except ValueError:
4150+
value = 120.0
4151+
return max(30.0, min(value, 600.0))
4152+
4153+
4154+
def _codex_chat_attempts() -> int:
4155+
raw_value = _first_value({}, "CODEX_CHAT_ATTEMPTS", "CODEX_MAX_RETRIES")
4156+
try:
4157+
value = int(raw_value) if raw_value else 2
4158+
except ValueError:
4159+
value = 2
4160+
return max(1, min(value, 4))
4161+
4162+
41104163
def _chat(
41114164
client: openai.OpenAI,
41124165
model: str,
41134166
user_prompt: str,
41144167
system_prompt: str = DEEP_PAPER_NOTE_SYSTEM_PROMPT,
41154168
) -> str:
4116-
max_attempts = 4
4169+
max_attempts = _codex_chat_attempts()
41174170
last_error: Exception | None = None
41184171
for attempt in range(max_attempts):
41194172
try:
@@ -4132,13 +4185,23 @@ def _chat(
41324185
if not _is_retryable_openai_status(exc) or attempt + 1 >= max_attempts:
41334186
break
41344187
time.sleep(_chat_retry_delay(attempt))
4188+
except openai.APITimeoutError as exc:
4189+
last_error = exc
4190+
if attempt + 1 >= max_attempts:
4191+
break
4192+
time.sleep(_chat_retry_delay(attempt))
41354193
except openai.APIConnectionError as exc:
41364194
last_error = exc
41374195
if attempt + 1 >= max_attempts:
41384196
break
41394197
time.sleep(_chat_retry_delay(attempt))
41404198
if isinstance(last_error, openai.APIStatusError):
41414199
raise RuntimeError(_openai_status_error_message(last_error, max_attempts)) from last_error
4200+
if isinstance(last_error, openai.APITimeoutError):
4201+
raise RuntimeError(
4202+
f"Codex 接口响应超时,已重试 {max_attempts} 次仍未成功。"
4203+
"当前默认单次超时为 120 秒;如果接口确实很慢,可以在 config.local.json 中设置 CODEX_TIMEOUT_SECONDS。"
4204+
) from last_error
41424205
if isinstance(last_error, openai.APIConnectionError):
41434206
raise RuntimeError(
41444207
f"Codex 接口连接失败,已重试 {max_attempts} 次仍未成功:服务端断开或网络链路不稳定。"
@@ -4477,7 +4540,11 @@ def frac(match: re.Match) -> str:
44774540
return text
44784541

44794542

4480-
def _asset_context(assets: list[PaperAsset]) -> str:
4543+
def _asset_context(
4544+
assets: list[PaperAsset],
4545+
text_preview_chars: int = 1500,
4546+
latex_preview_chars: int = 2000,
4547+
) -> str:
44814548
if not assets:
44824549
return "未抽取到图表截图。"
44834550
parts = []
@@ -4492,10 +4559,10 @@ def _asset_context(assets: list[PaperAsset]) -> str:
44924559
f"建议插入章节:{_target_section_for_asset(asset)},"
44934560
f"caption/context: {_clean_xml_text(asset.caption)}"
44944561
)
4495-
if asset.text:
4496-
text += f"\n表格文本预览:\n{_clean_xml_text(asset.text[:1500])}"
4497-
if asset.latex:
4498-
text += f"\nTexTeller LaTeX:{_clean_xml_text(asset.latex)}"
4562+
if asset.text and text_preview_chars > 0:
4563+
text += f"\n表格文本预览:\n{_clean_xml_text(asset.text[:text_preview_chars])}"
4564+
if asset.latex and latex_preview_chars > 0:
4565+
text += f"\nTexTeller LaTeX:{_clean_xml_text(asset.latex[:latex_preview_chars])}"
44994566
parts.append(text)
45004567
return "\n".join(parts)
45014568

‎paper_agent/skill_prompts.py‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
logger = logging.getLogger(__name__)
1212

1313
PAPER_AGENT_SKILL_ID = "paper-agent-paper-reading"
14+
_REFERENCE_CACHE: dict[str, str] = {}
1415

1516

1617
def paper_agent_skill_root() -> Path:
@@ -39,10 +40,10 @@ def _skillbridge_command() -> tuple[list[str], Path] | None:
3940
if not cli_entrypoint.exists():
4041
return None
4142

42-
if shutil.which("pnpm"):
43-
return (["pnpm", "skillbridge"], bridge_root)
4443
if shutil.which("node"):
4544
return (["node", str(cli_entrypoint)], bridge_root)
45+
if shutil.which("pnpm"):
46+
return (["pnpm", "skillbridge"], bridge_root)
4647
return None
4748

4849

@@ -61,6 +62,8 @@ def _load_reference_via_skillbridge(reference_name: str) -> str | None:
6162
cwd=str(cwd),
6263
capture_output=True,
6364
text=True,
65+
encoding="utf-8",
66+
errors="replace",
6467
timeout=30,
6568
check=False,
6669
)
@@ -74,7 +77,7 @@ def _load_reference_via_skillbridge(reference_name: str) -> str | None:
7477

7578
try:
7679
payload = json.loads(completed.stdout)
77-
except json.JSONDecodeError:
80+
except (TypeError, json.JSONDecodeError):
7881
logger.debug("SkillBridge prompt load did not return JSON.")
7982
return None
8083

@@ -90,16 +93,22 @@ def _load_reference_via_skillbridge(reference_name: str) -> str | None:
9093

9194

9295
def load_paper_skill_reference(reference_name: str, default: str = "") -> str:
96+
if reference_name in _REFERENCE_CACHE:
97+
return _REFERENCE_CACHE[reference_name] or default
98+
9399
bridge_text = _load_reference_via_skillbridge(reference_name)
94100
if bridge_text:
101+
_REFERENCE_CACHE[reference_name] = bridge_text
95102
return bridge_text
96103

97104
reference_path = paper_agent_skill_root() / "references" / reference_name
98105
try:
99106
text = reference_path.read_text(encoding="utf-8").strip()
100107
except OSError:
101108
return default
102-
return text or default
109+
result = text or default
110+
_REFERENCE_CACHE[reference_name] = result
111+
return result
103112

104113

105114
__all__ = [

0 commit comments

Comments
 (0)