@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
156 lines • 7.42 kB
JavaScript
import { embedCountingUsage, } from '../spi/embedding-provider.js';
import { chunkText } from './chunk.js';
import { ingestChunks } from './ingest.js';
/** Metadata key separating models that share a store. Reserved: it always wins over yours. */
export const RAG_ENTITY_KEY = 'ragEntity';
/** A required scope key was missing, from the search or from the row. Nothing ran. */
export class RagScopeRequiredError extends Error {
constructor(model, key, operation = 'ragSearch') {
super(`${model}.${operation} needs scope.${key}: this model's chunks are isolated by it`);
this.name = 'RagScopeRequiredError';
}
}
/**
* Declares RAG on a Lucid model, the way `withAuthFinder` declares auth:
*
* ```ts
* class ProjectDocument extends compose(BaseModel, withRag({
* store: () => store,
* embedder: () => embedder,
* text: (doc) => doc.textContent,
* scope: ['projectId'],
* })) {}
*
* await doc.ragIndex()
* await ProjectDocument.ragSearch('question', { scope: { projectId } })
* ```
*
* `row.delete()` removes its chunks, after the commit when inside a transaction. A savepoint's commit
* counts as one, so a later rollback of the outer transaction leaves the row without chunks until the
* next `ragIndex`. Nothing else removes them: a database `ON DELETE CASCADE`, a bulk
* `Model.query().delete()` and `deleteQuietly()` fire no hook, so call `ragRemove` or clean up yourself. Saving does NOT index: embedding is a slow, paid call that has no place in a
* `save()`, so call `ragIndex` from a job or wherever the text is known to have changed.
*/
// biome-ignore lint/suspicious/noExplicitAny: a model's attributes are only known to the caller
export function withRag(options) {
const scopeKeys = options.scope ?? [];
return (superclass) => {
class RagModel extends superclass {
// `this` is the concrete model here, not this mixin: the hook has to land on the subclass.
// biome-ignore-start lint/complexity/noThisInStatic: see above
static boot() {
if (Object.hasOwn(this, 'booted') && this.booted)
return;
super.boot();
this.after('delete', async (row) => {
// Inside a transaction the row may yet come back, so wait for the commit.
const { $trx: trx } = row;
if (trx === undefined) {
await row.ragRemove();
return;
}
trx.after('commit', () => row.ragRemove());
});
}
// biome-ignore-end lint/complexity/noThisInStatic: see above
get ragDocumentId() {
const model = this.constructor;
return `${model.table}:${String(this.$primaryKeyValue)}`;
}
/**
* Replaces this row's chunks and returns how many were written. The embeddings come first: if the
* provider fails, the previous chunks are still there.
*/
async ragIndex(text) {
const row = this;
const model = this.constructor;
const full = (text === undefined ? options.text?.(row) : text)?.trim();
const store = await options.store();
if (!full) {
await store.remove(this.ragDocumentId);
return 0;
}
const source = options.source?.(row) ?? undefined;
const scope = scopeValues(this, scopeKeys);
for (const key of scopeKeys) {
// Without it the chunks would be written where no search could ever reach them.
if (scope[key] === undefined || scope[key] === null) {
throw new RagScopeRequiredError(model.name, key, 'ragIndex');
}
}
const base = options.metadata?.(row);
const chunks = chunkText(full, options.chunk)
.slice(0, options.maxChunks)
.map((chunk, index) => ({
id: `${this.ragDocumentId}#${index}`,
text: chunk,
...(source !== undefined ? { source } : {}),
// Scope last: nothing can retag a chunk to another tenant.
metadata: {
...base,
...options.chunkMetadata?.(chunk, full, row),
...scope,
[RAG_ENTITY_KEY]: model.table,
},
}));
const documentId = this.ragDocumentId;
if (chunks.length === 0) {
await store.remove(documentId);
return 0;
}
return ingestChunks(chunks, {
embedder: await options.embedder(),
...(options.onUsage ? { onUsage: options.onUsage } : {}),
// `ingestChunks` only upserts, after embedding: that is the moment to drop the old chunks.
store: {
upsert: async (records) => {
if (store.replaceDocument !== undefined) {
await store.replaceDocument(documentId, records);
return;
}
await store.remove(documentId);
await store.upsert(records);
},
},
});
}
async ragRemove() {
const store = await options.store();
await store.remove(this.ragDocumentId);
}
static async ragSearch(query, search = {}) {
const scope = search.scope ?? {};
for (const key of scopeKeys) {
if (scope[key] === undefined || scope[key] === null) {
// biome-ignore lint/complexity/noThisInStatic: the concrete model's name, for the message
throw new RagScopeRequiredError(this.name, key);
}
}
const embedder = await options.embedder();
const { vectors, usage } = await embedCountingUsage(embedder, [query]);
if (usage !== undefined)
await options.onUsage?.(usage);
const store = await options.store();
return store.search(vectors[0] ?? [], {
topK: search.topK ?? 5,
// Scope last: a filter can narrow a search, never widen it past the scope.
filter: {
...search.filter,
...pick(scope, scopeKeys),
// biome-ignore lint/complexity/noThisInStatic: the concrete model's table
[RAG_ENTITY_KEY]: this.table,
},
...(search.minScore !== undefined ? { minScore: search.minScore } : {}),
});
}
}
return RagModel;
};
}
function pick(from, keys) {
return Object.fromEntries(keys.map((key) => [key, from[key]]));
}
function scopeValues(row, keys) {
return pick(row, keys);
}
//# sourceMappingURL=with-rag.js.map