Skip to content

Collections metrics silently evaluate stringified contexts character by character #3069

Open

Description

@rashmi09-sys

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

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?

Activity

  1. mangod12 commented on Oct 26, 2026

    @mangod12

    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.

  2. manjast commented on Oct 27, 2026

    @manjast

    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.

  3. rashmi09-sys commented on Oct 27, 2026

    @rashmi09-sys
    Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions