loopshield 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- loopshield/__init__.py +25 -0
- loopshield/adapters.py +222 -0
- loopshield/frameworks.py +522 -0
- loopshield/graph_analyzer.py +147 -0
- loopshield/mitigator.py +637 -0
- loopshield/models.py +32 -0
- loopshield/proxy.py +376 -0
- loopshield/py.typed +0 -0
- loopshield/semantic_analyzer.py +142 -0
- loopshield/shield.py +279 -0
- loopshield/transcript.py +205 -0
- loopshield-1.0.0.dist-info/METADATA +229 -0
- loopshield-1.0.0.dist-info/RECORD +15 -0
- loopshield-1.0.0.dist-info/WHEEL +5 -0
- loopshield-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: loopshield
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A lightweight, vendor-agnostic AI agent loop detection and self-healing middleware
|
|
5
|
+
Author-email: Your Name <your.email@example.com>
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
10
|
+
Classifier: Framework :: FastAPI
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
Requires-Dist: networkx>=3.0
|
|
14
|
+
Requires-Dist: numpy>=1.24.0
|
|
15
|
+
Requires-Dist: pydantic>=2.0
|
|
16
|
+
Requires-Dist: fastapi>=0.100.0
|
|
17
|
+
Requires-Dist: uvicorn>=0.22.0
|
|
18
|
+
Requires-Dist: httpx>=0.24.0
|
|
19
|
+
Provides-Extra: langchain
|
|
20
|
+
Requires-Dist: langchain>=0.1.0; extra == "langchain"
|
|
21
|
+
Requires-Dist: langgraph>=0.1.0; extra == "langchain"
|
|
22
|
+
Provides-Extra: langgraph
|
|
23
|
+
Requires-Dist: langgraph>=0.1.0; extra == "langgraph"
|
|
24
|
+
Provides-Extra: crewai
|
|
25
|
+
Requires-Dist: crewai>=0.1.0; extra == "crewai"
|
|
26
|
+
Provides-Extra: all
|
|
27
|
+
Requires-Dist: loopshield[crewai,langchain,langgraph]; extra == "all"
|
|
28
|
+
|
|
29
|
+
# LoopShield
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
33
|
+
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.
|
|
34
|
+
|
|
35
|
+
## How a call is intercepted
|
|
36
|
+
|
|
37
|
+
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`.
|
|
38
|
+
|
|
39
|
+
```mermaid
|
|
40
|
+
flowchart TD
|
|
41
|
+
agent["Agent or app"]
|
|
42
|
+
route["POST /v1/chat/completions"]
|
|
43
|
+
style{"Payload style"}
|
|
44
|
+
steps["Assistant turns become AgentSteps"]
|
|
45
|
+
inspect["LoopShield.inspect"]
|
|
46
|
+
graph["GraphAnalyzer<br/>exact tool-call cycle"]
|
|
47
|
+
semantic["SemanticAnalyzer<br/>cosine similarity of thoughts"]
|
|
48
|
+
loop{"Loop?"}
|
|
49
|
+
nudge["Intercepted assistant message<br/>intervention_prompt"]
|
|
50
|
+
budget{"Over SHIELD_MAX_TOKENS?"}
|
|
51
|
+
prune["prune_context<br/>keep system prompt and last 2 turns"]
|
|
52
|
+
openai["Upstream POST /v1/chat/completions"]
|
|
53
|
+
anthropic["Upstream POST /v1/messages"]
|
|
54
|
+
|
|
55
|
+
agent --> route --> style --> steps --> inspect
|
|
56
|
+
inspect --> graph
|
|
57
|
+
inspect --> semantic
|
|
58
|
+
graph --> loop
|
|
59
|
+
semantic --> loop
|
|
60
|
+
loop -->|yes| nudge
|
|
61
|
+
nudge --> agent
|
|
62
|
+
loop -->|no| budget
|
|
63
|
+
budget -->|yes| prune --> forward{"Provider"}
|
|
64
|
+
budget -->|no| forward
|
|
65
|
+
forward -->|OpenAI| openai
|
|
66
|
+
forward -->|Anthropic| anthropic
|
|
67
|
+
openai --> agent
|
|
68
|
+
anthropic --> agent
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
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.
|
|
72
|
+
|
|
73
|
+
When a loop is found, the JSON response still looks like a completion:
|
|
74
|
+
|
|
75
|
+
- OpenAI: `object` is `chat.completion`, and `choices[0].message.content` is the nudge.
|
|
76
|
+
- Anthropic: `type` is `message`, `role` is `assistant`, and the text block is the nudge.
|
|
77
|
+
- Both include `loopshield.intercepted`, `loopshield.loop_type` (`graph_cycle`, `semantic`, or `both`), and `loopshield.intervention_prompt`.
|
|
78
|
+
|
|
79
|
+
`stream: true` on an intercepted call is returned as server-sent events with the same nudge. `GET /health` returns `{"status": "ok"}`.
|
|
80
|
+
|
|
81
|
+
## Quick start
|
|
82
|
+
|
|
83
|
+
Build and run the gateway on port 8000. Point `UPSTREAM_API_BASE` at the provider you want clean calls to reach.
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
docker build -t loopshield:0.1.0 .
|
|
87
|
+
docker run --rm -p 8000:8000 -e UPSTREAM_API_BASE=https://api.openai.com -e SHIELD_SIMILARITY_THRESHOLD=0.92 loopshield:0.1.0
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Check the process, then send a chat completion through it. The provider key stays on the request; the container only forwards it.
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
curl http://127.0.0.1:8000/health
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
curl http://127.0.0.1:8000/v1/chat/completions \
|
|
98
|
+
-H "Authorization: Bearer $OPENAI_API_KEY" \
|
|
99
|
+
-H "Content-Type: application/json" \
|
|
100
|
+
-d "{\"model\":\"gpt-4.1\",\"messages\":[{\"role\":\"user\",\"content\":\"Summarize the deploy log.\"}]}"
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
An OpenAI SDK client uses the proxy as its base URL:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from openai import OpenAI
|
|
107
|
+
|
|
108
|
+
client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="sk-...")
|
|
109
|
+
completion = client.chat.completions.create(
|
|
110
|
+
model="gpt-4.1",
|
|
111
|
+
messages=[{"role": "user", "content": "Summarize the deploy log."}],
|
|
112
|
+
)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Anthropic-shaped traffic uses the same path. Set the upstream base to `https://api.anthropic.com` and send the provider headers the proxy already forwards:
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
docker run --rm -p 8000:8000 -e UPSTREAM_API_BASE=https://api.anthropic.com loopshield:0.1.0
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
curl http://127.0.0.1:8000/v1/chat/completions \
|
|
123
|
+
-H "x-api-key: $ANTHROPIC_API_KEY" \
|
|
124
|
+
-H "anthropic-version: 2023-06-01" \
|
|
125
|
+
-H "Content-Type: application/json" \
|
|
126
|
+
-d "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":256,\"system\":\"Be careful.\",\"messages\":[{\"role\":\"user\",\"content\":\"Summarize the deploy log.\"}]}"
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
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.
|
|
130
|
+
|
|
131
|
+
## Configuration
|
|
132
|
+
|
|
133
|
+
| Variable | Default | Meaning |
|
|
134
|
+
| --- | --- | --- |
|
|
135
|
+
| `UPSTREAM_API_BASE` | `https://api.openai.com` | Origin for forwarded calls. OpenAI traffic goes to `/v1/chat/completions`. Anthropic traffic goes to `/v1/messages`. |
|
|
136
|
+
| `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 `>`. |
|
|
137
|
+
| `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. |
|
|
138
|
+
| `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. |
|
|
139
|
+
| `SHIELD_MAX_SEMANTIC_REPEATS` | `2` | Minimum streak of consecutive similar thoughts, measured backward from the latest thought, required to flag a semantic loop. |
|
|
140
|
+
| `SHIELD_UPSTREAM_TIMEOUT` | `60` | Upstream HTTP timeout in seconds. |
|
|
141
|
+
|
|
142
|
+
The image sets `UPSTREAM_API_BASE`, `SHIELD_SIMILARITY_THRESHOLD`, and `SHIELD_MAX_TOKENS`. Override any of them with `docker run -e`.
|
|
143
|
+
|
|
144
|
+
Two detectors run on every request:
|
|
145
|
+
|
|
146
|
+
- **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.
|
|
147
|
+
- **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.
|
|
148
|
+
|
|
149
|
+
The proxy calls `inspect`, which does not keep request history on the shared process. Concurrent requests do not contaminate each other.
|
|
150
|
+
|
|
151
|
+
## Use the SDK in process
|
|
152
|
+
|
|
153
|
+
Install the library when the agent loop lives in your own code and you do not need the gateway:
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
pip install -e ".[dev]"
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Record each step. A verdict with `is_loop` carries the system nudge to send back to the model.
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
from loopshield import AgentStep, LoopShield
|
|
163
|
+
|
|
164
|
+
shield = LoopShield(similarity_threshold=0.92, max_cycles=1)
|
|
165
|
+
|
|
166
|
+
verdict = shield.step(
|
|
167
|
+
AgentStep(
|
|
168
|
+
thought="The config file should be at the project root.",
|
|
169
|
+
tool_name="read_file",
|
|
170
|
+
tool_args={"path": "config.txt"},
|
|
171
|
+
tokens_used=12,
|
|
172
|
+
)
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
if verdict.is_loop:
|
|
176
|
+
print(verdict.intervention_prompt)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
`@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.
|
|
180
|
+
|
|
181
|
+
`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.
|
|
182
|
+
|
|
183
|
+
## Framework integrations
|
|
184
|
+
|
|
185
|
+
`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.
|
|
186
|
+
|
|
187
|
+
**LangChain.** `shield.langchain_middleware(config)` returns an `AgentMiddleware`:
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
from langchain.agents import create_agent
|
|
191
|
+
|
|
192
|
+
agent = create_agent(model, tools, middleware=[shield.langchain_middleware({"max_tokens": 6000})])
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
- `wrap_tool_call` replaces a looping tool call with an error `ToolMessage` that carries the nudge. The tool does not run, and the model reads why on its next turn.
|
|
196
|
+
- `wrap_model_call` runs `prune_context` when the transcript is over budget. For a loop that reaches the model, it answers with the nudge before the LLM is called. Set `on_loop` to `inject` to append the nudge as a system message and let the model run.
|
|
197
|
+
|
|
198
|
+
**CrewAI.** `@shield.crewai_agent()` wraps `Agent.execute_task`, either on a class or on the method. It rebuilds the tool trajectory from `agent.tools_results`, or from the `Action` / `Action Input` lines in the string context. When the tools loop, the nudge is prepended to the `context` string that the next step reads.
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
@shield.crewai_agent()
|
|
202
|
+
class GuardedAgent(Agent): ...
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
**LangGraph.** `shield.langgraph_node()` wraps a node. A looping `state["messages"]` gets the system nudge as a state update, and the node is skipped for that pass. With `{"retry_node": "agent"}` it returns `Command(update=..., goto="agent")`, so the graph re-enters that node with the nudge in context. The `messages` channel needs an appending reducer such as `add_messages`.
|
|
206
|
+
|
|
207
|
+
```python
|
|
208
|
+
graph.add_node("agent", shield.langgraph_node(agent_node, config={"retry_node": "agent"}))
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## Development
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
python -m pytest
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Python 3.11 or newer. Tests live in `tests/` and cover tool-call cycles, semantic streaks, recovery after a nudge, context pruning, embedding adapters, and the proxy with a mocked upstream.
|
|
218
|
+
|
|
219
|
+
| Module | Role |
|
|
220
|
+
| --- | --- |
|
|
221
|
+
| `loopshield/models.py` | `AgentStep` and `LoopVerdict` |
|
|
222
|
+
| `loopshield/graph_analyzer.py` | Directed tool-call cycles |
|
|
223
|
+
| `loopshield/semantic_analyzer.py` | Cosine similarity of thoughts |
|
|
224
|
+
| `loopshield/mitigator.py` | Intervention nudge and context pruning |
|
|
225
|
+
| `loopshield/shield.py` | `LoopShield.step`, `inspect`, and `guard` |
|
|
226
|
+
| `loopshield/adapters.py` | Optional OpenAI and Ollama embedding wrappers |
|
|
227
|
+
| `loopshield/proxy.py` | FastAPI gateway served by uvicorn |
|
|
228
|
+
| `loopshield/transcript.py` | Chat messages from any framework to `AgentStep`s |
|
|
229
|
+
| `loopshield/frameworks.py` | LangChain, CrewAI, and LangGraph integrations |
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
loopshield/__init__.py,sha256=qTp8FZrHr0pVz7hofYJYrHAx_6M3lpSRGgvlRgBisSM,785
|
|
2
|
+
loopshield/adapters.py,sha256=oGbRzTS1GpYM2CarcmcUI5WhVjGfbcrKII5wbcNY8Ys,7928
|
|
3
|
+
loopshield/frameworks.py,sha256=62Q-ePF-r-bKWNeJh5-tQxRuQOscZk1IIkXIHiM0BWk,19630
|
|
4
|
+
loopshield/graph_analyzer.py,sha256=4c1lvKrBdjwYxvN8XgmpQYCk7qIMhemZAySuT8DUc6o,5172
|
|
5
|
+
loopshield/mitigator.py,sha256=RqZJo48Lg1Mc31TLk3PPdgF_wsQn43srhAK02IJCQQo,24482
|
|
6
|
+
loopshield/models.py,sha256=2gX5KmpFE4IQIcuh7O_xggih9lWrhHlinixQnkh3buU,875
|
|
7
|
+
loopshield/proxy.py,sha256=y-Zh0PJiZF4kJSlVeLsbDmoqIPxSj112QTQEdMrCUuA,14423
|
|
8
|
+
loopshield/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
loopshield/semantic_analyzer.py,sha256=I9vyBP7kHO6iaYDdSHpMvkcFt3g6BYgcgF4BHddej7o,5356
|
|
10
|
+
loopshield/shield.py,sha256=6b76wOfmODQEZRbZOvkHly1CA6llbg2DuImNM2FhNvg,10666
|
|
11
|
+
loopshield/transcript.py,sha256=Gb0K0xX4pGb3Ufs0YBXDhmpkK3XV-0yaSEQNZjSs-bQ,7324
|
|
12
|
+
loopshield-1.0.0.dist-info/METADATA,sha256=o9gvmm6EmvLBe8ZF6tKMzXUEEPkEHSLmaerXjBgfNLg,11775
|
|
13
|
+
loopshield-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
14
|
+
loopshield-1.0.0.dist-info/top_level.txt,sha256=eCBhD0q0S9DPX5rO9iC2kGXUSl_9iw9tMpdOlLPSW3Q,11
|
|
15
|
+
loopshield-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
loopshield
|