Retrieval over vault files
Answer a question from the text files a vault holds: list them, download and chunk the text, rank with embeddings and rerank, then ask chat.
A vault holds files that every member who can read it shares. This recipe answers a question from those files: it lists the vault's files, downloads the text ones, ranks their passages against the question, and asks chat to answer from the best of them. It chains the vault file calls with Embeddings, Rerank, and Chat.
The vault calls
Two calls read a vault's files: one lists them, one downloads a file's
content. Both need can_read on the vault.
# List the files the vault holds, newest first.
curl "https://api.cruxy.ai/api/v1/vaults/$VAULT_ID/files?limit=100" \
-H "Authorization: Bearer $CRUXY_API_KEY"
# Download one file's raw bytes.
curl https://api.cruxy.ai/api/v1/vaults/$VAULT_ID/files/$FILE_ID/content \
-H "Authorization: Bearer $CRUXY_API_KEY" \
-o handbook.mdThe full recipe
const BASE = 'https://api.cruxy.ai'
const vaultId = process.env.VAULT_ID
const auth = {
Authorization: `Bearer ${process.env.CRUXY_API_KEY}`,
'Content-Type': 'application/json',
}
async function api(path: string, init?: RequestInit) {
const res = await fetch(`${BASE}${path}`, { ...init, headers: auth })
if (!res.ok) throw new Error(`${path} failed: ${res.status} ${await res.text()}`)
return res
}
type VaultFile = { id: string; filename: string; content_type: string | null }
type Passage = { text: string; filename: string }
// 1. List every file in the vault, following next_cursor.
async function listVaultFiles(): Promise<VaultFile[]> {
const files: VaultFile[] = []
let cursor: string | null = null
do {
const query = new URLSearchParams({ limit: '100' })
if (cursor) query.set('cursor', cursor)
const page = await (await api(`/api/v1/vaults/${vaultId}/files?${query}`)).json()
files.push(...page.data)
cursor = page.next_cursor
} while (cursor)
return files
}
// 2. Download the text files and split them into passages.
async function loadPassages(files: VaultFile[]): Promise<Passage[]> {
const passages: Passage[] = []
for (const file of files) {
if (!file.content_type?.startsWith('text/')) continue // raw bytes only: skip non-text
const res = await api(`/api/v1/vaults/${vaultId}/files/${file.id}/content`)
const text = await res.text()
for (const part of text.split(/\n\s*\n/)) {
const trimmed = part.trim()
if (trimmed) passages.push({ text: trimmed, filename: file.filename })
}
}
return passages
}
// 3. Embed in batches. One request takes at most 512 inputs.
async function embed(input: string[]): Promise<number[][]> {
const vectors: number[][] = []
for (let i = 0; i < input.length; i += 512) {
const res = await api('/api/v1/embeddings', {
method: 'POST',
body: JSON.stringify({ model: 'cruxy-embed', input: input.slice(i, i + 512) }),
})
const { data } = await res.json()
const batch = data as { index: number; embedding: number[] }[]
vectors.push(...batch.sort((a, b) => a.index - b.index).map((d) => d.embedding))
}
return vectors
}
function cosine(a: number[], b: number[]): number {
let dot = 0
let na = 0
let nb = 0
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i]
na += a[i] * a[i]
nb += b[i] * b[i]
}
return dot / (Math.sqrt(na) * Math.sqrt(nb))
}
const question = 'Who do I hand the pager to at the end of an on-call shift?'
const passages = await loadPassages(await listVaultFiles())
if (passages.length === 0) throw new Error('the vault holds no text files to search')
// 4. Shortlist by cosine, then rerank the shortlist.
const vectors = await embed(passages.map((p) => p.text))
const [queryVector] = await embed([question])
const shortlist = passages
.map((passage, i) => ({ passage, score: cosine(queryVector, vectors[i]) }))
.sort((a, b) => b.score - a.score)
.slice(0, 20)
.map((s) => s.passage)
const reranked = await api('/api/v1/rerank', {
method: 'POST',
body: JSON.stringify({
model: 'cruxy-rerank',
query: question,
documents: shortlist.map((p) => p.text),
top_n: 5,
}),
})
const { results } = await reranked.json()
// A rerank index points into the shortlist you sent, not into `passages`.
const context = (results as { index: number }[]).map((r) => shortlist[r.index])
// 5. Ask chat inside the vault, grounded in the winning passages.
const chat = await api('/api/v1/chat', {
method: 'POST',
body: JSON.stringify({
model: 'saga',
stream: false,
vault_id: vaultId,
messages: [
{
role: 'system',
content:
'Answer only from the provided context, and name the file each fact comes from. If the answer is not in it, say you do not know.',
},
{
role: 'user',
content: `Context:\n${context.map((p) => `[${p.filename}]\n${p.text}`).join('\n\n')}\n\nQuestion: ${question}`,
},
],
}),
})
const completion = await chat.json()
console.log(completion.message.content)What to know before you run it
- Access is the caller's. The list and the download both answer
404vault_not_foundunless the key's user is a member who can read the vault and is not held. An index you build is only as private as where you keep it: store it with the same access as the vault. - A download is a use. A vault file is kept 365 days from its last use, and each download restarts that clock. Reading a file's metadata does not.
vault_idon the chat request makes the turn a chat inside the vault, so the vault's memory and standing rules apply. It is optional here: the passages reach the model through the message, not throughvault_id.- Index once, not per question. The script embeds the corpus on every run to stay short. In a real system, store the vectors beside the passages and embed only the question. List the vault again to pick up new files.
- Map indices back. A rerank
indexpoints into thedocumentsyou sent, which here is the shortlist. Retrieval-augmented generation explains the trap.
Documents and images
For a PDF, a Word document, or an image the vault holds, skip the index and
attach the file to the question. A vault file's id goes in file_ids like
any other file's, on a request that pins Cruxy-Version: 2026-10-05 or
later, and the gateway reads it only while you are a member who reads that
vault and is not held:
const res = await fetch('https://api.cruxy.ai/api/v1/chat', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.CRUXY_API_KEY}`,
'Content-Type': 'application/json',
'Cruxy-Version': '2026-10-05',
},
body: JSON.stringify({
model: 'saga',
stream: false,
vault_id: process.env.VAULT_ID,
messages: [
{
role: 'user',
content: 'Who do I hand the pager to at the end of an on-call shift?',
file_ids: [process.env.FILE_ID], // a PDF the vault holds
},
],
}),
})
if (!res.ok) throw new Error(`chat failed: ${res.status} ${await res.text()}`)
console.log((await res.json()).message.content)A file attached this way is billed as input on every turn that sends it, so for a large corpus, retrieve the passages instead.
Next steps
- Retrieval-augmented generation: the same pipeline over a corpus you hold yourself.
- Embeddings: the batch limits and the vector shape.
- Rerank: the score ordering and
top_n. - Memory: what
vault_idchanges about recall.