Skip to main content

core

The vault: one SQLite file that holds everything you have collected, and the search over it

A vault is one SQLite file that holds everything you have collected, such as web pages, papers, talk transcripts, PDFs, notes and source files. All of it is searchable together. Vault() opens the file $VISHALAKSHI_VAULT names, else ~/.vishalakshi/vault.db. Vault(path) opens or creates any other file. Vault(':memory:') makes a vault that lasts only as long as the process.

A Vault is a litesearch Index. litesearch decides how text is stored and found. Each thing you add becomes a document. litesearch splits a document along its headings into a tree of sections, which it calls nodes. It cuts the text of each section into chunks. It stores every chunk twice. One copy is text, for the full-text keyword search of SQLite. The other copy is a vector, a list of numbers from an embedding model. The model puts texts with similar meanings near each other. A search runs both lookups and merges the two rankings with reciprocal rank fusion (RRF). RRF scores each chunk by its rank in each list. It does not use the raw scores, because a keyword score and a vector distance cannot be compared. The default embedding model is blink-multilingual-64M. It is small and fast and covers over 100 languages, including Devanagari. encoder= picks another model (see concepts). Vault() without encoder= opens a shelf with the model the shelf records. upgrade_encoders() embeds again every shelf that potion-multilingual-128M, the former default, wrote.

The vault adds these to litesearch:


source

kinds

def kinds(
    kind
)->fastcore.foundation.L:

A kind filter as a list: 'note', 'note,web' and ['note','web'] all work. A kind with a minus sign, as in '-stats', is left out.


source

tidy_bc

def tidy_bc(
    bc:str
)->str:

Clean a breadcrumb: drop the Pages n–m: placeholder sections litesearch inserts, and any repeated part.


source

mk_encoder

def mk_encoder(
    model:NoneType=None, # an `ENCODERS` alias, any model2vec id, or an object with `.encode`
    dims:int=256, # dims for the hashing fallback only
    offline:bool=False, # skip the download attempt entirely
    dtype:type=float16, # stored width; litesearch's default everywhere
)->fastcore.basics.AttrDict:

Load the encoder that model names, or the default encoder. Fall back to hashing when loading fails. Return AttrDict(model, dims, method, name, note).


source

HashEmbed

def HashEmbed(
    dims:int=256, dtype:type=float16
):

litesearch’s hash_embed wrapped as an encoder with .encode, for a vault that must not download a model.


source

Vault

def Vault(
    path:str=None, # vault file; None -> $VISHALAKSHI_VAULT, else ~/.vishalakshi/vault.db
    encoder:NoneType=None, # an `ENCODERS` alias, a model2vec id, an `mk_encoder()` result, or None for the shelf's recorded encoder, else DFLT_ENC
    store:str='store', # chunk store name
    offline:bool=None, # never attempt a model download; None -> $VISHALAKSHI_OFFLINE
    dims:int=256, # dims for the hashing fallback
    db:NoneType=None, # an open litesearch Database to share; shelves pass the vault's
):

Everything you have collected, in one SQLite file, searchable as one collection.

Vault.temp() opens a vault on a new file in a temporary folder, with the hashing encoder. A test uses it, so it never opens the vault you read from.


source

Vault.temp

def temp(
    **kw
)->__main__.Vault:

A vault on a new file in a temporary folder, offline=True with the hashing encoder unless kw says otherwise.


source

Vault.note

def note(
    text:str, # what you want to remember
    title:str=None, # defaults to the first line
    tags:list=None, # free-form tags, kept in the doc's meta
    key:str='', # upsert key; defaults to `slug(title)` when a title is given. Same key, same document
    meta:dict=None, # merged into the doc's meta beside `tags` and `key`
)->dict:

Write a note, or replace the note with the same key or title; notes are searched with everything else.


source

slug

def slug(
    s:str, n:int=60, # characters kept; None keeps the whole slug
    translit:bool=False, # Indic scripts go to IAST first, so `संधि` gives `samdhi`
    symbols:bool=False, # `+ # &` become `plus sharp and`, so `C++` gives `c-plus-plus`
)->str:

A stable key from a title: ASCII-folded, lower-cased, hyphenated and clipped to n characters. With translit or symbols, an empty slug becomes c-<sha1[:8]>.


source

Vault.add_dir

def add_dir(
    dir:str, types:str='.pdf,.md,.markdown,.txt,.rst,.ipynb,.xml,.tei,.htm,.html,.conllu', kind:str=None,
    route:bool=True, # send Sanskrit sources to the Sanskrit shelf, file by file
    stop:NoneType=None, progress:NoneType=None,
    files:NoneType=None, # file these paths instead of walking `dir`, such as a `tree_files` list
    **kw
)->fastcore.foundation.L:

Add every document under a directory, skipping dotfiles, tests and build output, and send Sanskrit files to the Sanskrit shelf; stop and progress as in add_files.


source

Vault.add_files

def add_files(
    files, # paths to ingest, all onto *this* shelf
    kind:str=None, # override the kind inferred from the extension
    n_workers:int=None, # parse workers; 0 is serial, None picks by parse-heavy file count
    embed_batch:int=2000, # chunks embedded and written per flush; 0 writes per document
    stop:NoneType=None, # asked before each batch and each file; True stops, and the result's `unread` holds the rest
    progress:NoneType=None, # told `progress(done, total, batch)` after each batch
    batch:int=50, # files per batch when `stop` or `progress` is given
    refresh:str=None, # 'mtime' -> skip a filed file, unread, unless its mtime is past its `added_at`
    **kw
)->fastcore.foundation.L: # forwarded to add_file; `profile=` names a litesearch Profile, such as one with `nb_kw`

Add a list of files to this shelf, embedding and writing their chunks in batches; the result carries cancelled and unread.


source

run_steps

def run_steps(
    items, # what to work through
    f, # does one step: takes a list of items, returns a list of results
    size:int=1, # items per step
    stop:NoneType=None, # asked before each step; True stops, leaving the rest unread
    progress:NoneType=None, # told `progress(done, total, step)` after each step; its errors are swallowed
)->fastcore.foundation.L:

Run f over items a step at a time; the results carry cancelled and unread, the items no step reached.


source

Vault.add_file

def add_file(
    path:str, title:str=None, kind:str=None,
    stop:NoneType=None, # asked before the read; True files nothing and reports the path in `unread`
    progress:NoneType=None, # told `progress(1, 1, [path])` once the file is filed
    **kw
)->dict:

Add one local file to the vault.


source

Vault.assets

def assets(
    name:str=None
)->pathlib.Path:

The folder beside the vault file where extracted assets, such as PDF images and downloaded papers, are kept.


source

content_hash

def content_hash(
    src
)->str:

sha1 of the text a document was built from; pages are joined by newlines.


source

Vault.add

def add(
    src, # text, `[(page_no, text)]`, a file path, or a directory
    title:str=None, # document title; defaults to the filename, or the first line of text
    source:str=None, # url or path; defaults to the title. The document id is a hash of the source and the title
    kind:str=None, # one of KINDS: the facet you filter and report on
    meta:dict=None, # provenance: the query that found it, when, which tier fetched it
    force:bool=False, # re-ingest a source already present
    refresh:bool=True, # re-ingest text whose content hash differs from the filed hash. A file refreshes only through `force` or `housekeep`
    **kw
)->dict: # forwarded to litesearch add_doc (chunker, summarize, with_heading)

Add text, pages, a file or a directory to the vault, adding a source again only when its content changed.

slug makes the key of a note from its title. translit=True reads Indic scripts as IAST, and symbols=True keeps + # & as words. With either flag, a title with no letters gets a hash key, not an empty one.

test_eq(slug('saṃdhi', translit=True), 'samdhi')
test_eq(slug('संधि', translit=True), 'samdhi')
test_eq(slug('సంధి', translit=True), 'samdhi')                        # Telugu
test_eq(slug('C++ & C#', symbols=True), 'c-plus-plus-and-c-sharp')
test_eq(slug('😀🎉', symbols=True), 'c-' + hashlib.sha1('😀🎉'.encode()).hexdigest()[:8])
test_eq(slug('a b c d e f', n=5), 'a-b-c')
test_eq(slug('x'*80, n=None), 'x'*80)
# the defaults are byte-identical to the old slug, so note keys stay the same
_old = lambda s: re.sub(r'[^a-z0-9]+', '-', unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode().lower()).strip('-')[:60].strip('-')
for s in ('Late chunking', 'saṃdhi and sandhi', 'C++ tips', 'संधि', '😀', ''): test_eq(slug(s), _old(s))

search returns chunks. Each hit has a short snippet, the node_id of its section and the doc_id of its document. sections ranks whole sections instead. context returns the text to give a language model. It returns whole sections. Each section has a breadcrumb, the path of headings down to it, such as Attention › Multi-head. Each section also has a node_id, which read turns back into the full section. The related list of context holds sections as leads. They are found by vector similarity to the results, not by matching the question. context also adds two sections from each other shelf (shelves=2). It adds code sections (code=) when kosha has indexed the repository. rerank=True reorders the hits with a cross-encoder model. It needs the rerank extra (pip install 'vishalakshi[rerank]').

