File size: 11,378 Bytes
10dd572 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | import { createBaselineResolver, type BaselineResolver } from './baseline-resolver'
import { loadBaselineCatalog } from './baseline-catalog'
import { createCosineRetriever, type CosineRetriever } from './cosine-retriever'
import {
assertSearchCatalogResolvable,
readSearchCatalog
} from './search-catalog'
import { committedSearchVectors, type SearchVectorsSource } from './search-vectors'
import {
API_RAG_TOP_K,
type ApiCatalog,
type ApiCatalogPackage,
type ApiSearchInput,
type ApiSearchResult,
type CandidateEntry,
type EmbeddingModel,
type SearchCatalog,
type VerificationEntry
} from './types'
/** One class may own most of the best hits; past this many, its variants make room for others. */
const VARIANTS_PER_OWNER = 2
/** Rows past this one arrive as `rank, symbol, kind, score`; the Builder re-queries for detail. */
const FULL_DETAIL_ROWS = 3
interface PackageIndex {
catalog: ApiCatalog
resolver: BaselineResolver
retriever: CosineRetriever
}
export interface ApiRagServiceOptions {
embedding: EmbeddingModel
/** Packages this process may answer for. A package without a Search Catalog stays unregistered. */
packages: readonly ApiCatalogPackage[]
topK?: number
/** Defaults to the committed SearchDoc matrices under data/api-catalog. */
searchVectors?: SearchVectorsSource
}
/**
* The one query path of the product.
*
* symbols → Baseline Resolver → verification (does it exist?)
* query → SearchDoc retriever → candidates → Baseline facts (what is it?)
*
* Fails fast: a missing or malformed data file, an unresolvable search key, a missing
* model or a dimension mismatch stops the process instead of degrading to a guess.
*/
export class ApiRagService {
private readonly embedding: EmbeddingModel
private readonly searchVectors: SearchVectorsSource
private readonly topK: number
private readonly registrations = new Map<ApiCatalogPackage, SearchCatalog>()
private readonly indexes = new Map<ApiCatalogPackage, Promise<PackageIndex>>()
constructor(options: ApiRagServiceOptions) {
this.embedding = options.embedding
this.searchVectors = options.searchVectors ?? committedSearchVectors
this.topK = options.topK ?? API_RAG_TOP_K
for (const packageName of options.packages) {
const searchCatalog = readSearchCatalog(packageName)
if (searchCatalog) {
this.registrations.set(packageName, searchCatalog)
}
}
}
/** Packages with a Search Catalog. The tool registry follows this list. */
get registeredPackages(): ApiCatalogPackage[] {
return [...this.registrations.keys()]
}
isRegistered(packageName: ApiCatalogPackage): boolean {
return this.registrations.has(packageName)
}
/**
* Loads every index and encodes the SearchDoc matrix once. This is the single loading door: the
* composition root awaits it before the listener opens, and a missing or malformed data file
* aborts startup instead of degrading to a guess.
*/
async ready(): Promise<void> {
await Promise.all(this.registeredPackages.map((packageName) => this.packageIndex(packageName)))
}
async search(packageName: ApiCatalogPackage, input: ApiSearchInput): Promise<ApiSearchResult> {
if (!this.registrations.has(packageName)) {
throw new Error(`API RAG is not registered for ${packageName}: it has no Search Catalog`)
}
const query = input.query?.trim() ?? ''
const requested = (input.symbols ?? []).map((symbol) => symbol.trim()).filter(Boolean)
if (!query && requested.length === 0) {
throw new Error('search_api requires a query, symbols, or both')
}
const index = await this.packageIndex(packageName)
const verification: VerificationEntry[] = requested.map((symbol) => index.resolver.verify(symbol))
// Verify-only: no embedding, no candidates.
if (!query) {
return {
packageName: index.catalog.packageName,
packageVersion: index.catalog.packageVersion,
mode: 'verify',
verification,
candidates: []
}
}
const [queryEmbedding] = await this.embedding.embed([query])
// Score the whole index rather than a slice: scoring already visits every entry, and a symbol
// the Builder named must be pinnable however badly the query ranked it.
const hits = index.retriever.search(queryEmbedding, index.retriever.size)
const verifiedSymbols = verification
.filter((entry) => entry.verdict === 'FOUND' && entry.canonicalSymbol)
.map((entry) => entry.canonicalSymbol as string)
const candidates = selectCandidates((symbol) => index.resolver.resolve(symbol), hits, verifiedSymbols, this.topK)
// A member's owner is a full dotted path, and one class owns most of a search: repeating it
// costs more than every other field trim combined. Each distinct path is written once into
// `owners` and referenced by its short alias, which the Builder reads back through the map.
const owners = buildOwnerAliases([...verification, ...candidates])
// A verified symbol that also arrives as a candidate already carries its signature: the
// verdict points at that row rather than printing the same text twice. A verify-only answer
// keeps the signature, because there is no candidate to point at.
const rankBySymbol = new Map(candidates.map((candidate) => [candidate.symbol, candidate.rank]))
for (const entry of verification) {
const rank = entry.canonicalSymbol ? rankBySymbol.get(entry.canonicalSymbol) : undefined
if (rank === undefined) continue
delete entry.signature
entry.see_candidate = rank
}
return {
packageName: index.catalog.packageName,
packageVersion: index.catalog.packageVersion,
mode: requested.length > 0 ? 'hybrid' : 'discover',
query,
...(Object.keys(owners).length > 0 ? { owners } : {}),
verification,
candidates
}
}
private packageIndex(packageName: ApiCatalogPackage): Promise<PackageIndex> {
const cached = this.indexes.get(packageName)
if (cached) {
return cached
}
const pending = this.buildPackageIndex(packageName).catch((error: unknown) => {
this.indexes.delete(packageName)
throw error
})
this.indexes.set(packageName, pending)
return pending
}
private async buildPackageIndex(packageName: ApiCatalogPackage): Promise<PackageIndex> {
// Only a registered package reaches this point, so the Search Catalog is already in memory.
const searchCatalog = this.registrations.get(packageName)
if (!searchCatalog) {
throw new Error(`API RAG is not registered for ${packageName}: it has no Search Catalog`)
}
const catalog = await loadBaselineCatalog(packageName)
const resolver = createBaselineResolver(catalog)
assertSearchCatalogResolvable(searchCatalog, resolver, packageName)
// The document vectors are committed, so startup reads them instead of encoding 1352 rows.
// The loader proves the row order, the width and the model match this process.
const symbols = Object.keys(searchCatalog)
const dimensions = this.embedding.dimensions
const vectors = await this.searchVectors.load(packageName, symbols, dimensions)
const retriever = createCosineRetriever(
symbols.map((symbol, position) => ({
symbol,
searchDoc: searchCatalog[symbol],
embedding: vectors.subarray(position * dimensions, (position + 1) * dimensions)
})),
dimensions
)
return { catalog, resolver, retriever }
}
}
/**
* Writes each distinct owner path once and rewrites every `owner` field to its short alias.
* The alias is the last path segment; a second class with the same short name gets a `#2` suffix.
* Mutates the entries in place, so callers pass the objects they are about to return.
*/
export function buildOwnerAliases(entries: Array<{ owner?: string }>): Record<string, string> {
const aliasByPath = new Map<string, string>()
const aliases: Record<string, string> = {}
for (const entry of entries) {
const path = entry.owner
if (!path) continue
let alias = aliasByPath.get(path)
if (!alias) {
const base = path.split('.').pop() ?? path
alias = base
for (let suffix = 2; aliases[alias] !== undefined; suffix += 1) {
alias = `${base}#${suffix}`
}
aliases[alias] = path
aliasByPath.set(path, alias)
}
entry.owner = alias
}
return aliases
}
interface CandidateDraft {
symbol: string
score: number
kind: string
owner?: string
signature?: string
doc?: string
}
/**
* Fills the result window from the retriever's ranked rows, in three steps:
*
* 1. the symbols the Builder named come first, in the order it named them, so an answer never
* buries the API the caller already asked about;
* 2. past `variantsPerOwner` rows, a further member of the same class yields its slot, so one
* class cannot crowd out the API the query was actually about;
* 3. past `FULL_DETAIL_ROWS` rows a candidate arrives as one line, keeping the long tail
* discoverable without paying a signature and a doc for every row.
*/
export function selectCandidates(
resolve: (symbol: string) => { path: string; kind: string; owner?: string; signature?: string; doc?: string } | undefined,
hits: ReadonlyArray<{ symbol: string; score: number }>,
verifiedSymbols: readonly string[],
limit: number,
variantsPerOwner: number = VARIANTS_PER_OWNER
): CandidateEntry[] {
const drafts: CandidateDraft[] = hits.map((hit) => {
const resolved = resolve(hit.symbol)
const draft: CandidateDraft = {
symbol: resolved?.path ?? hit.symbol,
score: hit.score,
kind: resolved?.kind ?? 'unknown'
}
if (resolved?.owner) draft.owner = resolved.owner
if (resolved?.signature) draft.signature = resolved.signature
if (resolved?.doc) draft.doc = resolved.doc
return draft
})
const bySymbol = new Map(drafts.map((draft) => [draft.symbol, draft]))
const pinned: CandidateDraft[] = []
for (const symbol of verifiedSymbols) {
const draft = bySymbol.get(symbol)
if (draft && !pinned.includes(draft)) pinned.push(draft)
}
const pinnedSymbols = new Set(pinned.map((draft) => draft.symbol))
const kept: CandidateDraft[] = []
const ownerCounts = new Map<string, number>()
for (const draft of [...pinned, ...drafts.filter((entry) => !pinnedSymbols.has(entry.symbol))]) {
if (kept.length >= limit) break
const isPinned = pinnedSymbols.has(draft.symbol)
if (draft.owner) {
const used = ownerCounts.get(draft.owner) ?? 0
if (!isPinned && used >= variantsPerOwner) continue
ownerCounts.set(draft.owner, used + 1)
}
kept.push(draft)
}
return kept.map((draft, index) => {
const rank = index + 1
// A row the Builder named stays in full wherever it landed: it is the row it must call.
if (index < FULL_DETAIL_ROWS || pinnedSymbols.has(draft.symbol)) {
const entry: CandidateEntry = { rank, symbol: draft.symbol, score: draft.score, kind: draft.kind }
if (draft.owner) entry.owner = draft.owner
if (draft.signature) entry.signature = draft.signature
if (draft.doc) entry.doc = draft.doc
return entry
}
return { rank, symbol: draft.symbol, score: draft.score, kind: draft.kind }
})
}
|