Skip to main content

confidence-escalation

Find published releases on PyPI and changes in the changelog.

Framework-agnostic confidence-gated escalation middleware for LLM agents.

PyPI version Python 3.9+ License: MIT Coverage CI

Multi-signal confidence scoring (logprob + verbalized + ASR + tool risk) with threshold-based escalation policies and pluggable handlers. Includes native function-tool guards for OpenAI Agents and Pydantic AI, a LangChain response callback, and SDK-independent compatibility helpers for other frameworks. See the installer boundaries below.

Provides confidence-based controls relevant to human-agent trust risks; execution is blocked only where your application explicitly wires in a pre-action gate.


What it does and when to use it

This Python library helps agent application developers decide whether to continue, request review, restrict tools, or try another model when available confidence signals are weak. Use it when you can supply model or tool-risk signals and need a consistent escalation policy.

For example, a support agent proposes an account change. Your application first checks the user's permission, then evaluates confidence and invokes the change through the pre-action gate. If evidence is missing or the policy escalates, the action is not invoked. A review handler can record or route the request; your application must recheck permission and policy before resuming it.

Choose the right execution boundary

Need Use Limit
Review an answer or trigger a retry after generation ConfidenceEscalationMiddleware.call Scores after the wrapped operation; cannot undo its side effects
Check confidence before invoking an action ConfidenceEscalationMiddleware.call_guarded Requires evidence available before execution; does not grant resource access
Gate an async action AsyncConfidenceEscalationMiddleware.call_guarded Await the gate; cancellation cannot undo effects already started
Gate OpenAI Agents SDK function tools as_tool_guardrail() on OpenAIAgentsEscalationAdapter Configure each tool; lifecycle hooks alone do not block execution

Start with basic scoring and the policy example. For execution details, see the sync middleware, async middleware, and SDK guardrail example. The project guide compares the related libraries.

What the score does not prove

A score is a weighted heuristic, not a verified probability that an answer is correct. Verbalized confidence can be wrong; missing signals must not be treated as reassuring evidence. Choose thresholds using labeled outcomes from your own use case. The included six-case synthetic evaluation illustrates metrics, not production calibration. Confidence gating also does not replace identity checks, resource authorization, durable approval storage, or legal review.


Features

  • Multi-signal scoring — combine logprobs, verbalized confidence, and tool-call risk into a single composite score
  • Threshold policies — single-threshold, dual-threshold (normal + critical), composite multi-policy chains
  • Pluggable handlers — human-in-loop, model upgrade, tool restriction, compliance logging
  • Framework adapters — native OpenAI/Pydantic tool guards, a LangChain response callback, and retained caller-wired legacy helpers
  • EU AI Act Article 12 audit logging — structured JSON compliance log on every escalation
  • Zero required dependencies — core library runs with no dependencies; framework integrations are optional extras

Quick Start

Installation

Installer examples keep the security-qualified package floor. If that release is not yet available on PyPI, use the reviewed checkout or wheel; do not drop the floor to make pip select an older distribution.

Use a maintained Python 3.11+ runtime for production. Python 3.9/3.10 core compatibility remains available as legacy support; development and optional SDK floors are separate.

The base runtime supports Python 3.9+. Development and tests ([dev]) require Python 3.10+ with patched pytest>=9.0.3. Python 3.9 CI runs an installed-wheel core API smoke and compile check without development dependencies.

pip install 'confidence-escalation>=0.6.0'
# With LangChain:
pip install "confidence-escalation[langchain]>=0.6.0"
# With all retained security-qualified installers:
pip install "confidence-escalation[all]>=0.6.0"

Installer and SDK boundaries

The 2026-11-02 qualification resolves/audits minimum and current graphs on Python 3.11 and current graphs on Python 3.14. Native execution is tested in its declared 3.11/3.12 cells; the new 3.14 lane is core-only and does not establish all SDKs' native behavior. Lock and rescan the actual deployment graph; no claim covers every historical/future dependency combination.

Extra Qualified dependency floor Dependency Python floor
langchain langchain-core 1.3.3 <2 3.10
openai-agents openai-agents 0.22.3 <0.25, opentelemetry-api 1.45.1 3.10
pydantic-ai pydantic-ai 2.61.0 <3, opentelemetry-api 1.45.1 3.11
all the three retained runtime installers above 3.11
dev patched pytest 9.0.3, pytest-asyncio 1.3.0 and listed tools 3.10