These methods, and read and document, take pii=. The default is off. See pii. Every row also has age, the seconds since its document was filed, and stale. Stale rows sort last.


source

Vault.read

def read(
    node_id:str, max_chars:int=6000, store:str=None, # the shelf the section is on; None -> this one
    *, pii:str='off', pii_ner:bool=False, stale:bool=False
)->dict:

Rebuild one whole section from its chunks; store names the shelf when the node_id came from another one.


source

Vault.related

def related(
    node_id:str, limit:int=8, clip:int=300
)->fastcore.foundation.L:

The sections nearest an existing one in vector space, found from its stored vectors without embedding anything again.


source

Vault.context

def context(
    q:str, # the question
    sections:int=6, # operative sections returned
    related:int=8, # related sections reached by vector
    kind:str=None, # restrict to one or more KINDS ('note' or 'note,web')
    max_read:int=6000, # chars of assembled text per section
    code:int=None, # code sections to append; None -> 4 if kosha has indexed the repo
    shelves:int=2, # sections to append from each *other* shelf; 0 -> none
    dir:str=None, # repo for the code legs; None -> the cwd repo
    rerank:bool=False, # reorder the chunk hits before they are rolled up into sections
    include_noisy:bool=False, # include documents explicitly marked as noisy
    where:str=None, # extra chunk-store `WHERE`, e.g. `doc_id='…'` for one document
    *, pii:str='off', pii_ner:bool=False, stale:bool=False, **kw
)->fastcore.basics.AttrDict: # forwarded to litesearch context

The retrieval to hand a language model: whole sections with breadcrumbs and node_ids, related leads, and sections from other shelves and from code.


source

Vault.sections

def sections(
    q:str, limit:int=5, kind:str=None, per:int=3, rerank:bool=False, include_noisy:bool=False, where:str=None, *,
    pii:str='off', pii_ner:bool=False, stale:bool=False, **kw
)->list:

Search like search but return whole sections, best first, leaving noisy documents out unless asked.


source

Vault.search

def search(
    q:str, # query
    limit:int=10, # hits to return
    kind:str=None, # restrict to one or more KINDS ('note' or 'note,web')
    chars:int=300, # chars of each hit kept as `snippet`
    rerank:bool=False, # reorder the candidates with a cross-encoder (see below)
    include_noisy:bool=False, # include documents explicitly marked as noisy
    where:str=None, # extra chunk-store `WHERE`, ANDed with the kind and noisy filter
    *, pii:str='off', pii_ner:bool=False, stale:bool=False, **kw
)->fastcore.foundation.L: # forwarded to litesearch doc_search

Search this shelf’s chunks by keywords and meaning together; each hit carries a snippet, its breadcrumb and node_id, and noisy documents are left out.


source

gate

def gate(
    f
):

Make a retrieval method take pii= and pii_ner= and apply that policy to what it returns.

A node_id names a section. A doc_id names a document. doc(ref) finds the row of a document by its id, its exact source, or part of its title. document(ref) rebuilds a whole document in reading order and puts its headings back. A model reads this text to extract fields. Given a path that the vault has never seen, document reads the file from disk. read(node_id) rebuilds one section. toc returns the heading tree of the shelf or of one document.

The meta of a document holds where it came from and anything set with set_meta, such as its doctype. Adding a changed document again rewrites its meta. A lasting judgement about a document goes in the doc_marks table instead (see Marks below).


source

Vault.set_meta

def set_meta(
    doc_id:str, **kv
)->dict:

Merge key/values into one document’s meta, and return the merged dict.


source

Vault.document

def document(
    ref:str, # doc_id, source (url or path), or a title substring
    max_chars:int=40000, # cap on the text returned
    headings:bool=True, # put the node titles back as markdown headings
    disk:bool=True, # fall back to a path on disk the vault has never seen
    *, pii:str='off', pii_ner:bool=False, stale:bool=False
)->fastcore.basics.AttrDict:

Rebuild one whole document in reading order with its headings, or read a file the vault has never seen from disk.


source

Vault.doc

def doc(
    ref:str
)->dict:

Find one document’s row by doc_id, exact source or part of its title, with meta decoded.

Shelves

One vault file can hold several shelves. A shelf is a separate collection with its own chunks, section tree and vector index. A large corpus on one shelf, such as a thousand papers, does not crowd a small shelf out of the rankings. shelf(name) opens a shelf and creates it the first time. A shelf keeps the embedding model it was first written with. Reopening it with a different model raises an error, because vectors from two models cannot be compared. shelves() lists the shelves with their models and document counts. drop_shelf deletes a shelf. The main shelf is called store. SHELVES names the shelves that the vault itself uses: store, papers, sanskrit, code and data. Acquisition sends some kinds to their own shelf through KIND_SHELF, below.


