Metadata-Version: 2.4
Name: layer-context
Version: 0.2.0
Summary: Compression-powered Context infrastructure for Agentic Systems
License: MIT
Project-URL: Homepage, https://get-context-layer.lovable.app
Project-URL: Documentation, https://get-context-layer.lovable.app/docs
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28.0
Requires-Dist: cryptography>=41.0.0
Provides-Extra: compression
Requires-Dist: sentence-transformers>=2.2.0; extra == "compression"
Requires-Dist: numpy>=1.21.0; extra == "compression"
Requires-Dist: llmlingua>=0.2.0; extra == "compression"
Requires-Dist: torch>=2.0.0; extra == "compression"
Requires-Dist: transformers>=4.35.0; extra == "compression"
Dynamic: license-file

# layer-context

Python SDK for [ContextLayer](https://get-context-layer.lovable.app) - Compression-powered Context infrastructure for Agentic Systems.

## Installation

```bash
pip install layer-context
```

For compression features (context compression + prompt compression):

```bash
pip install layer-context[compression]

# Pre-download the embedding model (~80MB) to avoid first-call latency:
layer-context-download
```


## Quick Start

### Initialize

```python
from layer_context import CL

cl = CL(api_key="cl_sk_your_key_here")
```

### Create a Block

```python
cl.create_block("system-prompt")
```

### Get a Block Handle

```python
block = cl.block("system-prompt")
```

### Append Context

```python
block.append("You are a helpful assistant.")
block.append("Always respond in markdown.")

print(block.get_context())
# Output: "You are a helpful assistant.\nAlways respond in markdown."
```

### Update (Replace) Context

```python
block.update("You are a coding assistant. Use Python examples.")
```

### Delete Specific Content

```python
block.delete("Use Python examples.")

print(block.get_context())
# Output: "You are a coding assistant."
```

### Delete a Block

```python
cl.delete_block("system-prompt")
```

### Versioning

```python
block.create_version()

block.append("V2 content", version=2)
print(block.get_context(version=2))
```

### View History

```python
entries = block.get_history()
for entry in entries:
    print(f"{entry['action']}: {entry['content'][:50]}...")
```

### List All Blocks

```python
blocks = cl.list_blocks()
for b in blocks:
    print(b['name'])
```

## Context Compression

Compress your stored context to reduce token usage while preserving relevance to a given query. Uses sentence embeddings, TextRank, and TF-IDF — runs entirely on your machine.

```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("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)
# Original: ~80 tokens -> Compressed: ~30 tokens
```

### Arguments

| Argument | Type | Default | Description |
|---|---|---|---|
| `query` | `str` | *required* | Topic/question to optimize relevance for. |
| `version` | `int` | `1` | Which block version to compress. |
| `target_tokens` | `int \| None` | `None` | Max token budget. Defaults to ~50% of original. |
| `relevance_threshold` | `float` | `0.3` | Min cosine similarity to keep a sentence. |
| `dedup_threshold` | `float` | `0.85` | Similarity above which sentences are deduplicated. |
| `aggressive_pruning` | `bool` | `False` | Strip filler words and verbose phrases. |

### Convenience Shortcut

```python
compressed = cl.get_compressed("support_faq", query="billing question")
```

## Prompt Compression

Compress any prompt at token level before sending it to your LLM — reducing costs and improving accuracy.

```python
prompt = """You are a helpful customer support assistant for Acme Corp.
Always greet the user warmly and ask how you can help them today.
If the user asks about billing, explain our pricing tiers in detail.
We offer Basic ($9/mo), Pro ($29/mo), and Enterprise (custom pricing).
For password resets, direct users to the settings > security page.
Our refund policy allows full refunds within 30 days of purchase."""

# Compress the prompt by 50%
compressed = cl.compress_prompt(prompt, rate=50)
```

### Arguments

| Argument | Type | Default | Description |
|---|---|---|---|
| `prompt` | `str` | *required* | The prompt text to compress. |
| `rate` | `float` | `40` | Compression percentage (0-100). A rate of 40 removes ~40% of tokens. |

### Full Pipeline Example

```python
# 1. Get compressed context
context = cl.block("support_faq").get_compressed_context(
    query="billing question",
    target_tokens=50,
)

# 2. Build prompt
prompt = f"You are a support agent. {context} Answer the user's question."

# 3. Compress the final prompt
compressed_prompt = cl.compress_prompt(prompt, rate=40)

# 4. Send to LLM - fewer tokens, lower cost, higher accuracy
```

## License

MIT
