langchain-okf 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.egg-info/
6
+ *.egg
7
+ dist/
8
+ build/
9
+ .eggs/
10
+
11
+ # Virtual environments
12
+ .venv/
13
+ venv/
14
+ ENV/
15
+
16
+ # IDE
17
+ .idea/
18
+ .vscode/
19
+ *.swp
20
+ *.swo
21
+ .DS_Store
22
+
23
+ # Testing & Benchmarks
24
+ .pytest_cache/
25
+ .mypy_cache/
26
+ .ruff_cache/
27
+ htmlcov/
28
+ .coverage
29
+ coverage.xml
30
+ benchmarks/bundle_*/
31
+ benchmarks/**/.chroma/
32
+ **/.okf_cache.json
33
+ **/.okf_index_hash
34
+
35
+ # Distribution
36
+ *.tar.gz
37
+ *.whl
@@ -0,0 +1,109 @@
1
+ # Changelog
2
+
3
+ <!-- version list -->
4
+
5
+ ## v0.2.0 (2026-11-15)
6
+
7
+ ### Features
8
+
9
+ - Prune dependencies, add retriever over-fetching, and activate CI/CD workflows
10
+ ([#1](https://github.com/AyushDey/langchain-okf/pull/1),
11
+ [`be14087`](https://github.com/AyushDey/langchain-okf/commit/be140877197a61f42a24a94642d694a07ab21206))
12
+
13
+
14
+ ## Unreleased
15
+
16
+ ## 0.2.0 (2026-11-14)
17
+
18
+ ### Added
19
+ - Dependency pruning: pruned unused dependencies (`langchain-ollama`, `langchain-text-splitters`) from core dependencies, made `langchain-chroma` optional, and kept core lean (`langchain-core`, `pypdf`, `pyyaml`).
20
+ - Over-fetching in `OKFRetriever`: dynamically scales candidate pool when post-filters (`trust_tier`, `stale_after`, `status`, `tags`) are active to prevent result starvation.
21
+ - Thread-safe and non-blocking agent memory tools: `OKFWriteConceptTool` and `OKFVerifyConceptTool` wrapped in reentrant write locks and native async `_arun` implementations via `asyncio.to_thread`.
22
+ - In-memory cross-link caching: `OKFConcept.cross_links()` caches parsed markdown references to eliminate repeated regex scans across graph hops.
23
+ - Automated CI/CD workflows: GitHub Actions for multi-python testing matrix (3.10–3.13) and OIDC Trusted Publishing to PyPI.
24
+ - Millisecond-level reruns via caching: `OKFBundleGenerator` hashes content chunks (SHA-256) and caches LLM results in `.okf_cache.json` in the bundle directory. If chunks or images are unchanged, extraction runs in milliseconds and uses 0 LLM API calls.
25
+ - Parallel LLM extraction: `OKFBundleGenerator` executes LLM calls concurrently using thread pools (controlled via `max_concurrency`, default `4`) to speed up first-run extraction.
26
+ - Decorative image filtering: `OKFBundleGenerator` automatically skips analyzing decorative graphics, logos, banners, headers, and footers to save API costs and processing time. Uses a combination of size/aspect-ratio heuristics and multimodal LLM classification.
27
+ - Asset directory cleanup: `OKFBundleGenerator` removes any unused/irrelevant extracted images from the bundle's `assets/` directory at the end of the run.
28
+ - Model-agnostic chunking: `OKFBundleGenerator` accepts a `chunk_size` at
29
+ construction, and `generate(chunk_size=...)` overrides per call. When
30
+ unset, a conservative default is used that is reliable on any model, local
31
+ or hosted — no guessing from model names or context windows.
32
+ - Output-truncation recovery: when a model hits its output-token limit
33
+ mid-answer (`finish_reason == "length"` and equivalents), the chunk is split
34
+ in half and re-extracted recursively so no concepts are lost.
35
+ - Concept normalization: every extracted concept is guaranteed to have the
36
+ keys the pipeline depends on (`category`, `filename`, `type`, `title`,
37
+ `body`); concepts with no usable content are dropped.
38
+ - JSON salvage: complete concept objects are recovered from truncated or
39
+ malformed JSON arrays (unescaped newlines, trailing prose, cut-off output).
40
+ - Oversized-passage handling: a single paragraph/table larger than the chunk
41
+ budget is hard-split so no call ever exceeds the model's limits.
42
+ - Transient-error resilience: rate limits and 5xx provider errors (capacity,
43
+ timeouts, gateway failures) are retried with exponential backoff + jitter,
44
+ and the default attempt count was raised so a brief provider outage can
45
+ recover instead of failing instantly. Verbose multi-line SDK/provider errors
46
+ (e.g. Pydantic validation dumps) are collapsed to a single readable line with
47
+ the error type and any HTTP status code.
48
+
49
+ ### Changed
50
+ - Progress feedback: the chunk-size line notes whether the size is the default
51
+ or custom; per-chunk lines show a running elapsed clock; zero-concept chunks
52
+ and images are reported distinctly (pointing to the warnings above); image
53
+ extraction is announced with a note that it needs a multimodal LLM; and the
54
+ final "no concepts" warning suggests concrete next steps.
55
+
56
+ ### Fixed
57
+ - `FileExistsError` / nested-directory bug when a model returned a `category`
58
+ or `filename` containing slashes (e.g. `research/r_swa`), a `.md` suffix, or
59
+ other path characters. Category and filename are now sanitized to a single
60
+ flat, lowercased path segment, and writes disambiguate genuine collisions
61
+ (file-vs-directory, or two concepts resolving to the same path) with a
62
+ numeric suffix. Index links use the same sanitized names.
63
+ - `KeyError: 'category'` (and other missing keys) when building the
64
+ incremental-enrichment prompt from previously stored concepts — the prompt
65
+ now tolerates concepts with missing fields, and normalization prevents such
66
+ concepts from being stored in the first place.
67
+ - `shutil.SameFileError` when Docling-extracted images already live in the
68
+ bundle's `assets/` directory — `_copy_image_asset` now skips same-path copies.
69
+ - Message content returned as a list of content blocks (LangChain v1 chat
70
+ models) is now coerced to text before JSON parsing.
71
+
72
+ ## 0.1.0 (2026-06-27)
73
+
74
+ Initial release.
75
+
76
+ ### Components
77
+ - `OKFBundleLoader` — Load OKF bundles as LangChain Documents with type/tag filtering
78
+ - `OKFKnowledgeGraph` — Directed graph from OKF cross-links with neighbor/backlink/subgraph queries
79
+ - `OKFRetriever` — Graph-aware retriever combining vector similarity with cross-link expansion
80
+ - `OKFToolkit` — 4 agent tools (list, read, related, search) with source citations
81
+ - `OKFBundleGenerator` — Generate OKF bundles from PDFs, text, images, CSVs, URLs using an LLM
82
+ - Auto-detect incremental mode: re-running on an existing bundle merges new content
83
+ - Docling (MIT) as preferred extraction backend — structured text, tables, images, OCR
84
+ - Fallback chain: Docling → pymupdf → pypdf (choose by license needs)
85
+ - Domain-aware extraction with 7 presets + custom free-text domains
86
+ - Error recovery with automatic retry on LLM failures
87
+ - Progress logging with `verbose` flag and custom `logger` support
88
+ - Smart chunking at paragraph boundaries with tiny-chunk merging
89
+ - Anti-hallucination prompts strictly grounded in source material
90
+ - PDF image extraction with classification (diagram/table/chart/photo)
91
+ - Source citations embedded in every concept for traceability
92
+ - Works fully offline after initial model download
93
+ - `validate_bundle()` — Check OKF v0.1 conformance of a bundle directory
94
+
95
+ ### Integrations
96
+ - Embedding providers: OpenAI, Ollama, OpenRouter
97
+ - Vector stores: Chroma, pgvector, Pinecone, Qdrant, FAISS, Milvus
98
+ - Agent framework: LangChain v1 `create_agent` with middleware support
99
+ - Source extraction: Docling (MIT, recommended), pymupdf (AGPL), pypdf (BSD)
100
+ - Async support: `OKFRetriever` and all toolkit tools support async (`ainvoke`, `_arun`)
101
+
102
+ ### Infrastructure
103
+ - Built with hatchling, compatible with uv and pip
104
+ - PEP 735 `[dependency-groups]` for dev dependencies
105
+ - `py.typed` marker for type-checking support
106
+ - 90+ unit tests with mock LLM (no API keys needed)
107
+ - Integration test stubs (run with `OPENAI_API_KEY` set)
108
+ - Python 3.10+ (aligned with LangChain v1)
109
+ - All core dependencies MIT/BSD licensed
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ayush Dey
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,367 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-okf
3
+ Version: 0.2.0
4
+ Summary: LangChain integration for Google's Open Knowledge Format (OKF)
5
+ Project-URL: Repository, https://github.com/AyushDey/langchain-okf
6
+ Project-URL: Documentation, https://github.com/AyushDey/langchain-okf#readme
7
+ Project-URL: Changelog, https://github.com/AyushDey/langchain-okf/blob/main/CHANGELOG.md
8
+ Project-URL: Bug Tracker, https://github.com/AyushDey/langchain-okf/issues
9
+ Author: Ayush Dey
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: knowledge-base,knowledge-graph,langchain,okf,open-knowledge-format,rag,retrieval-augmented-generation
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: langchain-core>=0.3.0
26
+ Requires-Dist: pypdf>=4.0.0
27
+ Requires-Dist: pyyaml>=6.0
28
+ Provides-Extra: agent
29
+ Requires-Dist: langchain-text-splitters>=0.3.0; extra == 'agent'
30
+ Requires-Dist: langchain>=1.0.0; extra == 'agent'
31
+ Provides-Extra: all
32
+ Requires-Dist: docling>=2.100.0; extra == 'all'
33
+ Requires-Dist: faiss-cpu>=1.7.0; extra == 'all'
34
+ Requires-Dist: langchain-chroma>=0.2.0; extra == 'all'
35
+ Requires-Dist: langchain-milvus>=0.2.0; extra == 'all'
36
+ Requires-Dist: langchain-ollama>=0.3.0; extra == 'all'
37
+ Requires-Dist: langchain-openai>=0.3.0; extra == 'all'
38
+ Requires-Dist: langchain-openrouter>=0.2.0; extra == 'all'
39
+ Requires-Dist: langchain-pinecone>=0.2.0; extra == 'all'
40
+ Requires-Dist: langchain-postgres>=0.0.12; extra == 'all'
41
+ Requires-Dist: langchain-qdrant>=0.2.0; extra == 'all'
42
+ Requires-Dist: langchain-text-splitters>=0.3.0; extra == 'all'
43
+ Requires-Dist: langchain>=1.0.0; extra == 'all'
44
+ Provides-Extra: chroma
45
+ Requires-Dist: langchain-chroma>=0.2.0; extra == 'chroma'
46
+ Provides-Extra: dev
47
+ Requires-Dist: langchain-chroma>=0.2.0; extra == 'dev'
48
+ Requires-Dist: langchain-ollama>=0.3.0; extra == 'dev'
49
+ Requires-Dist: mypy>=1.10; extra == 'dev'
50
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
51
+ Requires-Dist: pytest>=7.0; extra == 'dev'
52
+ Requires-Dist: ruff>=0.4.0; extra == 'dev'
53
+ Provides-Extra: faiss
54
+ Requires-Dist: faiss-cpu>=1.7.0; extra == 'faiss'
55
+ Provides-Extra: loaders
56
+ Requires-Dist: docling>=2.100.0; extra == 'loaders'
57
+ Provides-Extra: loaders-legacy
58
+ Requires-Dist: beautifulsoup4>=4.12; extra == 'loaders-legacy'
59
+ Requires-Dist: docx2txt>=0.8; extra == 'loaders-legacy'
60
+ Requires-Dist: langchain-community>=0.4.0; extra == 'loaders-legacy'
61
+ Requires-Dist: pymupdf>=1.24.0; extra == 'loaders-legacy'
62
+ Requires-Dist: pypdf>=4.0; extra == 'loaders-legacy'
63
+ Provides-Extra: milvus
64
+ Requires-Dist: langchain-milvus>=0.2.0; extra == 'milvus'
65
+ Provides-Extra: ollama
66
+ Requires-Dist: langchain-ollama>=0.3.0; extra == 'ollama'
67
+ Provides-Extra: openai
68
+ Requires-Dist: langchain-openai>=0.3.0; extra == 'openai'
69
+ Provides-Extra: openrouter
70
+ Requires-Dist: langchain-openrouter>=0.2.0; extra == 'openrouter'
71
+ Provides-Extra: pgvector
72
+ Requires-Dist: langchain-postgres>=0.0.12; extra == 'pgvector'
73
+ Provides-Extra: pinecone
74
+ Requires-Dist: langchain-pinecone>=0.2.0; extra == 'pinecone'
75
+ Provides-Extra: qdrant
76
+ Requires-Dist: langchain-qdrant>=0.2.0; extra == 'qdrant'
77
+ Provides-Extra: vectorstore
78
+ Requires-Dist: langchain-chroma>=0.2.0; extra == 'vectorstore'
79
+ Requires-Dist: langchain-openai>=0.3.0; extra == 'vectorstore'
80
+ Description-Content-Type: text/markdown
81
+
82
+ # langchain-okf
83
+
84
+ [![PyPI version](https://img.shields.io/pypi/v/langchain-okf.svg)](https://pypi.org/project/langchain-okf/)
85
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
86
+ [![OKF v0.2 Compliant](https://img.shields.io/badge/OKF-v0.2%20Compliant-green.svg)](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)
87
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
88
+
89
+ **Plug-and-play, self-improving memory layer and knowledge graph retriever for LangChain agents**, fully conforming to Google's [Open Knowledge Format (OKF v0.2)](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md).
90
+
91
+ Delivers **sub-second cold loads, search, retrieval, real-time memory writes, and trust verification** with both local models (LM Studio, Ollama) and cloud providers (OpenAI, Anthropic, Gemini).
92
+
93
+ ---
94
+
95
+ ## Highlights
96
+
97
+ - ⚡ **Sub-Second Performance**:
98
+ - **Cold Index Reload in 7–10 ms** (via `.okf_index_hash` content fingerprinting — bypasses re-embedding).
99
+ - **In-Memory Graph Search in 0.02–0.4 ms** (instant bidirectional link traversals).
100
+ - **Dynamic Agent Memory Writes in 0.69 ms** ([`OKFWriteConceptTool`](file:///Users/ayushdey/Desktop/langchain-okf/langchain_okf/toolkit.py#L320)).
101
+ - **Trust Verification in 0.78 ms** ([`OKFVerifyConceptTool`](file:///Users/ayushdey/Desktop/langchain-okf/langchain_okf/toolkit.py#L398)).
102
+ - **Incremental Bundle Re-generation in 5–8 ms** (via SHA-256 `.okf_cache.json`).
103
+ - 🛡️ **OKF v0.2 Spec Conformance**:
104
+ - **Trust Tiers**: Automatic derivation: `human-reviewed` > `machine-confirmed` > `unverified`.
105
+ - **Provenance Tracking**: `sources: [{ resource, title, author }]` preserved through ingestion.
106
+ - **Lifecycle & Freshness**: `status: stable | draft | deprecated` and `stale_after` automatic eviction.
107
+ - **Audit Logging**: Root `index.md` (`okf_version: "0.2"`) and sequential `log.md` event logs.
108
+ - 🧠 **Self-Improving Agent Memory**:
109
+ - Agents can read, search, synthesize, write new concepts, and verify knowledge during execution.
110
+ - 📈 **Extreme Scalability (1 to 100s of PDFs)**:
111
+ - Parallel LLM chunk extraction with thread-pool concurrency (`max_concurrency`).
112
+ - Native PDF ingestion (`pypdf`, `docling`, or `pymupdf`) with lazy loading.
113
+ - Deduplication and prompt optimization to eliminate quadratic prompt bloat.
114
+
115
+ ---
116
+
117
+ ## Benchmark Results (LM Studio Live Server)
118
+
119
+ Tested on local LM Studio (`http://127.0.0.1:1234/v1`) using `google/gemma-4-12b` and `text-embedding-nomic-embed-text-v1.5` (768-dim):
120
+
121
+ | Operation | Latency | Sub-Second? | Mechanism |
122
+ | :--- | :---: | :---: | :--- |
123
+ | **LM Studio Embedding API Call** | `73.4 ms` | ✅ YES | Direct `/v1/embeddings` HTTP batch |
124
+ | **Cached Bundle Re-generation** | `8.46 ms` | ✅ YES | SHA-256 chunk cache in `.okf_cache.json` |
125
+ | **Persisted Index Reload** | `7.94 ms` | ✅ YES | Fingerprint caching via `.okf_index_hash` (92.9x speedup) |
126
+ | **Vector Similarity Search** | `25.2 ms` | ✅ YES | ChromaDB cosine similarity + graph hop |
127
+ | **Graph In-Memory Search** | `0.026 ms` | ✅ YES | In-memory `OKFKnowledgeGraph` traversal |
128
+ | **Agent Real-Time Memory Write** | `0.70 ms` | ✅ YES | Atomic file creation + graph update |
129
+ | **Agent Trust Tier Upgrade** | `0.83 ms` | ✅ YES | In-place frontmatter mutation + `log.md` event |
130
+
131
+ ---
132
+
133
+ ## Install
134
+
135
+ ```bash
136
+ pip install langchain-okf
137
+ ```
138
+
139
+ Install optional integrations as needed:
140
+
141
+ ```bash
142
+ # Embedding & LLM providers
143
+ pip install "langchain-okf[openai]" # OpenAI / LM Studio / Local OpenAI-compatible
144
+ pip install "langchain-okf[ollama]" # Ollama
145
+ pip install "langchain-okf[openrouter]" # OpenRouter
146
+
147
+ # Vector stores
148
+ pip install "langchain-okf[chroma]" # Chroma (file-based, default)
149
+ pip install "langchain-okf[pgvector]" # PostgreSQL + pgvector
150
+ pip install "langchain-okf[pinecone]" # Pinecone
151
+ pip install "langchain-okf[qdrant]" # Qdrant
152
+
153
+ # PDF & Document loaders
154
+ pip install pypdf # Fast, BSD-licensed PDF ingestion
155
+ pip install "langchain-okf[loaders]" # Docling (MIT) — structured text + tables + OCR
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Quick Start
161
+
162
+ ### 1. Sub-Second Retriever with Local Models (LM Studio or Ollama)
163
+
164
+ ```python
165
+ from langchain_openai import OpenAIEmbeddings
166
+ from langchain_okf import OKFRetriever
167
+
168
+ # Connect to LM Studio local server
169
+ embeddings = OpenAIEmbeddings(
170
+ base_url="http://127.0.0.1:1234/v1",
171
+ api_key="lm-studio",
172
+ model="text-embedding-nomic-embed-text-v1.5",
173
+ )
174
+
175
+ # Loads in ~7 ms on subsequent runs (skips re-embedding unchanged bundles)
176
+ retriever = OKFRetriever.from_bundle(
177
+ "./my_knowledge/",
178
+ embeddings=embeddings,
179
+ persist_directory="./my_knowledge/.chroma",
180
+ min_trust_tier="machine-confirmed", # Filter out unverified hallucinations
181
+ exclude_stale=True, # Automatically skip expired concepts
182
+ expand_depth=1, # Traverse markdown cross-links
183
+ )
184
+
185
+ docs = retriever.invoke("What are the core context engineering boundaries?")
186
+ for doc in docs:
187
+ print(f"[{doc.metadata.get('trust_tier')}] {doc.metadata.get('title')}")
188
+ ```
189
+
190
+ ---
191
+
192
+ ### 2. Self-Improving Agent Memory Layer
193
+
194
+ Equip your agent with the complete OKF v0.2 toolkit, enabling both retrieval and active memory authoring:
195
+
196
+ ```python
197
+ from langchain.agents import create_agent
198
+ from langchain_openai import ChatOpenAI
199
+ from langchain_okf import OKFToolkit
200
+
201
+ toolkit = OKFToolkit.from_bundle(
202
+ "./my_knowledge/",
203
+ actor="agent/customer-support-v1",
204
+ include_write_tools=True,
205
+ )
206
+ tools = toolkit.get_tools()
207
+
208
+ agent = create_agent(
209
+ model=ChatOpenAI(model="gpt-4o", temperature=0),
210
+ tools=tools,
211
+ system_prompt="You are an autonomous agent with persistent OKF memory.",
212
+ )
213
+ ```
214
+
215
+ The agent receives 6 specialized tools:
216
+
217
+ | Tool | Action | Latency | Purpose |
218
+ | :--- | :--- | :---: | :--- |
219
+ | `okf_search` | Keyword & title search | `< 0.1 ms` | Exact lookups across titles, tags, and bodies |
220
+ | `okf_read_concept` | Read full concept | `< 0.1 ms` | Inspect full body, metadata, trust tier, and sources |
221
+ | `okf_related_concepts` | Follow graph edges | `< 0.1 ms` | Inspect outgoing links and incoming backlinks |
222
+ | `okf_list_concepts` | Filtered browsing | `< 0.1 ms` | Filter by `type:`, `tag:`, `trust:`, or `status:` |
223
+ | `okf_write_concept` | **Write new memory** | `0.69 ms` | Agent saves learned rules, edge cases, and facts |
224
+ | `okf_verify_concept` | **Upgrade trust tier** | `0.78 ms` | Mark verified (`human-reviewed` or `machine-confirmed`) |
225
+
226
+ ---
227
+
228
+ ### 3. Generate Knowledge Bundles from PDFs and Documents
229
+
230
+ Ingest PDFs, markdown, text files, or CSVs and convert them into structured OKF concepts:
231
+
232
+ ```python
233
+ from langchain_openai import ChatOpenAI
234
+ from langchain_okf import OKFBundleGenerator
235
+
236
+ generator = OKFBundleGenerator(
237
+ llm=ChatOpenAI(model="gpt-4o", temperature=0),
238
+ output_dir="./my_knowledge/",
239
+ bundle_name="Technical Architecture",
240
+ domain="Microservices, distributed caching, and auth",
241
+ stale_after_days=90, # OKF v0.2 lifecycle management
242
+ max_concurrency=8, # Concurrently extract chunks
243
+ )
244
+
245
+ generator.add_sources([
246
+ "architecture_doc.pdf",
247
+ "deployment_runbook.md",
248
+ "service_api.txt",
249
+ ])
250
+
251
+ # Cold run extracts concepts; subsequent runs use SHA-256 chunk cache (5-8 ms)
252
+ bundle_path = generator.generate()
253
+ ```
254
+
255
+ ---
256
+
257
+ ### 4. Conformance Audit (OKF v0.2 Spec §11)
258
+
259
+ Verify bundle health against the official OKF specification:
260
+
261
+ ```python
262
+ from langchain_okf import validate_bundle
263
+
264
+ # Strict mode validates ISO 8601 UTC offsets, actor conventions, and sources
265
+ issues = validate_bundle("./my_knowledge/", strict=True)
266
+ if not issues:
267
+ print("✅ 100% OKF v0.2 spec compliant")
268
+ else:
269
+ for issue in issues:
270
+ print(f"⚠️ {issue}")
271
+ ```
272
+
273
+ ---
274
+
275
+ ## Scalability: Handling 20 to 100s of PDFs
276
+
277
+ `langchain-okf` is engineered from the ground up for high-throughput multi-document ingestion:
278
+
279
+ ```
280
+ [20–100+ PDFs] ──▶ Direct pypdf Stream (1–6s) ──▶ SHA-256 Chunk Hash Check
281
+ │
282
+ ┌─────────────────────────────────┴─────────────────────────────────┐
283
+ ▼ ▼
284
+ Uncached Chunks (New) Cached Chunks (Unchanged)
285
+ Multi-Worker Thread Pool Instant In-Memory Load (< 10 ms)
286
+ (Cloud LLM / local vLLM / LM Studio)
287
+ │ │
288
+ └─────────────────────────────────┬─────────────────────────────────┘
289
+ ▼
290
+ OKF v0.2 Markdown Knowledge Bundle
291
+ │
292
+ ▼
293
+ .okf_manifest.json + .okf_index_hash
294
+ │
295
+ ┌─────────────────────────────────┴─────────────────────────────────┐
296
+ ▼ ▼
297
+ Initial Build (Cold) Incremental Sync (Hot)
298
+ Batch Embeddings + ChromaDB Embeds ONLY Delta ΔN Concepts
299
+ O(N log N) or O(N/P) O(ΔN log N) -> O(1) for single additions
300
+ ```
301
+
302
+ 1. **Streaming PDF Extraction**:
303
+ - Uses zero-overhead `pypdf` stream processing to extract text and pages in memory.
304
+ - Extracts ~20 PDFs (200 pages) in **1.2s** and ~100 PDFs (1,000 pages) in **~6s**.
305
+ 2. **$O(1)$ Hash Caching (`.okf_cache.json`)**:
306
+ - Each text chunk is hashed with SHA-256.
307
+ - If 100 PDFs are ingested and only 2 are updated, only the modified chunks call the LLM. The other 98 PDFs load from cache in **milliseconds**.
308
+ 3. **Multi-Worker Concurrency (`max_concurrency`)**:
309
+ - Extraction runs on a configurable `ThreadPoolExecutor`.
310
+ - With cloud models or local vLLM / high-throughput endpoints, extraction scales linearly across available workers.
311
+ 4. **$O(\Delta N)$ Incremental Vector Indexing**:
312
+ - Tracks a per-concept content manifest (`.okf_manifest.json`).
313
+ - When a bundle is updated with new or modified documents, `OKFRetriever` detects the exact diff and embeds/indexes **only the changed concepts ($\Delta N$)** instead of rebuilding the whole index.
314
+ - For adding a single concept or document, time complexity drops from $O(N \log N)$ to **$O(1)$** (~15–20 ms).
315
+ 5. **Persistent Fingerprint Reload (`.okf_index_hash`)**:
316
+ - For unchanged bundles, `OKFRetriever` reattaches to the persisted vector store in **7–15 ms** ($O(1)$) regardless of whether the bundle contains 10 or 10,000 concepts.
317
+ 6. **Memory Footprint**:
318
+ - In-memory graph of 10,000 concepts uses less than 25 MB of RAM, with sub-millisecond Dijkstra and BFS hop lookups.
319
+
320
+ ---
321
+
322
+ ## Dynamic Benchmark Tool
323
+
324
+ A built-in benchmark harness lets you evaluate ingestion and retrieval performance on your own files:
325
+
326
+ ```bash
327
+ # Benchmark your own PDFs with LM Studio
328
+ uv run python benchmarks/run_benchmark_lmstudio.py paper1.pdf paper2.pdf
329
+
330
+ # Benchmark an entire directory
331
+ uv run python benchmarks/run_benchmark_lmstudio.py ./my_pdf_folder/
332
+
333
+ # Run with full live LLM extraction
334
+ uv run python benchmarks/run_benchmark_lmstudio.py report.pdf --live-llm
335
+ ```
336
+
337
+ ---
338
+
339
+ ## Components
340
+
341
+ | Component | Type | Description |
342
+ | :--- | :--- | :--- |
343
+ | `OKFBundleGenerator` | Generator | Multi-format ingestion (PDF, MD, TXT, CSV) with SHA-256 caching and concurrency |
344
+ | `OKFBundleLoader` | Document Loader | Generator-based lazy loading (`lazy_load`) with trust and staleness filters |
345
+ | `OKFRetriever` | Retriever | Hybrid vector similarity + cross-link expansion + persistent disk caching |
346
+ | `OKFKnowledgeGraph` | Graph Engine | Directed graph for sub-millisecond edge navigation and backlinks |
347
+ | `OKFToolkit` | Agent Toolkit | 6 tools for search, graph navigation, atomic writes, and trust verification |
348
+ | `validate_bundle` | Validator | Strict validator auditing OKF v0.2 schema, actors, ISO 8601 dates, and sources |
349
+
350
+ ---
351
+
352
+ ## Development & Testing
353
+
354
+ To run tests and linters locally:
355
+
356
+ ```bash
357
+ uv sync
358
+ uv run pytest tests/ -v
359
+ uv run ruff check langchain_okf/
360
+ uv run mypy langchain_okf/
361
+ ```
362
+
363
+ ---
364
+
365
+ ## License
366
+
367
+ MIT © Ayush Dey