source

Vault.shelves

def shelves()->fastcore.foundation.L:

List the shelves in this vault file with each one’s encoder, vector width and document count; a store with no docs table is left out.


source

Vault.shelf_names

def shelf_names(
    docs_only:bool=True, # False -> every store in `store_meta`, a store of names included
)->fastcore.foundation.L:

The names of the shelves in this vault file, in the order they were made. It counts nothing, so it costs one query.


source

Vault.drop_shelf

def drop_shelf(
    name:str, force:bool=False
)->dict:

Delete a shelf and its derived data. Refuse the main shelf unless force=True.


source

Vault.upgrade_encoders

def upgrade_encoders()->dict:

Re-encode with DFLT_ENC every shelf a former default (OLD_ENCS) wrote, and return the number of chunks re-encoded on each.


source

Vault.reencode

def reencode(
    encoder:NoneType=None
)->int:

Embed this shelf’s chunks and the names in its entity graph again with encoder (an ENCODERS alias or a model2vec id; default DFLT_ENC), record it for the shelf, and return the number of chunks.


source

Vault.shelf

def shelf(
    name:str, encoder:str=None,
    create:bool=True, # False -> None for a shelf that does not exist yet, and no table is made
    **kw
)->__main__.Vault:

Open another shelf in this vault file, with the encoder litesearch recorded for it.

Marks

A mark is a judgement about one document. The doc_marks table keeps it when the document is added again. There are three marks. noisy is for junk such as a cookie banner or a site footer. search, sections, context and ask leave noisy documents out. pii_override holds the privacy marks described on pii. stale says that a document no longer matches its source. Search still returns a stale document, flagged and sorted last. The vault clears the mark when the document is added again with new content. mark sets any of them. mark_noisy, mark_stale and the pii methods are the named ways to set a mark. marks() lists every mark on the shelf. marks(ref) returns the mark on one document.


source

Vault.marks

def marks(
    ref:NoneType=None
)->dict | fastcore.foundation.L:

Every judgement on this shelf, or the one on ref (an empty dict when there is none).


source

Vault.mark_stale

def mark_stale(
    ref, stale:bool=True, reason:str='', superseded:str=None
)->dict:

Say a document no longer reflects its source; retrieval still returns it, sorted last and flagged.


source

Vault.mark

def mark(
    ref, **kv
)->dict:

Record a judgement about one document in doc_marks; a key that is not a mark raises an error.

from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
    v = Vault(Path(d)/'test.db', offline=True)
    assert 'vault_stores' not in v.db.t                    # litesearch's store_meta is the one registry
    test_eq(v.db._store_meta('store')['encoder'], 'hash-256')
    assert v.shelves()[0]['store'] == 'store'
with TemporaryDirectory() as d:
    p = Path(d)/'test.db'
    a = Vault(p, offline=True)
    a.add('A report about polonium.', title='report')
    b = Vault(p, offline=True)
    assert b.doc('report')
    test_eq(len(b.shelves()), 1)
    assert 'feedback' in b.db.t
    assert 'rankers' in b.db.t
# A vault written before litesearch stamped encoders carries only `vault_stores` rows.
# The vault copies each row into `store_meta` once, on first use. `shelf()` then reopens with the encoder that wrote it.
# Nothing writes `vault_stores` rows again.
with TemporaryDirectory() as d:
    p = Path(d)/'old.db'
    a = Vault(p, offline=True); a.add('A report about polonium.', title='report')
    a.shelf('papers', encoder='hash', dims=64).add('Paper about thorium.', title='paper')
    a.db.q('update store_meta set encoder=?', [''])
    a.db.t.vault_stores.create(store=str, encoder=str, dims=int, method=str, added_at=float, pk='store')
    a.db.t.vault_stores.insert_all([dict(store='store', encoder='hash', dims=256, method='hash', added_at=time.time()),
                                    dict(store='papers', encoder='hash', dims=64, method='hash', added_at=time.time())])
    b = Vault(p, offline=True)
    test_eq(b.db._store_meta('store')['encoder'], 'hash-256')
    sh = b.shelf('papers')
    test_eq((sh.enc.method, sh.enc.dims, b.db._store_meta('papers')['encoder']), ('hash', 64, 'hash-64'))
    test_eq([s['dims'] for s in b.shelves()], [256, 64])
    test_fail(lambda: Vault(p, offline=True, store='papers'), contains='Two encoders')
