fix: clamp out-of-range content_index in _map_results_to_contents (#908)

Some LLM providers (e.g. Anthropic Haiku) return 1-indexed
content_index values. When only one content item is provided,
this causes KeyError: 1 since the dict only has key 0.

Clamp content_index to the valid range instead of crashing.

Fixes #873

Co-authored-by: easonysliu <easonysliu@tencent.com>
This commit is contained in:
eason 2026-04-08 15:10:59 +08:00 committed by GitHub
parent 2463efd0f2
commit 9790d904e0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1522,7 +1522,12 @@ def _map_results_to_contents(
"""Map created unit IDs back to original content items.""" """Map created unit IDs back to original content items."""
facts_by_content: dict[int, list[int]] = {i: [] for i in range(len(contents))} facts_by_content: dict[int, list[int]] = {i: [] for i in range(len(contents))}
for i, fact in enumerate(extracted_facts): for i, fact in enumerate(extracted_facts):
facts_by_content[fact.content_index].append(i) # Normalize content_index: some LLM providers return 1-indexed values.
# Clamp to valid range to prevent KeyError.
idx = fact.content_index
if idx < 0 or idx >= len(contents):
idx = min(max(idx, 0), len(contents) - 1) if len(contents) > 0 else 0
facts_by_content[idx].append(i)
result_unit_ids = [] result_unit_ids = []
unit_idx = 0 unit_idx = 0