Skip to main content
Glama
Library of Context
by hwillGIT

The Library of Context

CI Python 3.11+ License: MIT Local first

AI 上下文的虚拟内存:在模型之外持久化,在模型之内受限。

The Library of Context 虚拟内存架构

AI 模型的原生上下文窗口是有限的。长时间的对话最终会不断膨胀,直到旧信息被截断或压缩。对于通过其上下文治理器路由的调用,Library 会将每个记录的事件存储在 SQLite 中,并根据受保护事件、近期事件和检索记录组装出有界的模型请求。

可以把模型的上下文窗口想象成一张阅读桌。图书馆能容纳的书比书桌多得多,但图书管理员只摆出当前任务所需的书。更换任务就是更换书桌,而不是往上面堆更多的书。

[!IMPORTANT] 本项目扩展的是可寻址上下文,而不是模型的物理上下文窗口限制。它面向本地原型和协作,而非生产级多租户内存服务。有关明确的支持边界,请参阅能力状态。

为什么这与普通压缩不同

传统的压缩会将不断增长的对话记录变成更小、有损的延续,并可能使原始细节游离在活动工作流之外。Library 使用可逆的语义分页:

traditional:  growing transcript -> compacted transcript -> continue

Library:      durable event log -> bounded recent/protected context
                       |                    + relevant retrieved books
                       +-----------> fresh model request on every turn

原始事件是可检查和可恢复的。摘要可以成为导航辅助,但不必是唯一幸存的副本。

相关工作概览将此设计与模型长上下文方法、检索、提示压缩、提供商压缩、代理内存、检查点和推理运行时页面调度进行了比较。这里的"压缩"指的是一种更小、可能有损的延续表示,除非另一层保留其原始数据,否则这些原始数据无法独立寻址。

Related MCP server: local-memory-mcp

功能特性

  • 具有 prepare -> model call -> commit 生命周期操作的上下文治理器。

  • 持久的 SQLite 线程事件和事务性索引发件箱。

  • 用于即时读取自身上下文的、以 token 为目标且有事件边界的近期环;过大的事件仅在模型信封中被截断,而不会影响磁盘上的数据。

  • 有界的工作环,带有持久的 SQLite 发件箱,用于溢出和重启恢复。

  • 针对指令、决策、活动计划和未解决状态提供受保护的上下文。

  • 记录、嵌入和索引水位线,并带有队列健康状态。

  • 用全新的、有界的提示信封取代对话记录的增长。

  • 混合向量、SQLite FTS5、重要性和近期性检索。

  • 字节限制的进程内存和可选的一次性本地 Redis 热层。

  • 阅读桌交换报告:swapped_in、swapped_out 和 retained。

  • Python、本地 HTTP、CLI 和 STDIO MCP 集成接口。

  • 无依赖的哈希嵌入和可选的本地 Ollama 适配器。

当您的代理或模型网关将每一轮对话都路由到治理器时,治理器会自动运行。仅 MCP 的集成是协作式的:主机可以使用归档和阅读桌工具,但无法重写已经调用工具的模型请求,也无法替换未记录的内部压缩钩子。

架构概览

flowchart LR
    U[User or tool event] --> A[Durable SQLite append]
    A --> E[(Thread event log)]
    A --> O[(Transactional outbox)]
    A --> R[Recent context ring]
    O --> W[Bounded work ring]
    W --> I[Embed and index workers]
    I --> S[(SQLite library and FTS)]
    I --> C[RAM and optional Redis cache]
    R --> G[Context governor]
    S --> G
    P[Protected context] --> G
    G --> D[Bounded reading desk]
    D --> M[Native model context]
    M --> X[Assistant response]
    X --> A

图书馆隐喻

实现

阅读桌

发送给模型的严格有界提示

书

包含文本、来源、元数据和嵌入的上下文记录

目录

混合词法和向量检索

附近的书架

进程内存和可选的本地 Redis

书架

持久的 SQLite 后备存储

图书管理员