with TemporaryDirectory() as d:
    p = Path(d)/'test.db'

    a = Vault(p, offline=True)
    a.add('A report about polonium.', title='report')
    before = list(a.marks())

    b = Vault(p, offline=True)
    assert list(b.marks()) == before
with TemporaryDirectory() as d:
    v = Vault(Path(d)/'test.db', offline=True)
    v.add('A report about polonium.', title='report')

    assert 'doc_marks' in v.db.t
    assert v.marks() == []

    v.mark('report', noisy=True)
    assert v.marks('report')['noisy'] == 1
    assert not v.search('polonium')
    assert v.search('polonium', include_noisy=True)

A shelf opened from a vault shares the embedding model of the vault in memory. Opening many shelves loads the model once. offline=True and $VISHALAKSHI_OFFLINE also carry over to a new shelf. An offline vault never downloads a model.

# A shelf is a partition. It reuses the live encoder of the vault and does not load a second encoder.
from tempfile import mkdtemp

v = Vault(Path(mkdtemp())/'v.db')
s = v.shelf('project')
assert s.enc.model is v.enc.model      # the same object: a shelf per project used to cost a load each
assert s.name == 'project'

# `offline=True` has to survive into a brand-new shelf, or it does not mean "never download":
# a shelf with no registry row used to fall through to the default and load a real model
o = Vault(Path(mkdtemp())/'o.db', offline=True)
assert o.enc.method == 'hash' and o.shelf('fresh').enc.method == 'hash'

# An explicit encoder still wins, and a shelf already on disk is reopened with whatever wrote it.
r = v.shelf('papers', encoder='code')
assert r.enc.name == ENCODERS['code']
r.note('rank fusion needs only each leg ordering', title='RRF')
assert Vault(v.path).shelf('papers').enc.name == ENCODERS['code']
assert Vault(v.path).shelf('papers').search('rank fusion'), 'the reopened shelf lost its note'
print('shelf encoders:', {x['store']: x['encoder'] for x in v.shelves()})
shelf encoders: {'store': 'minishlab/blink-multilingual-64M', 'project': 'minishlab/blink-multilingual-64M', 'papers': 'minishlab/potion-code-16M-v2'}

Fetching 7 files:   0%|          | 0/7 [00:00<?, ?it/s]Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.

Fetching 7 files:  43%|####2     | 3/7 [00:00<00:00, 29.21it/s]
Fetching 7 files:  86%|########5 | 6/7 [00:00<00:00, 11.44it/s]
Fetching 7 files: 100%|##########| 7/7 [00:02<00:00,  2.93it/s]

KIND_SHELF sends documents of some kinds to their own shelf when they are added to the main shelf. arXiv papers go to papers. Sanskrit files go to sanskrit when add_dir finds them and ganapati is installed. search and sections look at one shelf only. context adds results from the other shelves (shelves=). elsewhere(q) searches every other shelf directly. Use it when the answer can be on another shelf.


source

Vault.elsewhere

def elsewhere(
    q:str, # the question
    limit:int=2, # sections taken from each other shelf
    shelves:bool=True, # True -> every other shelf; a list picks some
    max_read:int=2000, # chars kept per section
    errors:str='raise', # 'skip' -> a shelf that fails is logged and left out
)->fastcore.foundation.L:

Search the vault’s other shelves and return their best sections in the same shape as this shelf’s, each with its score, doc_title and source.


source

Vault.route

def route(
    kind:str
)->__main__.Vault:

The shelf a kind belongs on: self, unless KIND_SHELF sends it elsewhere.


source

sanskrit_facets

def sanskrit_facets()->bool:

Re-register Sanskrit profiles with lemmas and Monier-Williams glosses in metadata.


source

is_sanskrit_file

def is_sanskrit_file(
    path
)->bool:

Whether a Sanskrit reader is registered for this file.

with TemporaryDirectory() as d:
    v = Vault(Path(d)/'test.db', offline=True)
    v.add('A report about polonium.', title='report')

    sql = []
    v.db.conn.set_exec_trace(lambda cursor, statement, bindings:sql.append(statement) or True)

    v.search('polonium')
    v.sections('polonium')
    v.context('polonium', code=0, shelves=0)

    v.db.conn.set_exec_trace(None)

    ddl = [
        q for q in sql
        if q.lstrip().upper().startswith(('CREATE ', 'ALTER ', 'DROP '))
    ]
    assert ddl == [], ddl
