Skip to content

About

Python AI gateway to optimize LLM calls, reduce API costs, and stop runaway agent loops with self-healing guardrails for OpenAI, Anthropic, LangChain, and CrewAI.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

7 Commits

Folders and files

Repository files navigation

LoopShield™

LoopShield™

PyPI version License: MIT

⭐ Saving on LLM API costs or stopping runaway agent loops? Give this repository a Star to help other developers discover it!

LoopShield is a vendor-agnostic Python SDK and an OpenAI-compatible proxy that stops AI agents from burning tokens on the same tool cycle or the same thought. The proxy sits in front of the model provider. Every POST /v1/chat/completions is screened before it is forwarded. A detected loop comes back as a normal assistant message that tells the agent the repeating tool is locked and it must change strategy. The upstream provider is not called.

The core package depends only on networkx, numpy, and Pydantic v2. FastAPI, uvicorn, and httpx are an optional proxy extra. Embedding models are injected; the OpenAI and Ollama SDKs are not core dependencies.

How a call is intercepted

Clients keep speaking the provider’s chat API. LoopShield accepts an OpenAI Chat Completions body, and it also accepts an Anthropic Messages body on the same route. Anthropic shape is recognized from an anthropic-version header, a payload that has both system and max_tokens, or content blocks of type tool_use / tool_result.

flowchart TD
    A["Agent or app"] --> B["POST /v1/chat/completions"]
    B --> C["Assistant turns become AgentSteps"]
    C --> D["LoopShield.inspect"]
    
    D --> E["GraphAnalyzer: exact tool-call cycle"]
    D --> F["SemanticAnalyzer: cosine similarity of thoughts"]
    
    E --> G{"Loop detected?"}
    F --> G
    
    G -- "Yes" --> H["Return generated nudge (Intercepted payload)"]
    H --> A
    
    G -- "No" --> I{"Over SHIELD_MAX_TOKENS?"}
    I -- "Yes" --> J["Apply prune_context (Symmetrical Pruning)"]
    
    J --> K{"Provider Engine"}
    I -- "No" --> K
    
    K -- "OpenAI" --> L["Upstream POST /v1/chat/completions"]
    K -- "Anthropic" --> M["Upstream POST /v1/messages"]
    
    L --> A
    M --> A

    style B fill:#f9f,stroke:#333,stroke-width:2px
    style H fill:#f96,stroke:#333,stroke-width:2px
Loading

A clean request is forwarded with the caller’s Authorization, x-api-key, anthropic-version, anthropic-beta, openai-organization, and openai-project headers. LoopShield does not store those credentials.

When a loop is found, the JSON response still looks like a completion:

  • OpenAI: object is chat.completion, and choices.message.content is the nudge.
  • Anthropic: type is message, role is assistant, and the text block is the nudge.
  • Both include loopshield.intercepted, loopshield.loop_type (graph_cycle, semantic, or both), and loopshield.intervention_prompt.

stream: true on an intercepted call is returned as server-sent events with the same nudge. GET /health returns {"status": "ok"}.

Quick start

Build and run the gateway on port 8000. Point UPSTREAM_API_BASE at the provider you want clean calls to reach.

docker build -t loopshield:1.0.0 .
docker run --rm -p 8000:8000 -e UPSTREAM_API_BASE=https://openai.com -e SHIELD_SIMILARITY_THRESHOLD=0.92 loopshield:1.0.0

Check the process, then send a chat completion through it. The provider key stays on the request; the container only forwards it.

curl http://127.0.0
curl http://127.0.0 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"model\":\"gpt-4o\",\"messages\":[{\"role\":\"user\",\"content\":\"Summarize the deploy log.\"}]}"

An OpenAI SDK client uses the proxy as its base URL:

from openai import OpenAI

client = OpenAI(base_url="http://127.0.0", api_key="sk-...")
completion = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Summarize the deploy log."}],
)

Anthropic-shaped traffic uses the same path. Set the upstream base to https://anthropic.com and send the provider headers the proxy already forwards:

docker run --rm -p 8000:8000 -e UPSTREAM_API_BASE=https://anthropic.com loopshield:1.0.0
curl http://127.0.0 \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d "{\"model\":\"claude-3-5-sonnet-latest\",\"max_tokens\":256,\"system\":\"Be careful.\",\"messages\":[{\"role\":\"user\",\"content\":\"Summarize the deploy log.\"}]}"

The official Anthropic SDK posts to /v1/messages. This gateway accepts that payload shape on /v1/chat/completions, then forwards a clean call to {UPSTREAM_API_BASE}/v1/messages. If the upstream base already ends in /v1, that prefix is not doubled.

