-
-
Notifications
You must be signed in to change notification settings - Fork 24.8k
Expand file tree
/
Copy pathRetrieverTool.ts
More file actions
236 lines (211 loc) · 8.85 KB
/
Copy pathRetrieverTool.ts
File metadata and controls
236 lines (211 loc) · 8.85 KB
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
import { z } from 'zod/v3'
import { CallbackManager, CallbackManagerForToolRun, Callbacks, parseCallbackConfigArg } from '@langchain/core/callbacks/manager'
import { BaseDynamicToolInput, DynamicTool, StructuredTool, ToolInputParsingException } from '@langchain/core/tools'
import { BaseRetriever } from '@langchain/core/retrievers'
import { ICommonObject, INode, INodeData, INodeParams } from '../../../src/Interface'
import { getBaseClasses, resolveFlowObjValue, parseWithTypeConversion } from '../../../src/utils'
import { SOURCE_DOCUMENTS_PREFIX } from '../../../src/agents'
import { RunnableConfig } from '@langchain/core/runnables'
import { VectorStoreRetriever } from '@langchain/core/vectorstores'
import { processSearchFilter } from '../../retrievers/WeaviateRetriever/HybridSearchRetriever'
const howToUse = `Add additional filters to vector store. You can also filter with flow config, including the current "state":
- \`$flow.sessionId\`
- \`$flow.chatId\`
- \`$flow.chatflowId\`
- \`$flow.input\`
- \`$flow.state\`
`
type ZodObjectAny = z.ZodObject<any, any, any, any>
type IFlowConfig = { sessionId?: string; chatId?: string; input?: string; state?: ICommonObject }
interface DynamicStructuredToolInput<T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>>
extends BaseDynamicToolInput {
func?: (input: z.infer<T>, runManager?: CallbackManagerForToolRun, flowConfig?: IFlowConfig) => Promise<string>
schema: T
}
class DynamicStructuredTool<T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>> extends StructuredTool<
T extends ZodObjectAny ? T : ZodObjectAny
> {
static lc_name() {
return 'DynamicStructuredTool'
}
name: string
description: string
func: DynamicStructuredToolInput['func']
// @ts-ignore
schema: T
private flowObj: any
constructor(fields: DynamicStructuredToolInput<T>) {
super(fields)
this.name = fields.name
this.description = fields.description
this.func = fields.func
this.returnDirect = fields.returnDirect ?? this.returnDirect
this.schema = fields.schema
}
async call(arg: any, configArg?: RunnableConfig | Callbacks, tags?: string[], flowConfig?: IFlowConfig): Promise<string> {
const config = parseCallbackConfigArg(configArg)
if (config.runName === undefined) {
config.runName = this.name
}
let parsed
try {
parsed = await parseWithTypeConversion(this.schema, arg)
} catch (e) {
throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(arg))
}
const callbackManager_ = await CallbackManager.configure(
config.callbacks,
this.callbacks,
config.tags || tags,
this.tags,
config.metadata,
this.metadata,
{ verbose: this.verbose }
)
const runManager = await callbackManager_?.handleToolStart(
this.toJSON(),
typeof parsed === 'string' ? parsed : JSON.stringify(parsed),
undefined,
undefined,
undefined,
undefined,
config.runName
)
let result
try {
result = await this._call(parsed, runManager, flowConfig)
} catch (e) {
await runManager?.handleToolError(e)
throw e
}
if (result && typeof result !== 'string') {
result = JSON.stringify(result)
}
await runManager?.handleToolEnd(result)
return result
}
// @ts-ignore
protected _call(arg: any, runManager?: CallbackManagerForToolRun, flowConfig?: IFlowConfig): Promise<string> {
let flowConfiguration: ICommonObject = {}
if (typeof arg === 'object' && Object.keys(arg).length) {
for (const item in arg) {
flowConfiguration[`$${item}`] = arg[item]
}
}
// inject flow properties
if (this.flowObj) {
flowConfiguration['$flow'] = { ...this.flowObj, ...flowConfig }
}
return this.func!(arg as any, runManager, flowConfiguration)
}
setFlowObject(flow: any) {
this.flowObj = flow
}
}
class Retriever_Tools implements INode {
label: string
name: string
version: number
description: string
type: string
icon: string
category: string
baseClasses: string[]
credential: INodeParams
inputs: INodeParams[]
constructor() {
this.label = 'Retriever Tool'
this.name = 'retrieverTool'
this.version = 3.0
this.type = 'RetrieverTool'
this.icon = 'retrievertool.svg'
this.category = 'Tools'
this.description = 'Use a retriever as allowed tool for agent'
this.baseClasses = [this.type, 'DynamicTool', ...getBaseClasses(DynamicTool)]
this.inputs = [
{
label: 'Retriever Name',
name: 'name',
type: 'string',
placeholder: 'search_state_of_union'
},
{
label: 'Retriever Description',
name: 'description',
type: 'string',
description: 'When should agent uses to retrieve documents',
rows: 3,
placeholder: 'Searches and returns documents regarding the state-of-the-union.'
},
{
label: 'Retriever',
name: 'retriever',
type: 'BaseRetriever'
},
{
label: 'Return Source Documents',
name: 'returnSourceDocuments',
type: 'boolean',
optional: true
},
{
label: 'Additional Metadata Filter',
name: 'retrieverToolMetadataFilter',
type: 'json',
description: 'Add additional metadata filter on top of the existing filter from vector store',
optional: true,
additionalParams: true,
hint: {
label: 'What can you filter?',
value: howToUse
},
acceptVariable: true
}
]
}
async init(nodeData: INodeData, _: string, options: ICommonObject): Promise<any> {
const name = nodeData.inputs?.name as string
const description = nodeData.inputs?.description as string
const retriever = nodeData.inputs?.retriever as BaseRetriever
const returnSourceDocuments = nodeData.inputs?.returnSourceDocuments as boolean
const retrieverToolMetadataFilter = nodeData.inputs?.retrieverToolMetadataFilter
const input = {
name,
description
}
const flow = { chatflowId: options.chatflowid }
const func = async ({ input }: { input: string }, _?: CallbackManagerForToolRun, flowConfig?: IFlowConfig) => {
if (retrieverToolMetadataFilter) {
const flowObj = flowConfig
const metadataFilter =
typeof retrieverToolMetadataFilter === 'object' ? retrieverToolMetadataFilter : JSON.parse(retrieverToolMetadataFilter)
const newMetadataFilter = resolveFlowObjValue(metadataFilter, flowObj)
if (newMetadataFilter && typeof newMetadataFilter === 'object' && Object.keys(newMetadataFilter).length > 0) {
const vectorStore = (retriever as VectorStoreRetriever<any>).vectorStore
if (vectorStore.constructor.name === 'WeaviateStore' || vectorStore.lc_namespace?.includes('weaviate')) {
const client = (vectorStore as any).client
const indexName = (vectorStore as any).indexName
if (client && indexName) {
const newWeaviateMetadataFilter = processSearchFilter(newMetadataFilter, client, indexName)
const weaviateRetriever = retriever as VectorStoreRetriever
weaviateRetriever.filter = newWeaviateMetadataFilter
}
} else {
vectorStore.filter = newMetadataFilter
}
}
}
const docs = await retriever.invoke(input)
const content = docs.map((doc) => doc.pageContent).join('\n\n')
const sourceDocuments = JSON.stringify(docs)
return returnSourceDocuments ? content + SOURCE_DOCUMENTS_PREFIX + sourceDocuments : content
}
const schema = z.object({
input: z.string().describe('input to look up in retriever')
}) as any
const tool = new DynamicStructuredTool({ ...input, func, schema })
tool.setFlowObject(flow)
return tool
}
}
module.exports = { nodeClass: Retriever_Tools }