# a store of names (a graph's `entities` table) in store_meta is not a shelf: no query touches its missing docs table
with TemporaryDirectory() as d:
    v = Vault(Path(d)/'test.db', offline=True)
    v.shelf('papers').add('A paper about polonium.', title='paper')
    v.db.q('create table entities (id text primary key, content text, embedding blob, metadata text, uploaded_at text, kind text, canon text, freq int)')
    v.db.q("insert into store_meta(name, encoder) values ('entities', '')")
    sql, ex = [], v.db.execute
    v.db.execute = lambda s, *a, **k: sql.append(s) or ex(s, *a, **k)
    test_eq(v.shelves().attrgot('store'), ['store', 'papers'])
    test_eq(v.elsewhere('polonium', shelves=['papers', 'entities']).attrgot('store').unique(), ['papers'])
    test_eq(len(v.elsewhere('polonium')), 1)
    del v.db.execute
    test_eq([s for s in sql if 'entities_docs' in s], [])

    v.db.q("delete from store_meta where name='entities'")
    test_fail(lambda: v.shelf('entities'), contains='no doc_id')
    test_eq(v.db.q("select name from store_meta where name='entities'"), [])

    old = os.environ.get('VISHALAKSHI_VAULT')
    os.environ['VISHALAKSHI_VAULT'] = str(Path(d)/'env.db')
    try: test_eq(Vault(offline=True).path, str(Path(d)/'env.db'))
    finally: os.environ.pop('VISHALAKSHI_VAULT') if old is None else os.environ.update(VISHALAKSHI_VAULT=old)

shelf_names lists the shelves with no counts, for a caller that only needs the names. shelf(name, create=False) opens a shelf only when it exists.

with TemporaryDirectory() as d:
    v = Vault(Path(d)/'test.db', offline=True)
    v.shelf('papers').add('A paper.', title='paper'); v.shelf('data')
    v.db.q('create table entities (id text primary key, content text)')
    v.db.q("insert into store_meta(name, encoder) values ('entities', '')")
    test_eq(v.shelf_names(), ['store', 'papers', 'data'])            # the order of store_meta; no `entities`
    test_eq(v.shelf_names(docs_only=False), ['store', 'papers', 'data', 'entities'])
    before = v._tables()
    test_is(v.shelf('notyet', create=False), None)
    test_eq((v._tables(), 'notyet' in v.shelf_names(docs_only=False)), (before, False))   # nothing made
    test_eq(v.shelf('papers', create=False).t.docs.count, 1)

Each hit of elsewhere has the score of its section and the doc_title and source of its document, so a caller can merge the shelves by score. With errors='skip', a shelf that fails is logged and the other shelves still answer.

with TemporaryDirectory() as d:
    v = Vault(Path(d)/'test.db', offline=True)
    v.shelf('papers').add('# Polonium\n\nA paper about polonium and radium.', title='paper', source='https://x.test/p')
    v.shelf('data').add('# Polonium\n\nPolonium records, polonium counts.', title='records', source='data:po')
    hs = v.elsewhere('polonium')
    test_eq(set(hs.attrgot('store')), {'papers', 'data'})
    test_eq(hs.filter(lambda h: h.store == 'papers')[0].doc_title, 'paper')
    test_eq(hs.filter(lambda h: h.store == 'papers')[0].source, 'https://x.test/p')
    assert all(isinstance(h.score, float) for h in hs)
    test_eq(len(sorted(hs, key=lambda h: -h.score)), 2)              # one ranking across the shelves
    _sec = Vault.sections
    def _broken(self, *a, **k):
        if self.name == 'data': raise RuntimeError('broken shelf')
        return _sec(self, *a, **k)
    Vault.sections = _broken
    try:
        test_fail(lambda: v.elsewhere('polonium'), contains='broken shelf')   # the default raises
        test_eq(v.elsewhere('polonium', errors='skip').attrgot('store'), ['papers'])
    finally: Vault.sections = _sec
# `Vault.temp`, from the top of the notebook
import tempfile
_t = Vault.temp()
assert Path(_t.path).resolve().is_relative_to(Path(tempfile.gettempdir()).resolve())
test_eq((type(_t.enc.model), _t.name), (HashEmbed, 'store'))
test_ne(Vault.temp().path, _t.path)                    # a new file each time
test_eq(Vault.temp(store='papers').name, 'papers')

source

Vault.stats

def stats()->dict:

Row counts across the vault, by kind.


source

Vault.forget

def forget(
    doc_id:str
):

Remove a document, its sections, chunks and findings, and rebuild the vector index.


source

Vault.mark_noisy

def mark_noisy(
    ref, noisy:bool=True, reason:str=''
)->dict:

