Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

answer-relevance.test.ts 7.1 KB

You have to be logged in to leave a comment. Sign In
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
  1. import { matchesAnswerRelevance } from '../../src/matchers';
  2. import { ANSWER_RELEVANCY_GENERATE } from '../../src/prompts';
  3. import {
  4. DefaultEmbeddingProvider,
  5. DefaultGradingProvider,
  6. } from '../../src/providers/openai/defaults';
  7. import type { OpenAiEmbeddingProvider } from '../../src/providers/openai/embedding';
  8. describe('matchesAnswerRelevance', () => {
  9. beforeEach(() => {
  10. jest.clearAllMocks();
  11. jest.resetAllMocks();
  12. jest.spyOn(DefaultGradingProvider, 'callApi').mockReset();
  13. jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi').mockReset();
  14. jest.spyOn(DefaultGradingProvider, 'callApi').mockResolvedValue({
  15. output: 'foobar',
  16. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  17. });
  18. jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi').mockResolvedValue({
  19. embedding: [1, 0, 0],
  20. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  21. });
  22. });
  23. afterEach(() => {
  24. jest.restoreAllMocks();
  25. });
  26. it('should pass when the relevance score is above the threshold', async () => {
  27. const input = 'Input text';
  28. const output = 'Sample output';
  29. const threshold = 0.5;
  30. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  31. mockCallApi.mockImplementation(() => {
  32. return Promise.resolve({
  33. output: 'foobar',
  34. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  35. });
  36. });
  37. const mockCallEmbeddingApi = jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi');
  38. mockCallEmbeddingApi.mockImplementation(function (this: OpenAiEmbeddingProvider) {
  39. return Promise.resolve({
  40. embedding: [1, 0, 0],
  41. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  42. });
  43. });
  44. await expect(matchesAnswerRelevance(input, output, threshold)).resolves.toEqual({
  45. pass: true,
  46. reason: 'Relevance 1.00 is greater than threshold 0.5',
  47. score: 1,
  48. tokensUsed: {
  49. total: expect.any(Number),
  50. prompt: expect.any(Number),
  51. completion: expect.any(Number),
  52. cached: expect.any(Number),
  53. completionDetails: expect.any(Object),
  54. numRequests: 0,
  55. },
  56. metadata: {
  57. generatedQuestions: expect.arrayContaining([
  58. expect.objectContaining({
  59. question: expect.any(String),
  60. similarity: expect.any(Number),
  61. }),
  62. ]),
  63. averageSimilarity: 1,
  64. threshold: 0.5,
  65. },
  66. });
  67. expect(mockCallApi).toHaveBeenCalledWith(
  68. expect.stringContaining(ANSWER_RELEVANCY_GENERATE.slice(0, 50)),
  69. );
  70. expect(mockCallEmbeddingApi).toHaveBeenCalledWith('Input text');
  71. });
  72. it('should fail when the relevance score is below the threshold', async () => {
  73. const input = 'Input text';
  74. const output = 'Different output';
  75. const threshold = 0.5;
  76. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  77. mockCallApi.mockImplementation((text) => {
  78. return Promise.resolve({
  79. output: text,
  80. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  81. });
  82. });
  83. const mockCallEmbeddingApi = jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi');
  84. mockCallEmbeddingApi.mockImplementation((text) => {
  85. if (text.includes('Input text')) {
  86. return Promise.resolve({
  87. embedding: [1, 0, 0],
  88. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  89. });
  90. } else if (text.includes('Different output')) {
  91. return Promise.resolve({
  92. embedding: [0, 1, 0],
  93. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  94. });
  95. }
  96. return Promise.reject(new Error(`Unexpected input ${text}`));
  97. });
  98. await expect(matchesAnswerRelevance(input, output, threshold)).resolves.toEqual({
  99. pass: false,
  100. reason: 'Relevance 0.00 is less than threshold 0.5',
  101. score: 0,
  102. tokensUsed: {
  103. total: expect.any(Number),
  104. prompt: expect.any(Number),
  105. completion: expect.any(Number),
  106. cached: expect.any(Number),
  107. completionDetails: expect.any(Object),
  108. numRequests: 0,
  109. },
  110. metadata: {
  111. generatedQuestions: expect.arrayContaining([
  112. expect.objectContaining({
  113. question: expect.any(String),
  114. similarity: expect.any(Number),
  115. }),
  116. ]),
  117. averageSimilarity: 0,
  118. threshold: 0.5,
  119. },
  120. });
  121. expect(mockCallApi).toHaveBeenCalledWith(
  122. expect.stringContaining(ANSWER_RELEVANCY_GENERATE.slice(0, 50)),
  123. );
  124. expect(mockCallEmbeddingApi).toHaveBeenCalledWith(
  125. expect.stringContaining(ANSWER_RELEVANCY_GENERATE.slice(0, 50)),
  126. );
  127. });
  128. it('tracks token usage for successful calls', async () => {
  129. const input = 'Input text';
  130. const output = 'Sample output';
  131. const threshold = 0.5;
  132. const result = await matchesAnswerRelevance(input, output, threshold);
  133. expect(result.tokensUsed?.total).toBeGreaterThan(0);
  134. expect(result.tokensUsed?.prompt).toBeGreaterThan(0);
  135. expect(result.tokensUsed?.completion).toBeGreaterThan(0);
  136. expect(result.tokensUsed?.total).toBe(
  137. (result.tokensUsed?.prompt || 0) + (result.tokensUsed?.completion || 0),
  138. );
  139. expect(result.tokensUsed?.total).toBe(50);
  140. expect(result.tokensUsed?.cached).toBe(0);
  141. expect(result.tokensUsed?.completionDetails).toBeDefined();
  142. });
  143. it('should return metadata with generated questions and similarities', async () => {
  144. const input = 'What is the capital of France?';
  145. const output = 'The capital of France is Paris.';
  146. const threshold = 0.7;
  147. // Mock 3 different generated questions
  148. let callCount = 0;
  149. jest.spyOn(DefaultGradingProvider, 'callApi').mockImplementation(() => {
  150. const questions = [
  151. 'What is the capital city of France?',
  152. 'Which city is the capital of France?',
  153. "What is France's capital?",
  154. ];
  155. return Promise.resolve({
  156. output: questions[callCount++ % 3],
  157. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  158. });
  159. });
  160. // Mock embeddings with varying similarities
  161. jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi').mockImplementation((text) => {
  162. if (text === input) {
  163. return Promise.resolve({
  164. embedding: [1, 0, 0],
  165. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  166. });
  167. } else if (text.includes('capital') && text.includes('France')) {
  168. // Similar questions get high similarity
  169. return Promise.resolve({
  170. embedding: [0.9, 0.1, 0],
  171. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  172. });
  173. }
  174. return Promise.resolve({
  175. embedding: [0.8, 0.2, 0],
  176. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  177. });
  178. });
  179. const result = await matchesAnswerRelevance(input, output, threshold);
  180. expect(result.metadata).toBeDefined();
  181. expect(result.metadata?.generatedQuestions).toHaveLength(3);
  182. expect(result.metadata?.generatedQuestions[0]).toMatchObject({
  183. question: expect.stringContaining('capital'),
  184. similarity: expect.any(Number),
  185. });
  186. expect(result.metadata?.averageSimilarity).toBeCloseTo(0.99, 2);
  187. expect(result.metadata?.threshold).toBe(0.7);
  188. expect(result.pass).toBe(true);
  189. });
  190. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...