评测需额外安装对应 provider 包(如 trulens-providers-openai),只装 trulens 不够;接入 LangChain 或 LlamaIndex 需另装 trulens-apps-langchain 或 trulens-apps-llamaindex;LLM judge 评测依赖外部模型服务,需自行准备 API 凭证

trulens
trueraMIT活跃维护给 LLM 应用和 AI Agent 做评测与追踪的工具,能记录实验过程、量化效果并定位问题,方便持续迭代和上线监控。
Evaluation and Tracking for LLM Experiments and AI Agents
pip install trulens
pip install trulens trulens-providers-openaiREADME 未说明
开源 LLM 应用与 Agent 的追踪评测工具,帮你定位失败步骤并比较版本成本
给 LLM 应用和 AI Agent 做评测与追踪的工具,能记录实验过程、量化效果并定位问题,方便持续迭代和上线监控。
核心能力
- 用装饰器 instrument 任意函数,按 OTEL span 记录每步输入输出
- 基于 OpenTelemetry 原生追踪,可导出到任意 OTLP 后端
- 提供七个 Agent 专用评测器,覆盖计划、工具选择与执行效率
- 支持在线边跑边评与离线批量 Run API 两种评测方式
- 用 Selector API 指定任意 span 属性作为评测输入
容易踩的坑
- trulens-2.16.0TruLens 2.16.0最新正式版2026-10-19 · 2026-10-19 17:17 UTC
TruLens 2.16
This release adds new evaluation metrics and Jury reliability metadata, improves handling of unparsable judge scores, and fixes cost accounting, batch evaluation, and OpenTelemetry tracing.
Breaking changes and compatibility
- Streamlit-in-Snowflake dashboard support has been removed. (#2784)
- All packages now require Python 3.10 or later. The test matrix now includes Python 3.14. (#2896)
New features
- Added a deterministic
conversation_repetitionmetric. (#2898) - Added a requirement satisfaction metric. (#2910)
- Added
Jury.repeatedand reliability metadata on every Jury result. (#2854) - Client hooks now adopt inherited W3C trace context. (#2829)
Fixes
Evaluation scores and metrics
- Improved handling of unparsable judge responses:
- Excluded the parse-failure sentinel from score normalization, groundedness, and answerability scores. (#2833, #2834, #2864)
- Dropped jurors whose judges returned no parsable score and excluded unparsable scores from per-item averages. (#2837, #2917)
- Excluded unparsable scores from BatchEvaluator aggregation, leaderboard averages, and
compare_runs. (#2866, #2905, #2939) - Guardrails now reject unparsable and non-finite scores. (#2902)
- Validated structured-output scores against the configured scale and corrected chain-of-thought context relevance scoring to use the requested scale. (#2836, #2860)
- Added response labeling to the agreement judge prompt. (#2835)
- Added validation for retrieval relevance score lengths. (#2853)
- Deduplicated ideal DCG by golden chunk text in
ndcg_at_k. (#2857) - Skipped non-finite predictions during few-shot selection. (#2852)
- Preserved
min_score_val,max_score_val, andtemperatureinMetric.with_arguments. (#2922) - Fixed a pandas 3
get_grouperror when there is a single evaluation root. (#2937) - Corrected the
llm_providermodule import injury.py. (#2869)
Batch evaluation and core behavior
- Read batch column mappings from the original row and preserved results when output column names collide. (#2845, #2844)
- Kept BatchEvaluator independent of the optional feedback package. (#2901)
- Treated missing DataFrame cells as
Noneand preserved columns in empty batch DataFrames. (#2942, #2946) - Preserved retrieval order in
context_filterresults. (#2932) - Added a warning when
TruSessionis re-created with different settings. (#2944)
Cost accounting and reporting
- Prevented nested cost scopes fr
- trulens-2.15.0TruLens 2.15.02026-10-05 · 2026-10-05 13:44 UTC
查看更新说明
TruLens 2.15.0
OTel-native traces that travel end to end and stay evaluable
Three changes in this release work on the same OTel path: the trace now stays whole across the HTTP call to the provider, GenAI message content survives both persistence and export, and the finished trace can reach OTLP backends that only speak HTTP/protobuf.
-
Trace context crosses the HTTP boundary. TruLens instruments the caller, but the provider or gateway runs on the far side of an HTTP call, and nothing carried the active span's context across it, so the far end started a trace of its own. The new
trulens.core.otel.propagationmodule addsinject_trace_context(headers)plustracing_transport()andasync_tracing_transport(), httpx transports that inject the active span's W3C context before delegating. Attach one to a client, hand that client to a provider SDK, and the provider's server span is parented under your span. This is opt-in; nothing changes until you pass the transport. (#2792) by @selvaganesh19 -
Message content is persisted and can be selected. Per the OTel GenAI semantic conventions, prompts and completions are emitted as a
gen_ai.client.inference.operation.detailsspan event rather than as span attributes, and both the OTLP proto conversion and storage ignoredspan.events, sogen_ai.input.messagesandgen_ai.output.messagescould never be evaluated. Events are now persisted underrecord["events"]and written to the OTLP proto, andSelectorgainsspan_event_attributeandspan_event_nameas a fourth extraction mode so feedback functions can read them. Spans without events serialize byte-identically, so there is no migration and no golden fixture churn. (#2761) by @sfc-gh-jreini -
The trace reaches HTTP/protobuf-only backends.
otel_exporter="otlp"only ever built gRPC exporters, so an HTTP/protobuf-only OTLP endpoint failed with a missing-dependencyImportError.TruSessionnow takesotlp_protocol("grpc"or"http/protobuf"), honorsOTEL_EXPORTER_OTLP_PROTOCOLandOTEL_EXPORTER_OTLP_TRACES_PROTOCOL, and still defaults to gRPC. Client hooks gain the matchingTRULENS_OTLP_PROTOCOLvariable and a newTRULENS_DESTINATION=ai_gatewayfor Snowflake Cortex AI Gateways, which serve OTLP over HTTP/protobuf only;make_ai_gateway_otel_exporter()intrulens.connectors.snowflake.otel_exporterbuilds the same exporter for connector users. Hook export failures are now logged with turn, client, and conversation context instead of being swallowed by the journal worker. (#2785) by @sfc-gh-jreini
Putting them together
import os # Prompts and completions ride a span event, which is emitted only when content # capture is opted in. Without this, the span-event selectors below find nothing. os.environ["TRULENS_OTEL_CAPTURE_CONTENT"] = "true" import httpx from trulens.core import Metric from trulens.core import TruSession from trulens.core.feedback.selector import Selector from trulens.core.otel import propagation from trulens.otel.semconv.trace import GenAIEvents from trulens.otel.semconv.trace import SpanAttributes from trulens.providers.openai import OpenAI # The default exporter persists spans to the TruLens database, which is what # makes their events available to evaluate below. session = TruSession() # Carry the active span's trace context across the HTTP boundary, so the # provider's server span joins this trace instead of starting its own. provider = OpenAI( http_client=httpx.Client(transport=propagation.tracing_transport()) ) # Evaluate the message content that rides the GenAI span event. m_answer_relevance = Metric( implementation=provider.relevance_with_cot_reasons, name="Answer Relevance", ).on({ "prompt": Selector( span_type=SpanAttributes.SpanType.GENERATION, span_event_attribute=GenAIEvents.EventAttributes.INPUT_MESSAGES, span_event_name=GenAIEvents.CLIENT_INFERENCE_OP -
- trulens-2.14.0TruLens 2.14.02026-09-03 · 2026-09-03 14:43 UTC
查看更新说明
TruLens 2.14.0 Release Notes
Headline Features
Coding Agent Instrumentation
Instrument IDE hooks and coding agent workflows — including Claude Code and Cursor — with TruLens tracing. Capture the full execution trace of agentic coding sessions for evaluation and observability. (#2732) by @joshreini1
Production Trace Curation into Evaluation Datasets
Curate production traces into persisted evaluation datasets. Select and save real-world traces directly from your running application, building ground-truth datasets for offline evaluation without manual data collection. (#2722) by @Payal2000
Connector-Backed Prompt Management with Version Evaluation
Store, version, and evaluate prompt templates through the connector interface. Track prompt changes over time and evaluate the impact of prompt edits against your existing datasets and feedback functions. (#2717) by @dylanpulver
OTLP-Native Export and OTel Metrics Signal
Export traces and metrics directly via the OpenTelemetry Protocol, enabling integration with any OTLP-compatible backend. (#2681) by @RyanFlowerYes
Additional Features
- Streaming token tracking with TTFT and throughput metrics — OTEL instrumentation now captures streaming token counts, time-to-first-token, and throughput for LLM calls. (#2708) by @Abelo9996
- Ollama provider — New
trulens-providers-ollamapackage for running feedback functions against local Ollama models. (#2688) by @connectsudhindra-gif - Conversation metric customization —
additional_instructionsand chain-of-thought reasons support for conversation-scoped metrics. (#2710) by @dylanpulver
Dashboard Improvements
- Leaderboard record counts — Leaderboard metrics now show how many records each metric actually scored. (#2698) by @CTWalk
- TTFT in the Records page — Time-to-first-token is now visible in the latency view on the Records page. (#2696) by @connectsudhindra-gif
- Conversation thread column labels — Conversation-scoped thread columns are now labeled "latest" instead of "avg" to reflect their actual semantics. (#2750) by @Abelo9996
- Topic Adherence score consistency — Topic Adherence scores now match between the results table and conversation metrics view. (#2733) by @Abelo9996
Bug Fixes
- LLM judge rating extraction — Fixed a bug where the judge's stated scale description was incorrectly parsed as its numeric rating. (#2726) by @arthi-arumugam-git
ndcg_at_kshape crash andcohens_kappalabel mutation —ndcg_at_kno longer crashes on mismatched shapes;cohens_kappano longer mutates its input labels. (#2709) by @ClaireXi99- Ground-truth row ordering — Benchmark scoring now processes ground-truth rows in row order, not index-label order. (#2737) by @arthi-arumugam-git
- IR metric undefined results — IR metrics now report
naninstead of0.0when undefined (e.g., empty relevance lists). (#2738) by @arthi-arumugam-git - Duplicate chunk handling in IR metrics —
recall_at_kandndcg_at_kare now correctly bounded when retrieved chunks contain duplicates. (#2747) by @Abelo9996 - Temperature argument for conversation metrics —
temperaturestays positional on conversation metric calls, fixing a regression. (#2728) by @BetterAndBetterII - Dataset and ground-truth read round-trips — Fixed serialization round-trip errors when reading datasets and ground-truth entries from the database. (#2735) by @Abelo9996
- Feedback definition re-insert — Feedback definition updates are now persisted correctly on re-insert. (#2743) by @Abelo9996
compute_metricsmessage formatting — Status messages now build from metric names, not raw objects. (#2745) by @Abelo9996- Anthropic cost tracking — Fixed a crash in the Anthropic provider when tracking costs via
core_endpoint.Cost. (#2756) by @Abelo9996 methods_to_instrumentexistence check — App wrappers now useLens.getfor
- trulens-2.13.1TruLens 2.13.12026-08-20 · 2026-08-20 18:47 UTC
查看更新说明
TruLens 2.13.1 Patch Release
Bug Fixes
fix(core): allow dill 0.4.x by @sfc-gh-jreini in https://github.com/truera/trulens/pull/2711 fix(providers): import torch and transformers lazily in huggingface provider
- trulens-2.12.0TruLens 2.12.02026-08-06 · 2026-08-06 20:52 UTC
查看更新说明
TruLens 2.12: Conversation Evaluation, Better Judge Alignment, and RAG Citation Accuracy
TruLens 2.12 expands evaluation from individual records to complete conversations. It also adds citation-quality evaluation for RAG, tools for aligning LLM judges with human labels, trace-level metrics for agents, and adapters that turn TruLens metrics into reinforcement-learning rewards.
Evaluate Complete Conversations
Built with contributions by @Payal2000 @maitraymukeshkumarmodi-aiml @joshreini1
Many assistant failures only become visible across multiple turns. A response can look reasonable in isolation while contradicting an earlier answer, losing context, or failing to make progress toward the user's goal.
TruLens 2.12 adds conversation-level selectors, metrics, storage, and dashboard views. Record related turns under one
conversation_id, then use.on_conversation()to evaluate the complete ordered transcript once:from trulens.core import Metric from trulens.providers.openai import OpenAI provider = OpenAI(model_engine="gpt-5-mini") conversation_coherence = Metric( implementation=provider.coherence_across_turns, name="Coherence Across Turns", ).on_conversation() with tru_chatbot(conversation_id="conv-climate-001") as recording: for user_input in turns: chatbot.invoke( {"input": user_input}, )Turn-level and conversation-level metrics can run on the same application. Turn metrics still produce one score per record; conversation metrics receive all ordered
{"input", "output"}pairs and produce one score for the conversation.Measure Citation Accuracy in RAG Applications
Contributed by @rhiannalitchfield
The new
citation_accuracyevaluator measures whether citations in a response are supported by retrieved context. It works with inline or prose citations, does not require numbered[N]markers, and penalizes claims that should be cited but are left unsupported.from trulens.core import Metric from trulens.core import Selector citation_accuracy = Metric( implementation=provider.citation_accuracy, name="Citation Accuracy", selectors={ "response": Selector.select_record_output(), "context": Selector.select_context(collect_list=True), }, agg=np.mean, )Use
citation_attributionwhen your application emits explicit[N]markers and you want binary detection of misattribution. Usecitation_accuracywhen citations are inline or when you want a graded measure that also captures missing citations.Improve LLM Judge Alignment
Contributed by @maitraymukeshkumarmodi-aiml
FewShotOptimizerselects examples that improve agreement between an LLM judge and a labeled evaluation set. It uses greedy forward selection and supports Pearson and Spearman correlation, precision, recall, F1, Cohen's kappa, accuracy, and MAE.from trulens.feedback.optimize import FewShotOptimizer optimizer = FewShotOptimizer( feedback_fn=provider.relevance, candidates=candidate_examples, eval_dataset=held_out_examples, n_examples=3, metric="spearman", ) result = optimizer.optimize() examples = optimizer.format_examples(result.best_examples) score = provider.relevance( prompt="What is the capital of France?", response="Paris is the capital of France.", examples=examples, )Use TruLens Metrics as RL Reward Functions
Contributed by @maitraymukeshkumarmodi-aiml
Th
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
🦑 TruLens

TruLens finds where your agent fails and where you can cut cost without losing quality. Open source, OpenTelemetry-native.
Instrument any app with a decorator, score every step with LLM judges that explain themselves, then compare versions and ship the one that earns it. Tracing is OpenTelemetry-native, so a trace is portable to any OTLP backend, and evaluations run either as traces land or over a dataset after the fact.
Read more about the core concepts behind TruLens including Metrics, the RAG Triad, and Honest, Harmless and Helpful Evals.
Trace every step
Latency, inputs, outputs, tokens and cost, recorded per step, so a bad answer has a traceable cause rather than a vibe.

Compare versions, ship the frontier
Scores, latency and cost per app version, so the tradeoff is visible instead of guessed. The cheapest version is often not the worst one.

Don't take our word for it
TruLens judges are graded against human annotations, out of the box.
| Result | Metric | Detail |
|---|---|---|
| 95% | Agent errors caught with Agent GPA on TRAIL/GAIA | 267 of 281 human-annotated errors, against 55% for the baseline trace judge (arXiv:2510.08847) |
| 0.81 | Groundedness F1 on LLM-AggreFact | Ahead of a fine-tuned proprietary model, Bespoke-MiniCheck-7B, on F1, precision and recall over an 11,000-example holdout (RAG triad benchmarks) |
| 0.93 | Context relevance NDCG@5 | First of five tools on three of four ranking metrics, ahead of WandB Weave, RAGAS, DeepEval and UpTrain (AIMultiple, 23 March 2026) |
| 4.2:1 | Context relevance adversarial win-loss | Scored the correct passage over a near-copy with one fact swapped 4.2 times for every reversal, against 3.3:1 for the next best tool (AIMultiple) |
Adopted by AI teams at
Walmart Global Tech, Cisco, J.P. Morgan Chase, Equinix, VMware by Broadcom, Hitachi Digital Services, Thomson Reuters, phData, HID Global and others. See ADOPTERS.md.
Installation and Setup
Install the trulens pip package from PyPI.
pip install trulens
Install with a specific LLM provider for feedback evaluation:
pip install trulens trulens-providers-openai # OpenAI / Azure OpenAI
pip install trulens trulens-providers-orcarouter # OrcaRouter (OpenAI-compatible gateway)
pip install trulens trulens-providers-litellm # LiteLLM (Anthropic, Cohere, Mistral, …)
pip install trulens trulens-providers-google # Google Gemini
pip install trulens trulens-providers-bedrock # AWS Bedrock
pip install trulens trulens-providers-cortex # Snowflake Cortex
pip install trulens trulens-providers-huggingface # HuggingFace
pip install trulens trulens-providers-langchain # LangChain models
Install with a specific app framework integration:
pip install trulens trulens-apps-langchain # LangChain / LangGraph
pip install trulens trulens-apps-llamaindex # LlamaIndex
Quick Usage
Walk through how to instrument and evaluate a RAG built from scratch with TruLens.
Key Features
🔭 OpenTelemetry-based tracing
TruLens instrumentation is built on OpenTelemetry. Every function call, LLM generation, retrieval, and tool invocation is captured as a structured OTEL span. This makes TruLens interoperable with existing observability infrastructure — export traces to Jaeger, Grafana Tempo, Datadog, New Relic, or any OTLP-compatible backend.
from trulens.core.otel.instrument import instrument
from trulens.otel.semconv.trace import SpanAttributes
class MyRAG:
@instrument(
span_type=SpanAttributes.SpanType.RETRIEVAL,
attributes={
SpanAttributes.RETRIEVAL.QUERY_TEXT: "query",
SpanAttributes.RETRIEVAL.RETRIEVED_CONTEXTS: "return",
},
)
def retrieve(self, query: str) -> list: ...
🤖 Agentic evaluations
Seven purpose-built evaluators for agentic systems — each measuring a distinct aspect of agent behavior:
| Evaluator | What it measures |
|---|---|
| LogicalConsistency | Reasoning coherence; flags hallucinations and unsupported assertions |
| ExecutionEfficiency | Redundant steps, unnecessary retries, wasted computation |
| PlanAdherence | Whether execution followed the stated plan |
| PlanQuality | Intrinsic plan quality — strategy, not outcome |
| ToolSelection | Right tool chosen for each subtask |
| ToolCalling | Argument validity and output interpretation |
| ToolQuality | External tool/service reliability |
📊 Batch and inline evaluation
Run evaluations alongside your app, on existing data, or in offline batch mode:
# Inline — evaluate as the app runs
with tru_recorder as recording:
response = my_app.query("What is TruLens?")
# Batch — evaluate a pre-collected dataset using the Run API
from trulens.core.run import RunConfig
run_config = RunConfig(
run_name="batch_eval_v1",
dataset_name="eval_questions",
source_type="TABLE",
dataset_spec={"input": "QUESTION"},
invocation_max_workers=8,
metric_max_workers=4,
)
run = tru_app.add_run(run_config=run_config)
run.start()
run.compute_metrics([relevance, groundedness])
🔌 MCP support
Instrument Model Context Protocol tool calls
with the MCP span type to capture tool name, arguments, output, and latency:
@instrument(span_type=SpanAttributes.SpanType.MCP)
def call_mcp_tool(self, tool_name: str, arguments: dict) -> str: ...
🎯 Selector API
Target any span attribute for evaluation using the flexible Selector API:
from trulens.core import Metric, Selector
f_context_relevance = Metric(
name="Context Relevance",
implementation=provider.context_relevance,
selectors={
"question": Selector.select_record_input(),
"context": Selector.select_context(collect_list=False),
},
)
Supported LLM Providers
| Provider | Package |
|---|---|
| OpenAI / Azure OpenAI | trulens-providers-openai |
| LiteLLM (Anthropic, Cohere, Mistral, and more) | trulens-providers-litellm |
| Google Gemini | trulens-providers-google |
| AWS Bedrock | trulens-providers-bedrock |
| Snowflake Cortex | trulens-providers-cortex |
| HuggingFace | trulens-providers-huggingface |
| LangChain models | trulens-providers-langchain |
| OrcaRouter (OpenAI-compatible gateway) | trulens-providers-orcarouter |
💡 Contributing & Community
Interested in contributing? See our contributing guide for more details.
The best way to support TruLens is to give us a ⭐ on GitHub and join our discourse community!