Mark a document as noise, which search, sections, context and ask then leave out.


source

Vault.sources

def sources(
    kind:str=None, include_noisy:bool=True
)->fastcore.foundation.L:

List this shelf’s documents, newest first, with their meta, age and noisy and stale marks; noisy ones are included unless include_noisy=False.


source

Vault.show_topics

def show_topics(
    limit:int=20, docs:int=8, **kw
):

Print topic_tree as an indented listing.


source

fmt_topics

def fmt_topics(
    tree, width:int=44
)->str:

Format a topic_tree as an indented listing in plain ASCII.


source

Vault.topic_tree

def topic_tree(
    limit:int=20, # topics returned, largest first
    docs:int=8, # documents listed under each topic
    min_chunks:int=2, # skip a topic carried by fewer chunks than this
)->fastcore.foundation.L:

List the topics connect found, largest first, with the documents each one runs through.


source

Vault.map

def map(
    min_count:int=2, force:bool=False, **kw
)->fastcore.basics.AttrDict:

Group the shelf’s chunks into labelled topics, reading the topics connect saved, when there are any, instead of clustering again.

put files a record whose meta changes more often than its text, such as a concept with its review state. It runs add. When the text is unchanged, nothing is embedded again and the new meta is merged in with set_meta.


source

Vault.put

def put(
    text:str, # the text to embed; unchanged text is not embedded again
    source:str, # the upsert key
    kind:str, # one of KINDS, or your own record kind
    title:str=None, # defaults to the first line of `text`
    meta:dict=None, # merged into the meta of the document, also when the text is unchanged
    **kw
)->dict: # forwarded to `add`

Add text under source, or merge meta into the document already there when its text is unchanged. Return the dict from add.

by_source is the exact lookup that goes with put. doc(ref) falls back to a match on the title, so it can return another record; by_source never does.


source

Vault.by_source

def by_source(
    src:str, # the source the document was filed under
    shelf:str=None, # the shelf to look on; None -> this one
)->dict | None:

The newest document filed under exactly src, with meta decoded, or None. There is no fallback to the title.

A minus sign leaves a kind out. kind='-stats,-marker' searches every kind but those two, and kind='note,-marker' mixes the two forms.

v = Vault(':memory:', offline=True)
for t, k in (('polonium in a note', 'note'), ('polonium stats row', 'stats'), ('polonium marker', 'marker'), ('polonium page', 'web')):
    v.add(t, source=f's:{k}', kind=k)
_ks = lambda kind: {v.t.docs.get(h.doc_id)['kind'] for h in v.search('polonium', kind=kind)}
test_eq(_ks('-stats,-marker'), {'note', 'web'})
test_eq(_ks(['-stats']), {'note', 'web', 'marker'})
test_eq(_ks('note,web,-web'), {'note'})
test_eq(_ks(''), {'note', 'web', 'stats', 'marker'})
test_eq(len(v.sources(kind='-note')), 3)

source


source

Vault.connect

def connect(
    graph:bool=True, # build the typed entity graph over new chunks (vruksha)
    topics:bool=True, # (re)write the labelled topic nodes
    chat:NoneType=None, # a urai Chat; None builds one with `new_chat()`
    seed:bool=False, # regex-seed structured citations (a legal corpus booster)
)->dict:

Build the entity graph, which needs a model, and the topic nodes that graph_search, map and topic_tree read.


source

Vault.build_graph

def build_graph(
    chat:NoneType=None, seed:bool=False, **kw
)->dict:

Have a model extract entities and relations from chunks not yet processed, with vruksha, into the entity graph of the shelf. A hosted chat runs only when every document on the shelf is Open.

with TemporaryDirectory() as d:
    v = Vault(Path(d)/'test.db', offline=True)
    v.add('Main report about polonium.', title='main')

    papers = v.shelf('papers')
    papers.add('Paper about thorium.', title='paper')

    sql = []
    v.db.conn.set_exec_trace(
        lambda cursor, statement, bindings:
            sql.append(statement) or True
    )

    v.context('thorium', code=0, shelves=2)

    v.db.conn.set_exec_trace(None)

    ddl = [
        q for q in sql
        if q.lstrip().upper().startswith(('CREATE ', 'ALTER ', 'DROP '))
    ]
    assert ddl == [], ddl
from tempfile import TemporaryDirectory

class _Chat:
    "A scripted extraction, so the graph is the same every run and no model is asked for."
    runtime = 'litert'   # it stands in for the local default; a hosted chat builds only over an all-Open shelf
    def oneshot(self, u, **k):
        return ('{"summary":"a report","entities":[{"name":"polonium","type":"substance"}],'
                '"relations":[{"src":"polonium","rel":"appears_in","dst":"report"}]}')

