layer-context 0.1.5
Context Layer SDK - versioned context infrastructure for AI apps
License: MIT
Requires Python: >=3.8

# Context Layer

Python SDK for [ContextLayer](https://get-context-layer.lovable.app) - versioned context infrastructure for AI apps.

## Installation

```bash
pip install layer-context
```

For client-side encryption (optional):
```bash
pip install layer-context cryptography
```

## Quick Start

```python
from layer_context import CL

cl = CL(api_key="cl_sk_your_key_here")

# Create a block
cl.create_block("system-prompt")

# Get a block handle
block = cl.block("system-prompt")

# Append context
block.append("You are a helpful assistant.")
block.append("Always respond in markdown.")

# Get compiled context
print(block.get_context())
# Output: "You are a helpful assistant.\nAlways respond in markdown."

# Update (replace entire context)
block.update("You are a coding assistant. Use Python examples.")

# Delete specific content
block.delete("Use Python examples.")

# Read updated context
print(block.get_context())
# Output: "You are a coding assistant."

# Create a new version
block.create_version()

# Work with specific versions
block.append("V2 content", version=2)
print(block.get_context(version=2))

# View history
entries = block.get_history()

# List all blocks
blocks = cl.list_blocks()
```
## Client-Side Encryption

Enable zero-knowledge encryption so your context is encrypted before it leaves your machine:

```python
cl = CL(
    api_key="cl_sk_your_key_here",
    encryption_key="my-secret-passphrase"
)

block = cl.block("private-data")
block.append("Sensitive context here")

# Data is stored encrypted on the server
# Only you can read it with the same encryption_key
print(block.get_context())  # Decrypted automatically
```

> **Note:** Requires `pip install cryptography`. The server never sees your plaintext data.

## Context Compression

Compress your context locally using sentence embeddings, TextRank, and TF-IDF — no LLM or API keys needed.

### Installation

```bash
pip install layer-context[compression]
```

This installs `sentence-transformers` and `numpy`. The `all-MiniLM-L6-v2` model (~80MB) is downloaded once on first use.

### Usage

```python
block = cl.block("support_faq")
block.append("You are a customer support assistant for Acme Corp.")
block.append("Always greet the user warmly and ask how you can help.")
block.append("If the user asks about billing, explain our pricing tiers.")
block.append("We offer Basic ($9/mo), Pro ($29/mo), and Enterprise (custom).")
block.append("For password resets, direct users to settings > security.")
block.append("Generally speaking, you should always be polite and helpful.")
block.append("Our refund policy allows refunds within 30 days of purchase.")

compressed = block.get_compressed_context(
    query="How much does the Pro plan cost?",
    target_tokens=50,
    aggressive_pruning=True,
)

print(compressed)
# Output (approx): "We offer Basic ($9/mo), Pro ($29/mo), and Enterprise (custom).
#   If the user asks about billing, explain our pricing tiers."
# Original: ~80 tokens -> Compressed: ~30 tokens
```

### Arguments

| Argument | Type | Default | Description |
|---|---|---|---|
| `query` | `str` | *required* | Topic/question to optimize relevance for. Sentences irrelevant to this are dropped. |
| `version` | `int` | `1` | Which block version to compress. |
| `target_tokens` | `int \| None` | `None` | Max token budget for output. Defaults to ~50% of original token count. |
| `relevance_threshold` | `float` | `0.3` | Min cosine similarity to `query` to keep a sentence. Lower = keep more, higher = stricter. |
| `dedup_threshold` | `float` | `0.85` | Similarity above which sentences are deduplicated. Only the best representative is kept. |
| `aggressive_pruning` | `bool` | `False` | When `True`, strips filler words, hedge phrases, verbose constructions, and example clauses. |

### Convenience Shortcut

```python
# Equivalent to cl.block("support_faq").get_compressed_context(...)
compressed = cl.get_compressed("support_faq", query="billing question")
```

### How It Works

```
Raw context
  → Sentence splitting
  → Relevance filter (cosine similarity vs query ≥ threshold)
  → Semantic dedup (cluster similar sentences, keep best)
  → TextRank + TF-IDF density scoring
  → Token budget selection
  → Optional aggressive pruning
  → Reorder by original position
Compressed context
```

The entire pipeline runs locally on your machine. No API calls, no extra costs.

## License

MIT