Skip to main content

kaos-nlp-core

Part of Kelvin Agentic OS (KAOS) — open agentic infrastructure for legal work, built by 273 Ventures. See the full KAOS package map for the rest of the stack.

PyPI - Version Python License CI

kaos-nlp-core is a high-performance NLP primitives library for KAOS — a pure-Rust core with Python bindings via PyO3/Maturin. It provides the text-processing building blocks the rest of the stack relies on: SIMD-accelerated string operations, multi-pattern matching, finite-state transducers, sentence segmentation, BM25 retrieval, fuzzy hashing, and typed Python wrappers throughout.

It is dependency-light: the BASE install pulls kaos-nlp-core itself, numpy>=2.1 (used by similarity, chunker/aggregation marshalling, and retrieval helpers — see pyproject.toml:54), and the bundled Punkt sentence-segmenter model (~12 MB). Optional extras layer in the rest of the KAOS ecosystem.

Use and authorship disclosure

kaos-nlp-core provides deterministic primitives — segmentation, chunking, tokenization, search, aggregation, hashing — that take text in and produce text spans / scores / hashes back. No network calls, no LLM calls, no provider-side data transmission happens from this package; everything runs in-process. Downstream consumers (notably kaos-llm-core Programs) may transmit text derived from these primitives to LLM providers, so callers handling sensitive data should check the consuming package's data-handling disclosure.

This codebase is AI-assisted: substantial portions were generated with Claude (Anthropic) and human-reviewed before commit. Public behavior is covered by the test suite under tests/; large-corpus scale tests are opt-in (pytest tests/scale -m slow) and require the HF JSONL fixtures (USC, EDGAR, patents). Bug reports welcome via GitHub Issues; security reports follow SECURITY.md.

Install

uv add kaos-nlp-core
# or
pip install kaos-nlp-core

kaos-nlp-core requires Python 3.13 or newer. The published wheels are cp313-abi3 — one wheel per OS/architecture covers every CPython 3.13+ minor (3.13, 3.14, 3.15, …). No re-release needed when 3.15 ships.

Platform coverage: Linux x86_64 (manylinux), Linux aarch64 (manylinux), macOS arm64, Windows x86_64, Windows arm64. musllinux wheels were last published in 0.1.0a2 — Alpine users should pin <=0.1.0a2 for now.

Quick start

from kaos_nlp_core import tokenizer, algorithms

# Two output shapes for tokenization:
#   tokenize_words → list[str]        — just the surface forms (fastest)
#   tokenize       → list[TokenSpan]  — .text / .start / .end when you
#                                       need character offsets back into
#                                       the source string
words = tokenizer.tokenize_words("kaos-nlp-core ships fast NLP primitives.")
print(words)
# ['kaos-nlp-core', 'ships', 'fast', 'NLP', 'primitives']

for s in tokenizer.tokenize("kaos-nlp-core ships fast NLP primitives.")[:3]:
    print(f"{s.start}-{s.end}: {s.text!r}")
# 0-13: 'kaos-nlp-core'
# 14-19: 'ships'
# 20-24: 'fast'

# Multi-byte safe (CJK + emoji) — offsets are CHARACTER offsets, not bytes
for s in tokenizer.tokenize("東京 emoji 😀 test"):
    print(f"{s.start}-{s.end}: {s.text!r}")
# 0-2: '東京'
# 3-8: 'emoji'
# 9-10: '😀'
# 11-15: 'test'

# Algorithms always return rich typed results
result = algorithms.levenshtein("kitten", "sitting")
print(f"distance={result.distance} similarity={result.similarity:.4f}")
# distance=3.0 similarity=0.5714

# Readability: one-shot helpers for the common scores, or a full report
from kaos_nlp_core.readability import flesch_kincaid_grade, readability_report
print(round(flesch_kincaid_grade("The cat sat on the mat. The dog ate a bone."), 2))
# -1.65
report = readability_report("The cat sat on the mat. The dog ate a bone.")
print(report.counts.words, round(report.scores.flesch_reading_ease, 1))
# 11 116.7

No install needed to try it — uv run pulls the wheel on the fly:

uv run --with kaos-nlp-core python -c "
from kaos_nlp_core.readability import flesch_kincaid_grade, readability_report

text = 'Hello, world. Readability scoring is now built into kaos-nlp-core.'
print('Flesch-Kincaid grade:', round(flesch_kincaid_grade(text), 2))

