trulens

trueraMIT活跃维护

给 LLM 应用和 AI Agent 做评测与追踪的工具,能记录实验过程、量化效果并定位问题,方便持续迭代和上线监控。

Evaluation and Tracking for LLM Experiments and AI Agents

trulens-2.16.0发布于 2026-10-19 17:17 UTC3,637star +8 / 7 天391fork同步于 2026-11-10 17:41 UTC

怎么上手

由 README 提炼,执行前请确认
pip install trulens
pip install trulens trulens-providers-openai
硬件要求按 README 说明

README 未说明

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

开源 LLM 应用与 Agent 的追踪评测工具,帮你定位失败步骤并比较版本成本

给 LLM 应用和 AI Agent 做评测与追踪的工具,能记录实验过程、量化效果并定位问题,方便持续迭代和上线监控。

核心能力

  • 用装饰器 instrument 任意函数,按 OTEL span 记录每步输入输出
  • 基于 OpenTelemetry 原生追踪,可导出到任意 OTLP 后端
  • 提供七个 Agent 专用评测器,覆盖计划、工具选择与执行效率
  • 支持在线边跑边评与离线批量 Run API 两种评测方式
  • 用 Selector API 指定任意 span 属性作为评测输入

容易踩的坑

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

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本trulens-2.16.0
  1. 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_repetition metric. (#2898)
    • Added a requirement satisfaction metric. (#2910)
    • Added Jury.repeated and 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, and temperature in Metric.with_arguments. (#2922)
    • Fixed a pandas 3 get_group error when there is a single evaluation root. (#2937)
    • Corrected the llm_provider module import in jury.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 None and preserved columns in empty batch DataFrames. (#2942, #2946)
    • Preserved retrieval order in context_filter results. (#2932)
    • Added a warning when TruSession is re-created with different settings. (#2944)

    Cost accounting and reporting

    • Prevented nested cost scopes fr
  2. 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.propagation module adds inject_trace_context(headers) plus tracing_transport() and async_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.details span event rather than as span attributes, and both the OTLP proto conversion and storage ignored span.events, so gen_ai.input.messages and gen_ai.output.messages could never be evaluated. Events are now persisted under record["events"] and written to the OTLP proto, and Selector gains span_event_attribute and span_event_name as 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-dependency ImportError. TruSession now takes otlp_protocol ("grpc" or "http/protobuf"), honors OTEL_EXPORTER_OTLP_PROTOCOL and OTEL_EXPORTER_OTLP_TRACES_PROTOCOL, and still defaults to gRPC. Client hooks gain the matching TRULENS_OTLP_PROTOCOL variable and a new TRULENS_DESTINATION=ai_gateway for Snowflake Cortex AI Gateways, which serve OTLP over HTTP/protobuf only; make_ai_gateway_otel_exporter() in trulens.connectors.snowflake.otel_exporter builds 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
    
  3. 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-ollama package for running feedback functions against local Ollama models. (#2688) by @connectsudhindra-gif
    • Conversation metric customization — additional_instructions and 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_k shape crash and cohens_kappa label mutation — ndcg_at_k no longer crashes on mismatched shapes; cohens_kappa no 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 nan instead of 0.0 when undefined (e.g., empty relevance lists). (#2738) by @arthi-arumugam-git
    • Duplicate chunk handling in IR metrics — recall_at_k and ndcg_at_k are now correctly bounded when retrieved chunks contain duplicates. (#2747) by @Abelo9996
    • Temperature argument for conversation metrics — temperature stays 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_metrics message 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_instrument existence check — App wrappers now use Lens.get for
  4. 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

  5. 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_accuracy evaluator 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_attribution when your application emits explicit [N] markers and you want binary detection of misattribution. Use citation_accuracy when citations are inline or when you want a graded measure that also captures missing citations.

    Improve LLM Judge Alignment

    Contributed by @maitraymukeshkumarmodi-aiml

    FewShotOptimizer selects 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

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    PyPI - Version Azure Build Status GitHub PyPI - Downloads Docs Ask DeepWiki

    🦑 TruLens

    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.

    TruLens trace waterfall

    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.

    TruLens leaderboard

    Don't take our word for it

    TruLens judges are graded against human annotations, out of the box.

    ResultMetricDetail
    95%Agent errors caught with Agent GPA on TRAIL/GAIA267 of 281 human-annotated errors, against 55% for the baseline trace judge (arXiv:2510.08847)
    0.81Groundedness F1 on LLM-AggreFactAhead of a fine-tuned proprietary model, Bespoke-MiniCheck-7B, on F1, precision and recall over an 11,000-example holdout (RAG triad benchmarks)
    0.93Context relevance NDCG@5First of five tools on three of four ranking metrics, ahead of WandB Weave, RAGAS, DeepEval and UpTrain (AIMultiple, 23 March 2026)
    4.2:1Context relevance adversarial win-lossScored 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.

    Open In
Colab

    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:

    EvaluatorWhat it measures
    LogicalConsistencyReasoning coherence; flags hallucinations and unsupported assertions
    ExecutionEfficiencyRedundant steps, unnecessary retries, wasted computation
    PlanAdherenceWhether execution followed the stated plan
    PlanQualityIntrinsic plan quality — strategy, not outcome
    ToolSelectionRight tool chosen for each subtask
    ToolCallingArgument validity and output interpretation
    ToolQualityExternal 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

    ProviderPackage
    OpenAI / Azure OpenAItrulens-providers-openai
    LiteLLM (Anthropic, Cohere, Mistral, and more)trulens-providers-litellm
    Google Geminitrulens-providers-google
    AWS Bedrocktrulens-providers-bedrock
    Snowflake Cortextrulens-providers-cortex
    HuggingFacetrulens-providers-huggingface
    LangChain modelstrulens-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!