Unavailable SDKs now fail dependency resolution on older Python; Python-version markers no longer silently omit the requested SDK. The version-bounded install commands prevent pip from choosing an earlier project release with weaker contracts.

CrewAI, legacy AutoGen and Google ADK install extras are quarantined and removed from all; their pure compatibility helpers and public imports remain. Current CrewAI constrains affected Chroma; legacy AutoGen requires unpatched diskcache; current Google ADK caps OpenTelemetry API below its patched 1.45.1 floor. No incompatible resolver override is applied. A clean native migration needs separate qualification before those installers return. An unknown-extra pip warning is not SDK installation support.

The LangChain shim inherits the SDK's native callback base and propagates callback errors. It observes generated responses, after any generation effects; it is not a pre-action gate. Keep independent authorization and explicit call_guarded/native tool-input enforcement before side effects.

Basic Scoring

from confidence_escalation import MultiSignalConfidenceScorer

scorer = MultiSignalConfidenceScorer(
    weights={"logprob": 0.5, "verbalized": 0.3, "tool_risk": -0.2}
)

score = scorer.score(
    logprobs=[-0.1, -0.3, -0.2],
    verbalized_response="I am 70% confident about this answer.",
    tool_call_risk=0.15,
)

print(f"Confidence: {score.value:.3f}")   # e.g. 0.712
print(f"Reliable: {score.is_reliable()}")  # True (above 0.6 default)

Threshold Policy + Human-in-Loop

from confidence_escalation import (
    ThresholdPolicy,
    EscalationAction,
    HumanInLoopHandler,
    ComplianceLoggingHandler,
    ConfidenceEscalationMiddleware,
)

def notify_human(ctx, result):
    print(f"Routing to human review: session={ctx['session_id']}, confidence={result.confidence_score:.3f}")

policy = ThresholdPolicy(
    threshold=0.65,
    action=EscalationAction.HUMAN_IN_LOOP,
    critical_threshold=0.3,
    critical_action=EscalationAction.ABORT,
)

middleware = ConfidenceEscalationMiddleware(
    policy=policy,
    handlers=[
        HumanInLoopHandler(callback=notify_human),
        ComplianceLoggingHandler(),
    ],
)

result = middleware.call(
    agent_step=lambda: my_llm.invoke(messages),
    context={"session_id": "abc123", "model": "claude-sonnet-4-6"},
    logprobs=[-0.4, -0.5],
)

if result["escalation"]["triggered"]:
    print("Escalated — stopping agent execution.")

Model Upgrade Handler

from confidence_escalation import ModelUpgradeHandler, ThresholdPolicy, EscalationAction

handler = ModelUpgradeHandler(
    upgrade_map={
        "claude-haiku-4-5": "claude-sonnet-4-6",
        "claude-sonnet-4-6": "claude-opus-4-7",
    }
)

policy = ThresholdPolicy(threshold=0.7, action=EscalationAction.MODEL_UPGRADE)
result = policy.evaluate(score, context={"model": "claude-haiku-4-5"})

if result.triggered:
    upgrade_info = handler.handle(result, context={"model": "claude-haiku-4-5"})
    print(f"Retry with: {upgrade_info['upgraded_model']}")

Tool Restriction

from confidence_escalation import ToolRestrictionHandler, ThresholdPolicy, EscalationAction

handler = ToolRestrictionHandler(
    high_risk_tools=["delete_record", "send_email", "execute_sql"],
    allow_read_only=True,
)

policy = ThresholdPolicy(threshold=0.65, action=EscalationAction.TOOL_RESTRICTION)
result = policy.evaluate(score, context={"available_tools": ["get_customer", "delete_record"]})

if result.triggered:
    restriction = handler.handle(result, context={"available_tools": agent_tools})
    safe_tools = restriction["allowed_tools"]
    # Re-invoke agent with only safe_tools

LangChain Integration

from confidence_escalation.adapters.langchain import LangChainEscalationAdapter
from confidence_escalation.handlers import HumanInLoopHandler

adapter = LangChainEscalationAdapter(
    threshold=0.65,
    handlers=[HumanInLoopHandler(raise_on_trigger=True)],
)

# Attach as LangChain callback
chain = LLMChain(llm=llm, callbacks=[adapter.as_callback()])

# Or call directly from a LangGraph node
def research_node(state):
    response = llm.invoke(state["messages"])
    try:
        adapter.on_llm_end(response.content, logprobs=response.response_metadata.get("logprobs"))
    except HumanInLoopHandler.HumanReviewRequired:
        return {"status": "escalated"}
    return {"response": response.content}

