Files
template-app/modules/knowledge/core/search.ts
T

39 lines
1.5 KiB
TypeScript

// The search: one collection, one query, cited answers. The embedding leaves the process (the
// procedure is an effect), the ranking is the vector store's, and every answer carries where it
// came from: the file, the chunk, and the snippet a person reads.
import { forbidden, internal } from "@conusai-kit/core"
import { MAX_SEARCH_RESULTS, type SearchResult } from "../contract/index.js"
import { requireCollection } from "./collections.js"
import { type KnowledgeDeps, type KnowledgeScope, knowledgeEnabled } from "./ports.js"
export async function searchKnowledge(
deps: KnowledgeDeps,
scope: KnowledgeScope,
input: { collectionName: string; query: string; limit?: number | undefined },
): Promise<{ results: SearchResult[] }> {
if (!(await knowledgeEnabled(deps, scope))) throw forbidden("knowledge is switched off for this project")
await requireCollection(deps, scope, input.collectionName)
const service = deps.search
if (!service) throw internal("the knowledge search service is not bound in this process")
const limit = Math.min(input.limit ?? 10, MAX_SEARCH_RESULTS)
const hits = await service.search(scope, {
collectionName: input.collectionName,
query: input.query,
limit,
actorId: scope.actor.userId,
})
return {
results: hits.map((hit): SearchResult => {
return {
fileId: hit.fileId,
filename: hit.filename,
collectionName: hit.collectionName,
snippet: hit.snippet,
score: hit.score,
chunk: hit.chunk,
}
}),
}
}