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
|
- import { matchesAnswerRelevance } from '../../src/matchers';
- import { ANSWER_RELEVANCY_GENERATE } from '../../src/prompts';
- import {
- DefaultEmbeddingProvider,
- DefaultGradingProvider,
- } from '../../src/providers/openai/defaults';
- import type { OpenAiEmbeddingProvider } from '../../src/providers/openai/embedding';
- describe('matchesAnswerRelevance', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- jest.resetAllMocks();
- jest.spyOn(DefaultGradingProvider, 'callApi').mockReset();
- jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi').mockReset();
- jest.spyOn(DefaultGradingProvider, 'callApi').mockResolvedValue({
- output: 'foobar',
- tokenUsage: { total: 10, prompt: 5, completion: 5 },
- });
- jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi').mockResolvedValue({
- embedding: [1, 0, 0],
- tokenUsage: { total: 5, prompt: 2, completion: 3 },
- });
- });
- afterEach(() => {
- jest.restoreAllMocks();
- });
- it('should pass when the relevance score is above the threshold', async () => {
- const input = 'Input text';
- const output = 'Sample output';
- const threshold = 0.5;
- const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
- mockCallApi.mockImplementation(() => {
- return Promise.resolve({
- output: 'foobar',
- tokenUsage: { total: 10, prompt: 5, completion: 5 },
- });
- });
- const mockCallEmbeddingApi = jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi');
- mockCallEmbeddingApi.mockImplementation(function (this: OpenAiEmbeddingProvider) {
- return Promise.resolve({
- embedding: [1, 0, 0],
- tokenUsage: { total: 5, prompt: 2, completion: 3 },
- });
- });
- await expect(matchesAnswerRelevance(input, output, threshold)).resolves.toEqual({
- pass: true,
- reason: 'Relevance 1.00 is greater than threshold 0.5',
- score: 1,
- tokensUsed: {
- total: expect.any(Number),
- prompt: expect.any(Number),
- completion: expect.any(Number),
- cached: expect.any(Number),
- completionDetails: expect.any(Object),
- numRequests: 0,
- },
- metadata: {
- generatedQuestions: expect.arrayContaining([
- expect.objectContaining({
- question: expect.any(String),
- similarity: expect.any(Number),
- }),
- ]),
- averageSimilarity: 1,
- threshold: 0.5,
- },
- });
- expect(mockCallApi).toHaveBeenCalledWith(
- expect.stringContaining(ANSWER_RELEVANCY_GENERATE.slice(0, 50)),
- );
- expect(mockCallEmbeddingApi).toHaveBeenCalledWith('Input text');
- });
- it('should fail when the relevance score is below the threshold', async () => {
- const input = 'Input text';
- const output = 'Different output';
- const threshold = 0.5;
- const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
- mockCallApi.mockImplementation((text) => {
- return Promise.resolve({
- output: text,
- tokenUsage: { total: 10, prompt: 5, completion: 5 },
- });
- });
- const mockCallEmbeddingApi = jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi');
- mockCallEmbeddingApi.mockImplementation((text) => {
- if (text.includes('Input text')) {
- return Promise.resolve({
- embedding: [1, 0, 0],
- tokenUsage: { total: 5, prompt: 2, completion: 3 },
- });
- } else if (text.includes('Different output')) {
- return Promise.resolve({
- embedding: [0, 1, 0],
- tokenUsage: { total: 5, prompt: 2, completion: 3 },
- });
- }
- return Promise.reject(new Error(`Unexpected input ${text}`));
- });
- await expect(matchesAnswerRelevance(input, output, threshold)).resolves.toEqual({
- pass: false,
- reason: 'Relevance 0.00 is less than threshold 0.5',
- score: 0,
- tokensUsed: {
- total: expect.any(Number),
- prompt: expect.any(Number),
- completion: expect.any(Number),
- cached: expect.any(Number),
- completionDetails: expect.any(Object),
- numRequests: 0,
- },
- metadata: {
- generatedQuestions: expect.arrayContaining([
- expect.objectContaining({
- question: expect.any(String),
- similarity: expect.any(Number),
- }),
- ]),
- averageSimilarity: 0,
- threshold: 0.5,
- },
- });
- expect(mockCallApi).toHaveBeenCalledWith(
- expect.stringContaining(ANSWER_RELEVANCY_GENERATE.slice(0, 50)),
- );
- expect(mockCallEmbeddingApi).toHaveBeenCalledWith(
- expect.stringContaining(ANSWER_RELEVANCY_GENERATE.slice(0, 50)),
- );
- });
- it('tracks token usage for successful calls', async () => {
- const input = 'Input text';
- const output = 'Sample output';
- const threshold = 0.5;
- const result = await matchesAnswerRelevance(input, output, threshold);
- expect(result.tokensUsed?.total).toBeGreaterThan(0);
- expect(result.tokensUsed?.prompt).toBeGreaterThan(0);
- expect(result.tokensUsed?.completion).toBeGreaterThan(0);
- expect(result.tokensUsed?.total).toBe(
- (result.tokensUsed?.prompt || 0) + (result.tokensUsed?.completion || 0),
- );
- expect(result.tokensUsed?.total).toBe(50);
- expect(result.tokensUsed?.cached).toBe(0);
- expect(result.tokensUsed?.completionDetails).toBeDefined();
- });
- it('should return metadata with generated questions and similarities', async () => {
- const input = 'What is the capital of France?';
- const output = 'The capital of France is Paris.';
- const threshold = 0.7;
- // Mock 3 different generated questions
- let callCount = 0;
- jest.spyOn(DefaultGradingProvider, 'callApi').mockImplementation(() => {
- const questions = [
- 'What is the capital city of France?',
- 'Which city is the capital of France?',
- "What is France's capital?",
- ];
- return Promise.resolve({
- output: questions[callCount++ % 3],
- tokenUsage: { total: 10, prompt: 5, completion: 5 },
- });
- });
- // Mock embeddings with varying similarities
- jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi').mockImplementation((text) => {
- if (text === input) {
- return Promise.resolve({
- embedding: [1, 0, 0],
- tokenUsage: { total: 5, prompt: 2, completion: 3 },
- });
- } else if (text.includes('capital') && text.includes('France')) {
- // Similar questions get high similarity
- return Promise.resolve({
- embedding: [0.9, 0.1, 0],
- tokenUsage: { total: 5, prompt: 2, completion: 3 },
- });
- }
- return Promise.resolve({
- embedding: [0.8, 0.2, 0],
- tokenUsage: { total: 5, prompt: 2, completion: 3 },
- });
- });
- const result = await matchesAnswerRelevance(input, output, threshold);
- expect(result.metadata).toBeDefined();
- expect(result.metadata?.generatedQuestions).toHaveLength(3);
- expect(result.metadata?.generatedQuestions[0]).toMatchObject({
- question: expect.stringContaining('capital'),
- similarity: expect.any(Number),
- });
- expect(result.metadata?.averageSimilarity).toBeCloseTo(0.99, 2);
- expect(result.metadata?.threshold).toBe(0.7);
- expect(result.pass).toBe(true);
- });
- });
|