ragas icon indicating copy to clipboard operation
ragas copied to clipboard

Collections metrics silently evaluate stringified contexts character by character

Open rashmi09-sys opened this issue 1 month ago • 3 comments

Version: main @ 298b682. Reproduced offline with a counting fake client; no API calls.

What happens

Collections metrics (ragas.metrics.collections) accept a single string for retrieved_contexts / reference_contexts, even though they're typed List[str]. A string is iterable, so:

  • ContextPrecision / ContextUtilization make one judge call per character. For 3 contexts of ~500 characters: 3 calls as a list, 1,494 calls as a string. The score is normal-looking (1.000), with no error or warning.
  • Faithfulness, ContextRecall, ContextRelevance, ResponseGroundedness, ContextEntityRecall, SummaryScore, SQLSemanticEquivalence do "\n".join(contexts), so the judge sees [\n'\nP\na\nr\ni\ns…. You get a score computed on garbage.
  • NoiseSensitivity and the multi-modal metrics also loop per item, so they treat each character as one context.

The legacy path doesn't have this problem: SingleTurnSample(retrieved_contexts="['a']") raises a ValidationError.

How users hit it

local/csv, the backend the docs use for Dataset, stores every value as text, as its docstring documents. A context list saved with a dataset comes back as "['chunk 1', 'chunk 2']". Passing row["retrieved_contexts"] from a reloaded dataset into a collections metric triggers this.

Reproduce

import asyncio, tempfile
from ragas import Dataset
from ragas.llms.base import InstructorLLM
from ragas.metrics.collections import ContextPrecision

class FakeClient:  # counts judge calls; every context is "useful"
    def __init__(self):
        self.calls, outer = 0, self
        class C:
            async def create(self, *a, response_model, **k):
                outer.calls += 1
                return response_model(reason="useful", verdict=1)
        self.chat = type("Chat", (), {"completions": C()})()
        self.client = self

chunk = ("Paris is the capital and most populous city of France. " * 9).strip()
row = {"user_input": "What is the capital of France?", "reference": "Paris",
       "retrieved_contexts": [chunk, chunk, chunk]}

async def score(ctx):
    client = FakeClient()
    m = ContextPrecision(llm=InstructorLLM(client=client, model="fake", provider="openai"))
    r = await m.ascore(user_input=row["user_input"], reference=row["reference"], retrieved_contexts=ctx)
    return client.calls, r.value

with tempfile.TemporaryDirectory() as root:
    ds = Dataset(name="rag", backend="local/csv", root_dir=root); ds.append(row); ds.save()
    reloaded = Dataset.load(name="rag", backend="local/csv", root_dir=root)[0]["retrieved_contexts"]

print(type(reloaded).__name__, asyncio.run(score(row["retrieved_contexts"])), asyncio.run(score(reloaded)))
# str (3, 0.99999...) (1494, 0.99999...)   <- 498x the judge calls, same-looking score

Expected

A clear error before any judge call, e.g. retrieved_contexts must be a list of strings, not a single str, plus a hint when the value looks like a stringified list.

Why it matters

  • Silent wrong scores: nothing tells you the metric didn't evaluate your contexts.
  • Silent cost: judge calls scale with the character count (about 500× here). On a real dataset that's a large, unexpected bill.

Not a duplicate of

  • #2261 / #2452: the LangChain EvaluatorChain dropped valid string items from a list, which gave 0.0. That's a different code path (integrations/langchain.py) and the opposite failure.
  • #2860 / #2861 / #2865: backend serialization issues (CSV keys, JSONL dates), not metric input validation.

Proposed fix

Add a small shared check in metrics/collections/base.py, called first in each collections metric that takes a context list. A string is rejected with a ValueError before any LLM call; lists, tuples, None and the existing empty checks are unchanged.

I have a tested patch available and would be happy to open a PR. Would maintainers prefer immediate validation with ValueError, or a deprecation warning first?

rashmi09-sys avatar Oct 26 '26 09:10 rashmi09-sys

Hi maintainers — I’m interested in helping with this. The report suggests that a scalar string can be iterated character by character by the collections metrics, producing misleading scores and extra judge calls. Is this still an issue you’d like fixed, and what behavior would you prefer for scalar strings: reject them with a clear validation error, or support parsing stringified lists in a defined way? If the scope is still open, I can investigate a focused fix with regression tests.

mangod12 avatar Oct 26 '26 18:10 mangod12

The dataset guide uses local/csv for nested metadata, but CSV reloads it as a string. #3070 already has the validation fix and a JSONL hint.

Would a small docs-only PR help? I could switch that example to JSONL, include a complete save/load example and explain where CSV still fits. No changes to metrics or backends. If you're already covering the docs in #3070, I'll leave that with you.

manjast avatar Oct 27 '26 14:10 manjast

Thanks Stefan! #3070 only covers validation, so a separate docs PR would be helpful. Feel free to go ahead : )

rashmi09-sys avatar Oct 27 '26 14:10 rashmi09-sys