CrewAI Integration

from crewai import Agent
from confidence_escalation.adapters.crewai import CrewAIEscalationAdapter

adapter = CrewAIEscalationAdapter(threshold=0.65)

agent = Agent(
    role="Research Specialist",
    goal="Analyze market trends",
    backstory="...",
    step_callback=adapter.step_callback,
)

Google ADK Integration

from google.adk.agents import BaseAgent
from confidence_escalation.adapters.google_adk import ADKEscalationAdapter

class GovernedAgent(BaseAgent):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._escalation = ADKEscalationAdapter(threshold=0.65)

    async def _run_async_impl(self, ctx):
        async for event in self._llm_agent._run_async_impl(ctx):
            if event.is_final_response():
                result = self._escalation.evaluate_event(event, ctx)
                if result["triggered"]:
                    yield self._escalation.build_escalation_event(result)
                    return
            yield event

Composite Policy Chains

from confidence_escalation import ThresholdPolicy, EscalationAction
from confidence_escalation.policy import CompositePolicy

policy = CompositePolicy(policies=[
    ThresholdPolicy(threshold=0.25, action=EscalationAction.ABORT),
    ThresholdPolicy(threshold=0.55, action=EscalationAction.HUMAN_IN_LOOP),
    ThresholdPolicy(threshold=0.75, action=EscalationAction.COMPLIANCE_LOG),
])

result = policy.evaluate(score, context={"session_id": "abc"})
# First matching threshold wins

OWASP Agentic AI Coverage

OWASP ASI ID Risk Coverage
ASI-09 Human-Agent Trust Exploitation Confidence gating before high-stakes actions
ASI-02 Tool Misuse Tool restriction handler removes high-risk tools at low confidence
ASI-03 Identity/Privilege Abuse ComplianceLoggingHandler creates immutable audit trail


License

MIT License. See LICENSE.

Reliability updates (0.2.0)

Explicit call_guarded pre-action gating; finite/range input validation and missing-signal metadata; reproducible synthetic evaluation. Introduced in 0.2.0.

ConfidenceEscalationMiddleware.call scores after execution. Use middleware.call_guarded(action, confidence, *args, context=context, **kwargs) before side effects. Escalation or explicitly missing evidence raises PermissionError without invoking the action. Re-evaluate after human review; callbacks do not grant approval. This gate does not replace identity/resource authorization.

Scores/thresholds must be finite in [0,1], log probabilities finite and non-positive. Missing signals are marked; weights are heuristics, not calibrated probabilities. Run python benchmarks/evaluate.py to reproduce results. Six synthetic hand-labeled cases illustrate coverage, error/abstention, Brier score, and aggregate confidence bias. They are not representative or fitted calibration; collect independently labeled domain outcomes before choosing deployment thresholds.

For your own labeled tasks, use the held-out evaluation workflow. It separates validation threshold selection from test reporting, compares supplied scores with simpler baselines, rejects overlapping groups, and keeps unknown outcomes explicit. Brier/reliability metrics require a declared probability target; no calibration model or measured production improvement is supplied.

September 2026 boundary review (0.3.0)

Add async pre-action gating, await async callable objects, reject deferred execution through the synchronous gate, and exercise native SDK tool input guardrails with the real Runner.

Use await AsyncConfidenceEscalationMiddleware().call_guarded(action, confidence) for async side effects. The async class lives in confidence_escalation.async_middleware. Low or missing confidence blocks before invocation; sync callables run in a worker thread, async callables and returned awaitables are awaited. Cancellation cannot undo effects already started. The synchronous gate rejects async actions and awaitable results; use the async API instead. Confidence checks do not replace identity/resource authorization.

For OpenAI Agents SDK integration, install pip install ".[dev,openai-agents]" from this checkout on Python 3.10+. SDK 0.22.3 and 0.24.0 are tested through its actual Runner with a scripted local model and tracing disabled:

from agents import function_tool
from confidence_escalation.adapters.openai_agents import OpenAIAgentsEscalationAdapter
adapter = OpenAIAgentsEscalationAdapter()

# Populate from application-controlled pre-action evaluation, keyed by call ID.
# An empty mapping blocks every call; never populate it with a constant approval.
evidence_by_call_id = {}

def evidence_for_call(data):
    return evidence_by_call_id.get(data.context.tool_call_id)

@function_tool(tool_input_guardrails=[adapter.as_tool_guardrail(evidence_for_call)])
async def protected_action() -> str:
    return "performed"

