# LLMSlim
**Long-term memory and context selection for AI agents and coding tools, with no LLM call.**
LLMSlim stores what users and agents say word for word, then returns the parts that answer a question within a
token budget you set. It runs as an MCP server, a Python library or a small HTTP server.
[](https://pypi.org/project/llmslim/)
[](https://pepy.tech/projects/llmslim)
[](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.Thanatos9404/llmslim)
[](LICENSE)
[](https://glama.ai/mcp/servers/Thanatos9404/llmslim)
[**Examples**](examples/) • [**Documentation**](https://www.llmslim.app/docs) • [**Live Studio Playground**](https://www.llmslim.app) • [**Sarvam Integration**](https://www.llmslim.app/integrations/sarvam) • [**Benchmarks**](#-benchmarks--radical-transparency) • [**Changelog**](CHANGELOG.md)
A real Python session with llmslim 0.11.1 from PyPI, typed by a script and recorded with asciinema (script, recording).
## Use it in 30 seconds
Each MCP setup below starts the same server, `llmslim mcp`, with [uv](https://docs.astral.sh/uv/) (Python 3.10 or
newer). Memory goes to a local SQLite file, `~/.llmslim/memory.db`.
**One click:**
[](https://vscode.dev/redirect/mcp/install?name=llmslim&config=%7B%22command%22%3A%22uvx%22%2C%22args%22%3A%5B%22--from%22%2C%22llmslim%5Bmcp%5D%3D%3D0.11.2%22%2C%22llmslim%22%2C%22mcp%22%5D%7D)
[](https://cursor.com/en/install-mcp?name=llmslim&config=eyJjb21tYW5kIjoidXZ4IiwiYXJncyI6WyItLWZyb20iLCJsbG1zbGltW21jcF09PTAuMTEuMiIsImxsbXNsaW0iLCJtY3AiXX0%3D)
[](https://lmstudio.ai/install-mcp?name=llmslim&config=eyJjb21tYW5kIjoidXZ4IiwiYXJncyI6WyItLWZyb20iLCJsbG1zbGltW21jcF09PTAuMTEuMiIsImxsbXNsaW0iLCJtY3AiXX0%3D)
[](https://goose-docs.ai/extension?cmd=uvx&arg=--from&arg=llmslim%5Bmcp%5D%3D%3D0.11.2&arg=llmslim&arg=mcp&id=llmslim&name=LLMSlim&description=Long-term%20memory%20for%20agents%20with%20no%20LLM%20in%20the%20loop)
[](https://kiro.dev/launch/mcp/add?name=llmslim&config=%7B%22command%22%3A%22uvx%22%2C%22args%22%3A%5B%22--from%22%2C%22llmslim%5Bmcp%5D%3D%3D0.11.2%22%2C%22llmslim%22%2C%22mcp%22%5D%7D)
| Tool | Run |
| :--- | :--- |
| Claude Code | `claude mcp add llmslim -- uvx --from "llmslim[mcp]" llmslim mcp` |
| Claude Code plugin | `/plugin marketplace add Thanatos9404/llmslim`, then `/plugin install llmslim@llmslim` |
| Codex | `codex mcp add llmslim -- uvx --from "llmslim[mcp]" llmslim mcp` |
| GitHub Copilot CLI | `copilot mcp add llmslim -- uvx --from "llmslim[mcp]" llmslim mcp` |
| Gemini CLI | `gemini extensions install https://github.com/Thanatos9404/llmslim` |
| Hermes Agent | `hermes plugins install llmslim --enable`, then `hermes config set context.engine llmslim`: a context engine that compacts long conversations locally ([plugin](plugins/hermes/README.md)) |
The first start downloads LLMSlim and its dependencies. If a client gives up waiting, run
`uvx --from "llmslim[mcp]" llmslim mcp --help` once to fill uv's cache, then restart the client.
**Python** (`pip install llmslim`, Python 3.9 or newer):
```python
from llmslim.memory import Memory
mem = Memory("memory.db") # a SQLite file; Memory("postgresql://...") with llmslim[postgres]
mem.add([{"role": "user", "content": "I'm allergic to peanuts."}], user_id="asha")
context = mem.search("Am I allergic to anything?", user_id="asha", budget=1500)
print(context.text) # put it in your prompt as data, not instructions
```
**TypeScript** (`npm install llmslim`, Node 18 or newer), against `llmslim serve` (`pip install "llmslim[server]"`):
```ts
import { LLMSlim } from "llmslim";
const slim = new LLMSlim(); // http://127.0.0.1:8080 unless LLMSLIM_BASE_URL is set
await slim.memories.add({ userId: "asha", messages: "I'm allergic to peanuts." });
const context = await slim.memories.search({ userId: "asha", query: "Am I allergic to anything?", budget: 1500 });
```
Runnable examples, each with a test: [Claude Code memory](examples/claude-code-memory/),
[LangChain agent](examples/langchain-agent-memory/), [Pydantic AI agent](examples/pydantic-ai-memory/),
[big logs](examples/fit-context-big-logs/) and [TypeScript](examples/typescript-client/).
If LLMSlim is useful, a star helps others find it. Feedback is welcome in [issues](https://github.com/Thanatos9404/llmslim/issues).
## What it does
- **Five MCP tools:** `remember`, `recall`, `list_memories`, `forget` and `fit_context`.
- **Stores messages word for word** in SQLite or Postgres. Nothing is summarized or extracted on the way in.
- **Recalls within a token budget.** `recall` returns the stored messages that answer a question, under their dates
and whole where they fit, within the budget you set. `fit_context` shrinks a long log or document to a budget.
- **Fixes the scope at server start.** The user and agent ids are set when the server starts, not by the model, so a
model steered by injected text can't read or delete another user's memory.
- **Makes no LLM call.** By default, storing and recalling are plain code: no model, no embedding API, no API key.
- **MIT licensed.** The library needs Python 3.9 or newer, the MCP server 3.10 or newer.
Beyond memory, LLMSlim Core also compresses and plans prompts, chat history, retrieved documents and tool schemas
into token budgets: see the sections below.
### Why no LLM call
Storing is a database write and recall is deterministic ranking code. So what comes back is what was said, not a
model's rewrite of it, and the same history and question always give the same context, which makes recall easy to
test. The memory server and `llmslim serve` make no network calls of their own. What does reach the network:
installing from PyPI (including `uvx`'s first run of a version) and tiktoken downloading its tokenizer file once.
The trade-off: the default lexical mode matches words, not meanings, so a question phrased differently from the
stored message can miss it. `relevance="semantic"` adds an optional cross-encoder for that (`llmslim[semantic]`,
which downloads the model the first time). See the [limits](docs/MEMORY.md#limits).
---
## Compress a prompt in 60 seconds
**1. Install** LLMSlim Core from PyPI (Python 3.9+). Running it needs no API key, model, or network call:
```bash
pip install llmslim
```
**2. Run** this snippet:
```python
from llmslim import compress
ticket = """
Hi team, I hope you are all doing well and had a good weekend.
I am writing about invoice INV-2291, which charged us $480 instead of $240.
We upgraded to the Pro plan on 3 September, but the old Basic plan was billed as well.
Our finance lead was asking about this during the weekly sync, which ran long as usual.
Please refund the duplicate $240 charge to the card ending 4417.
Thanks so much, and let me know if you need anything else from me.
"""
result = compress(ticket, target_ratio=0.6) # target: keep about 60% of the tokens
print(result.compressed_text)
print(f"{result.original_tokens} -> {result.compressed_tokens} tokens ({result.reduction_percent:.1f}% fewer)")
```
**3. What you should see** (llmslim 0.11.1, base install):
```text
Hi team, I hope you are all doing well and had a good weekend. I am writing about invoice INV-2291, which charged us $480 instead of $240. We upgraded to the Pro plan on 3 September, but the old Basic plan was billed as well. Please refund the duplicate $240 charge to the card ending 4417.
112 -> 72 tokens (35.7% fewer)
```
Two of the six sentences are dropped; the invoice number, amounts, plan change,
and refund request are kept. The default extractive mode only selects sentences
from your input, so the same input always gives the same output. The base install
estimates tokens at about 4 characters per token and prints a one-line warning
saying so. With `pip install "llmslim[fast-tokens]"`, tokens are counted with
tiktoken instead: on this input the same four sentences are kept, and the count
reads `107 -> 72 tokens (32.7% fewer)`.
**Next:** [Docs](https://www.llmslim.app/docs) • [Platform beta](https://www.llmslim.app/platform) • [Issues](https://github.com/Thanatos9404/llmslim/issues)
---
## LLMSlim Core and LLMSlim Platform
**The context layer for production AI agents.**
*This repository is **LLMSlim Core** (v0.11.2, MIT): local-first context planning and compression that fits prompts, conversation history, RAG, memory, and tool schemas into real token budgets while preserving instructions and execution boundaries.*
[](https://pypi.org/project/llmslim/)
[](https://github.com/Thanatos9404/llmslim/actions)
[](https://github.com/Thanatos9404/llmslim)
[](https://www.llmslim.app)
[](https://www.sarvam.ai/startup-program)
| | **LLMSlim Core** | **LLMSlim Platform** |
|---|---|---|
| Version | 0.11.2 | 0.9.1 beta |
| License | MIT, this repository | Proprietary, private beta |
| Install | `pip install llmslim` | By invitation; not published to PyPI |
| What it does | Compresses, plans, and traces model-visible context inside your Python process | Builds on Core: a verifiable timeline of agent state, explainable and replayable context decisions, and outcome-driven context policies that start in shadow mode |
Core is and stays fully open source. Platform is a separate product that depends on
Core; none of its code lives in this repository. Read more and request beta access at
[llmslim.app/platform](https://www.llmslim.app/platform).
What's new in Core: the [agent context runtime (v0.7.0)](#agent-context-runtime-v070)
and the [cache-aware context runtime (v0.7.1)](#cache-aware-context-runtime-v071).
Both are in the PyPI package from 0.7.1 onward; 0.7.0 was tagged but not published to PyPI.
---
## Adaptive Context Planner (v0.6.0)
LLMSlim is no longer only a fixed-ratio prompt compressor. The Adaptive
Context Planner chooses safe representations for each context item, then uses
a deterministic constrained allocator to fit the highest-value context into a
finite model budget. The original `compress()` API remains fully supported.
The v0.6.0 release adds explainable per-item decisions, explicit infeasibility
reporting, post-plan validation, token and cost telemetry, policy presets, and
optional Sarvam AI, Zoho, and MongoDB integrations while keeping the base
installation local-first and provider-neutral.
```python
from llmslim import plan_context
plan = plan_context(
messages=[
{"role": "system", "content": "Answer only from verified context."},
{"role": "user", "content": "When does Acme renew?"},
],
documents=[{"content": "CRM: Acme renews on 2026-11-30."}],
query="Acme renewal date",
model="sarvam-105b",
max_input_tokens=8_000,
reserve_output_tokens=512,
)
assert plan.feasible
print(plan.final_context)
print(plan.metrics.planned_tokens, plan.metrics.estimated_input_cost_after)
```
Planning works offline with the base install. Optional integrations are
isolated behind extras:
```bash
pip install "llmslim[sarvam]" # Sarvam provider (official sarvamai SDK)
pip install "llmslim[zoho]" # CRM and WorkDrive context sources
pip install "llmslim[mongodb]" # explicit memory and Atlas retrieval
```
See the [architecture](docs/planning/ARCHITECTURE.md),
[algorithm](docs/planning/ALGORITHM.md), [security model](docs/planning/SECURITY.md),
[CLI](docs/planning/CLI.md), and [measured offline benchmark](docs/releases/v0.6.0-RELEASE_GATE.md#frozen-benchmark-result).
---
## Startup programs
_*` variables; see `.env.example`):
| Provider / Framework | What ships in Core | Pattern |
| :--- | :--- | :--- |
| **Sarvam AI** | `llmslim[sarvam]`: `SarvamProvider`/`AsyncSarvamProvider`, `SarvamLanguageTools`, `SarvamDocumentSource`, `annotate_languages()`/`normalize_scripts()`, `sarvam_messages()` | Local planning + official `sarvamai` Python SDK, guarded with dated INR prices |
| **Exa** | `llmslim[exa]`: `ExaSearchSource`, vendor-neutral `WebSearchSource` | Untrusted RAG context items with URL, date and rank provenance; spend capped in USD |
| **Neo4j** | `llmslim[neo4j]`: `Neo4jContextStore` | Explicit tenant-scoped temporal memory: `supersede()`, `recall(as_of=...)`, `history()`, `conflicts()` |
| **OpenAI** | `openai_compatible_request()`, `openai_responses_request()` | Execution-free request builders; your code sends the request |
| **Anthropic Claude** | `anthropic_messages_request()` | Execution-free request builder with optional prompt-cache markers |
| **Google Gemini** | `gemini_generate_request()`, `gemini_cached_content_request()` | Execution-free request builders |
| **vLLM / self-hosted** | `vllm_chat_request()` | Execution-free request builder |
| **OpenAI Agents SDK** | `llmslim[agents]`: `make_openai_agents_input_filter()`, `to_openai_agents_tools()` | Text-only model-input filter; the SDK keeps execution and tool ownership |
| **LangChain** | `llmslim[langchain]`: `LLMSlimCompressor` | `BaseDocumentCompressor` for `ContextualCompressionRetriever` |
| **LlamaIndex** | `llmslim[llamaindex]`: `LLMSlimPostprocessor` | `BaseNodePostprocessor` for query engines |
| **Haystack** | `llmslim[haystack]`: `LLMSlimDocumentCompressor` | Pipeline component between retriever and prompt builder |
| **gptme** | `llmslim[gptme]`: `LLMSlimContextProvider` | Context provider for gptme's compaction (entry point `llmslim`) |
| **Hermes Agent** | `LLMSlimContextEngine` (no extra) | `ContextEngine` plugin; no LLM call, cache-stable prefix |
| **Pydantic AI** | `llmslim[pydantic-ai]`: `llmslim_history_processor()` | History processor that keeps tool calls and returns paired |
For other frameworks there is no dedicated adapter. LLMSlim works with any framework
that can pass plain message lists (`{"role": ..., "content": ...}` dicts) or document
strings; you write the few lines of glue that pass LLMSlim's output to your client.
---
## 📜 License & Citation
LLMSlim is open-source software licensed under the **MIT License**. See [LICENSE](LICENSE) for full details.
If you use LLMSlim in your research or production systems, please cite:
```bibtex
@software{llmslim2026,
author = {Yashvardhan Thanvi},
title = {LLMSlim: Deterministic Context Compression and Contract-Safe Tool Schemas for LLMs},
year = {2026},
publisher = {GitHub},
url = {https://github.com/Thanatos9404/llmslim}
}
```
Built with precision for developers everywhere. Accepted into the Sarvam Startup Program.
---
## Agent Context Runtime (v0.7.0)
Version 0.7.0 added a per-turn context path for agent applications (0.7.0 was
not published to PyPI; install 0.7.1 or later).
The host supplies messages, retrieved documents, memories, tool results, and
authorized tool schemas; LLMSlim returns a quality-checked model input and an
explainable local trace. Model calls and tool execution stay with the host.
```python
from llmslim import ContextRuntime, generic_request
runtime = ContextRuntime(model="sarvam-105b", max_input_tokens=8_000)
prepared = runtime.prepare_sync(
user_input="When does Acme renew?",
messages=[{"role": "system", "content": "Use verified dates."}],
documents=[{"id": "contract", "content": "Acme renews on 9 November 2026."}],
)
if prepared.feasible:
request = generic_request(prepared) # the host sends this to its model
print(request["messages"])
print(prepared.trace.explain())
```
The runtime includes `ContextEnvelope`, `ContextGraph`, `ContextPolicy`,
progressive planning, quality gates, bounded in-memory sessions, and
execution-free adapters for generic, Sarvam, OpenAI-compatible, and text-only
OpenAI Agents applications. `ContextTrace` omits prompt bodies by default.
The existing `compress()` and `plan_context()` APIs continue to work.
See the [architecture](docs/runtime/ARCHITECTURE.md),
[security model](docs/runtime/SECURITY.md),
[integrations](docs/runtime/INTEGRATIONS.md),
[migration guide](docs/releases/v0.7.0-MIGRATION.md),
[benchmark](docs/releases/v0.7.0-BENCHMARK.md), and
[engineering report](docs/releases/v0.7.0-ENGINEERING-REPORT.md).
## Cache-Aware Context Runtime (v0.7.1)
Cache planning is an opt-in layer for repeated agent turns. LLMSlim identifies
stable provider-visible prefixes, keeps append-only conversation context when
safe, fingerprints cache-sensitive settings, and reports local cache estimates
separately from provider-reported usage. A tenant-scoped `CacheManager` stores
metadata and provider references, never prompt bodies or KV tensors.
```python
from llmslim import CacheManager, CachePolicy, ContextRuntime
runtime = ContextRuntime(
model="generic-128k",
cache_policy=CachePolicy(mode="auto", provider="openai", tenant_id="my-workspace"),
cache_manager=CacheManager(),
)
prepared = runtime.prepare_sync(
session_id="conversation-1",
messages=[{"role": "system", "content": "Use verified sources."}],
user_input="What changed?",
)
print(prepared.trace.to_dict()["cache"])
```
Execution-free request builders cover OpenAI Responses, Anthropic Messages,
Gemini cached resources, and self-hosted vLLM. An advanced in-process
Transformers adapter validates KV continuation state. OpenAI provider-stateful
continuation and Gemini cached-resource creation require explicit host opt-in.
Sarvam prompt caching remains unverified and is disabled by default. The
Context Inspector shows prefix segmentation and cache diagnostics without
calling a provider. See [caching guidance](docs/runtime/CACHING.md),
[multi-turn benchmark](docs/releases/v0.7.1-BENCHMARK.md), and
[engineering report](docs/releases/v0.7.1-ENGINEERING-REPORT.md).
## Open-source security tooling
[Snyk](https://snyk.io/) provides developer security tooling for open-source projects. Learn more about its [Secure Developer Program](https://snyk.io/open-source/).