ek.agents.wrappers#
Optional WRAP adapters: Inspect AI, uqlm, Ragas and DeepEval as ek strategies.
ek.agents scores episodes in pure python; this module is the batteries-included layer for
teams who already run these libraries. Every adapter imports its backend lazily (at call
time, guarded by requires_extra()), so import ek stays light, and each
takes an injectable backend object so it can be tested – and used – without network access.
The dependency direction stays ek -> backend, never the reverse. Inspect AI, Ragas and
DeepEval come with ek[agents]; uqlm (heavy: torch/transformers) with ek[agreement].
run_inspect()– run an Inspect AI eval and get gradedEpisodes back (Inspect’sepochsare ek’s trials, so the result feedsreliabilitydirectly).UqlmConsistencySignal– black-box sample-and-vote self-consistency fromuqlm(a[0, 1]confidence), aSignal(expensive:cost_tier=3).RagasSignal– reference-free Ragas metrics (faithfulness, answer relevancy, context precision) as aSignalover a RAG sample.DeepEvalMetric– DeepEval’sToolCorrectnessMetric/TaskCompletionMetric/GEvalas ekmetrics. Confident-AI telemetry is disabled before the import. NoteToolCorrectnessMetricdivides bylen(expected_tools)– it is recall-flavored, not F1 (compareek’s own cost-awaretool_call).
Example (a fake backend, no extra needed):
>>> class FakeUQ:
... def score(self, prompt):
... return 0.75
>>> UqlmConsistencySignal(scorer=FakeUQ())("What is 2+2?")
0.75
Module Attributes
Env var that opts out of DeepEval's Confident-AI telemetry (set before importing it). |
|
Sample count for uqlm's black-box scorers (a keyword default, not a magic number). |
|
uqlm black-box scorer used when none is named. |
|
Ragas metric used when none is named. |
|
ek's metric name -> Ragas class name in the legacy |
|
ek's metric name -> Ragas class name in |
|
ek name -> (DeepEval class name, needs an LLM judge). |
|
Test-case fields a GEval judge reads when |
Functions
Opt out of Confident-AI telemetry (idempotent; never overrides an explicit choice). |
|
|
Run an Inspect AI eval and return its samples as graded |
Classes
|
A DeepEval metric as an ek |
|
A reference-free Ragas metric as a |
|
Self-consistency confidence in |
- ek.agents.wrappers.DEEPEVAL_KINDS = {'geval': 'GEval', 'task_completion': 'TaskCompletionMetric', 'tool_correctness': 'ToolCorrectnessMetric'}#
ek name -> (DeepEval class name, needs an LLM judge).
- ek.agents.wrappers.DEEPEVAL_TELEMETRY_ENV = 'DEEPEVAL_TELEMETRY_OPT_OUT'#
Env var that opts out of DeepEval’s Confident-AI telemetry (set before importing it).
- ek.agents.wrappers.DEFAULT_GEVAL_PARAMS = ('input', 'actual_output')#
Test-case fields a GEval judge reads when
evaluation_paramsis not given. DeepEval >= 4 refuses a plainLLMTestCasewithout them (it would otherwise evaluate a trace).
- ek.agents.wrappers.DEFAULT_NUM_RESPONSES = 5#
Sample count for uqlm’s black-box scorers (a keyword default, not a magic number).
- ek.agents.wrappers.DEFAULT_RAGAS_METRIC = 'faithfulness'#
Ragas metric used when none is named.
- ek.agents.wrappers.DEFAULT_UQLM_SCORER = 'noncontradiction'#
uqlm black-box scorer used when none is named.
- class ek.agents.wrappers.DeepEvalMetric(kind='tool_correctness', *, metric=None, **metric_kwargs)[source]#
Bases:
objectA DeepEval metric as an ek
Metricover anEpisode.score(episode, gold)builds a DeepEvalLLMTestCasefrom the episode’s output and tool calls (goldis the expected output string, or a mapping withexpected_output/expected_tools) and returns DeepEval’s score as an ekScore.tool_correctnessis recall-flavored (divides bylen(expected_tools)), not F1: the label says so, anddetail['flavor']records it.- Parameters:
kind (
str) –tool_correctness|task_completion|geval.metric (
Any) – An injected DeepEval-shaped metric (.measure(case),.score);Nonebuilds the real one lazily (telemetry disabled first).**metric_kwargs – Passed to the DeepEval constructor (e.g.
criteria=for GEval, andmodel=– a model name or aDeepEvalBaseLLM– for any of them: DeepEval >= 4 builds its default OpenAI judge at construction, so withoutmodel=it needsOPENAI_API_KEYeven fortool_correctness). For GEval,namedefaults to"ek_geval"andevaluation_paramstoDEFAULT_GEVAL_PARAMS(strings are accepted).
- ek.agents.wrappers.RAGAS_COLLECTION_METRICS = {'answer_relevancy': 'AnswerRelevancy', 'context_precision': 'ContextPrecisionWithoutReference', 'faithfulness': 'Faithfulness'}#
ek’s metric name -> Ragas class name in
ragas.metrics.collections(Ragas >= 0.4, the API that survives 1.0) – metrics take anInstructorBaseRagasLLM(llm_factory) and exposeascore(**fields) -> MetricResult.answer_relevancyalso needsembeddings=.
- ek.agents.wrappers.RAGAS_METRICS = {'answer_relevancy': 'ResponseRelevancy', 'context_precision': 'LLMContextPrecisionWithoutReference', 'faithfulness': 'Faithfulness'}#
ek’s metric name -> Ragas class name in the legacy
ragas.metricsAPI (deprecated since Ragas 0.4) – metrics take aBaseRagasLLMand exposesingle_turn_ascore(sample).
- class ek.agents.wrappers.RagasSignal(metric=None, *, name='faithfulness', llm=None, cost_tier=3, **metric_kwargs)[source]#
Bases:
objectA reference-free Ragas metric as a
Signalover a RAG sample.The sample is a mapping/object with
user_input(orquestion),response(oranswer) andretrieved_contexts(orcontexts). The score is in[0, 1]. Ragas metrics call an LLM, so pass a configuredmetric(orllm=to build one).Both Ragas metric APIs are accepted: the collections API (
ascore(**fields)returning aMetricResult;ragas.metrics.collections, the one that survives Ragas 1.0) and the legacy one (single_turn_ascore(SingleTurnSample); deprecated since Ragas 0.4).- Parameters:
metric (
Any) – A Ragas metric object (either API), orNoneto buildnamefromllm.name (
str) –faithfulness|answer_relevancy|context_precision.llm (
Any) – The judge, used whenmetricisNone. AnInstructorBaseRagasLLM(fromragas.llms.llm_factory) builds the collections metric; any other Ragas LLM wrapper (e.g.LangchainLLMWrapper) builds the legacy one.cost_tier (
int) –3– an LLM call per sample.**metric_kwargs (
Any) – Passed to the Ragas constructor (e.g.embeddings=foranswer_relevancy).
Example
>>> class Fake: ... async def single_turn_ascore(self, sample): return 0.5 >>> RagasSignal(Fake())({"question": "q", "answer": "a", "contexts": ["c"]}) 0.5
- class ek.agents.wrappers.UqlmConsistencySignal(scorer=None, *, llm=None, scorer_name='noncontradiction', num_responses=5, cost_tier=3)[source]#
Bases:
objectSelf-consistency confidence in
[0, 1]fromuqlm’s black-box scorers.Samples
num_responsesgenerations for the prompt and measures how much they agree (non-contradiction, exact match, semantic negentropy, …). Raw and uncalibrated: calibrate before gating (Hard Rule 1).- Parameters:
scorer (
Any) – A backend withscore(prompt) -> float(tests / custom sampling), orNoneto build uqlm’sBlackBoxUQfromllm.llm (
Any) – A LangChain chat model, required whenscorerisNone. uqlm reads itstemperatureattribute, so it must have one.scorer_name (
str) – The uqlm scorer column to read (default"noncontradiction", which downloads an NLI model on first use;"exact_match"needs none).num_responses (
int) – Samples per prompt.cost_tier (
int) –3– it pays fornum_responsesextra generations.
Example
>>> class Fake: ... def score(self, prompt): return 2.0 # out-of-range is clamped >>> UqlmConsistencySignal(scorer=Fake())("q") 1.0
- ek.agents.wrappers.disable_deepeval_telemetry()[source]#
Opt out of Confident-AI telemetry (idempotent; never overrides an explicit choice).
- Return type:
- ek.agents.wrappers.run_inspect(tasks, *, model=None, epochs=None, scorer=None, success_threshold=1.0, log_dir=None, **eval_kwargs)[source]#
Run an Inspect AI eval and return its samples as graded
Episodes.A thin convenience over
inspect_ai.eval+episodes_from_inspect_log(): one episode per sample per epoch, graded by the sample’s score (scorer, else the first) reachingsuccess_threshold. Run withepochs=kand the result is a k-trial run – hand it toreliability()forpass^k, or tocost_report()for cost per successful task.- Parameters:
tasks (
Any) – Anythinginspect_ai.evalaccepts (aTask, a task function, a registry name, a list of them).model (
Any) – The model under test (e.g."openai/gpt-4o");Nonelets Inspect useINSPECT_EVAL_MODEL."mockllm/model"runs offline at no cost.epochs (
Optional[int]) – Trials per sample (Inspect’sepochs);Nonekeeps the task’s own setting.scorer (
Optional[str]) – Which scorer’s value grades success (default: each sample’s first score).success_threshold (
float) – A sample succeeds when its score value is>=this.log_dir (
Optional[str]) – Where Inspect writes its.evallogs.Noneuses a temporary directory that is removed once the episodes are read – pass a path to keep the logs.**eval_kwargs (
Any) – Passed toinspect_ai.eval(limit=,solver=, …).displaydefaults to"none".
- Raises:
RuntimeError – if any eval did not finish with status
success(a partial run is not a k-trial run, and grading it as one would understate failures).- Return type:
Note
inspect_ai.evalis synchronous and refuses to run inside an event loop; from async code, callinspect_ai.eval_asyncand pass each log toepisodes_from_inspect_log.