Attach adapter.as_hooks() to Runner for lifecycle observations; hooks alone are not the execution boundary. Tool input guardrails raise the SDK tripwire before a triggered function tool executes. Migration to explicit evidence: direct evaluate_tool_gate() calls must supply confidence=ConfidenceScore(...); native guardrails use a synchronous or asynchronous evidence_provider(data) returning a ConfidenceScore for that invocation. Missing or invalid evidence blocks even at threshold zero. Provider failures also stop the call; the SDK may wrap the exception. No score from an earlier response is reused. Tool risk is separate tool_risk policy context and never converted into correctness confidence. The default threshold policy compares the supplied confidence; use an explicit policy if risk should alter the decision. high_risk_tools=None selects defaults, while an empty set now stays empty. Lifecycle tool hooks do not evaluate confidence policies without evidence. Post-response scoring is unchanged.

The application owns evidence provenance, freshness, binding to tool arguments, and resource authorization. Supplying a number does not prove calibration or correctness. The example mapping is an integration placeholder, not durable approval storage. This does not cover hosted tools or calls outside the configured SDK tool path.

Official tool guardrail guidance distinguishes input guardrails before execution from output checks afterward. Lifecycle signatures include agent, tool, response, and output arguments exercised by the regression test. Run python -m pytest tests/test_openai_sdk_execution.py; the dedicated CI installs the SDK so this check cannot silently skip there.

Completed AsyncConfidenceEscalationMiddleware.stream() token streams now retain and deliver their final decision to events and a synchronous event_sink, including successful results and failed-handler outcomes. Tokens are already visible before this evaluation; use call_guarded for pre-action checks. Handler failures propagate after all dispatched handlers finish; they are not successful escalation delivery. If both a handler and the sink fail, the original handler exception is raised with the sink exception as its cause. A sink-only error propagates after the local event has been retained. Awaitable sink results are rejected; supply a synchronous durable enqueue callback. Interrupted streams do not produce a completed-response decision.

On Python 3.11+, the optional pydantic-ai extra supplies the native capability integration, tested with Pydantic AI 2.61.0 and its provider-free TestModel. Use Agent(model, capabilities=[adapter.as_hooks()]). Native SDK skip exceptions prevent escalated tools from executing. Since 0.6.0, configure PydanticAIEscalationAdapter(evidence_provider=resolve_evidence), where resolve_evidence(ctx, call, tool_def, args) returns a ConfidenceScore or an awaitable score for that invocation. Missing/invalid evidence blocks even at threshold zero. User, tool and assistant message text is not used to infer pre-action confidence. Direct adapter.gate() calls require confidence=score; response_text and logprobs are no longer gate inputs. Bind evidence to the current tool call and validated arguments; the application owns provenance, freshness and independent authorization. A supplied number is not proof of calibration or correctness. Provider errors stop execution and are not reused as a previous score. Run pytest tests/test_pydantic_sdk_execution.py with that extra installed.

Metadata

Release files for confidence-escalation 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for confidence-escalation 0.6.0
File Size Uploaded Provenance Actions
confidence_escalation-0.6.0.tar.gz 86.0 kB With provenance Details for confidence_escalation-0.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for confidence-escalation 0.6.0
File Interpreter ABI Platform Actions
confidence_escalation-0.6.0-py3-none-any.whl Python 3 none any Details for confidence_escalation-0.6.0-py3-none-any.whl

Total release size: 123.1 kB

Release files / confidence_escalation-0.6.0.tar.gz

Download URL confidence_escalation-0.6.0.tar.gz
Size 86.0 kB
Tags Source
SHA-256 checksum
How to use checksums
eb76eca67249a9e4ed7b571baa5ef78175e33bb2eadf0cb6738fe3b334332658
BLAKE2b-256 checksum
How to use checksums
f158701901e965243d8c6ed4beaa5ac7524d62f715d7cedeac200940a422908a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 2, 2026.

Transparency log

Release files / confidence_escalation-0.6.0-py3-none-any.whl

Download URL confidence_escalation-0.6.0-py3-none-any.whl
Size 37.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c3c60e7d7f2e9b296179b589108fc5c51400586ee1f64005e41f5f3f27b45b80
BLAKE2b-256 checksum
How to use checksums
315925e209fa1d8f221d5a4d1dfb49f412087bd4a7838871438ff66bf4b1fdaa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 2, 2026.

Transparency log

Security for confidence-escalation 0.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for confidence_escalation-0.6.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 2, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page