Skip to main content

Detect infinite loops in LLM agentic workflows and interrupt them

Project description

TokenCircuit

TokenCircuit Logo

The Pre-Model Intervention Engine for Autonomous Agents.

PyPI Python Versions CI License <20µs/turn overhead


TokenCircuit in action

Most guardrails are blunt instruments. They wait for your agent to burn $50 in API credits, hit a hard recursion_limit, and crash—wiping the state and returning an error to your user.

TokenCircuit is a surgical, pre-model intervention layer. Using zero-dependency semantic shingling, it detects paraphrased loops before the next LLM call. Instead of just killing the run, it uses a Progressive Intervention Protocol (Nudge → Override → Hard Stop) to safely rewrite the transcript and force the agent to pivot strategies.

< 20µs overhead per turn. Zero network calls. 100% local.

Key Features

  • Progressive Intervention Protocol: Escalates from a Nudge (soft coaching injection) to an Override (surgical transcript compaction) before a Hard Stop (clean termination with state preserved).
  • Zero-Dependency Semantic Loop Detection: Shingle-based fingerprinting catches paraphrased loops without embedding models, tokenizers, network calls, or external APIs.
  • Atomic Transcript Surgery: Removes orphaned tool-call transactions to prevent LLM API validation errors (400 Bad Request) before they happen.
  • Zero-Trust Privacy: Every detection runs in your process. No telemetry, no prompts leave your RAM.

Quick Start

TokenCircuit natively integrates with LangGraph v1.0.8+ through official extension points—no monkey-patching required.

from langgraph.prebuilt import ToolNode, create_react_agent
from tokencircuit import InterventionEngine
from tokencircuit.adapters.langgraph import tc_pre_model_hook, tc_wrap_tool_call

engine = InterventionEngine()
safe_tools = ToolNode(tools, wrap_tool_call=tc_wrap_tool_call(engine.get_thread_ledger))
agent = create_react_agent(
    model,
    tools=safe_tools,
    pre_model_hook=lambda s: tc_pre_model_hook(s, engine=engine),
)

The hook intercepts the agent before each LLM call, runs the intervention pipeline (~20µs), and returns ephemeral message mutations. No graph state is modified—the original checkpoint remains clean.

Manual graph with named hooks

from tokencircuit import InterventionConfig, InterventionEngine
from tokencircuit.adapters.langgraph import tc_pre_model_hook

engine = InterventionEngine(config=InterventionConfig(...))
builder.add_node(
    "agent", call_model,
    pre_model_hook=lambda s: tc_pre_model_hook(s, engine=engine, node_name="agent"),
)

Universal Framework Support

TokenCircuit's core engine is 100% zero-dependency. Framework adapters are strictly isolated as optional dependencies to protect your supply chain.

CrewAI

pip install "tokencircuit[crewai]"
from crewai import Crew, Agent, Task
from tokencircuit.adapters.crewai import instrument_crewai

my_crew = Crew(agents=[...], tasks=[...])
safe_crew = instrument_crewai(my_crew, config=my_config)
safe_crew.kickoff()

Raw OpenAI / AsyncOpenAI

pip install "tokencircuit[openai]"
from openai import OpenAI
from tokencircuit.adapters.openai import TokenCircuitClient

client = TokenCircuitClient(OpenAI(), config=my_config)
# Drop-in replacement. Loops are intercepted before the HTTP request.
response = client.chat.completions.create(...)

Installation

pip install tokencircuit                    # Core engine
pip install "tokencircuit[langgraph]"       # + LangGraph adapter
pip install "tokencircuit[crewai]"          # + CrewAI adapter
pip install "tokencircuit[cli]"             # + TUI Dashboard

Performance

Benchmarked on the full intervention pipeline:

Scenario Latency
decide() hot path (PASS) ~1.4 µs
decide() with NUDGE ~3.5 µs
process() full pipeline ~20 µs
process() with tool calls ~33 µs

Zero external embedding dependencies. All detection is local shingle-based fingerprinting.

Production Audit & Mathematical Guarantees

TokenCircuit was built for zero-trust, high-throughput enterprise environments. It undergoes ruthless structural auditing to ensure it never crashes an agent or corrupts state.

  • Zero PII Telemetry: Telemetry is strictly isolated to integers and enum metadata. A mathematical proof in the payload compiler ensures that raw user prompts, tool arguments, and tool results are structurally excluded and cannot leak.
  • Bounded Algorithm Complexity: The semantic loop detector uses stdlib tokenization and guarantees a worst-case shingle comparison complexity of O(N). A hard cap on the sliding window prevents CPU algorithmic blowups even on massive multi-turn infinite loops.
  • Atomic Transcript Surgery: TokenCircuit adheres strictly to LangGraph v1.0.8+ API boundaries. Stray, duplicate, or dangling tool calls resulting from an intervention are surgically stripped from the LLM prompt, definitively eliminating OpenAI/Anthropic 400 Bad Request API errors.
  • Async & Event-Loop Safety: All metrics fire asynchronously in daemon threads. Core pre-model hooks and interceptors run perfectly synchronously, ensuring they never starve or block the primary application event loop.

Supported Frameworks

  • LangGraph: Native pre_model_hook and ToolNode(wrap_tool_call=...) integration (v1.0.8+).
  • CrewAI: Execution hook support (crewai>=0.60) for proactive intervention.

Built for the 2026 Agentic Economy.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tokencircuit-8.1.0.tar.gz (31.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tokencircuit-8.1.0-py3-none-any.whl (33.9 kB view details)

Uploaded Python 3

File details

Details for the file tokencircuit-8.1.0.tar.gz.

File metadata

  • Download URL: tokencircuit-8.1.0.tar.gz
  • Upload date:
  • Size: 31.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for tokencircuit-8.1.0.tar.gz
Algorithm Hash digest
SHA256 bde91c979312c2c9b2234921ad5f234d00c9f5832fd93717dfb7d217eae4b801
MD5 ef2d4a5cf3a64c64263dd66af643c514
BLAKE2b-256 928ef994ae6a77427b2e8cc19731d3ec0ca49574b314d7c82155e69f2d420122

See more details on using hashes here.

File details

Details for the file tokencircuit-8.1.0-py3-none-any.whl.

File metadata

  • Download URL: tokencircuit-8.1.0-py3-none-any.whl
  • Upload date:
  • Size: 33.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for tokencircuit-8.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e161fa91f73e6d3d3d3a04dcdf7b1f0919df9a874dd4c76e8a31ee72719407ab
MD5 81c2af01cea09c3592a0b858141f842d
BLAKE2b-256 4ea5785fcea49ecde7187a3316d3f8e4ce7806d36e85f5f49cc8c7a397d8d92c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page