Configuration

Variable Default Meaning
UPSTREAM_API_BASE https://openai.com Origin for forwarded calls. OpenAI traffic goes to /v1/chat/completions. Anthropic traffic goes to /v1/messages.
SHIELD_SIMILARITY_THRESHOLD 0.92 Cosine similarity, from 0 to 1, above which two thoughts count as the same line of reasoning. The comparison is strict >.
SHIELD_MAX_TOKENS 8000 Estimated token budget. Over this, prune_context keeps the leading system prompt and the last two turns, and collapses repeated tool errors in the middle.
SHIELD_MAX_CYCLES 1 A directed tool cycle is a loop when it completes more times than this. 1 allows one lap and flags the second. 0 flags the first time the cycle closes.
SHIELD_MAX_SEMANTIC_REPEATS 2 Minimum streak of consecutive similar thoughts, measured backward from the latest thought, required to flag a semantic loop.
SHIELD_UPSTREAM_TIMEOUT 60 Upstream HTTP timeout in seconds.

The image sets UPSTREAM_API_BASE, SHIELD_SIMILARITY_THRESHOLD, and SHIELD_MAX_TOKENS. Override any of them with docker run -e.

Two detectors run on every request:

  • Graph. Each tool call is a node of tool_name plus normalized arguments. Consecutive calls are directed edges. The same cycle walked again, including a tool calling itself with the same arguments, is a graph loop.
  • Semantic. Thoughts are compared with cosine similarity. With no embedding model configured, the proxy uses an in-process TF-IDF bag-of-words embedder. Identical text scores 1.0. A streak breaks at the first thought that does not exceed the threshold.

The proxy calls inspect, which does not keep request history on the shared process. Concurrent requests do not contaminate each other.

Use the SDK in process

Install the library when the agent loop lives in your own code and you do not need the gateway:

pip install -e ".[all]"

Record each step. A verdict with is_loop carries the system nudge to send back to the model.

from loopshield import AgentStep, LoopShield

shield = LoopShield(similarity_threshold=0.92, max_cycles=1)

verdict = shield.step(
    AgentStep(
        thought="The config file should be at the project root.",
        tool_name="read_file",
        tool_args={"path": "config.txt"},
        tokens_used=12,
    )
)

if verdict.is_loop:
    print(verdict.intervention_prompt)

@shield.guard wraps a function that takes an AgentStep. When the new step closes a loop, the decorator returns the LoopVerdict and does not call the function. Pass an initialized OpenAI or Ollama client as embedding= to replace the TF-IDF fallback; pass embed_fn= for any other model. Do not pass both.

prune_context(messages, max_tokens_estimate) takes OpenAI-style message dicts. It estimates tokens from token_count, tokens, or usage.total_tokens when present, otherwise from character length at about four characters per token. It handles tool execution histories symmetrically, stripping the triggering tool calls alongside their matching failed results to keep payload layouts structurally valid.

🧪 Testing & Trajectory Calibration

When writing validation scripts or executing automated loops locally, follow these mechanical matching patterns to ensure detection matches expectations:

  1. The Circuit Rule (max_cycles=1): A directed tool graph cycle requires a full circuit path (lap) to close before registering. Triggering a loop with max_cycles=1 means the agent must run through two distinct laps sequentially (e.g., Tool A -> Tool B -> Tool A -> Tool B -> Tool A). The system permits the initial repetition step to run safely and flags on the fifth step.
  2. Textless Tool Submissions: When an assistant turn executes tool blocks without writing a text thought parameter, LoopShield automatically groups the tool_name and tool_args into a unified structural key. Always maintain key-value pairing integrity inside tool_args parameters during unit tests.
  3. Pure Reasoning Streams: To evaluate consecutive semantic similarities when an agent rephrases plans without calling any execution functions, supply a tracking constant into tool_name (e.g., tool_name="thought_only") to pass schema requirements cleanly.

Framework integrations

loopshield/frameworks.py plugs the same engine into LangChain, CrewAI, and LangGraph. Each framework is an optional install (pip install "loopshield[langchain]", [langgraph], [crewai]). The hooks keep no history on the shield, so one LoopShield can serve concurrent runs.

LangChain. shield.langchain_middleware(config) returns a native AgentMiddleware wrapper.

  • The tool hook intercepts the loop dynamically before the execution runs.
  • The model hook invokes prune_context natively when the execution transcript breaches configuration budgets.

About

Python AI gateway to optimize LLM calls, reduce API costs, and stop runaway agent loops with self-healing guardrails for OpenAI, Anthropic, LangChain, and CrewAI.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages