-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathretriever.ts
448 lines (416 loc) · 12.7 KB
/
retriever.ts
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/**
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Action, GenkitError, defineAction, z } from '@genkit-ai/core';
import { Registry } from '@genkit-ai/core/registry';
import { Document, DocumentData, DocumentDataSchema } from './document.js';
import { EmbedderInfo } from './embedder.js';
export {
Document,
DocumentDataSchema,
type DocumentData,
type MediaPart,
type Part,
type TextPart,
} from './document.js';
/**
* Retriever implementation function signature.
*/
export type RetrieverFn<RetrieverOptions extends z.ZodTypeAny> = (
query: Document,
queryOpts: z.infer<RetrieverOptions>
) => Promise<RetrieverResponse>;
/**
* Indexer implementation function signature.
*/
export type IndexerFn<IndexerOptions extends z.ZodTypeAny> = (
docs: Array<Document>,
indexerOpts: z.infer<IndexerOptions>
) => Promise<void>;
const RetrieverRequestSchema = z.object({
query: DocumentDataSchema,
options: z.any().optional(),
});
const RetrieverResponseSchema = z.object({
documents: z.array(DocumentDataSchema),
// TODO: stats, etc.
});
type RetrieverResponse = z.infer<typeof RetrieverResponseSchema>;
const IndexerRequestSchema = z.object({
documents: z.array(DocumentDataSchema),
options: z.any().optional(),
});
/**
* Zod schema of retriever info metadata.
*/
export const RetrieverInfoSchema = z.object({
label: z.string().optional(),
/** Supported model capabilities. */
supports: z
.object({
/** Model can process media as part of the prompt (multimodal input). */
media: z.boolean().optional(),
})
.optional(),
});
export type RetrieverInfo = z.infer<typeof RetrieverInfoSchema>;
/**
* A retriever action type.
*/
export type RetrieverAction<CustomOptions extends z.ZodTypeAny = z.ZodTypeAny> =
Action<typeof RetrieverRequestSchema, typeof RetrieverResponseSchema> & {
__configSchema?: CustomOptions;
};
/**
* An indexer action type.
*/
export type IndexerAction<IndexerOptions extends z.ZodTypeAny = z.ZodTypeAny> =
Action<typeof IndexerRequestSchema, z.ZodVoid> & {
__configSchema?: IndexerOptions;
};
function retrieverWithMetadata<
RetrieverOptions extends z.ZodTypeAny = z.ZodTypeAny,
>(
retriever: Action<
typeof RetrieverRequestSchema,
typeof RetrieverResponseSchema
>,
configSchema?: RetrieverOptions
): RetrieverAction<RetrieverOptions> {
const withMeta = retriever as RetrieverAction<RetrieverOptions>;
withMeta.__configSchema = configSchema;
return withMeta;
}
function indexerWithMetadata<
IndexerOptions extends z.ZodTypeAny = z.ZodTypeAny,
>(
indexer: Action<typeof IndexerRequestSchema, z.ZodVoid>,
configSchema?: IndexerOptions
): IndexerAction<IndexerOptions> {
const withMeta = indexer as IndexerAction<IndexerOptions>;
withMeta.__configSchema = configSchema;
return withMeta;
}
/**
* Creates a retriever action for the provided {@link RetrieverFn} implementation.
*/
export function defineRetriever<
OptionsType extends z.ZodTypeAny = z.ZodTypeAny,
>(
registry: Registry,
options: {
name: string;
configSchema?: OptionsType;
info?: RetrieverInfo;
},
runner: RetrieverFn<OptionsType>
) {
const retriever = defineAction(
registry,
{
actionType: 'retriever',
name: options.name,
inputSchema: options.configSchema
? RetrieverRequestSchema.extend({
options: options.configSchema.optional(),
})
: RetrieverRequestSchema,
outputSchema: RetrieverResponseSchema,
metadata: {
type: 'retriever',
info: options.info,
},
},
(i) => runner(new Document(i.query), i.options)
);
const rwm = retrieverWithMetadata(
retriever as Action<
typeof RetrieverRequestSchema,
typeof RetrieverResponseSchema
>,
options.configSchema
);
return rwm;
}
/**
* Creates an indexer action for the provided {@link IndexerFn} implementation.
*/
export function defineIndexer<IndexerOptions extends z.ZodTypeAny>(
registry: Registry,
options: {
name: string;
embedderInfo?: EmbedderInfo;
configSchema?: IndexerOptions;
},
runner: IndexerFn<IndexerOptions>
) {
const indexer = defineAction(
registry,
{
actionType: 'indexer',
name: options.name,
inputSchema: options.configSchema
? IndexerRequestSchema.extend({
options: options.configSchema.optional(),
})
: IndexerRequestSchema,
outputSchema: z.void(),
metadata: {
type: 'indexer',
embedderInfo: options.embedderInfo,
},
},
(i) =>
runner(
i.documents.map((dd) => new Document(dd)),
i.options
)
);
const iwm = indexerWithMetadata(
indexer as Action<typeof IndexerRequestSchema, z.ZodVoid>,
options.configSchema
);
return iwm;
}
export interface RetrieverParams<
CustomOptions extends z.ZodTypeAny = z.ZodTypeAny,
> {
retriever: RetrieverArgument<CustomOptions>;
query: string | DocumentData;
options?: z.infer<CustomOptions>;
}
/**
* A type that can be used to pass a retriever as an argument, either using a reference or an action.
*/
export type RetrieverArgument<
CustomOptions extends z.ZodTypeAny = z.ZodTypeAny,
> = RetrieverAction<CustomOptions> | RetrieverReference<CustomOptions> | string;
/**
* Retrieves documents from a {@link RetrieverArgument} based on the provided query.
*/
export async function retrieve<CustomOptions extends z.ZodTypeAny>(
registry: Registry,
params: RetrieverParams<CustomOptions>
): Promise<Array<Document>> {
let retriever: RetrieverAction<CustomOptions>;
if (typeof params.retriever === 'string') {
retriever = await registry.lookupAction(`/retriever/${params.retriever}`);
} else if (Object.hasOwnProperty.call(params.retriever, 'info')) {
retriever = await registry.lookupAction(
`/retriever/${params.retriever.name}`
);
} else {
retriever = params.retriever as RetrieverAction<CustomOptions>;
}
if (!retriever) {
throw new Error('Unable to resolve the retriever');
}
const response = await retriever({
query:
typeof params.query === 'string'
? Document.fromText(params.query)
: params.query,
options: params.options,
});
return response.documents.map((d) => new Document(d));
}
/**
* A type that can be used to pass an indexer as an argument, either using a reference or an action.
*/
export type IndexerArgument<CustomOptions extends z.ZodTypeAny = z.ZodTypeAny> =
IndexerReference<CustomOptions> | IndexerAction<CustomOptions> | string;
/**
* Options passed to the index function.
*/
export interface IndexerParams<
CustomOptions extends z.ZodTypeAny = z.ZodTypeAny,
> {
indexer: IndexerArgument<CustomOptions>;
documents: Array<DocumentData>;
options?: z.infer<CustomOptions>;
}
/**
* Indexes documents using a {@link IndexerArgument}.
*/
export async function index<CustomOptions extends z.ZodTypeAny>(
registry: Registry,
params: IndexerParams<CustomOptions>
): Promise<void> {
let indexer: IndexerAction<CustomOptions>;
if (typeof params.indexer === 'string') {
indexer = await registry.lookupAction(`/indexer/${params.indexer}`);
} else if (Object.hasOwnProperty.call(params.indexer, 'info')) {
indexer = await registry.lookupAction(`/indexer/${params.indexer.name}`);
} else {
indexer = params.indexer as IndexerAction<CustomOptions>;
}
if (!indexer) {
throw new Error('Unable to utilize the provided indexer');
}
return await indexer({
documents: params.documents,
options: params.options,
});
}
/**
* Zod schema of common retriever options.
*/
export const CommonRetrieverOptionsSchema = z.object({
k: z.number().describe('Number of documents to retrieve').optional(),
});
/**
* A retriver reference object.
*/
export interface RetrieverReference<CustomOptions extends z.ZodTypeAny> {
name: string;
configSchema?: CustomOptions;
info?: RetrieverInfo;
}
/**
* Helper method to configure a {@link RetrieverReference} to a plugin.
*/
export function retrieverRef<
CustomOptionsSchema extends z.ZodTypeAny = z.ZodTypeAny,
>(
options: RetrieverReference<CustomOptionsSchema>
): RetrieverReference<CustomOptionsSchema> {
return { ...options };
}
// Reuse the same schema for both indexers and retrievers -- for now.
export const IndexerInfoSchema = RetrieverInfoSchema;
/**
* Indexer metadata.
*/
export type IndexerInfo = z.infer<typeof IndexerInfoSchema>;
export interface IndexerReference<CustomOptions extends z.ZodTypeAny> {
name: string;
configSchema?: CustomOptions;
info?: IndexerInfo;
}
/**
* Helper method to configure a {@link IndexerReference} to a plugin.
*/
export function indexerRef<
CustomOptionsSchema extends z.ZodTypeAny = z.ZodTypeAny,
>(
options: IndexerReference<CustomOptionsSchema>
): IndexerReference<CustomOptionsSchema> {
return { ...options };
}
function itemToDocument<R>(
item: any,
options: SimpleRetrieverOptions
): Document {
if (!item)
throw new GenkitError({
status: 'INVALID_ARGUMENT',
message: `Items returned from simple retriever must be non-null.`,
});
if (typeof item === 'string') return Document.fromText(item);
if (typeof options.content === 'function') {
const transformed = options.content(item);
return typeof transformed === 'string'
? Document.fromText(transformed)
: new Document({ content: transformed });
}
if (typeof options.content === 'string' && typeof item === 'object')
return Document.fromText(item[options.content]);
throw new GenkitError({
status: 'INVALID_ARGUMENT',
message: `Cannot convert item to document without content option. Item: ${JSON.stringify(item)}`,
});
}
function itemToMetadata(
item: any,
options: SimpleRetrieverOptions
): Document['metadata'] {
if (typeof item === 'string') return undefined;
if (Array.isArray(options.metadata) && typeof item === 'object') {
const out: Record<string, any> = {};
options.metadata.forEach((key) => (out[key] = item[key]));
return out;
}
if (typeof options.metadata === 'function') return options.metadata(item);
if (!options.metadata && typeof item === 'object') {
const out = { ...item };
if (typeof options.content === 'string') delete out[options.content];
return out;
}
throw new GenkitError({
status: 'INVALID_ARGUMENT',
message: `Unable to extract metadata from item with supplied options. Item: ${JSON.stringify(item)}`,
});
}
/**
* Simple retriever options.
*/
export interface SimpleRetrieverOptions<
C extends z.ZodTypeAny = z.ZodTypeAny,
R = any,
> {
/** The name of the retriever you're creating. */
name: string;
/** A Zod schema containing any configuration info available beyond the query. */
configSchema?: C;
/**
* Specifies how to extract content from the returned items.
*
* - If a string, specifies the key of the returned item to extract as content.
* - If a function, allows you to extract content as text or a document part.
**/
content?: string | ((item: R) => Document['content'] | string);
/**
* Specifies how to extract metadata from the returned items.
*
* - If an array of strings, specifies list of keys to extract from returned objects.
* - If a function, allows you to use custom behavior to extract metadata from returned items.
*/
metadata?: string[] | ((item: R) => Document['metadata']);
}
/**
* defineSimpleRetriever makes it easy to map existing data into documents that
* can be used for prompt augmentation.
*
* @param options Configuration options for the retriever.
* @param handler A function that queries a datastore and returns items from which to extract documents.
* @returns A Genkit retriever.
*/
export function defineSimpleRetriever<
C extends z.ZodTypeAny = z.ZodTypeAny,
R = any,
>(
registry: Registry,
options: SimpleRetrieverOptions<C, R>,
handler: (query: Document, config: z.infer<C>) => Promise<R[]>
) {
return defineRetriever(
registry,
{
name: options.name,
configSchema: options.configSchema,
},
async (query, config) => {
const result = await handler(query, config);
return {
documents: result.map((item) => {
const doc = itemToDocument(item, options);
if (typeof item !== 'string')
doc.metadata = itemToMetadata(item, options);
return doc;
}),
};
}
);
}