@tonytruong/chatbot-ai-lib
Version:
AI-powered healthcare automation, document parsing, OpenAI, embeddings, RAG, vector DB, Facebook OAuth.
68 lines • 2.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCollection = getCollection;
exports.saveEmbeddings = saveEmbeddings;
exports.querySimilar = querySimilar;
const tslib_1 = require("tslib");
const chromadb_1 = require("chromadb");
const openai_1 = require("../../../config/openai");
const logger_1 = require("../../../shared/logger");
const COLLECTION_NAME = "chatbot-ingest";
const DEFAULT_EMBEDDING_MODEL = "text-embedding-ada-002";
const getEmbedder = (apiKey, model) => new chromadb_1.OpenAIEmbeddingFunction({
openai_api_key: apiKey,
openai_model: model,
});
const getClient = (chromaUrl) => new chromadb_1.ChromaClient({ path: chromaUrl });
function getCollection(options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const apiKey = (options === null || options === void 0 ? void 0 : options.apiKey) || openai_1.OPENAI_API_KEY;
const model = (options === null || options === void 0 ? void 0 : options.model) || DEFAULT_EMBEDDING_MODEL;
const chromaUrl = (options === null || options === void 0 ? void 0 : options.chromaUrl) || openai_1.CHROMA_URL;
const embedder = getEmbedder(apiKey, model);
const client = getClient(chromaUrl);
let collection;
try {
collection = yield client.getCollection({ name: COLLECTION_NAME });
}
catch (e) {
collection = yield client.createCollection({
name: COLLECTION_NAME,
embeddingFunction: embedder,
});
}
return collection;
});
}
function saveEmbeddings(embeddings_1, texts_1) {
return tslib_1.__awaiter(this, arguments, void 0, function* (embeddings, texts, metadatas = [], options, ids) {
const collection = yield getCollection(options);
const finalIds = ids && ids.length === texts.length
? ids
: texts.map((_, i) => `vec-${Date.now()}-${i}`);
yield collection.add({
ids: finalIds,
embeddings,
documents: texts,
metadatas,
});
});
}
function querySimilar(queryEmbedding_1) {
return tslib_1.__awaiter(this, arguments, void 0, function* (queryEmbedding, topK = 3, options, filter) {
try {
const collection = yield getCollection(options);
const results = yield collection.query({
queryEmbeddings: [queryEmbedding],
nResults: topK,
where: filter,
});
return results;
}
catch (error) {
logger_1.logger.error('❌ Chroma query error:', error.message);
throw error;
}
});
}
//# sourceMappingURL=VectorDBService.js.map