Skip to main content

Antigravity Context Shield Banner

🛡️ Antigravity Context Shield (antigravity-context-shield)

Python 3.11+ License: MIT CI Coverage Code Style: Black

Dynamic Context Compactor & Semantic State Graph for Long-Running Autonomous AI Agents.

antigravity-context-shield is an open-source, production-ready Python library engineered to eliminate Context Degradation ("Context Rot"), Silent Context Drift, and Hallucination Accumulation in long-running agent loops (e.g. software engineering agents, browser automation, long task loops).


🎯 The Problem

As autonomous agent loops execute over hours or days, context windows fill up with raw tool outputs (e.g., thousands of lines of terminal stdout, large file reads) and stale reasoning paths. Standard implementations suffer from:

  1. Naive Truncation: Drops crucial initial instructions, setup parameters, or system constraints.
  2. Raw RAG Dumping: Loses temporal ordering, state mutations, and causal dependencies.
  3. Infinite Error Loops: Agents repeatedly attempt failing tool commands with identical parameters without realizing system state hasn't changed.

🚀 Key Features

  • ⚡ Active Context Pruning Engine: Automatically compresses long terminal outputs and raw file reads while preserving stack traces and structural signatures. Collapses duplicate/polling action sequences into high-level notices.
  • 🕸️ Semantic State Graph (SSG): Models multi-turn execution as a Directed Acyclic Graph (DAG) of Turns, Tools, and State updates. Extracts the minimal active causal execution path, discarding failed/abandoned attempts.
  • 🛡️ Anti-Hallucination Guardrails: Pre-turn middleware that cross-references proposed prompt claims against active state nodes to detect state drift and block action redundancy.
  • 🔌 Framework Agnostic & SDK Adapters: Native hooks for Google Antigravity SDK (google-antigravity), LangChain, and LlamaIndex.

📊 Benchmarks

Metric Without Shield With antigravity-context-shield Improvement
5-Turn Agent History 8,605 chars (~2,150 tokens) 1,383 chars (~345 tokens) 83.93% Reduction
Redundant Tool Loop Deflection 0% (Loops indefinitely) 100% (Pre-emptively blocked) Zero Hallucination Loops
Test Coverage N/A 90% Unit Test Coverage Production Ready

📐 Architecture

flowchart LR
    subgraph Execution Loop
        User[User Goal] --> Agent[Autonomous Agent]
        Agent --> Shield[Context Shield Middleware]
        Shield --> Guard[Anti-Hallucination Guardrails]
        Guard --> Model[LLM / Gemini Dispatch]
    end

    subgraph Memory Architecture
        Model --> Tools[Tool Executions]
        Tools --> Pruner[Active Context Pruner]
        Tools --> SSG[Semantic State Graph DAG]
        Pruner --> ActiveContext[Compacted Active History]
        SSG --> ActiveContext
        ActiveContext --> Agent
    end

🛠️ Quickstart

Installation

pip install antigravity-context-shield

1. Integrating with Google Antigravity SDK

from google.antigravity import LocalAgentConfig
from antigravity_context_shield import ContextShieldAntigravityAdapter, ContextShieldConfig

# Instantiate Shield Config & Adapter
shield_config = ContextShieldConfig(
    max_message_length=1000,
    enable_terminal_pruning=True,
    enable_file_read_pruning=True,
    enable_duplicate_run_pruning=True,
    enable_guardrails=True
)

shield_adapter = ContextShieldAntigravityAdapter(config=shield_config)

# Register hooks with LocalAgentConfig
agent_config = LocalAgentConfig(
    hooks=shield_adapter.get_registered_hooks()
)

2. Standalone Compaction Engine

from antigravity_context_shield import ContextCompactorEngine, Message, MessageRole, ToolCall

engine = ContextCompactorEngine()

messages = [
    Message(role=MessageRole.USER, content="Run build tests."),
    Message(
        role=MessageRole.ASSISTANT, 
        content="Running pytest...", 
        tool_calls=[ToolCall(id="tc1", name="bash", arguments={"cmd": "pytest"}, output="VERY LONG STDOUT LOG...")]
    )
]

compacted_messages = engine.compact_messages(messages)

3. LangChain & LlamaIndex Callback Handlers

from antigravity_context_shield import ContextShieldLangChainCallbackHandler

handler = ContextShieldLangChainCallbackHandler()
# Pass `handler` into LangChain agent callbacks: agent.run(..., callbacks=[handler])

🧪 Running Examples & Tests

Run Unit Tests

pytest -v --cov=src/antigravity_context_shield tests/

Run Benchmark Demonstration Scripts

# Baseline without shield (watch context size grow)
python3 examples/run_without_shield.py

# With Shield enabled (watch >80% token reduction)
python3 examples/run_with_shield.py

📄 License

Distributed under the MIT License. See LICENSE for details.

Download files

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

Source Distribution

antigravity_context_shield-0.1.0.tar.gz (891.1 kB view details)

Uploaded Source

Built Distribution

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

antigravity_context_shield-0.1.0-py3-none-any.whl (22.3 kB view details)

Uploaded Python 3

File details

Details for the file antigravity_context_shield-0.1.0.tar.gz.

File metadata

File hashes

Hashes for antigravity_context_shield-0.1.0.tar.gz
Algorithm Hash digest
SHA256 77dba6f1a98c52666c6be1f8432a57d308c601dd20546a1876883b542c5ac357
MD5 66783a940d1a4d1b1fae0f12443e247a
BLAKE2b-256 e5c4865046b63e96a0afdecafc4c89ac16f1b4f87844246593ac46ac93a76c91

See more details on using hashes here.

File details

Details for the file antigravity_context_shield-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for antigravity_context_shield-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 71252d533a7d475ecb13a27b542c79019606576f459541f7e36744b6ec7f0350
MD5 e981ff15de46c06e4e129dec45adb5a0
BLAKE2b-256 1414330b09777c3d21b07457aeebfeae52ac5f57ad2efacfcb47b55c35145ada

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 files

Supported by

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