-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsearch.ts
230 lines (195 loc) · 5.57 KB
/
search.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
import { collections, models } from "@hypermode/modus-sdk-as";
import { EmbeddingsModel } from "@hypermode/modus-sdk-as/models/experimental/embeddings";
import { getProduct, getCart } from "./crud";
import { ProductSearchResult, ProductSearchObject, consts } from "./types";
export function recommendProductByCart(
cartId: string,
maxItems: i32,
): ProductSearchResult {
const productSearchRes = new ProductSearchResult(
consts.productNameCollection,
consts.searchMethod,
"success",
"",
);
const cart = getCart(cartId);
if (cart === null || cart.items.length === 0) {
productSearchRes.status = "error";
productSearchRes.error = "Cart not found";
return productSearchRes;
}
const cartVecs: f32[][] = [];
for (let i = 0; i < cart.items.length; i++) {
const vec = collections.getVector(
consts.productNameCollection,
consts.searchMethod,
cart.items[i].Product.id,
);
cartVecs.push(vec);
}
const sumVec: f32[] = [];
for (let i = 0; i < cartVecs[0].length; i++) {
sumVec[i] = 0;
for (let j = 0; j < cartVecs.length; j++) {
sumVec[i] += cartVecs[j][i];
}
}
const normalizedVec = normalize(sumVec);
const cartProductIds = cart.items.map<string>((item) => item.Product.id);
const semanticSearchRes = collections.searchByVector(
consts.productNameCollection,
consts.searchMethod,
normalizedVec,
maxItems + cart.items.length,
);
if (!semanticSearchRes.isSuccessful) {
productSearchRes.status = semanticSearchRes.status;
productSearchRes.error = semanticSearchRes.error;
return productSearchRes;
}
for (let i = 0; i < semanticSearchRes.objects.length; i++) {
if (cartProductIds.includes(semanticSearchRes.objects[i].key)) {
continue;
}
const searchObj = getSearchObject(
semanticSearchRes.objects[i].key,
semanticSearchRes.objects[i].score,
semanticSearchRes.objects[i].distance,
);
productSearchRes.searchObjs.push(searchObj);
}
productSearchRes.searchObjs = productSearchRes.searchObjs.slice(0, maxItems);
return productSearchRes;
}
export function searchProducts(
query: string,
maxItems: i32,
thresholdStars: f32 = 0.0,
inStockOnly: boolean = false,
): ProductSearchResult {
const productSearchRes = new ProductSearchResult(
consts.productNameCollection,
consts.searchMethod,
"success",
"",
);
const semanticSearchRes = collections.search(
consts.productNameCollection,
consts.searchMethod,
query,
maxItems,
true,
);
if (!semanticSearchRes.isSuccessful) {
productSearchRes.status = semanticSearchRes.status;
productSearchRes.error = semanticSearchRes.error;
return productSearchRes;
}
if (inStockOnly) {
for (let i = 0; i < semanticSearchRes.objects.length; i++) {
const inStockRes = collections.getText(
consts.isProductStockedCollection,
semanticSearchRes.objects[i].key,
);
const inStock = inStockRes === "true";
if (!inStock) {
semanticSearchRes.objects.splice(i, 1);
i--;
}
}
}
const rankedResults = reRankAndFilterSearchResultObjects(
semanticSearchRes.objects,
thresholdStars,
);
for (let i = 0; i < rankedResults.length; i++) {
const searchObj = getSearchObject(
rankedResults[i].key,
rankedResults[i].score,
rankedResults[i].distance,
);
productSearchRes.searchObjs.unshift(searchObj);
}
return productSearchRes;
}
function getSearchObject(
key: string,
score: f64,
distance: f64,
): ProductSearchObject {
return new ProductSearchObject(getProduct(key), score, distance);
}
function reRankAndFilterSearchResultObjects(
objs: collections.CollectionSearchResultObject[],
thresholdStars: f32,
): collections.CollectionSearchResultObject[] {
for (let i = 0; i < objs.length; i++) {
const starRes = collections.getText(
consts.productStarCollection,
objs[i].key,
);
let stars = parseFloat(starRes);
if (isNaN(stars)) {
stars = 0;
}
const inStockRes = collections.getText(
consts.isProductStockedCollection,
objs[i].key,
);
const inStock = inStockRes === "true";
if (!inStock) {
objs[i].score *= 0.5;
}
objs[i].score *= stars * 0.1;
}
objs.sort((a, b) => {
if (a.score < b.score) {
return -1;
} else if (a.score > b.score) {
return 1;
} else {
return 0;
}
});
const filteredResults: collections.CollectionSearchResultObject[] = [];
for (let i = 0; i < objs.length; i++) {
const starRes = collections.getText(
consts.productStarCollection,
objs[i].key,
);
let stars = parseFloat(starRes);
if (isNaN(stars)) {
stars = 0;
}
if (stars >= thresholdStars) {
filteredResults.push(objs[i]);
}
}
return filteredResults;
}
export function miniLMEmbed(texts: string[]): f32[][] {
const model = models.getModel<EmbeddingsModel>(consts.embeddingModel);
const input = model.createInput(texts);
const output = model.invoke(input);
return output.predictions;
}
// Function to calculate the magnitude of a vector
function magnitude(vec: f32[]): f32 {
let sum: f32 = 0.0;
for (let i = 0; i < vec.length; i++) {
sum += vec[i] * vec[i];
}
return f32(Math.sqrt(sum));
}
// Function to normalize a vector
function normalize(vec: f32[]): f32[] {
const mag = magnitude(vec);
if (mag == 0) {
throw new Error("Cannot normalize a zero vector");
}
const normalizedVec: f32[] = [];
for (let i = 0; i < vec.length; i++) {
normalizedVec.push(vec[i] / mag);
}
return normalizedVec;
}