TruLens developer on retainer: default context extractor receives List[Document] as Python repr string — groundedness evaluator scores against metadata-polluted context — 0.42 groundedness for 6 months on answers that are actually correct — TruLens developer on monthly retainer

trulens-eval 0.27.0 • LangChain 0.2.12 • FAISS vector store • OpenAI GPT-4o evaluator • Select.RecordCalls path extracts List[Document] repr • context includes metadata fields source, page, chunk_id, embedding_model • groundedness 0.42 average vs 0.81 post-fix • 6 months of false low scores • fix: custom context extractor to doc.page_content • 2.5h retainer engagement

Northgate LLM Systems Inc. builds enterprise RAG systems for legal document review. After deploying TruLens to monitor groundedness in their document Q&A pipeline, they ran into a confounding discrepancy that persisted for six months: the TruLens groundedness metric averaged 0.42, well below their SLA threshold of 0.75, while their weekly manual review of 20 sampled questions consistently produced correct, well-supported answers that reviewers estimated at roughly 0.82 groundedness. The team had been iterating on their RAG pipeline — switching embedding models, adjusting chunk sizes, tuning retrieval k — trying to improve the TruLens score without any success. They could not understand why their instrumented metric and their human reviewers were so far apart. The TruLens retainer developer’s diagnosis required one hour of inspection to identify: the groundedness evaluator was not measuring faithfulness. It was measuring the GPT-4o model’s ability to parse Python object notation.

Northgate’s TruLens setup used a standard TruChain wrapper with a Select.RecordCalls path to extract the retrieval context. The configuration looked correct at a glance:

# evaluation/setup_trulens.py
# Northgate LLM Systems Inc.
# trulens-eval 0.27.0, langchain 0.2.12, Python 3.11

from trulens_eval import TruChain, Feedback, Select, Tru
from trulens_eval.feedback.provider import OpenAI as TruOpenAI

tru = Tru(database_url="sqlite:///trulens_eval.db")

provider = TruOpenAI(model_engine="gpt-4o")

f_groundedness = (
    Feedback(
        provider.groundedness_measure_with_cot_reasons,
        name="Groundedness",
    )
    .on(
        Select.RecordCalls.chain.__call__.args.inputs["context"]
    )
    .on_output()
)

tru_rag = TruChain(
    rag_chain,
    app_id="legal-doc-qa-v3",
    feedbacks=[f_groundedness, f_context_relevance],
)

# rag/chain.py
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_core.runnables import RunnableParallel, RunnablePassthrough

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
vectorstore = FAISS.load_local("legal_docs_index", embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})

# Context is passed as List[Document] directly — not converted to string
rag_chain = RunnableParallel(
    {
        "context": retriever,           # Returns List[Document]
        "input": RunnablePassthrough(),
    }
) | {
    "answer": prompt | llm | StrOutputParser(),
    "context": lambda x: x["context"],  # Pass-through List[Document]
}

