n8n-nodes-query-retriever-rerank
Version:
Advanced n8n community node for intelligent document retrieval with multi-step reasoning, reranking, and comprehensive debugging
76 lines (73 loc) • 3.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseStrategy = void 0;
const debugging_1 = require("../shared/debugging");
class BaseStrategy {
constructor() {
this.debugManager = new debugging_1.DebugManager('base', {});
}
// Common helper methods available to all strategies
// Generate answer using language model
async generateAnswer(docs, query, context) {
var _a;
if (docs.length === 0) {
return 'No relevant documents found in the vector store.';
}
// Prepare context from retrieved documents
const docContext = docs.map((doc, index) => `Document ${index + 1}:\n${doc.pageContent}\n`).join('\n');
// Use custom prompt template if provided, otherwise use default
const defaultTemplate = `Use the following pieces of context to answer the question at the end.
{context}
Question: {question}
Answer:`;
const promptTemplate = ((_a = context.config.promptTemplate) === null || _a === void 0 ? void 0 : _a.trim()) || defaultTemplate;
const prompt = promptTemplate
.replace('{context}', docContext)
.replace('{question}', query);
this.debugManager.setAnswerGenerationData({
contextLength: docContext.length,
promptLength: prompt.length
});
// Generate answer using the language model
const answerStart = Date.now();
const response = await context.model.invoke(prompt);
this.debugManager.addTiming('answerGeneration', answerStart);
return typeof response === 'string' ? response : response.content || response.text || String(response);
}
// Format result for different return types
formatResult(answer, docs, context) {
// For "none" strategy, return only documents without generating an answer
if (!answer) {
return {
sourceDocuments: docs.map((doc) => ({
pageContent: doc.pageContent,
metadata: doc.metadata
}))
};
}
// Return structured JSON when returning source documents
if (context.config.returnRankedDocuments) {
return {
answer,
sourceDocuments: docs.map((doc) => ({
pageContent: doc.pageContent,
metadata: doc.metadata
}))
};
}
// Simple answer return (no source documents)
return { answer };
}
// Handle debug data storage
async handleDebugging(originalQuery, context) {
if (!context.debugging || !context.memory)
return;
const debugData = this.debugManager.finalize();
await debugging_1.DebugManager.storeInMemory(debugData, context.model, context.memory, context.llmDebugAnalysis, originalQuery);
}
// Initialize debug manager for the strategy
initializeDebugManager(strategyName, config) {
this.debugManager = new debugging_1.DebugManager(strategyName, config);
}
}
exports.BaseStrategy = BaseStrategy;