llamaIndex - ✅(Solved) Fix fix(metrics): CohereRankingMeasure catches IndexError instead of KeyError for missing API key [1 pull requests, 1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
run-llama/llama_index#21362Fetched 2026-04-12 13:24:06
View on GitHub
Comments
0
Participants
1
Timeline
1
Reactions
0
Participants
Timeline (top)
cross-referenced ×1

In llama-index-core/llama_index/core/evaluation/retrieval/metrics.py, the CohereRankingMeasure.__init__ method catches IndexError when accessing os.environ["COHERE_API_KEY"]. However, dict/os.environ key lookups raise KeyError, not IndexError. IndexError is only raised for sequence index operations (e.g., list[n]).

This means the except branch is never triggered when COHERE_API_KEY is absent — instead Python propagates an unhandled KeyError with no helpful message.

Error Message

import os os.environ.pop("COHERE_API_KEY", None) from llama_index.core.evaluation.retrieval.metrics import CohereRankingMeasure CohereRankingMeasure()

Raises: KeyError: 'COHERE_API_KEY' (not the helpful ValueError)

Root Cause

In llama-index-core/llama_index/core/evaluation/retrieval/metrics.py, the CohereRankingMeasure.__init__ method catches IndexError when accessing os.environ["COHERE_API_KEY"]. However, dict/os.environ key lookups raise KeyError, not IndexError. IndexError is only raised for sequence index operations (e.g., list[n]).

This means the except branch is never triggered when COHERE_API_KEY is absent — instead Python propagates an unhandled KeyError with no helpful message.

Fix Action

Fix

Change except IndexError: to except KeyError: on line ~445 of metrics.py.

PR fix notes

PR #21363: fix(metrics): catch KeyError not IndexError for missing COHERE_API_KEY; fix truncated warning in token splitter

Description (problem / solution / changelog)

Summary

Fixes two bugs in llama-index-core:

  • Bug A (evaluation/retrieval/metrics.py): CohereRankingMeasure.__init__ caught IndexError when accessing os.environ["COHERE_API_KEY"]. os.environ raises KeyError on missing keys — IndexError is never triggered, so the helpful ValueError message was never shown. Changed to except KeyError.
  • Bug B (node_parser/text/token.py): _logger.warning() was called with two separate positional f-strings; Python's logging.warning accepts only one message argument — the second argument was silently ignored, truncating the warning. Concatenated into a single f-string.

Test plan

  • Confirm CohereRankingMeasure() with no COHERE_API_KEY env var raises ValueError (not KeyError)
  • Confirm token splitter warning shows full message: "Got a split of size N, larger than chunk size M."
  • Run existing tests: pytest llama-index-core/tests/ -k "token" — 50 passed

Closes #21362

Changed files

  • llama-index-core/llama_index/core/evaluation/retrieval/metrics.py (modified, +1/-1)
  • llama-index-core/llama_index/core/node_parser/text/token.py (modified, +1/-1)

Code Example

import os
os.environ.pop("COHERE_API_KEY", None)
from llama_index.core.evaluation.retrieval.metrics import CohereRankingMeasure
CohereRankingMeasure()
# Raises: KeyError: 'COHERE_API_KEY'  (not the helpful ValueError)
RAW_BUFFERClick to expand / collapse

Description

In llama-index-core/llama_index/core/evaluation/retrieval/metrics.py, the CohereRankingMeasure.__init__ method catches IndexError when accessing os.environ["COHERE_API_KEY"]. However, dict/os.environ key lookups raise KeyError, not IndexError. IndexError is only raised for sequence index operations (e.g., list[n]).

This means the except branch is never triggered when COHERE_API_KEY is absent — instead Python propagates an unhandled KeyError with no helpful message.

Steps to Reproduce

import os
os.environ.pop("COHERE_API_KEY", None)
from llama_index.core.evaluation.retrieval.metrics import CohereRankingMeasure
CohereRankingMeasure()
# Raises: KeyError: 'COHERE_API_KEY'  (not the helpful ValueError)

Expected Behavior

Raises ValueError with message: "Must pass in cohere api key or specify via COHERE_API_KEY environment variable".

Actual Behavior

Raises unhandled KeyError: 'COHERE_API_KEY' — the except IndexError block is never reached.

Fix

Change except IndexError: to except KeyError: on line ~445 of metrics.py.

Also Fixed

In llama-index-core/llama_index/core/node_parser/text/token.py, _logger.warning() was called with two separate positional arguments (two f-strings), causing only the first to be logged — the second f-string was silently discarded. The two strings have been concatenated into one f-string so the complete message "Got a split of size {split_len}, larger than chunk size {chunk_size}." is emitted.

extent analysis

TL;DR

Change the except IndexError: block to except KeyError: in the CohereRankingMeasure.__init__ method to correctly handle the absence of the COHERE_API_KEY environment variable.

Guidance

  • Identify the line of code where the except IndexError: block is located (around line 445 of metrics.py) and update it to except KeyError:.
  • Verify that the COHERE_API_KEY environment variable is set before running the CohereRankingMeasure class.
  • Test the updated code by running the Steps to Reproduce section and ensure that it raises a ValueError with the expected message instead of an unhandled KeyError.
  • Review other parts of the codebase for similar issues where IndexError is caught instead of KeyError for dictionary key lookups.

Example

try:
    api_key = os.environ["COHERE_API_KEY"]
except KeyError:
    raise ValueError("Must pass in cohere api key or specify via COHERE_API_KEY environment variable")

Notes

This fix assumes that the intention is to raise a ValueError with a helpful message when the COHERE_API_KEY environment variable is not set. If the desired behavior is different, additional changes may be necessary.

Recommendation

Apply the workaround by changing the except IndexError: block to except KeyError: to ensure that the code correctly handles the absence of the COHERE_API_KEY environment variable and raises a ValueError with a helpful message.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING