Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

evaluate-adapter.test.ts

206 lines5.9 KB

1import { describe, expect, it, vi } from 'vitest'
2import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
3import { OpenAIEvaluateAdapter } from '../src/adapters/evaluate'
4import type { EvaluateOptions, WireQuestion } from '@tanstack/ai/adapters'
5import type { Decision } from 'openai/resources/decisions'
6import type { OpenAIEvaluateModel } from '../src/adapters/evaluate'
7​
8const testLogger = resolveDebugOption(false)
9​
10/**
11 * Test-only subclass exposing the SDK client's `decisions.create` to
12 * `vi.spyOn`, same pattern as `TestOpenAIEmbeddingAdapter`.
13 */
14class TestOpenAIEvaluateAdapter<
15 TModel extends OpenAIEvaluateModel,
16> extends OpenAIEvaluateAdapter<TModel> {
17 spyOnDecisionsCreate() {
18 return vi.spyOn(this.client.decisions, 'create')
19 }
21​
22const questions: Record<string, WireQuestion> = {
23 queue: {
24 type: 'choice',
25 instructions: 'Which team should handle this ticket?',
26 criteria: { billing: 'Payments, invoices, refunds', tech: null },
27 },
28 urgency: {
29 type: 'score',
30 instructions: 'How urgent is this ticket?',
31 criteria: ['low', 'medium', 'high'],
32 },
33 refund: {
34 type: 'noul',
35 instructions: 'Is the customer asking for a refund?',
36 },
38​
39function decision(answers: Decision['answers']): Decision {
40 return {
41 model: 'gpt-6-luna',
42 answers,
43 usage: {
44 input_tokens: 40,
45 input_tokens_details: { cache_write_tokens: 0, cached_tokens: 0 },
46 output_tokens: 0,
47 output_tokens_details: { reasoning_tokens: 0 },
48 total_tokens: 40,
49 },
50 }
52​
53const allAnswers = decision([
54 {
55 type: 'choice',
56 name: 'queue',
57 choice: 'billing',
58 probabilities: [
59 { value: 'billing', probability: 0.95 },
60 { value: 'tech', probability: 0.05 },
61 ],
62 confidence: 0.93,
63 },
64 {
65 type: 'score',
66 name: 'urgency',
67 score: 1.1,
68 probabilities: [
69 { value: 0, label: 'low', probability: 0.1 },
70 { value: 1, label: 'medium', probability: 0.7 },
71 { value: 2, label: 'high', probability: 0.2 },
72 ],
73 confidence: 0.55,
74 },
75 { type: 'predicate', name: 'refund', probability: 0.92 },
76])
77​
78function setup(response: Decision = allAnswers) {
79 const adapter = new TestOpenAIEvaluateAdapter(
80 { apiKey: 'test' },
81 'gpt-6-luna',
82 )
83 const spy = adapter.spyOnDecisionsCreate()
84 spy.mockResolvedValue(response)
85 return { adapter, spy }
87​
88function run(
89 adapter: OpenAIEvaluateAdapter<'gpt-6-luna'>,
90 state: EvaluateOptions['state'] = 'Charged twice',
91 qs: Record<string, WireQuestion> = questions,
92) {
93 return adapter.evaluate({
94 model: 'gpt-6-luna',
95 state,
96 questions: qs,
97 logger: testLogger,
98 })
100​
101describe('OpenAI evaluate adapter', () => {
102 it('sends questions as a named Decisions question array', async () => {
103 const { adapter, spy } = setup()
104 await run(adapter)
105 expect(spy.mock.calls[0]?.[0].questions).toEqual([
106 {
107 type: 'choice',
108 name: 'queue',
109 instructions: 'Which team should handle this ticket?',
110 choices: [
111 { value: 'billing', description: 'Payments, invoices, refunds' },
112 { value: 'tech' },
113 ],
114 },
115 {
116 type: 'score',
117 name: 'urgency',
118 instructions: 'How urgent is this ticket?',
119 levels: [{ label: 'low' }, { label: 'medium' }, { label: 'high' }],
120 },
121 {
122 type: 'predicate',
123 name: 'refund',
124 instructions: 'Is the customer asking for a refund?',
125 },
126 ])
127 })
128​
129 it('sends object state as JSON input', async () => {
130 const { adapter, spy } = setup()
131 await run(adapter, { subject: 'Charged twice' })
132 expect(spy.mock.calls[0]?.[0].input).toBe('{"subject":"Charged twice"}')
133 })
134​
135 it('folds predicate criteria into the instructions', async () => {
136 const { adapter, spy } = setup()
137 await run(adapter, 'Refund please', {
138 refund: {
139 type: 'noul',
140 instructions: 'Refund?',
141 criteria: { true: 'asks for money back', false: 'anything else' },
142 },
143 })
144 expect(spy.mock.calls[0]?.[0].questions[0]?.instructions).toBe(
145 'Refund?\nTrue means: asks for money back\nFalse means: anything else',
146 )
147 })
148​
149 it('maps a choice answer to the wire record', async () => {
150 const { adapter } = setup()
151 const result = await run(adapter)
152 expect(result.answers.queue).toEqual({
153 type: 'choice',
154 choice: 'billing',
155 probabilities: { billing: 0.95, tech: 0.05 },
156 confidence: 0.93,
157 })
158 })
159​
160 it('maps a score answer to legend and index-keyed probabilities', async () => {
161 const { adapter } = setup()
162 const result = await run(adapter)
163 expect(result.answers.urgency).toEqual({
164 type: 'score',
165 score: 1.1,
166 legend: { '0': 'low', '1': 'medium', '2': 'high' },
167 probabilities: { '0': 0.1, '1': 0.7, '2': 0.2 },
168 confidence: 0.55,
169 })
170 })
171​
172 it('maps a predicate answer to noul', async () => {
173 const { adapter } = setup()
174 const result = await run(adapter)
175 expect(result.answers.refund).toEqual({ type: 'noul', noul: 0.92 })
176 })
177​
178 it('maps usage tokens', async () => {
179 const { adapter } = setup()
180 const result = await run(adapter)
181 expect(result.usage).toEqual({
182 promptTokens: 40,
183 completionTokens: 0,
184 totalTokens: 40,
185 })
186 })
187​
188 it('keeps an answer for a question named __proto__ as an own key', async () => {
189 const { adapter } = setup(
190 decision([{ type: 'predicate', name: '__proto__', probability: 0.5 }]),
191 )
192 const result = await run(adapter)
193 expect(Object.keys(result.answers)).toEqual(['__proto__'])
194 })
195​
196 it('throws when a question is refused', async () => {
197 const { adapter } = setup(decision([{ type: 'refusal', name: 'refund' }]))
198 await expect(run(adapter)).rejects.toThrow('"refund"')
199 })
200​
201 it('rethrows SDK errors', async () => {
202 const { adapter, spy } = setup()
203 spy.mockRejectedValue(new Error('401 Unauthorized'))
204 await expect(run(adapter)).rejects.toThrow('401 Unauthorized')
205 })
206})