Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
3import { createCloudflareDecider } from '../src/adapters/evaluate'
4import type { WireQuestion } from '@tanstack/ai'
5import type { CloudflareGatewayOptions } from '../src/utils/config'
6
7const logger = resolveDebugOption(false)
8
9const MODEL = 'typesafe/jev'
10
11const state = { subject: 'Invoice 1842' }
12
13const questions = {
14 queue: {
15 type: 'choice',
16 instructions: 'Which team should handle this ticket?',
17 criteria: {
18 billing: 'Payments, invoices, refunds',
19 tech: 'Bugs, outages, integrations',
20 },
21 },
22 urgency: {
23 type: 'score',
24 instructions: 'How urgent is this ticket?',
25 criteria: ['low', 'medium', 'high'],
26 },
27 refund: {
28 type: 'noul',
29 instructions: 'Is the customer asking for a refund?',
30 },
31} satisfies Record<string, WireQuestion>
32
33const answers = {
34 queue: {
35 type: 'choice',
36 choice: 'billing',
37 probabilities: { billing: 0.82, tech: 0.18 },
38 confidence: 0.91,
39 },
40 urgency: {
41 type: 'score',
42 score: 1.6,
43 confidence: 0.78,
44 legend: { '0': 'low', '1': 'medium', '2': 'high' },
45 probabilities: { '0': 0.05, '1': 0.3, '2': 0.65 },
46 },
47 refund: {
48 type: 'noul',
49 noul: 0.81,
50 },
51}
52
53function createRestDecider(
54 fetchMock: typeof fetch,
55 gateway?: CloudflareGatewayOptions,
56) {
57 return createCloudflareDecider(MODEL, {
58 accountId: 'acc',
59 apiKey: 'tok',
60 fetch: fetchMock,
61 ...(gateway ? { gateway } : {}),
62 })
63}
64
65function evaluate(adapter: ReturnType<typeof createRestDecider>) {
66 return adapter.evaluate({
67 model: MODEL,
68 state,
69 questions,
70 logger,
71 })
72}
73
74describe('evaluate adapter', () => {
75 it('maps TypeSafe answers and usage from a REST 200 and forwards gateway headers', async () => {
76 const fetchMock = vi.fn<typeof fetch>(async () =>
77 Response.json({
78 success: true,
79 result: {
80 model: 'jev-1.13.0',
81 answers,
82 usage: { input_tokens: 12, output_tokens: 4 },
83 },
84 }),
85 )
86 const adapter = createRestDecider(fetchMock, {
87 id: 'g1',
88 skipCache: true,
89 })
90
91 const result = await evaluate(adapter)
92
93 expect(result).toEqual({
94 model: 'jev-1.13.0',
95 answers: {
96 queue: {
97 type: 'choice',
98 choice: 'billing',
99 probabilities: { billing: 0.82, tech: 0.18 },
100 confidence: 0.91,
101 },
102 urgency: {
103 type: 'score',
104 score: 1.6,
105 confidence: 0.78,
106 legend: { '0': 'low', '1': 'medium', '2': 'high' },
107 probabilities: { '0': 0.05, '1': 0.3, '2': 0.65 },
108 },
109 refund: {
110 type: 'noul',
111 noul: 0.81,
112 },
113 },
114 usage: {
115 promptTokens: 12,
116 completionTokens: 4,
117 totalTokens: 16,
118 },
119 })
120
121 expect(fetchMock).toHaveBeenCalledTimes(1)
122 const call = fetchMock.mock.calls[0]
123 if (!call) {
124 throw new Error('expected fetch to be called')
125 }
126 const [url, init] = call
127 expect(String(url)).toBe(
128 'https://api.cloudflare.com/client/v4/accounts/acc/ai/run/typesafe/jev',
129 )
130 expect(init?.method).toBe('POST')
131 const body = init?.body
132 if (typeof body !== 'string') {
133 throw new Error('expected a JSON string body')
134 }
135 expect(JSON.parse(body)).toEqual({
136 state: { subject: 'Invoice 1842' },
137 questions: {
138 queue: {
139 type: 'choice',
140 instructions: 'Which team should handle this ticket?',
141 criteria: {
142 billing: 'Payments, invoices, refunds',
143 tech: 'Bugs, outages, integrations',
144 },
145 },
146 urgency: {
147 type: 'score',
148 instructions: 'How urgent is this ticket?',
149 criteria: ['low', 'medium', 'high'],
150 },
151 refund: {
152 type: 'noul',
153 instructions: 'Is the customer asking for a refund?',
154 },
155 },
156 })
157 const headers = new Headers(init?.headers)
158 expect(headers.get('authorization')).toBe('Bearer tok')
159 expect(headers.get('cf-aig-gateway-id')).toBe('g1')
160 expect(headers.get('cf-aig-skip-cache')).toBe('true')
161 })
162
163 it('throws when Workers AI returns an error status', async () => {
164 const fetchMock = vi.fn<typeof fetch>(
165 async () => new Response('nope', { status: 502 }),
166 )
167 const adapter = createRestDecider(fetchMock)
168
169 await expect(evaluate(adapter)).rejects.toThrow(
170 'Workers AI request for typesafe/jev failed (502): nope',
171 )
172 })
173})