for name, value in readability_report(text).scores.to_dict().items():
    print(f'{name:28s} {value if isinstance(value, bool) else round(value, 2)}')
"
# Flesch-Kincaid grade: 9.77
# flesch_reading_ease          33.07
# flesch_kincaid_grade         9.77
# automated_readability_index  8.56
# coleman_liau_index           12.25
# smog_index                   8.84
# gunning_fog                  6.24
# lix                          37.83
# rix                          1.5
# smog_valid                   False

(smog_valid: False is the honesty flag: SMOG's calibration assumes ≥30 sentences. Dale-Chall is omitted entirely until you supply a familiar-word list.)

The _words shortcut exists wherever skipping offsets is meaningful work (tokenization). Everywhere else — segmentation (segment_sentences, segment_paragraphs, segment_lines), pattern matching, similarity algorithms — the API only ships the rich typed shape, because the metadata is the value.

Concepts

The package is organized around a small set of typed primitives.

Concept What it is
Algorithms kaos_nlp_core.algorithms — Levenshtein, Hamming, Jaro-Winkler, longest common substring, edit-distance variants. SIMD fast paths via stringzilla; ASCII fast paths before Unicode fallbacks.
Tokenizer kaos_nlp_core.tokenizer — Unicode-aware word/sentence tokenization with byte→char offset translation via build_byte_to_char_table(). Multi-byte safe (Latin diacritics, CJK, emoji).
Segmentation kaos_nlp_core.segmentation — Punkt sentence segmenter (bundled model models/default.npkt.gz, ~12 MB Apache-2.0 NLTK port).
Matching kaos_nlp_core.matching — Aho-Corasick multi-pattern matching, FST-backed fuzzy lookup via Levenshtein automata, regex.
Search kaos_nlp_core.search — BM25 retrieval, Searcher, sentence/paragraph search; pickle-safe with KNC magic header for index files.
Structures kaos_nlp_core.structures — Vocabulary, InvertedIndex, SparseTermMatrix, SimilarityMatrix. Compact, pickle-safe, bincode-2.0 backed.
Hashing kaos_nlp_core.hashing — CTPH (context-triggered piecewise hashing) via blake3, MinHash, LSH index, near-duplicate grouping.
Lexicon kaos_nlp_core.lexicon — query expansion, semantic graph traversal, gazetteer lookups.
Documents kaos_nlp_core.documents — Document, DocumentCollection with JSONL / HuggingFace loaders.
Quality kaos_nlp_core.quality — text-quality heuristics (token ratios, Unicode block distribution).
Readability kaos_nlp_core.readability — Flesch, Flesch-Kincaid, ARI, Coleman-Liau, SMOG, Gunning Fog, Dale-Chall, LIX/RIX with verified formula provenance; Rust-backed counting, CMUdict-exact syllables with tuned heuristic fallback.

CLI

kaos-nlp-core ships a kaos-nlp administrative CLI plus an optional kaos-nlp-serve MCP server (loopback-only by default; --http requires KAOS_NLP_HTTP_TOKEN as an operator acknowledgement that a reverse proxy is fronting authentication):

kaos-nlp tokenize doc.txt --lowercase --json          # word tokenization with spans
kaos-nlp segment doc.txt --mode sentences             # sentence segmentation (Punkt)
kaos-nlp compare "Robert" "Rupert" --algorithm jaro-winkler
kaos-nlp find "pattern" doc.txt --case-insensitive    # SIMD substring search
kaos-nlp index build corpus.txt --output idx.kncidx   # native persisted index
kaos-nlp search --index idx.kncidx "query terms"      # ranked search (BM25 default)
kaos-nlp hash doc.txt --algorithm ctph                # fuzzy hash
kaos-nlp duplicates ./corpus/ --threshold 0.5         # near-duplicate detection
kaos-nlp encode "Robert" --algorithm soundex          # phonetic encoding
kaos-nlp vocab build doc.txt --type frequency         # build vocabulary
kaos-nlp analyze doc.txt --json                       # text statistics report
kaos-nlp readability doc.txt --json                   # Flesch/FK/SMOG/Fog scores

kaos-nlp-serve            # MCP server, stdio transport
kaos-nlp-serve --http     # MCP server, streamable HTTP (operator-token gated)

Every command supports --json for machine-readable output. CLI search reads both the native persisted index format (KNC) and legacy .json bundles.

The CLI also runs without installing, via uvx:

uvx --from kaos-nlp-core kaos-nlp readability doc.txt --json

Note: 17 MCP tools are registered by register_nlp_tools(). Until 0.1.0a2, the [mcp] extra is reserved but unpopulated — manually run pip install kaos-core kaos-mcp before using kaos-nlp-serve. Once siblings publish to PyPI, pip install kaos-nlp-core[mcp] will cover the full install. Until then kaos-nlp-serve exits with an actionable install hint if kaos-core or kaos-mcp are missing.

Compatibility & status

Aspect
Python 3.13, 3.14 (informational matrix entries for 3.14t free-threaded and 3.15-dev). One cp313-abi3 wheel per OS/arch covers all 3.13+ minors.
OS Linux (manylinux, x86_64 + aarch64), macOS arm64, Windows x86_64, Windows arm64. macOS x86_64 deliberately skipped (Apple ended Intel sales in 2023); musllinux last shipped in 0.1.0a2.
Maturity Alpha. The public API is documented in kaos_nlp_core.__all__.
Stability policy Pre-1.0: minor bumps may change behaviour. Every change is documented in CHANGELOG.md.
Test coverage 298 Rust unit tests + Python pytest suite. Round-trip offset tests cover ASCII, multi-byte Latin, CJK, and emoji.
Type checker Validated with ty, Astral's Python type checker.

Companion packages

kaos-nlp-core is one of the packages in the Kelvin Agentic OS. The broader stack:

Package Layer What it does
kaos-core Core Foundational runtime, MCP-native types, registries, execution engine, VFS
kaos-content Core Typed document AST: Block/Inline, provenance, views
kaos-mcp Bridge FastMCP server, kaos management CLI, MCP resource templates
kaos-pdf Extraction PDF → AST with provenance
kaos-web Extraction Web extraction, browser automation, search, domain intelligence
kaos-office Extraction DOCX / PPTX / XLSX readers + writers to AST
kaos-tabular Extraction DuckDB-powered SQL analytics
kaos-source Data Government + financial data connectors (Federal Register, eCFR, EDGAR, GovInfo, PACER, GLEIF)
kaos-llm-client LLM Multi-provider LLM transport
kaos-llm-core LLM Typed LLM programming (Signatures, Programs, Optimizers)
kaos-nlp-core Primitives (Rust) High-performance NLP primitives
kaos-nlp-transformers ML Dense embeddings + retrieval
kaos-graph Primitives (Rust) Graph algorithms + RDF/SPARQL
kaos-ml-core Primitives (Rust) Classical ML on the document AST
kaos-citations Legal Legal citation extraction, resolution, verification
kaos-agents Agentic Agent runtime, memory, recipes
kaos-reference Sample Reference module for module authors

Packages depend on kaos-core; everything else is opt-in. Mix and match the ones you need.

Development

git clone https://github.com/273v/kaos-nlp-core
cd kaos-nlp-core
uv sync --group dev
uv run maturin develop --release

Install pre-commit hooks (recommended — they run the same checks as CI on every commit, scoped to staged files):

uvx pre-commit install
uvx pre-commit run --all-files     # one-time full sweep

Manual QA commands (the same set CI runs):

cargo fmt --check
cargo clippy --no-default-features --all-targets -- -D warnings
cargo test --no-default-features --lib
uv run ruff format --check python/kaos_nlp_core tests
uv run ruff check python/kaos_nlp_core tests
uv run ty check python/kaos_nlp_core tests
uv run pytest tests/

Build from source

uv build
uv pip install dist/*.whl

Contributing

Issues and pull requests are welcome. See CONTRIBUTING.md for setup, quality gates, pull request expectations, and engineering standards. By contributing you agree to follow the project conduct expectations and certify the Developer Certificate of Origin v1.1 — sign every commit with git commit -s. Please open an issue before starting on a non-trivial change so we can align on scope.

Security

For security issues, please do not file a public issue. Report privately via GitHub Private Vulnerability Reporting or email security@273ventures.com. See SECURITY.md for the full disclosure policy.

License

Apache License 2.0 — see LICENSE and NOTICE.

Copyright 2026 273 Ventures LLC. Built for kelvin.legal.

Release files for kaos-nlp-core 0.1.11

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kaos-nlp-core 0.1.11
File Size Uploaded
kaos_nlp_core-0.1.11.tar.gz 59.5 MB Details

Built distributions (wheels)

Table of built distributions (wheels) for kaos-nlp-core 0.1.11
File
kaos_nlp_core-0.1.11-cp313-abi3-win_arm64.whl CPython 3.13 abi3 Windows ARM64 Details
kaos_nlp_core-0.1.11-cp313-abi3-win_amd64.whl CPython 3.13 abi3 Windows x86-64 Details
kaos_nlp_core-0.1.11-cp313-abi3-manylinux_2_28_x86_64.whl CPython 3.13 abi3 Linux glibc 2.28+ x86-64 Details
kaos_nlp_core-0.1.11-cp313-abi3-manylinux_2_28_aarch64.whl CPython 3.13 abi3 Linux glibc 2.28+ ARM64 Details
kaos_nlp_core-0.1.11-cp313-abi3-macosx_11_0_arm64.whl CPython 3.13 abi3 macOS 11.0+ ARM64 Details

Total release size: 307.6 MB

Release files / kaos_nlp_core-0.1.11.tar.gz

Download URL kaos_nlp_core-0.1.11.tar.gz
Size 59.5 MB
Tags Source
SHA-256 checksum
How to use checksums
1e6d4abc97f51fe548f1419731c596f9077e7e6db0e855ebb55e7a380d5b38e1
BLAKE2b-256 checksum
How to use checksums
2cfe35b733806a33ca07833bf60d537481e4669025323738b45d6b0d34ffb2d5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 23, 2026.

Transparency log

Release files / kaos_nlp_core-0.1.11-cp313-abi3-win_arm64.whl

Download URL kaos_nlp_core-0.1.11-cp313-abi3-win_arm64.whl
Size 49.3 MB
Tags CPython 3.13 Windows ARM64 abi3
SHA-256 checksum
How to use checksums
6d2a8be193df6f37f99fb9d0c2859cfc99f1a2cc8afd9e6455fc17f361ac31f8
BLAKE2b-256 checksum
How to use checksums
8a9457e9f1caf2658de6ac068055bb87c312b0ac01415e5f87d0dfb00f8b0426
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 23, 2026.

Transparency log

Release files / kaos_nlp_core-0.1.11-cp313-abi3-win_amd64.whl

Download URL kaos_nlp_core-0.1.11-cp313-abi3-win_amd64.whl
Size 49.5 MB
Tags CPython 3.13 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
b120f524eb83a90999941fd368c66f4d6f8baacbf89b6a991051ca8de8bd77aa
BLAKE2b-256 checksum
How to use checksums
d76d57f3cfd2db2c867a80d8e598b6040575ebbc0c952213f420d1cb1bd10e32
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 23, 2026.

Transparency log

Release files / kaos_nlp_core-0.1.11-cp313-abi3-manylinux_2_28_x86_64.whl

Download URL kaos_nlp_core-0.1.11-cp313-abi3-manylinux_2_28_x86_64.whl
Size 50.2 MB
Tags CPython 3.13 Linux glibc 2.28+ x86-64 abi3
SHA-256 checksum
How to use checksums
4e488d377c065934ff575e726d79e42fe11446dcec2c761f6d7404e6105b6e38
BLAKE2b-256 checksum
How to use checksums
e03c4c773310d83a60f2a061bdf04d023dc1eb938f6060283dd44f08f634ef20
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 23, 2026.

Transparency log

Release files / kaos_nlp_core-0.1.11-cp313-abi3-manylinux_2_28_aarch64.whl

Download URL kaos_nlp_core-0.1.11-cp313-abi3-manylinux_2_28_aarch64.whl
Size 49.5 MB
Tags CPython 3.13 Linux glibc 2.28+ ARM64 abi3
SHA-256 checksum
How to use checksums
a30de10555eb1de5aea17f6b4414308a9e7974b98e79db3757f2cee7b379cdfc
BLAKE2b-256 checksum
How to use checksums
6007ed39413ff8b583451e7a1e1858a2dfda7178d1a502826e061f148f4c4d1a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 23, 2026.

Transparency log

Release files / kaos_nlp_core-0.1.11-cp313-abi3-macosx_11_0_arm64.whl

Download URL kaos_nlp_core-0.1.11-cp313-abi3-macosx_11_0_arm64.whl
Size 49.7 MB
Tags CPython 3.13 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
9ff48613814d85446fdf301801702418a5fbccfac584de6f02a4e8b3a3a8d90d
BLAKE2b-256 checksum
How to use checksums
b4801dcea4124bb16292fb0c11c71aad93cfba60e364d3771924cdbc0ff37419
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 23, 2026.

Transparency log
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page