The issue is in how Select.RecordCalls.chain.__call__.args.inputs["context"] interacts with the chain’s output type. In Northgate’s chain, context is a List[Document] — a Python list of LangChain Document objects returned by the FAISS retriever. TruLens’s Feedback.on() method selects this value and passes it to groundedness_measure_with_cot_reasons. The provider function calls str() on the received context before constructing the evaluator prompt. str() on a List[Document] produces the Python repr: a string that begins [Document(page_content='Section 14.3 Contract Termination. Either party may terminate...', and continues with the full metadata dictionary — metadata={'source': 's3://legal-docs/master-service-agreement-v7.pdf', 'page': 23, 'chunk_id': 'msa_v7_chunk_0441', 'embedding_model': 'text-embedding-3-large', 'created_at': '2026-04-15T09:23:41Z', 'doc_type': 'msa', 'client_id': 'northgate_internal', 'indexed_at': '2026-04-16T02:11:08Z'}. The GPT-4o groundedness evaluator receives this Python object notation as its “context” and must parse the repr structure to locate the actual text content before it can assess whether the answer is grounded in that content.

The retainer developer confirmed the issue by fetching a recent TruLens record and navigating the Select path to inspect the actual value received by the evaluator:

# diagnosis/inspect_trulens_context.py
# Examine what TruLens passes to the groundedness evaluator.

from trulens_eval import Tru, Select
from trulens_eval.schema import Record

tru = Tru(database_url="sqlite:///trulens_eval.db")

# Fetch a recent record and inspect the context value
records_df, _ = tru.get_records_and_feedback(app_ids=["legal-doc-qa-v3"])
recent_record = records_df.iloc[0]

# Deserialize the TruLens Record
record = Record.model_validate_json(recent_record["record_json"])

# Navigate the Select path to see the actual context value
context_selector = Select.RecordCalls.chain.__call__.args.inputs["context"]
context_value = context_selector.get(record)

print(f"Context type: {type(context_value)}")
print(f"Context repr (first 500 chars): {str(context_value)[:500]}")
print(f"Context repr length: {len(str(context_value))}")

# Output:
# Context type: <class 'list'>
# Context repr (first 500 chars):
# [Document(page_content='Section 14.3 Contract Termination. Either party may terminate this agreement ...
# metadata={'source': 's3://legal-docs/master-service-agreement-v7.pdf', 'page': 23,
# 'chunk_id': 'msa_v7_chunk_0441', 'embedding_model': 'text-embedding-3-large',
# 'created_at': '2026-04-15T09:23:41Z', 'doc_type': 'msa', 'client_id': 'northgate_internal', ...
# Context repr length: 4,847

The full context repr was 4,847 characters, of which approximately 1,100 characters were actual document content across 4 documents and approximately 3,747 characters were Python object notation: opening brackets, Document(page_content= wrappers, closing parentheses, and the complete metadata dictionaries for each document. The GPT-4o evaluator was receiving a string that was 77% overhead and 23% signal. For a typical answer like “The agreement requires 90 days’ written notice for termination under Section 14.3”, the evaluator had to find “90 days” inside page_content='Section 14.3 Contract Termination. Either party may terminate this agreement by providing not less than 90 calendar days\' written notice...' — with escaped apostrophes, Python string delimiters, and surrounding metadata competing for the evaluator’s chain-of-thought budget. The 0.42 score was not measuring groundedness. It was measuring the evaluator’s parser.

The fix was a custom context extractor that maps over the Document list and returns only page_content, then passes the result through Feedback.on() with a .map() transformer:

# evaluation/setup_trulens_fixed.py
from trulens_eval import TruChain, Feedback, Select, Tru
from trulens_eval.feedback.provider import OpenAI as TruOpenAI
from langchain.schema import Document
from typing import Union

tru = Tru(database_url="sqlite:///trulens_eval.db")
provider = TruOpenAI(model_engine="gpt-4o")

def extract_page_content(context: Union[list, str]) -> str:
    """
    Extract plain text from a list of LangChain Document objects.
    Returns a clean context string with only page_content — no Python
    repr, no metadata fields, no object notation.
    """
    if isinstance(context, list):
        parts = []
        for item in context:
            if hasattr(item, 'page_content'):
                parts.append(item.page_content)
            elif isinstance(item, dict) and 'page_content' in item:
                parts.append(item['page_content'])
            else:
                parts.append(str(item))
        return "\n\n---\n\n".join(parts)
    return str(context)

# Fixed feedback function: .map() extracts page_content before evaluation
f_groundedness = (
    Feedback(
        provider.groundedness_measure_with_cot_reasons,
        name="Groundedness",
    )
    .on(
        Select.RecordCalls.chain.__call__.args.inputs["context"].map(
            lambda doc: doc.page_content
            if hasattr(doc, 'page_content')
            else str(doc)
        )
    )
    .on_output()
)

tru_rag = TruChain(
    rag_chain,
    app_id="legal-doc-qa-v4",   # New app_id to separate pre/post fix metrics
    feedbacks=[f_groundedness, f_context_relevance],
)

After deploying the custom context extractor, the TruLens groundedness metric immediately recovered to 0.81 on the same query set — matching the manually-reviewed estimate of 0.82 within measurement noise. The retainer developer re-ran the evaluation on 50 historical queries by replaying the chain with the new TruChain configuration and confirmed the result was stable. The 0.42 score had been an artifact of the evaluation infrastructure, not a signal about the RAG pipeline quality.

The six-month impact of this issue was significant in engineering terms. The team had been spending 4–6 engineer-hours per week investigating what they believed were groundedness problems in their RAG pipeline. They had changed the FAISS index configuration twice, adjusted chunk sizes from 512 to 768 tokens, switched the embedding model from text-embedding-ada-002 to text-embedding-3-large, and experimented with reranking. None of these changes improved the TruLens score meaningfully, because the score was not sensitive to pipeline quality — it was measuring the evaluator LLM’s ability to parse Python repr notation, which does not change when you swap embedding models. All of the configuration changes had been wasted engineering effort chasing a metric that was measuring the wrong thing.

The postmortem identified a process gap: Northgate had never run a baseline evaluation to verify that the TruLens metrics were calibrated against their manual review. They had assumed that configuring TruLens correctly meant the metrics were meaningful. After the fix, the team added a calibration step to their evaluation onboarding process: whenever a new feedback function is configured, it must be run against 20 hand-labeled query-answer-context triples with known ground-truth scores, and the TruLens score must correlate with the ground-truth scores at r > 0.8 before the feedback function is used for production monitoring. This calibration check takes 30 minutes and would have caught the Document repr issue in the first week of deployment.

Total retainer engagement: 2.5 hours (0.5h initial triage: review TruLens dashboard for low groundedness scores, compare against manual review results, note 0.42 vs ~0.82 discrepancy, examine TruChain configuration, check context selector path; 1.0h diagnostic: write inspect_trulens_context.py to fetch TruLens records and navigate the Select path, print the actual context value received by the evaluator, confirm it is the Python repr of List[Document] including all metadata fields, measure repr length at 4,847 characters vs actual content at ~1,100 characters; 0.5h fix implementation: write extract_page_content function and Feedback.on() with .map() to extract only page_content, rerun evaluation on 50 historical queries with clean context, confirm groundedness 0.81; 0.5h documentation: write postmortem, update retainer work log in HourTab with trulens-eval version, context extractor issue, and fix).

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →