|
| 1 | +import { createTestServer } from '@ai-sdk/test-server/with-vitest'; |
| 2 | +import { describe, expect, it, vi } from 'vitest'; |
| 3 | +import { GatewayGenerationInfoFetcher } from './gateway-generation-info'; |
| 4 | +import type { FetchFunction } from '@ai-sdk/provider-utils'; |
| 5 | +import { |
| 6 | + GatewayAuthenticationError, |
| 7 | + GatewayInternalServerError, |
| 8 | + GatewayResponseError, |
| 9 | +} from './errors'; |
| 10 | + |
| 11 | +function createFetcher({ |
| 12 | + headers, |
| 13 | + fetch, |
| 14 | +}: { |
| 15 | + headers?: () => Record<string, string>; |
| 16 | + fetch?: FetchFunction; |
| 17 | +} = {}) { |
| 18 | + return new GatewayGenerationInfoFetcher({ |
| 19 | + baseURL: 'https://api.example.com', |
| 20 | + headers: headers ?? (() => ({ Authorization: 'Bearer test-token' })), |
| 21 | + fetch, |
| 22 | + }); |
| 23 | +} |
| 24 | + |
| 25 | +const mockGenerationResponse = { |
| 26 | + data: { |
| 27 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 28 | + total_cost: 0.00123, |
| 29 | + upstream_inference_cost: 0.0011, |
| 30 | + usage: 0.00123, |
| 31 | + created_at: '2024-01-01T00:00:00.000Z', |
| 32 | + model: 'gpt-4', |
| 33 | + is_byok: false, |
| 34 | + provider_name: 'openai', |
| 35 | + streamed: true, |
| 36 | + finish_reason: 'stop', |
| 37 | + latency: 200, |
| 38 | + generation_time: 1500, |
| 39 | + native_tokens_prompt: 100, |
| 40 | + native_tokens_completion: 50, |
| 41 | + native_tokens_reasoning: 0, |
| 42 | + native_tokens_cached: 0, |
| 43 | + native_tokens_cache_creation: 0, |
| 44 | + billable_web_search_calls: 0, |
| 45 | + }, |
| 46 | +}; |
| 47 | + |
| 48 | +describe('GatewayGenerationInfoFetcher', () => { |
| 49 | + const server = createTestServer({ |
| 50 | + 'https://api.example.com/*': { |
| 51 | + response: { |
| 52 | + type: 'json-value', |
| 53 | + body: mockGenerationResponse, |
| 54 | + }, |
| 55 | + }, |
| 56 | + }); |
| 57 | + |
| 58 | + describe('getGenerationInfo', () => { |
| 59 | + it('should fetch from the correct endpoint with generation ID', async () => { |
| 60 | + const fetcher = createFetcher(); |
| 61 | + |
| 62 | + await fetcher.getGenerationInfo({ |
| 63 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 64 | + }); |
| 65 | + |
| 66 | + expect(server.calls[0].requestMethod).toBe('GET'); |
| 67 | + const url = new URL(server.calls[0].requestUrl); |
| 68 | + expect(url.pathname).toBe('/v1/generation'); |
| 69 | + expect(url.searchParams.get('id')).toBe('gen_01ARZ3NDEKTSV4RRFFQ69G5FAV'); |
| 70 | + }); |
| 71 | + |
| 72 | + it('should transform snake_case response fields to camelCase', async () => { |
| 73 | + const fetcher = createFetcher(); |
| 74 | + |
| 75 | + const result = await fetcher.getGenerationInfo({ |
| 76 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 77 | + }); |
| 78 | + |
| 79 | + expect(result).toEqual({ |
| 80 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 81 | + totalCost: 0.00123, |
| 82 | + upstreamInferenceCost: 0.0011, |
| 83 | + usage: 0.00123, |
| 84 | + createdAt: '2024-01-01T00:00:00.000Z', |
| 85 | + model: 'gpt-4', |
| 86 | + isByok: false, |
| 87 | + providerName: 'openai', |
| 88 | + streamed: true, |
| 89 | + finishReason: 'stop', |
| 90 | + latency: 200, |
| 91 | + generationTime: 1500, |
| 92 | + promptTokens: 100, |
| 93 | + completionTokens: 50, |
| 94 | + reasoningTokens: 0, |
| 95 | + cachedTokens: 0, |
| 96 | + cacheCreationTokens: 0, |
| 97 | + billableWebSearchCalls: 0, |
| 98 | + }); |
| 99 | + }); |
| 100 | + |
| 101 | + it('should unwrap the data envelope', async () => { |
| 102 | + const fetcher = createFetcher(); |
| 103 | + |
| 104 | + const result = await fetcher.getGenerationInfo({ |
| 105 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 106 | + }); |
| 107 | + |
| 108 | + // Result should be the data object directly, not { data: ... } |
| 109 | + expect('data' in result).toBe(false); |
| 110 | + expect(result.id).toBe('gen_01ARZ3NDEKTSV4RRFFQ69G5FAV'); |
| 111 | + }); |
| 112 | + |
| 113 | + it('should not have snake_case fields in result', async () => { |
| 114 | + const fetcher = createFetcher(); |
| 115 | + |
| 116 | + const result = await fetcher.getGenerationInfo({ |
| 117 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 118 | + }); |
| 119 | + |
| 120 | + expect('total_cost' in result).toBe(false); |
| 121 | + expect('is_byok' in result).toBe(false); |
| 122 | + expect('provider_name' in result).toBe(false); |
| 123 | + expect('created_at' in result).toBe(false); |
| 124 | + expect('generation_time' in result).toBe(false); |
| 125 | + expect('finish_reason' in result).toBe(false); |
| 126 | + }); |
| 127 | + |
| 128 | + it('should pass headers correctly', async () => { |
| 129 | + const fetcher = createFetcher({ |
| 130 | + headers: () => ({ |
| 131 | + Authorization: 'Bearer custom-token', |
| 132 | + 'Custom-Header': 'custom-value', |
| 133 | + }), |
| 134 | + }); |
| 135 | + |
| 136 | + await fetcher.getGenerationInfo({ |
| 137 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 138 | + }); |
| 139 | + |
| 140 | + expect(server.calls[0].requestHeaders).toEqual({ |
| 141 | + authorization: 'Bearer custom-token', |
| 142 | + 'custom-header': 'custom-value', |
| 143 | + }); |
| 144 | + }); |
| 145 | + |
| 146 | + it('should handle 401 authentication errors', async () => { |
| 147 | + server.urls['https://api.example.com/*'].response = { |
| 148 | + type: 'error', |
| 149 | + status: 401, |
| 150 | + body: JSON.stringify({ |
| 151 | + error: { |
| 152 | + message: 'Unauthorized', |
| 153 | + type: 'authentication_error', |
| 154 | + }, |
| 155 | + }), |
| 156 | + }; |
| 157 | + |
| 158 | + const fetcher = createFetcher(); |
| 159 | + |
| 160 | + try { |
| 161 | + await fetcher.getGenerationInfo({ |
| 162 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 163 | + }); |
| 164 | + expect.fail('Should have thrown an error'); |
| 165 | + } catch (error) { |
| 166 | + expect(GatewayAuthenticationError.isInstance(error)).toBe(true); |
| 167 | + const authError = error as GatewayAuthenticationError; |
| 168 | + expect(authError.statusCode).toBe(401); |
| 169 | + } |
| 170 | + }); |
| 171 | + |
| 172 | + it('should handle 500 internal server errors', async () => { |
| 173 | + server.urls['https://api.example.com/*'].response = { |
| 174 | + type: 'error', |
| 175 | + status: 500, |
| 176 | + body: JSON.stringify({ |
| 177 | + error: { |
| 178 | + message: 'Failed to retrieve usage data', |
| 179 | + type: 'internal_server_error', |
| 180 | + }, |
| 181 | + }), |
| 182 | + }; |
| 183 | + |
| 184 | + const fetcher = createFetcher(); |
| 185 | + |
| 186 | + await expect( |
| 187 | + fetcher.getGenerationInfo({ |
| 188 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 189 | + }), |
| 190 | + ).rejects.toThrow(GatewayInternalServerError); |
| 191 | + }); |
| 192 | + |
| 193 | + it('should handle malformed JSON error responses', async () => { |
| 194 | + server.urls['https://api.example.com/*'].response = { |
| 195 | + type: 'error', |
| 196 | + status: 500, |
| 197 | + body: '{ invalid json', |
| 198 | + }; |
| 199 | + |
| 200 | + const fetcher = createFetcher(); |
| 201 | + |
| 202 | + try { |
| 203 | + await fetcher.getGenerationInfo({ |
| 204 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 205 | + }); |
| 206 | + expect.fail('Should have thrown an error'); |
| 207 | + } catch (error) { |
| 208 | + expect(GatewayResponseError.isInstance(error)).toBe(true); |
| 209 | + const responseError = error as GatewayResponseError; |
| 210 | + expect(responseError.statusCode).toBe(500); |
| 211 | + } |
| 212 | + }); |
| 213 | + |
| 214 | + it('should use custom fetch function when provided', async () => { |
| 215 | + const mockFetch = vi.fn().mockResolvedValue( |
| 216 | + new Response(JSON.stringify(mockGenerationResponse), { |
| 217 | + status: 200, |
| 218 | + headers: { 'Content-Type': 'application/json' }, |
| 219 | + }), |
| 220 | + ); |
| 221 | + |
| 222 | + const fetcher = createFetcher({ fetch: mockFetch }); |
| 223 | + |
| 224 | + const result = await fetcher.getGenerationInfo({ |
| 225 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 226 | + }); |
| 227 | + |
| 228 | + expect(mockFetch).toHaveBeenCalled(); |
| 229 | + expect(result.totalCost).toBe(0.00123); |
| 230 | + expect(result.model).toBe('gpt-4'); |
| 231 | + }); |
| 232 | + |
| 233 | + it('should encode special characters in generation ID', async () => { |
| 234 | + const fetcher = createFetcher(); |
| 235 | + |
| 236 | + await fetcher.getGenerationInfo({ |
| 237 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 238 | + }); |
| 239 | + |
| 240 | + const url = new URL(server.calls[0].requestUrl); |
| 241 | + expect(url.searchParams.get('id')).toBe('gen_01ARZ3NDEKTSV4RRFFQ69G5FAV'); |
| 242 | + }); |
| 243 | + |
| 244 | + it('should handle BYOK generation response', async () => { |
| 245 | + server.urls['https://api.example.com/*'].response = { |
| 246 | + type: 'json-value', |
| 247 | + body: { |
| 248 | + data: { |
| 249 | + ...mockGenerationResponse.data, |
| 250 | + is_byok: true, |
| 251 | + upstream_inference_cost: 0.0009, |
| 252 | + provider_name: 'anthropic', |
| 253 | + model: 'claude-sonnet-4', |
| 254 | + }, |
| 255 | + }, |
| 256 | + }; |
| 257 | + |
| 258 | + const fetcher = createFetcher(); |
| 259 | + const result = await fetcher.getGenerationInfo({ |
| 260 | + id: 'gen_01ARZ3NDEKTSV4RRFFQ69G5FAV', |
| 261 | + }); |
| 262 | + |
| 263 | + expect(result.isByok).toBe(true); |
| 264 | + expect(result.upstreamInferenceCost).toBe(0.0009); |
| 265 | + expect(result.providerName).toBe('anthropic'); |
| 266 | + }); |
| 267 | + }); |
| 268 | +}); |
0 commit comments