Library of Context
コンテキストの図書館
AIコンテキストのための仮想メモリ:モデルの外で永続化し、モデルの内で制限する。
AIモデルには有限のネイティブコンテキストウィンドウがあります。長い会話はやがて拡大し、古い情報が切り詰められたり圧縮されたりします。コンテキストガバナーを経由する呼び出しでは、図書館は各記録イベントをSQLiteに保存し、保護されたイベント、最近のイベント、および取得されたレコードから制限付きのモデルリクエストを組み立てます。
モデルのコンテキストウィンドウを読書机と考えてください。図書館は机よりもはるかに多くの本を収容できますが、司書は現在のタスクに必要な本だけを机の上に並べます。タスクを変更すると机が置き換わります。本を上に積み重ねるわけではありません。
[!IMPORTANT] このプロジェクトはアドレス可能なコンテキストを拡張するものであり、モデルの物理的なコンテキストウィンドウの制限を拡張するものではありません。これはローカルプロトタイプとコラボレーションを目的としており、本番のマルチテナントメモリサービスではありません。明示的なサポート境界については機能ステータスを参照してください。
通常の圧縮との違い
従来の圧縮は、成長するトランスクリプトをより小さく、損失のある継続に変換し、元の詳細がアクティブなワークフローの外に残る可能性があります。図書館は可逆的なセマンティックページングを使用します:
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スレッドイベントとトランザクションインデックスアウトボックス。
トークンターゲット、イベント境界の最近のリング。即時の自己コンテキスト読み取り動作を提供します。過大なイベントはモデルエンベロープ内でのみ切り詰められ、ディスク上では切り詰められません。
オーバーフローと再起動回復のための永続的なSQLiteアウトボックスを備えた制限付きワークリング。
指示、決定、アクティブな計画、未解決の状態のための保護されたコンテキスト。
記録、埋め込み、インデックスされたウォーターマークとキュー健全性ステータス。
トランスクリプトの成長を置き換える新鮮で制限付きのプロンプトエンベロープ。
ハイブリッドベクトル、SQLite FTS5、重要度、および新しさの検索。
バイト境界のプロセスRAMとオプションの使い捨てローカル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図書館の比喩 | 実装 |
読書机 | モデルに送信される厳密に制限されたプロンプト |
本 | テキスト、出典、メタデータ、埋め込みを持つコンテキストレコード |
カタログ | ハイブリッド語彙およびベクトル検索 |
近くの書架 | プロセスRAMとオプションのローカル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 quickstartmacOSまたは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ゲートウェイ |
|
MCPもモデル呼び出しフックもないクローズドホスト | 透過的な統合なし |
Codex、Python、HTTP構成の例についてはエージェントに図書館を追加するを参照してください。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ゲートウェイは以下を使用できます:
ツール | 用途 |
| ユーザーターンを記録し、制限付きの次のリクエストを構築する |
| アシスタントまたはツールの結果を記録する |
| 重要な状態をすべてのプロンプトで対象に保つ |
| 保護された状態を通常のページングに戻す |
| ウォーターマーク、キュープレッシャー、ワーカー健全性を検査する |
| インデックスが記録されたウォーターマークに達するまで待機する |
図書館は棚上げ、検索、読書机、ステートレスセッション、ガバナーツールを公開します。ゲートウェイ専用ツールは、返されたmessagesを完全な次のモデルリクエストとして送信するホストでのみ有効にしてください。
ローカルHTTP API
python -m library_of_context --no-redis serveガバナーエンドポイントは次のとおりです:
メソッド | パス | 目的 |
|
| 永続的な追加と制限付きプロンプト構築 |
|
| 永続的なアシスタント/ツール結果の追加 |
|
| 保護されたコンテキストを追加 |
|
| 保護されたコンテキストを解放 |
|
| 非同期インデックス可視性を待機 |
|
| ガバナー状態とウォーターマークを検査 |
/books、/library/ingest、/catalog/query、/desk/* ルートは低レベルのライブラリを公開します。サーバーはループバックにバインドされ、認証はありません。他のマシンに直接公開しないでください。
ストレージ階層
最近のリング: スレッドごとの順序付きイベント。イベント数と推定トークンターゲットで制限されます。1つの過大なイベントは、新鮮なコンテキストが見えるように常駐する場合があります。プロンプト組み立ては、そのモデル可視ビューをハードエンベロープ予算に切り詰めます。これはLRUではありません。会話の順序が重要です。
プロセスRAM: ホットな本と検索結果のためのバイト境界LRU。
ローカルRedis: ホットな本、クエリ、机、TTL、無効化世代のためのオプションの共有キャッシュ。
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 doctordoctorはストレージティアをチェックしながら設定されたSQLiteデータベースを開きます。上記の例はdata/redis-check.sqliteを作成します。
SQLiteとプロセスRAMで十分な場合は、どこでも--no-redisを使用してください。
パフォーマンス制限
プロンプト組み立ては制限されており、記録されたイベントはトランザクションアウトボックスを使用します。FTSは制限付きの候補セットを返しますが、ベクトル検索は名前空間内のすべてのライブレコードを正確にスコアリングします。したがって、大規模カタログのスケール主張には測定された証拠が必要であり、正確なパスが宣言された制限を超える場合は、制限付きベクトル検索アダプターが必要です。
パフォーマンスとスケーリングは、測定、SLO基準、ベンチマーク質問を定義します。なぜこれらの改善か?は、より単純な代替案、採用トリガー、証拠ゲートを比較し、ロードマップは条件付き作業を順序付けます。
ドキュメント
ドキュメント | 目的 |
不変条件、階層、一貫性、進化 | |
隣接するコンテキストおよびメモリの手法との一次情報比較 | |
準備/コミットのプロトコルと障害時の挙動 | |
実装済み、実験中、計画中、非対応の境界 | |
教育的なビジュアルウォークスルー | |
監査証跡、NFRs、ベンチマークゲート | |
根拠、反論、代替案、導入トリガー | |
ローカルファーストのコラボレーションとプロモーションの設計 | |
マイルストーンと未解決のリサーチクエスチョン | |
主要な提案に必要な「なぜ / なぜそうしないのか / 根拠」の形式 | |
開発ワークフローと貢献領域 | |
脅威モデルと脆弱性の報告 |
設計を形作るために
未解決の設計上の質問には、以下のものがあります:
どのコンテキストを自動的に保護すべきか、誰がそれを解放できるのか?
ドキュメントQAではなくエージェントスレッドに対して、検索品質はどのように測定すべきか?
100,000〜1,000,000チャンクに適したローカルANNアダプターとは何か?
ブランチはどのようにコンテキストを継承、置き換え、マージすべきか?
プライベートスレッドからチームカタログに昇格させても安全で有用な知識はどれか?
共有イベントプレーンはRedis Streams、NATS JetStream、または別のブローカーを使うべきか?
ACLの失効は、クラウドをプロンプトのクリティカルパスに置かずに、ローカルキャッシュを どのように無効化すべきか?
異なるモデルトークナイザー間で、ユーザーにとって予測可能なトークン圧力ポリシーとは 何か?
詳細なリストは ROADMAP.md にあります。質問、ベンチマーク結果、設計メモ、 アダプター、障害テスト、批判を歓迎します。
コントリビューション
CONTRIBUTING.md を読み、リサーチクエスチョンや設計提案をオープンし、 プルリクエストは焦点を絞ってください。このプロジェクトは特に、再現可能な 検索ベンチマーク、ANNアダプター、トークナイザー統合、プライバシーレビュー、キューおよび クラッシュテスト、エージェントフレームワークのゲートウェイを歓迎します。
ライセンス
MIT © Library of Context のコントリビューター。
Available Tools
16 toolslibrary_consultARead-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_flushCIdempotent
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_releaseAIdempotent
Release one protected event so it can be paged normally. The durable event is retained.
Inputs: event_id (required), collection, session_id.
library_context_statusBRead-onlyIdempotent
Read context-governor watermarks, queue occupancy, prompt pressure, and worker health for one agent thread.
Inputs: collection, session_id.
library_desk_getARead-onlyIdempotent
Read the latest bounded reading desk snapshot for a session.
Inputs: collection, session_id.
library_desk_refreshARead-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_stopAIdempotent
Stop periodic refresh for a reading-desk session. The current snapshot remains available.
Inputs: collection, session_id.
library_desk_watchBIdempotent
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_documentADestructiveIdempotent
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_statsARead-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
Scored across 16 tools
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.
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.
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.
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
Cloud-hosted MCP server for durable AI memory
Cross-tool persistent memory and context for AI assistants over MCP.
Persistent memory for AI agents to retain, retrieve, and recall conversation context through MCP.
One MCP server for the services your AI needs: memory, files, Microsoft 365, kanban and more.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceAn MCP server that extends AI agents' context window by providing tools to store, retrieve, and search memories, allowing agents to maintain history and context across long interactions.1MIT
- FlicenseNot gradedqualityDmaintenanceA local MCP server that provides semantic memory storage and retrieval for coding and AI agents, enabling durable context across chat sessions.4-
- AlicenseBqualityDmaintenanceMCP server providing context usage estimation, conversation compaction, and durable semantic memory via local embeddings and SQLite.1728 npm3MIT
- AlicenseNot gradedqualityCmaintenanceAn MCP server that provides persistent long-term memory for AI agents via local SQLite storage with low token overhead, enabling memory storage, retrieval, and management across sessions.1MIT