-
Notifications
You must be signed in to change notification settings - Fork 313
/
MultiModalEmbedding.ts
71 lines (63 loc) · 1.97 KB
/
MultiModalEmbedding.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
import {
ImageNode,
MetadataMode,
ModalityType,
splitNodesByType,
type BaseNode,
type ImageType,
} from "../Node.js";
import type { MessageContentDetail } from "../llm/types.js";
import { extractImage, extractSingleText } from "../llm/utils.js";
import { BaseEmbedding, batchEmbeddings } from "./types.js";
/*
* Base class for Multi Modal embeddings.
*/
export abstract class MultiModalEmbedding extends BaseEmbedding {
abstract getImageEmbedding(images: ImageType): Promise<number[]>;
/**
* Optionally override this method to retrieve multiple image embeddings in a single request
* @param texts
*/
async getImageEmbeddings(images: ImageType[]): Promise<number[][]> {
return Promise.all(
images.map((imgFilePath) => this.getImageEmbedding(imgFilePath)),
);
}
async transform(nodes: BaseNode[], _options?: any): Promise<BaseNode[]> {
const nodeMap = splitNodesByType(nodes);
const imageNodes = nodeMap[ModalityType.IMAGE] ?? [];
const textNodes = nodeMap[ModalityType.TEXT] ?? [];
const embeddings = await batchEmbeddings(
textNodes.map((node) => node.getContent(MetadataMode.EMBED)),
this.getTextEmbeddings.bind(this),
this.embedBatchSize,
_options,
);
for (let i = 0; i < textNodes.length; i++) {
textNodes[i].embedding = embeddings[i];
}
const imageEmbeddings = await batchEmbeddings(
imageNodes.map((n) => (n as ImageNode).image),
this.getImageEmbeddings.bind(this),
this.embedBatchSize,
_options,
);
for (let i = 0; i < imageNodes.length; i++) {
imageNodes[i].embedding = imageEmbeddings[i];
}
return nodes;
}
async getQueryEmbedding(
query: MessageContentDetail,
): Promise<number[] | null> {
const image = extractImage(query);
if (image) {
return await this.getImageEmbedding(image);
}
const text = extractSingleText(query);
if (text) {
return await this.getTextEmbedding(text);
}
return null;
}
}