|
| 1 | +import { Document } from '@langchain/core/documents' |
| 2 | +import { VectorStore, VectorStoreRetriever, VectorStoreRetrieverInput } from '@langchain/core/vectorstores' |
| 3 | +import { INode, INodeData, INodeParams, INodeOutputsValue } from '../../../src/Interface' |
| 4 | +import { handleEscapeCharacters } from '../../../src' |
| 5 | +import { z } from 'zod' |
| 6 | +import { convertStructuredSchemaToZod, ExtractTool } from '../../sequentialagents/commonUtils' |
| 7 | +import { ChatGoogleGenerativeAI } from '@langchain/google-genai' |
| 8 | + |
| 9 | +const queryPrefix = 'query' |
| 10 | +const defaultPrompt = `Extract keywords from the query: {{${queryPrefix}}}` |
| 11 | + |
| 12 | +class ExtractMetadataRetriever_Retrievers implements INode { |
| 13 | + label: string |
| 14 | + name: string |
| 15 | + version: number |
| 16 | + description: string |
| 17 | + type: string |
| 18 | + icon: string |
| 19 | + category: string |
| 20 | + badge?: string |
| 21 | + baseClasses: string[] |
| 22 | + inputs: INodeParams[] |
| 23 | + outputs: INodeOutputsValue[] |
| 24 | + |
| 25 | + constructor() { |
| 26 | + this.label = 'Extract Metadata Retriever' |
| 27 | + this.name = 'extractMetadataRetriever' |
| 28 | + this.version = 1.0 |
| 29 | + this.type = 'ExtractMetadataRetriever' |
| 30 | + this.icon = 'dynamicMetadataRetriever.svg' |
| 31 | + this.category = 'Retrievers' |
| 32 | + this.description = 'Extract keywords/metadata from the query and use it to filter documents' |
| 33 | + this.baseClasses = [this.type, 'BaseRetriever'] |
| 34 | + this.badge = 'BETA' |
| 35 | + this.inputs = [ |
| 36 | + { |
| 37 | + label: 'Vector Store', |
| 38 | + name: 'vectorStore', |
| 39 | + type: 'VectorStore' |
| 40 | + }, |
| 41 | + { |
| 42 | + label: 'Chat Model', |
| 43 | + name: 'model', |
| 44 | + type: 'BaseChatModel' |
| 45 | + }, |
| 46 | + { |
| 47 | + label: 'Query', |
| 48 | + name: 'query', |
| 49 | + type: 'string', |
| 50 | + description: 'Query to retrieve documents from retriever. If not specified, user question will be used', |
| 51 | + optional: true, |
| 52 | + acceptVariable: true |
| 53 | + }, |
| 54 | + { |
| 55 | + label: 'Prompt', |
| 56 | + name: 'dynamicMetadataFilterRetrieverPrompt', |
| 57 | + type: 'string', |
| 58 | + description: 'Prompt to extract metadata from query', |
| 59 | + rows: 4, |
| 60 | + additionalParams: true, |
| 61 | + default: defaultPrompt |
| 62 | + }, |
| 63 | + { |
| 64 | + label: 'JSON Structured Output', |
| 65 | + name: 'dynamicMetadataFilterRetrieverStructuredOutput', |
| 66 | + type: 'datagrid', |
| 67 | + description: |
| 68 | + 'Instruct the model to give output in a JSON structured schema. This output will be used as the metadata filter for connected vector store', |
| 69 | + datagrid: [ |
| 70 | + { field: 'key', headerName: 'Key', editable: true }, |
| 71 | + { |
| 72 | + field: 'type', |
| 73 | + headerName: 'Type', |
| 74 | + type: 'singleSelect', |
| 75 | + valueOptions: ['String', 'String Array', 'Number', 'Boolean', 'Enum'], |
| 76 | + editable: true |
| 77 | + }, |
| 78 | + { field: 'enumValues', headerName: 'Enum Values', editable: true }, |
| 79 | + { field: 'description', headerName: 'Description', flex: 1, editable: true } |
| 80 | + ], |
| 81 | + optional: true, |
| 82 | + additionalParams: true |
| 83 | + }, |
| 84 | + { |
| 85 | + label: 'Top K', |
| 86 | + name: 'topK', |
| 87 | + description: 'Number of top results to fetch. Default to vector store topK', |
| 88 | + placeholder: '4', |
| 89 | + type: 'number', |
| 90 | + additionalParams: true, |
| 91 | + optional: true |
| 92 | + } |
| 93 | + ] |
| 94 | + this.outputs = [ |
| 95 | + { |
| 96 | + label: 'Extract Metadata Retriever', |
| 97 | + name: 'retriever', |
| 98 | + baseClasses: this.baseClasses |
| 99 | + }, |
| 100 | + { |
| 101 | + label: 'Document', |
| 102 | + name: 'document', |
| 103 | + description: 'Array of document objects containing metadata and pageContent', |
| 104 | + baseClasses: ['Document', 'json'] |
| 105 | + }, |
| 106 | + { |
| 107 | + label: 'Text', |
| 108 | + name: 'text', |
| 109 | + description: 'Concatenated string from pageContent of documents', |
| 110 | + baseClasses: ['string', 'json'] |
| 111 | + } |
| 112 | + ] |
| 113 | + } |
| 114 | + |
| 115 | + async init(nodeData: INodeData, input: string): Promise<any> { |
| 116 | + const vectorStore = nodeData.inputs?.vectorStore as VectorStore |
| 117 | + let llm = nodeData.inputs?.model |
| 118 | + const llmStructuredOutput = nodeData.inputs?.dynamicMetadataFilterRetrieverStructuredOutput |
| 119 | + const topK = nodeData.inputs?.topK as string |
| 120 | + const dynamicMetadataFilterRetrieverPrompt = nodeData.inputs?.dynamicMetadataFilterRetrieverPrompt as string |
| 121 | + const query = nodeData.inputs?.query as string |
| 122 | + const finalInputQuery = query ? query : input |
| 123 | + |
| 124 | + const output = nodeData.outputs?.output as string |
| 125 | + |
| 126 | + if (llmStructuredOutput && llmStructuredOutput !== '[]') { |
| 127 | + try { |
| 128 | + const structuredOutput = z.object(convertStructuredSchemaToZod(llmStructuredOutput)) |
| 129 | + |
| 130 | + if (llm instanceof ChatGoogleGenerativeAI) { |
| 131 | + const tool = new ExtractTool({ |
| 132 | + schema: structuredOutput |
| 133 | + }) |
| 134 | + // @ts-ignore |
| 135 | + const modelWithTool = llm.bind({ |
| 136 | + tools: [tool] |
| 137 | + }) as any |
| 138 | + llm = modelWithTool |
| 139 | + } else { |
| 140 | + // @ts-ignore |
| 141 | + llm = llm.withStructuredOutput(structuredOutput) |
| 142 | + } |
| 143 | + } catch (exception) { |
| 144 | + console.error(exception) |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + const retriever = DynamicMetadataRetriever.fromVectorStore(vectorStore, { |
| 149 | + structuredLLM: llm, |
| 150 | + prompt: dynamicMetadataFilterRetrieverPrompt, |
| 151 | + topK: topK ? parseInt(topK, 10) : (vectorStore as any)?.k ?? 4 |
| 152 | + }) |
| 153 | + |
| 154 | + if (output === 'retriever') return retriever |
| 155 | + else if (output === 'document') return await retriever.getRelevantDocuments(finalInputQuery) |
| 156 | + else if (output === 'text') { |
| 157 | + let finaltext = '' |
| 158 | + |
| 159 | + const docs = await retriever.getRelevantDocuments(finalInputQuery) |
| 160 | + |
| 161 | + for (const doc of docs) finaltext += `${doc.pageContent}\n` |
| 162 | + |
| 163 | + return handleEscapeCharacters(finaltext, false) |
| 164 | + } |
| 165 | + |
| 166 | + return retriever |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +type RetrieverInput<V extends VectorStore> = Omit<VectorStoreRetrieverInput<V>, 'k'> & { |
| 171 | + topK?: number |
| 172 | + structuredLLM: any |
| 173 | + prompt: string |
| 174 | +} |
| 175 | + |
| 176 | +class DynamicMetadataRetriever<V extends VectorStore> extends VectorStoreRetriever<V> { |
| 177 | + topK = 4 |
| 178 | + structuredLLM: any |
| 179 | + prompt = '' |
| 180 | + |
| 181 | + constructor(input: RetrieverInput<V>) { |
| 182 | + super(input) |
| 183 | + this.topK = input.topK ?? this.topK |
| 184 | + this.structuredLLM = input.structuredLLM ?? this.structuredLLM |
| 185 | + this.prompt = input.prompt ?? this.prompt |
| 186 | + } |
| 187 | + |
| 188 | + async getFilter(query: string): Promise<any> { |
| 189 | + const structuredResponse = await this.structuredLLM.invoke(this.prompt.replace(`{{${queryPrefix}}}`, query)) |
| 190 | + return structuredResponse |
| 191 | + } |
| 192 | + |
| 193 | + async getRelevantDocuments(query: string): Promise<Document[]> { |
| 194 | + const newFilter = await this.getFilter(query) |
| 195 | + // @ts-ignore |
| 196 | + this.filter = { ...this.filter, ...newFilter } |
| 197 | + const results = await this.vectorStore.similaritySearchWithScore(query, this.topK, this.filter) |
| 198 | + |
| 199 | + const finalDocs: Document[] = [] |
| 200 | + for (const result of results) { |
| 201 | + finalDocs.push( |
| 202 | + new Document({ |
| 203 | + pageContent: result[0].pageContent, |
| 204 | + metadata: result[0].metadata |
| 205 | + }) |
| 206 | + ) |
| 207 | + } |
| 208 | + return finalDocs |
| 209 | + } |
| 210 | + |
| 211 | + static fromVectorStore<V extends VectorStore>(vectorStore: V, options: Omit<RetrieverInput<V>, 'vectorStore'>) { |
| 212 | + return new this<V>({ ...options, vectorStore }) |
| 213 | + } |
| 214 | +} |
| 215 | + |
| 216 | +module.exports = { nodeClass: ExtractMetadataRetriever_Retrievers } |
0 commit comments