import { Pinecone, type Index } from "@pinecone-database/pinecone"; import { config, requireKeys } from "./config.js"; import type { Chunk, ScoredChunk } from "./types.js"; /** * Thin wrapper around the managed Pinecone vector DB. Replaces the old on-disk * index: vectors + chunk text now live in Pinecone, so the RAG server holds no * index in memory and the corpus can grow without touching the deployment. * * Records are upserted as { id: chunk.id, values: embedding, metadata: chunk * fields }. Chunk text is stored in metadata so a query returns everything the * pipeline needs (no second lookup). We use a single namespace per index. */ let client: Pinecone | null = null; function getClient(): Pinecone { requireKeys("pineconeApiKey"); client ??= new Pinecone({ apiKey: config.pineconeApiKey }); return client; } /** Returns the namespace-bound index handle used for all data operations. */ export function getIndex(): Index { const root = getClient().index(config.pineconeIndexName); return config.pineconeNamespace ? root.namespace(config.pineconeNamespace) : root; } /** * Create the serverless index if it doesn't exist yet (free Starter tier lives * in AWS us-east-1). Dimension is pinned to the embedding size; metric is cosine * (embeddings are L2-normalized, so cosine == dot product). */ export async function ensureIndexExists(): Promise { const pc = getClient(); const existing = await pc.listIndexes(); if (existing.indexes?.some((i) => i.name === config.pineconeIndexName)) return; console.log(`Creating Pinecone index "${config.pineconeIndexName}" (${config.embeddingDims} dims, cosine)...`); await pc.createIndex({ name: config.pineconeIndexName, dimension: config.embeddingDims, metric: "cosine", spec: { serverless: { cloud: "aws", region: "us-east-1" } }, waitUntilReady: true, }); } interface VectorRecordMeta { docId: string; text: string; source: string; title?: string; topic?: string; } /** Retry a Pinecone call with exponential backoff, surviving transient network * blips and outages that would otherwise kill a long ingest. */ async function withRetry(fn: () => Promise, label: string, attempts = 6): Promise { let lastErr: unknown; for (let i = 0; i < attempts; i++) { try { return await fn(); } catch (err) { lastErr = err; if (i === attempts - 1) break; const wait = Math.min(30_000, 1_000 * 2 ** i); const msg = err instanceof Error ? err.message : String(err); console.warn(`\n[pinecone] ${label} failed (attempt ${i + 1}/${attempts}); retrying in ${wait}ms: ${msg}`); await new Promise((r) => setTimeout(r, wait)); } } throw lastErr; } /** Upsert a batch of chunks with their embeddings (vectors must align with chunks). */ export async function upsertChunks(chunks: Chunk[], vectors: number[][]): Promise { const records = chunks.map((c, i) => { // Pinecone metadata rejects undefined values, so include optionals only when set. const metadata: VectorRecordMeta = { docId: c.docId, text: c.text, source: c.source }; if (c.title) metadata.title = c.title; if (c.topic) metadata.topic = c.topic; return { id: c.id, values: vectors[i]!, metadata: metadata as unknown as Record }; }); await withRetry(() => getIndex().upsert({ records }), "upsert"); } /** Dense similarity search; returns chunks reconstructed from match metadata. */ export async function queryVector(vector: number[], topK: number): Promise { const res = await getIndex().query({ topK, vector, includeMetadata: true }); return (res.matches ?? []).map((m) => { const meta = (m.metadata ?? {}) as Partial; return { id: m.id, docId: meta.docId ?? m.id, text: meta.text ?? "", source: meta.source ?? "", ...(meta.title ? { title: meta.title } : {}), ...(meta.topic ? { topic: meta.topic } : {}), score: m.score ?? 0, via: ["vector"], } satisfies ScoredChunk; }); } /** The index's configured vector dimension, or null if it can't be read. A * mismatch with config.embeddingDims means queries embed at the wrong size and * retrieval is silently garbage, so callers assert on this at startup. */ export async function indexDimension(): Promise { try { const desc = await getClient().describeIndex(config.pineconeIndexName); return desc.dimension ?? null; } catch { return null; } } /** Total vector count in the active namespace (used for /health + stats). */ export async function indexStats(): Promise<{ count: number }> { const stats = await getClient().index(config.pineconeIndexName).describeIndexStats(); const ns = config.pineconeNamespace || ""; const count = ns ? stats.namespaces?.[ns]?.recordCount ?? 0 : stats.totalRecordCount ?? 0; return { count }; } /** Delete every vector in the active namespace (used by `ingest --fresh`). */ export async function clearNamespace(): Promise { try { await getIndex().deleteAll(); } catch (err) { // deleteAll throws 404 when the namespace doesn't exist yet — that's fine. const msg = err instanceof Error ? err.message : String(err); if (!/404|not found/i.test(msg)) throw err; } }