-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
base.ts
209 lines (170 loc) Β· 5.16 KB
/
base.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
import { distance, similarity } from "ml-distance";
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import { ChainValues } from "@langchain/core/utils/types";
import { OpenAIEmbeddings } from "@langchain/openai";
import {
CallbackManagerForChainRun,
Callbacks,
BaseCallbackConfig,
} from "@langchain/core/callbacks/manager";
import {
PairwiseStringEvaluator,
PairwiseStringEvaluatorArgs,
StringEvaluator,
StringEvaluatorArgs,
} from "../base.js";
/**
*
* Embedding Distance Metric.
*
* COSINE: Cosine distance metric.
* EUCLIDEAN: Euclidean distance metric.
* MANHATTAN: Manhattan distance metric.
* CHEBYSHEV: Chebyshev distance metric.
* HAMMING: Hamming distance metric.
*/
export type EmbeddingDistanceType =
| "cosine"
| "euclidean"
| "manhattan"
| "chebyshev";
/**
* Embedding Distance Evaluation Chain Input.
*/
export interface EmbeddingDistanceEvalChainInput {
/**
* The embedding objects to vectorize the outputs.
*/
embedding?: EmbeddingsInterface;
/**
* The distance metric to use
* for comparing the embeddings.
*/
distanceMetric?: EmbeddingDistanceType;
}
type VectorFunction = (xVector: number[], yVector: number[]) => number;
/**
* Get the distance function for the given distance type.
* @param distance The distance type.
* @return The distance function.
*/
export function getDistanceCalculationFunction(
distanceType: EmbeddingDistanceType
): VectorFunction {
const distanceFunctions: { [key in EmbeddingDistanceType]: VectorFunction } =
{
cosine: (X: number[], Y: number[]) => 1.0 - similarity.cosine(X, Y),
euclidean: distance.euclidean,
manhattan: distance.manhattan,
chebyshev: distance.chebyshev,
};
return distanceFunctions[distanceType];
}
/**
* Compute the score based on the distance metric.
* @param vectors The input vectors.
* @param distanceMetric The distance metric.
* @return The computed score.
*/
export function computeEvaluationScore(
vectors: number[][],
distanceMetric: EmbeddingDistanceType
): number {
const metricFunction = getDistanceCalculationFunction(distanceMetric);
return metricFunction(vectors[0], vectors[1]);
}
/**
* Use embedding distances to score semantic difference between
* a prediction and reference.
*/
export class EmbeddingDistanceEvalChain
extends StringEvaluator
implements EmbeddingDistanceEvalChainInput
{
requiresReference = true;
requiresInput = false;
outputKey = "score";
embedding?: EmbeddingsInterface;
distanceMetric: EmbeddingDistanceType = "cosine";
constructor(fields: EmbeddingDistanceEvalChainInput) {
super();
this.embedding = fields?.embedding || new OpenAIEmbeddings();
this.distanceMetric = fields?.distanceMetric || "cosine";
}
_chainType() {
return `embedding_${this.distanceMetric}_distance` as const;
}
async _evaluateStrings(
args: StringEvaluatorArgs,
config: Callbacks | BaseCallbackConfig | undefined
): Promise<ChainValues> {
const result = await this.call(args, config);
return { [this.outputKey]: result[this.outputKey] };
}
get inputKeys(): string[] {
return ["reference", "prediction"];
}
get outputKeys(): string[] {
return [this.outputKey];
}
async _call(
values: ChainValues,
_runManager: CallbackManagerForChainRun | undefined
): Promise<ChainValues> {
const { prediction, reference } = values;
if (!this.embedding) throw new Error("Embedding is undefined");
const vectors = await this.embedding.embedDocuments([
prediction,
reference,
]);
const score = computeEvaluationScore(vectors, this.distanceMetric);
return { [this.outputKey]: score };
}
}
/**
* Use embedding distances to score semantic difference between two predictions.
*/
export class PairwiseEmbeddingDistanceEvalChain
extends PairwiseStringEvaluator
implements EmbeddingDistanceEvalChainInput
{
requiresReference = false;
requiresInput = false;
outputKey = "score";
embedding?: EmbeddingsInterface;
distanceMetric: EmbeddingDistanceType = "cosine";
constructor(fields: EmbeddingDistanceEvalChainInput) {
super();
this.embedding = fields?.embedding || new OpenAIEmbeddings();
this.distanceMetric = fields?.distanceMetric || "cosine";
}
_chainType() {
return `pairwise_embedding_${this.distanceMetric}_distance` as const;
}
async _evaluateStringPairs(
args: PairwiseStringEvaluatorArgs,
config?: Callbacks | BaseCallbackConfig
): Promise<ChainValues> {
const result = await this.call(args, config);
return { [this.outputKey]: result[this.outputKey] };
}
get inputKeys(): string[] {
return ["prediction", "predictionB"];
}
get outputKeys(): string[] {
return [this.outputKey];
}
async _call(
values: ChainValues,
_runManager: CallbackManagerForChainRun | undefined
): Promise<ChainValues> {
const { prediction, predictionB } = values;
if (!this.embedding) throw new Error("Embedding is undefined");
const vectors = await this.embedding.embedDocuments([
prediction,
predictionB,
]);
const score = computeEvaluationScore(vectors, this.distanceMetric);
return { [this.outputKey]: score };
}
}