use_chat
def use_chat(
f
):Build chats with f instead of Urai’s Chat inside the block. The swap applies to the whole process. A threaded host passes mk_chat= to ask instead.
ask answers a question from the vault with a language model. Urai is the chat library that vishalakshi calls. Rishi provides the model backends, and Urai registers them the first time a chat is built.
A model id names the model, and the id selects the backend. The local backends are LiteRT, MLX, llama.cpp and Ollama. A hosted API id looks like claude/sonnet or gpt-4.1-nano.
With no id, the vault uses gemma-4-E2B. This small model runs on this machine through LiteRT and needs no API key. Set $VISHALAKSHI_MODEL to use a different default.
LiteRT is asked for the GPU backend. When no GPU is available, LiteRT uses its default backend and a warning appears. Set $VISHALAKSHI_GPU=0 to keep LiteRT on the CPU.
chat_kw= passes any other chat constructor argument, such as a temperature.
Build chats with f instead of Urai’s Chat inside the block. The swap applies to the whole process. A threaded host passes mk_chat= to ask instead.
Return True when new_chat builds Urai’s own Chat, which is the case when no replacement factory is set or when the factory is Urai’s Chat.
Build a new chat for model. Every model call in the vault builds a fresh chat here.
Import Urai with Rishi’s backends registered. Raise ImportError when Rishi is missing.
Return kw with LiteRT’s GPU backend added, when model runs on LiteRT and kw has no backend or engine.
Return True when runtime rt runs on this machine. Ollama counts as local only when $OLLAMA_HOST points at this machine.
Return the sections that answer cites as [n], in order of first citation.
Split a reply into (answer, thinking). thinking is the model’s reasoning block.
Build the prompt text: the numbered sections, the related sections by title, then the question.
ask(question) calls context to retrieve the sections of the vault that best match the question. mk_prompt numbers the sections [1], [2] and so on. It also lists the related sections by title only. A related section is a neighbour of a retrieved section in vector similarity. The question does not retrieve it.
The system prompt VAULT_SP tells the model to answer only from the sections and to cite the number of each section it used. ask returns the answer and cited. cited lists the sections that the answer cites. Each entry has a node_id that read opens.
The context budget is sections=4 and max_chars=1500. max_chars is the number of characters kept from each section.
To ask about particular documents, pass ref= with one or more documents, or use ask_doc from extract. doc_context then puts the named documents first, whole, as sections [1] to [n]. The named documents share doc_chars characters. doc_context adds related sections from the rest of the vault after them.
def doc_context(
ref, # a doc_id, source, title or path, or a list of them
question:str, # the question the other sections are retrieved for
related:int=3, # sections to add from the rest of the vault
max_chars:int=12000, # characters of the named documents, shared between them
*, pii:str='off', pii_ner:bool=False, stale:bool=False
)->fastcore.basics.AttrDict:Build a context with the documents ref names as whole sections [1] to [n], followed by related sections from the rest of the vault.
Return the prompt line that names which numbered sections are the documents asked about.
mk_chat= gives ask a chat that the host already runs, such as a model that an app has loaded. ask then builds no new chat. The privacy check reads the runtime of the chat that ask uses. A hosted chat passed by mistake is treated as hosted.
A section is private in three cases. The detector finds personal identifiers in it. Its document is marked as personal. Its document has a level above Open for another reason, such as the document type or the shelf floor.
Before ask sends anything, it drops each related section that holds personal information. When ref= names documents, it also drops each retrieved section that holds personal information. pii= then sets what happens to the remaining sections:
pii= |
what happens when the sections are private |
|---|---|
local |
A model on this machine answers. The model is pii_model, else $VISHALAKSHI_PII_MODEL, else the default model. It runs under PII_SP, a system prompt that forbids repeating any personal detail. If that chat is not local, ask sends nothing and the answer says so. |
redact |
ask masks the recognised identifiers in the text, heading line, title and source of each section. The model named by model= then answers, hosted or not. |
refuse |
No model is asked. The answer says what was held back. |
The default policy is local when a local runtime is installed, and redact when none is. pii='off' is not valid for ask. It gives a warning and applies the default. The policy field of the result names the policy that ran.
Under every policy, a hosted model receives a Local only section as the bare line [n] [withheld: local only]. The line has no heading, title or source. send_check below explains the rule.
Under redact, ask does not mask a name that has no title before it, such as Dr. Name detection is on by default (pii_ner=True).
ask scans each answer over private sections again before it returns the answer. It masks any identifier that the model repeated, and leaked lists the kinds of identifier.
The result also has the prompt and the context that the model read. Under local they hold the private sections whole. A host that gives the result to a hosted model must pass on only answer and cited.
send_check runs before anything goes to a model. For each document, page or piece of text, it decides one of three outcomes: whole, masked, or withheld. Withheld means not sent.
send_check returns the decisions in rows, and the subsets send, masked and withheld. It also returns a why sentence for a person to read before the send. An example is gpt-4.1-nano, hosted. 1 personal document masked, 1 document open, 1 local-only document withheld.
send_rule holds the rule:
model_local decides which models are local. LiteRT, MLX and llama.cpp are always local. Ollama is local only when $OLLAMA_HOST points at this machine. Every other runtime is hosted. A chat that names no runtime is hosted.allow=True does not change this.redact, a Personal item goes to a hosted model masked. Under local and refuse, it is withheld.off, and when allow=True.allow=True allows once. It sends Personal items whole for that one call, as policy='off' does.ask, explain, categorize, extract, read_doc, reparse and proofread all decide through this rule. The decision covers everything that goes with the text. A document’s title, headings and source path are masked or withheld with it. A page image is read with the document’s title in its prompt. send_check judges the title with the page.
build_graph sends every chunk to its chat with nothing to mask. connect calls build_graph. A hosted chat builds the graph only when every document on the shelf is Open. Otherwise build_graph sends nothing and the result says why.
Masking replaces only what the detector recognises. A document marked Personal by hand, with nothing recognisable in it, goes to a hosted model under redact exactly as stored.
The send_log table of the vault records each send to a hosted model. A row has the time, the document and pages, the model and runtime, the policy, and the kinds of personal information when known. sends(ref) reads the log, newest first. The log has no row for a send to a local model or for a withheld item.
Read the send log, newest first: what went to a hosted model, when and to which model, for one document when ref names it.
def send_check(
refs:NoneType=None, # documents: a doc_id, source or title, or a list of them
pages:NoneType=None, # pages: `(ref, page)` pairs or `{doc_id, page}` dicts
text:NoneType=None, # text with no document behind it: a string or a list of them
model:NoneType=None, # an id or a built chat; None -> $VISHALAKSHI_MODEL
policy:str='redact', # off|local|redact|refuse: what a hosted model gets of a Personal item
allow:bool=False, # allow once: Personal items go whole; Local only still never does
image:bool=False, # the items go as page images, which cannot be masked
level:str=None, # a level the items start at, above what they would have
ner:bool=True, # look for names in `text` too
)->fastcore.basics.AttrDict:Decide, before a send, which documents, pages or texts go to model whole, masked or withheld, with a sentence saying so.
Return the sentence that says where a send goes and how many items go whole, masked or withheld.
Return whole, masked or withheld for one item, from its level, local, policy, allow and image.
Return True when model, an id or a built chat, runs on this machine. A chat with no runtime, or an id that Urai cannot place, counts as hosted.
def explain(
node_id:str, model:str=None, chat_kw:dict=None, max_chars:int=6000,
sp:str="You answer questions from a personal research vault.\n\nYou are given numbered sections retrieved from the user's own corpus: papers, web pages,\ntranscripts, files and their own notes. Answer only from those sections.\n\nRules:\n- Cite every claim with the bracketed number of the section it came from, like [2]. A sentence\n drawing on two sections cites both.\n- If the sections do not answer the question, say exactly what is missing rather than filling the\n gap from memory. A vault that admits a hole is useful; one that guesses is not.\n- Sections marked RELATED were reached by association, not by matching the question. Use them for\n context or to point somewhere worth reading next, and say so when you do.\n- Prefer the user's own notes when they conflict with a source, and flag the disagreement.",
mk_chat:NoneType=None,
pii:str=None, # local|redact|refuse; None -> local when a local runtime exists, else redact
pii_model:str=None, pii_ner:bool=True
)->fastcore.basics.AttrDict:Have a model explain one section and say what related sections in the vault add to it or contradict.
def ask(
question:str, # what you want to know
ref:NoneType=None, # documents to ask about: a doc_id, source, title or path, or a list of them
schema:NoneType=None, # answer as this shape instead of prose: a SCHEMAS key, dataclass, or 'field:type' spec
model:str=None, # an id, a path, `mlx/…`; None -> $VISHALAKSHI_MODEL
chat_kw:dict=None, # anything else Urai's `Chat` takes: temp, runtime, think, …
sections:int=4, # operative sections retrieved
related:int=6, # associative sections offered as leads
kind:str=None, # restrict retrieval to one or more KINDS
code:int=None, # code sections to add; None -> 4 if kosha has indexed the repo
dir:str=None, # repo for the code legs; None -> the cwd repo
max_chars:int=1500, # chars of each retrieved section shown to the model
doc_chars:int=8000, # chars of `ref`'s documents shown to the model, shared between them
sp:str="You answer questions from a personal research vault.\n\nYou are given numbered sections retrieved from the user's own corpus: papers, web pages,\ntranscripts, files and their own notes. Answer only from those sections.\n\nRules:\n- Cite every claim with the bracketed number of the section it came from, like [2]. A sentence\n drawing on two sections cites both.\n- If the sections do not answer the question, say exactly what is missing rather than filling the\n gap from memory. A vault that admits a hole is useful; one that guesses is not.\n- Sections marked RELATED were reached by association, not by matching the question. Use them for\n context or to point somewhere worth reading next, and say so when you do.\n- Prefer the user's own notes when they conflict with a source, and flag the disagreement.", # system prompt
mk_chat:NoneType=None, # build chats with this instead of `new_chat`; same signature
pii:str=None, # local|redact|refuse; None -> local when a local runtime exists, else redact
pii_model:str=None, # the local model that answers then; None -> $VISHALAKSHI_PII_MODEL
pii_ner:bool=True, # also look for names that follow a title such as Dr; a pattern, not a model
instruction:str='', # an instruction from the questioner, for a second turn
stale:bool=False, # include retained pages beyond the file's current end
**kw
)->fastcore.basics.AttrDict: # forwarded to Vault.contextAnswer a question from the vault, or about the documents ref names, citing the numbered sections the answer used.
Return the policy ask applies: pii when given, else local when a local runtime is installed, else redact. off gives a warning and the default.
Return True when the runtime of model, by default the PII model, runs on this machine and is installed.
CachedChat records the replies of a model on disk and plays them back. Tests and these pages use it to show real answers without a model run. The vault treats a CachedChat as any other chat.
The recording folder is path, else $VISHALAKSHI_CHAT_CACHE, else chatcache in the working directory.
A question with no recording raises an error. When $VISHALAKSHI_RECORD_CHAT is set, the question goes to the real model and CachedChat records the reply. The next run answers from disk.
Building a CachedChat registers Rishi’s runtimes, as new_chat does. runtime then names the backend of the id and builds no engine.
A chat that replays recorded replies from disk. It uses this package’s default model, cache folder and recording switch.
The default budget is sections=4 and max_chars=1500. Six sections of 4,000 characters each overflowed the context window of the 2B default model. LiteRT reported this as a send failure with no explanation (evals/RESULTS.md).
When a send fails this way, ask gives a warning and tries once more on a new chat. The second try uses the first two sections, each cut to a third of max_chars, and no related sections.
Retrieval needs no model. Only the answer needs one. mk_prompt builds the exact text that the model reads. The cell below prints one prompt.
[1] Late chunking beats naive chunking because context survives the split.
(source: note:04111d439a73, pages 0–0)
Late chunking beats naive chunking because context survives the split.
---
[2] repo › ../vishalakshi/core.py:209
(source: ../vishalakshi/core.py:209)
def search(self:Vault,
q:str, # query
limit:int=10, # hits to return
kind:str=No
# a document to ask about becomes section [1] in full, and the rest of the vault follows it
_dc = _v.doc_context('doc 3', 'rank fusion', related=2)
test_eq(_dc.results[0].breadcrumb, 'doc 3')
test_eq(_dc.results[0].text, _v.document('doc 3').text) # the whole document, not a chunk
assert all(r.doc_id != _dc.doc.doc_id for r in _dc.results[1:]) # never the document itself twice
test_eq(len(_v.doc_context('doc 3', 'rank fusion', max_chars=200).results[0].text), 200)
assert mk_prompt('rank fusion', _dc, note=_dc.note).endswith(_dc.note + 'Question: rank fusion')
# several docs: each is a numbered section; max_chars is a shared window
_dc2 = _v.doc_context(['doc 3', 'doc 5'], 'rank fusion', related=2, max_chars=600)
test_eq(_dc2.results.attrgot('breadcrumb')[:2], ['doc 3', 'doc 5'])
test_eq([len(r.text) for r in _dc2.results[:2]], [300, 300])
assert all(r.doc_id not in set(_dc2.docs.attrgot('doc_id')) for r in _dc2.results[2:])
test_eq(len(_dc2.results), 4) # 2 named + related=2
assert '[1]–[2] are the documents' in _dc2.note, _dc2.note
test_eq(doc_note(1)[:19], '[1] is the document')# reasoning: full pair, truncated opener, or MLX closing-only tag
test_eq(split_reasoning('<think>weighing [1]</think>\n\nRRF fuses ranks [2].'),
('RRF fuses ranks [2].', 'weighing [1]'))
test_eq(split_reasoning('weighing [1]</think>\n\nRRF fuses ranks [2].'),
('RRF fuses ranks [2].', 'weighing [1]'))
test_eq(split_reasoning('RRF fuses ranks [2].'), ('RRF fuses ranks [2].', ''))
# a section the reasoning weighed and dropped must not come back as a citation
test_eq(cited(split_reasoning('cites [1]</think> cites nothing')[0], res), [])pii explains the detector and the marks. The cells below show what ask does with them. They use a stand-in chat that records everything it receives. A leak appears as a recorded call.
The check runs on the chat that ask built, before ask sends anything. The next cell passes a hosted chat under the default local policy. ask does not call the model.
'held back: these sections hold personal information (card, email, phone) and remote is not a local runtime, so nothing was sent to it'
With a local runtime, ask sends the private sections to the local model under PII_SP. PII_SP tells the model to answer with counts, kinds and totals instead of personal details, and to say what it held back.
_seen.clear()
r = _v.ask('what is on invoice 4471?', mk_chat=_chat('litert',
'One invoice, 240.00 GBP, due in September. Holding back the name, email, phone and card. '
'Tell me what you need: a total, a due date, or a yes/no.'))
test_eq(_seen['runtime'], 'litert')
test_eq(_seen['sp'], PII_SP) # not VAULT_SP: that one tells it to cite, and a citation points at the text
test_eq(r.get('refused', False), False)
r.answer'One invoice, 240.00 GBP, due in September. Holding back the name, email, phone and card. Tell me what you need: a total, a due date, or a yes/no.'
instruction= sends a follow-up turn. When the local model holds something back, it names an instruction that would let it answer, such as “give me the total and the due date”. The caller sends that instruction with the same question.
'Total 240.00 GBP, due 2026-09-01.'
ask scans every answer over private sections again before it returns the answer. It masks identifiers that the model repeated, and leaked lists their kinds.
{'email': 1, 'card': 1}
pii='redact' masks the recognised identifiers in the text of each section. A hosted model then answers. A name is masked only when a title such as Dr comes before it. “Ada Lovelace” is not masked, as a real-model cell further down shows.
'An invoice for 240.00 GBP [1]'
ask scrubs the fields of a structured answer (schema=) in the same way. An API key counts as personal information, as an email address does. A hosted chat is refused for a section that holds an API key, and for a document marked by hand.
These cells replay replies that CachedChat recorded from real models. They run without the models. Each cell shows one rule or one way a call can fail.
The vault holds nothing private here. The default local model on its default backend answers and cites section [1].
r = model_ask(open_vault, q)
test_eq((r.model, r.runtime), (dflt_model, 'litert')) # gemma-4-E2B on LiteRT, unasked for
test_eq(r.pii.has_pii, False) # nothing private: one model, VAULT_SP, no scrubbing
test_eq(r.cited.attrgot('n'), [1]) # it cited [1]...
assert r.cited[0]['node_id'], r.cited # ...and [1] resolves to a section of the vault
r.answer'Reciprocal rank fusion combines rankings from legs that share no vector space by summing $1/(60 + \\text{rank})$ over the legs [1].'
The same question goes to a hosted model. Only the model id changes.
'Reciprocal rank fusion combines the rankings from different legs by summing the reciprocals of their ranks plus 60, specifically using the formula 1/(60 + rank) for each leg. A document that is ranked well in multiple legs will have a higher combined score, making it outperform documents that are only ranked well in a single leg [1].'
The vault holds an invoice. The local model answers under PII_SP. ask scans the answer again before it returns it.
r = model_ask(private_vault, pq)
test_eq(sorted(r.pii.identifying), ['card', 'email', 'phone'])
test_eq((r.model, r.runtime), (pii_model_, 'litert')) # local, so it answered rather than refusing
test_eq(r.get('refused', False), False)
# answer must not contain invoice PII; r.leaked says model vs scrubber
for s in ('ada@example.com', '4111 1111 1111 1111', '020 7946 0958', 'Ada Lovelace'): assert s not in r.answer, (s, r.answer)
r.answer, r.get('leaked')('I am holding back the specific personal details from the invoice.\nThe invoice is for an amount of 240.00 GBP, due on 2026-09-01.',
None)
Under pii='local', a hosted model= does not receive private sections. The local pii_model answers instead. A hosted model named as pii_model also receives nothing. The check sees a hosted chat and refuses.
# naming a hosted model where the sections are private routes to the local one instead
test_eq(model_ask(private_vault, pq, model=CLOUD).runtime, 'litert')
r = model_ask(private_vault, pq, model=CLOUD, pii_model=CLOUD) # ...and naming it as the *local* one is refused
test_eq((r.refused, r.runtime, r.answer.startswith('held back')), (True, 'remote', True))
# nothing was sent, and the proof is that there is nothing to replay: a call would have been
# recorded under one of these two keys, and neither is in the cache
_c = ch_fn(CLOUD).cache
for _sp in (VAULT_SP, PII_SP): assert f'{CLOUD}|call|{_sp}|{r.prompt}' not in _c
r.answer'held back: these sections hold personal information (card, email, phone) and remote is not a local runtime, so nothing was sent to it'
pii='redact' masks the identifiers, and a hosted model answers. “Ada Lovelace” has no title before it. The detector does not mask it, and it reaches the hosted model.
r = model_ask(private_vault, pq, model=CLOUD, pii='redact')
test_eq((r.model, r.runtime, r.get('refused', False)), (CLOUD, 'remote', False))
test_eq('[CARD]' in r.prompt and '[EMAIL]' in r.prompt, True) # what the network actually carried
for s in ('ada@example.com', '4111 1111 1111 1111', '020 7946 0958'):
assert s not in r.prompt, s
assert 'Ada Lovelace' in r.prompt # ...and the limit of it, pinned rather than discovered
r.answer'Invoice 4471 is for Ada Lovelace, with contact details including email and phone number. It shows an amount of 240.00 GBP, due on 2026-09-01, and the payment is to be made using a card ending in [CARD] (specific digits not provided) [1].'
The follow-up turn with instruction=, against the real local model.
r = model_ask(private_vault, pq, instruction='Give me the amount and the due date only, and no name.')
assert 'Instruction from the questioner' in r.prompt
test_eq((r.runtime, r.get('refused', False)), ('litert', False))
for s in ('ada@example.com', '4111 1111 1111 1111', '020 7946 0958'): assert s not in r.answer, s
r.answer'Amount: 240.00 GBP, Due Date: 2026-09-01.'