上下文治理器和检索策略

书车

有界的异步工作环

借阅台账

持久的线程事件日志和发件箱

快速开始

默认配置只需要 Python 3.11 或更高版本。Redis 是可选的。

在 Windows PowerShell 中:

git clone https://github.com/hwillGIT/library-of-context.git
cd library-of-context
py -3.11 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e .
.\.venv\Scripts\python.exe -m library_of_context quickstart

在 macOS 或 Linux 上:

git clone https://github.com/hwillGIT/library-of-context.git
cd library-of-context
python3 -m venv .venv
.venv/bin/python -m pip install -e .
.venv/bin/python -m library_of_context quickstart

快速入门练习了保护、提示组装、事件记录、索引和清理,并使用临时数据库。它不使用 Redis、Docker、云服务或模型 API。继续阅读安装指南。

将其添加到您已运行的代理中

您的集成点

结果

支持 MCP 的现有代理

协作式归档、检索和阅读桌替换

拥有每次模型调用的 Python 或 HTTP 网关

通过 prepare -> model -> commit 自动进行有界上下文

没有 MCP 且没有模型调用钩子的封闭主机

无透明集成

有关 Codex、Python 和 HTTP 配置示例,请参阅将 Library 添加到您的代理。配置 MCP 服务器后,请重启客户端或开始新会话;配置不会影响已在进行中的聊天。

运行自动治理的 Python 文本代理

from library_of_context import GovernedTextAgent, LibraryOfContext


def call_my_model(messages: list[dict[str, str]]) -> str:
    return my_model_client.generate(messages=messages)


with LibraryOfContext("data/library.sqlite", redis_url="") as library:
    with library.open_context_governor(
        "agent-thread-42",
        token_budget=12_000,
        recent_token_budget=4_000,
        protected_token_budget=2_000,
    ) as context:
        context.protect(
            "Production changes require a canary wave.",
            label="deployment-policy",
        )

        agent = GovernedTextAgent(
            context,
            call_my_model,
            system_prompt="Work carefully and cite retrieved project evidence.",
        )
        response = agent.turn(
            "Diagnose the deployment failure.",
            turn_id="request-0001",
        )
        context.flush(timeout=5)
        print(context.status()["watermarks"])

回调必须只发送提供的 messages;它不能附加另一个对话记录或继续提供程序管理的对话。内置适配器仅支持文本。结构化工具调用、流、附件和多模态内容需要自定义序列化适配器。

有关完整协议,请参阅上下文治理器。

MCP 集成

对于普通的 MCP 代理,请使用 integrations/README.md 中项目隔离的模板和可随时合并的代理指令。这是协作式内存;它不控制主机的原生对话记录。

可以使用以下命令检查原始本地 STDIO 服务器:

python -m library_of_context.mcp_server --no-redis

拥有模型调用边界的自定义 MCP 网关可以使用:

工具

用途

library_context_prepare

记录用户轮次并构建有界的下一个请求

library_context_commit

记录助手或工具结果

library_context_protect

保持关键状态对每个提示都可用

library_context_release

将受保护状态恢复到正常分页

library_context_status

检查水位线、队列压力和工作线程健康状态

library_context_flush

等待索引达到记录的水位线

Library 公开了归档、检索、阅读桌、无状态会话和治理器工具。仅在将返回的 messages 作为完整的下一个模型请求发送的主机中启用仅网关工具。

本地 HTTP API

python -m library_of_context --no-redis serve

治理器端点为:

方法

路径

用途

POST

/context/prepare

持久追加加有界提示构建

POST

/context/commit

持久助手/工具结果追加

POST

/context/protect

添加受保护的上下文

POST

/context/release

释放受保护的上下文

POST

/context/flush

等待异步索引可见性

GET

/context/status/{session}

检查治理器状态和水位线

