Skip to main content

confidence-escalation

Source release candidate: 0.5.0 (not yet published). See release notes.

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. Works with LangChain, LangGraph, CrewAI, AutoGen, Google ADK, and any Python agent framework.

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. The current published version is 0.3.0.

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 — LangChain callbacks, CrewAI step_callback, AutoGen reply function wrapper, Google ADK event interceptor
  • 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

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
# With LangChain:
pip install "confidence-escalation[langchain]"
# With all frameworks:
pip install "confidence-escalation[all]"

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 event_sink, including handler results. 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. 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. The configured score can use prior response text; it is not independent authorization or calibrated correctness evidence. Run pytest tests/test_pydantic_sdk_execution.py with that extra installed.

Metadata

Release files for confidence-escalation 0.5.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.5.0
File Size Uploaded Provenance Actions
confidence_escalation-0.5.0.tar.gz 61.3 kB With provenance Details for confidence_escalation-0.5.0.tar.gz

Built distribution (wheel)

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

Total release size: 96.9 kB

Release files / confidence_escalation-0.5.0.tar.gz

Download URL confidence_escalation-0.5.0.tar.gz
Size 61.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b28edec54edac8126a98ee658c7257e918641891ca14b0f6d9137214f7da94df
BLAKE2b-256 checksum
How to use checksums
03b378fd5f73efd68d67a48100f91479bc43627688ee52b5496003d8804fa35c
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.5.0-py3-none-any.whl

Download URL confidence_escalation-0.5.0-py3-none-any.whl
Size 35.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
69d89781aafb0bc6871b69678898164d8d739fa16f0263d1767a6fbc0b626746
BLAKE2b-256 checksum
How to use checksums
106a0b94ec924eeee5cbf4a87c9f8c9eaa5fa4d4451c4b37e50a608e891c568c
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.5.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.5.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