From 9790d904e0765b9d499f75bdfd0f347141442601 Mon Sep 17 00:00:00 2001 From: eason <85663565+mango766@users.noreply.github.com> Date: Wed, 8 Apr 2026 15:10:59 +0800 Subject: [PATCH] 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 --- .../hindsight_api/engine/retain/orchestrator.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/hindsight-api-slim/hindsight_api/engine/retain/orchestrator.py b/hindsight-api-slim/hindsight_api/engine/retain/orchestrator.py index 2c577444..9870553c 100644 --- a/hindsight-api-slim/hindsight_api/engine/retain/orchestrator.py +++ b/hindsight-api-slim/hindsight_api/engine/retain/orchestrator.py @@ -1522,7 +1522,12 @@ def _map_results_to_contents( """Map created unit IDs back to original content items.""" facts_by_content: dict[int, list[int]] = {i: [] for i in range(len(contents))} 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 = [] unit_idx = 0