/books、/library/ingest、/catalog/query 和 /desk/* 路由公开了更底层的库。服务器绑定到回环地址,并且没有身份验证。不要将其直接暴露给其他机器。

存储层次结构

  1. 近期环: 按线程排序的事件,受事件数量和估计 token 目标的限制。一个过大的事件可以驻留在内存中,以便新上下文可见;提示组装会将其模型可见视图截断到硬性信封预算内。这不是 LRU;对话顺序很重要。

  2. 进程内存: 用于热书和检索结果的字节限制 LRU。

  3. 本地 Redis: 用于热书、查询、书桌、TTL 和失效世代的可选共享缓存。

  4. SQLite: 权威事件、发件箱、文本、元数据、FTS 和向量存储。

Redis 是一次性的。默认的本地 Redis 配置不是持久的消息代理,不应将其用作团队事件流。

在 Windows 上释放本地 Redis

不需要 Docker 和云账户。随附的 PowerShell 脚本会在 Ubuntu WSL 中安装 Redis 服务。它需要 WSL 2、Ubuntu 发行版和 systemd:

powershell -ExecutionPolicy Bypass -File .\scripts\install-local-redis.ps1
.\.venv\Scripts\python.exe -m library_of_context --db data/redis-check.sqlite doctor

doctor 在检查存储层时打开配置的 SQLite 数据库。上面的示例创建了 data/redis-check.sqlite。

如果 SQLite 加进程内存就足够了,请在所有地方使用 --no-redis。

性能限制

提示组装是有界的,记录的事件使用事务性发件箱。FTS 返回有界的候选集,而向量检索对命名空间中的每个活动记录进行精确评分。因此,大型目录的规模声明需要经过测量的证据,并且当精确路径超过声明的限制时,需要一个有界的向量搜索适配器。

性能和扩展定义了测量、SLO 标准和基准问题。为什么这些改进?比较了更简单的替代方案、采用触发因素和证据门,而路线图则对条件性工作进行了排序。

文档

文档

用途

架构

不变量、层级、一致性与演进

相关研究与设计全景

与相邻上下文和记忆方法的原始来源对比

上下文治理

准备/提交协议与故障行为

能力状态

已实现、实验性、计划中及不支持的范围

系统讲解

教学式可视化讲解

性能与扩展

审计证据、非功能需求与基准门槛

为何做这些改进?

理由、反驳论点、替代方案与采纳驱动因素

团队架构

本地优先协作与推广设计

路线图

里程碑与开放研究问题

决策模板

重大提案所需的“为什么/为什么不/证据”格式

贡献指南

开发流程与贡献领域

安全

威胁模型与漏洞报告

参与设计

开放的设计问题包括:

  • 哪些上下文应自动受到保护,谁可以释放它们?

  • 如何衡量代理线程而非文档问答的检索质量?

  • 对于 10 万到 100 万个块,合适的本地 ANN 适配器是什么?

  • 分支应如何继承、合并和覆盖上下文?

  • 哪些知识是安全且有价值的,可以从私有线程提升到团队目录?

  • 共享事件平面应使用 Redis Streams、NATS JetStream 还是其他消息代理?

  • ACL 撤销应如何使本地缓存失效,而无需将云服务置于提示关键路径中?

  • 对于不同模型的 tokenizer,哪种 token 压力策略能让用户获得可预测的体验?

更完整的列表见 ROADMAP.md。欢迎提出问题和基准测试结果、设计说明、适配器、故障测试以及批评意见。

贡献

请阅读 CONTRIBUTING.md,提出研究问题或设计提案,并保持拉取请求聚焦。本项目特别欢迎可复现的检索基准、ANN 适配器、tokenizer 集成、隐私审查、队列与崩溃测试,以及代理框架网关。

许可证

MIT © Library of Context 贡献者。

Available Tools

16 tools
library_consultA
Read-onlyIdempotent

Search the off-desk Library with hybrid vector, lexical, importance, and recency ranking without changing the reading desk.

Inputs: subject (required), max_books, collection, catalog_filters, +1 more.

library_context_commitB

Durably append the assistant or tool result after a governed model call. The outbox indexes it asynchronously while the recent ring makes it immediately visible.

Inputs: content (required), role, event_id, metadata, +8 more.

library_context_flushC
Idempotent

Wait until this thread's durable outbox has been embedded and indexed through its recorded watermark.

Inputs: collection, session_id, timeout_seconds.

library_context_prepareB

Durably append a user turn, then return the complete bounded semantic-paging envelope for the next model call. Send only the returned messages to the model.

Inputs: user_message (required), focus, event_id, metadata, +10 more.

library_context_protectA

Persist critical instructions, decisions, active plans, or unresolved state as protected context that remains eligible for every governed prompt until released.

Inputs: content (required), role, label, event_id, +7 more.

library_context_releaseA
Idempotent

Release one protected event so it can be paged normally. The durable event is retained.

Inputs: event_id (required), collection, session_id.

library_context_statusB
Read-onlyIdempotent

Read context-governor watermarks, queue occupancy, prompt pressure, and worker health for one agent thread.

Inputs: collection, session_id.

library_desk_getA
Read-onlyIdempotent

Read the latest bounded reading desk snapshot for a session.

Inputs: collection, session_id.

library_desk_refreshA
Read-onlyIdempotent

Replace a session's bounded reading desk with books relevant to the current subject. Returns the prompt-ready context plus swapped-in, swapped-out, and retained IDs.

Inputs: subject (required), keep_open, max_books, collection, +3 more.

library_desk_stopA
Idempotent

Stop periodic refresh for a reading-desk session. The current snapshot remains available.

Inputs: collection, session_id.

library_desk_watchB
Idempotent

Refresh a reading desk immediately and periodically thereafter for a long-running task. A later focus change should call library_desk_refresh or start this tool again.

Inputs: subject (required), keep_open, max_books, collection, +4 more.

library_message_recordB

Shelve one conversation message for a virtual-context session. External model gateways should record assistant replies after each response.

Inputs: role (required), content (required), collection, importance, +1 more.

library_prompt_buildC

Build a complete stateless model-input envelope from bounded recent turns plus a replacement reading desk. Full history remains shelved on disk instead of growing the live prompt.

Inputs: max_books, collection, session_id, record_user, +4 more.

library_shelveA

Persist one concise book of context to the local Library. Use for durable decisions, constraints, findings, and user-approved memories—not transient chatter or secrets.

Inputs: text (required), source, book_id, catalog, +3 more.

library_shelve_documentA
DestructiveIdempotent

Chunk and persist a larger local text document as multiple books. Set replace_edition to replace prior chunks from the same source.

Inputs: text (required), source (required), catalog, collection, +4 more.

library_statsA
Read-onlyIdempotent

Inspect Library tier health, usage, cache hit/miss counters, and embedding configuration.

Inputs: collection.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.3/5.0

    Scored across 16 tools

    Disambiguation3/5

    The tools split into understandable areas (shelving, reading desk, context governor), but several pairs overlap in behavior: desk_refresh/desk_watch, context_prepare/prompt_build, and message_record/context_commit can all be confused without close reading. Descriptions mostly disambiguate them, but the boundaries are not immediately obvious from names alone.

    Naming Consistency4/5

    The library_ prefix plus domain area gives a predictable feel, especially for the desk_* and context_* families. A few standalone verbs/nouns like library_shelve, library_consult, and library_stats break the noun_verb pattern, but these are minor deviations.

    Tool Count3/5

    At 16 tools, the surface is slightly heavy and crosses the usual well-scoped range, though the three subsystems (library, desk, and context governor) explain most entries. A couple of prompt/recording tools could likely be consolidated without losing core functionality.

    Completeness4/5

    The context lifecycle is well covered: shelve/consult, desk refresh/get/watch/stop, and prepare/commit/protect/release/status/flush form coherent workflows. Missing direct book-level listing/removal or get-by-ID is a minor gap, but it does not create a dead end for the main use cases.

    Related MCP Connectors

    Related MCP Servers