with TemporaryDirectory() as d:
    v = Vault(Path(d)/'test.db', offline=True)
    v.add("A scheduled report about polonium.", title="report")
    result = v.connect(chat=_Chat())

    assert result['entities'] > 0
    assert v.search('polonium')
    result

Try it

The cells below use the default embedding model. With offline=True the vault uses hash_embed from litesearch. hash_embed needs no download and matches spelling, not meaning. stats()['encoder'] says which model is in use.

v = Vault(':memory:')
v.note('Late chunking beats naive chunking because context survives the split.', tags=['retrieval'])
v.add('# Attention\n\nScaled dot-product attention weights values by query-key similarity.\n\n'
      '## Multi-head\n\nHeads attend to different subspaces in parallel.', 'Attention', kind='note')
v.stats()
{'docs': 2,
 'nodes': 5,
 'chunks': 3,
 'encoder': 'model2vec',
 'entities': 0,
 'path': ':memory:',
 'by_kind': {'note': 2}}
test_eq(v.stats()['docs'], 2)
test_eq(v.stats()['encoder'], 'model2vec')
assert v.search('chunking')[0]['snippet']
# a hit is a handle plus enough text to recognise it, not the chunk itself; the scoring
# internals the two legs disagree about (`rank`, `_dist`, `_rrf_score`, `rowid`) stay inside
_h = v.search('chunking')[0]
test_eq(sorted(_h), ['age', 'breadcrumb', 'doc_id', 'node_id', 'page', 'score', 'snippet', 'stale'])
assert len(v.search('chunking', chars=20)[0]['snippet']) <= 20
assert v.read(_h['node_id'])['text']          # the handle opens what the snippet came from
test_eq([d['kind'] for d in v.sources()], ['note', 'note'])
test_eq(len(v.sources(kind='web')), 0)
test_eq(len(v.search('chunking', kind='web')), 0)
d = v.doc('Attention')                          # by title substring
test_eq(v.doc(d['id'])['title'], 'Attention')   # by doc_id
test_eq(v.doc(d['source'])['title'], 'Attention')  # by source
test_eq(v.doc('nothing in here'), None)

whole = v.document('Attention')
test_eq((whole.origin, whole.nodes), ('vault', 3))   # the root, the heading, the subheading
# every section, in document order, with the headings that say what each one is
assert whole.text.index('Scaled dot-product') < whole.text.index('## Multi-head') < whole.text.index('subspaces')
test_eq(v.document('Attention', headings=False).text.find('## Multi-head'), -1)
test_eq(v.document('Attention', max_chars=20).text, whole.text[:20])
test_eq(v.document('Attention', max_chars=20).truncated, True)
# a `Pages n–m:` node title is build_tree's placeholder, not a heading the document wrote
v.add('Prose with no headings at all, long enough to chunk and to be stored in the vault.', 'plain')
assert '# Pages' not in v.document('plain').text and 'Prose with no' in v.document('plain').text

test_eq(v.set_meta(d['id'], doctype='paper')['doctype'], 'paper')
test_eq(v.doc(d['id'])['meta']['doctype'], 'paper')                 # survives the round trip
test_eq(v.set_meta(d['id'], reviewed=True)['doctype'], 'paper')     # merged, not replaced
test_fail(lambda: v.document('no such document'), contains='no document in the vault')

By default add_files reads each file again and files it again when its text changed. refresh='mtime' skips a filed file without reading it, unless its mtime is past the time it was filed. That saves the parse of each unchanged notebook or PDF. add_dir and add_tree pass it on.

test_eq(tidy_bc('Attention › Pages 1–1: Scaled dot-product › Multi-head'), 'Attention › Multi-head')
test_eq(tidy_bc(None), '')
# a window with a blank first line leaves the placeholder bare, and it is still a placeholder
test_eq(tidy_bc('Doc › Pages 1–1: › Body'), 'Doc › Body')
from functools import partial
from vishalakshi.ask import CHAT_CACHE, CachedChat, use_chat
# the extraction replays from recordings, so the tests run without the model; VISHALAKSHI_RECORD_CHAT=1 records a miss
with use_chat(partial(CachedChat, path=CHAT_CACHE)): r = v.connect()
assert r['entities'] > 0
# `entities` is what each batch wrote and `merged` what resolution folded away again, so the rows
# left are the difference: one batch covers a corpus this size, and stats counts no topic node
test_eq(v.stats()['entities'], r['entities'] - r['merged'])