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

azure.test.ts

286 lines9.7 KB

1import { afterEach, describe, expect, it, vi } from 'vitest'
2​
3import { AZURE_MODELS_URL, AZURE_REASONING_URL } from '../azure-models.ts'
4import { AZURE_PRICES_URL, AZURE_PRICING_PAGE_URL } from '../azure-pricing.ts'
5import { AZURE_SPEC_URL, provider } from './azure.ts'
6​
7/** Excerpts of the two Learn articles' markdown twins (2026-10-06). */
8const MODELS = `::: zone pivot="azure-openai"
9​
10## O-Series models
11​
12| Model ID | Description | Max request (tokens) | Training data (up to) |
13| --- | --- | --- | --- |
14\`o3-deep-research\` is only available with Foundry Agent Service. The \`o9\` family is not a model.
15​
16| \`o3\` (2025-04-16) | - Chat Completions API. - Structured outputs. - Text and image processing. - Functions, tools, and parallel tool calling. | Input: 200,000 Output: 100,000 | May 31, 2024 |
17​
18## Image generation models
19​
20| Model ID | Max request (characters) |
21| --- | --- |
22| \`gpt-image-2\` | 4,000 |
23​
24::: zone-end
26​
27const REASONING = [
28 '| **Feature** | **o3**,**2025-04-16** |',
29 '| --- | --- |',
30 '| **Reasoning effort** | ✅ |',
31 '| Chat Completions API | ✅ |',
32 '',
33 "`max` works only with GPT-6 or GPT-5.6 models and the Responses API. `xhigh` works only with GPT-6, GPT-5.6, GPT-5.5, GPT-5.4, and `gpt-5.1-codex-max` models. `minimal` works only with the original GPT-5 reasoning models. `minimal` doesn't work with `gpt-5.1` or greater. **Options (model-dependent)**: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`",
34 '^5^`gpt-5-pro` only supports `reasoning_effort``high`, this is the default value even when not explicitly passed to the model.',
35 "^7^`gpt-5.6`, `gpt-5.5`, `gpt-5.4`, `gpt-5.2`, `gpt-5.1`, `gpt-5.1-codex`, `gpt-5.1-codex-max`, and `gpt-5.1-codex-mini` support `'None'` as a value for the `reasoning_effort` parameter.",
36 '^\\*^`gpt-5-codex` also does not support `reasoning_effort``minimal`.',
37].join('\n')
38​
39const CHAT_SPEC = {
40 openapi: '3.2.0',
41 paths: {
42 '/chat/completions': {
43 post: {
44 requestBody: {
45 content: {
46 'application/json': {
47 schema: {
48 properties: {
49 messages: { type: 'array' },
50 max_completion_tokens: { type: 'integer' },
51 max_tokens: {
52 description:
53 'This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with o1 series models.',
54 },
55 },
56 },
57 },
58 },
59 },
60 },
61 },
62 },
64​
65const PAGE_TWO = 'https://prices.azure.com/api/retail/prices?page=2'
66const PRICES: Record<string, unknown> = {
67 [AZURE_PRICES_URL]: {
68 Items: [
69 { skuName: 'o3 0416 Inp glbl', unitOfMeasure: '1K', retailPrice: 0.002 },
70 ],
71 NextPageLink: PAGE_TWO,
72 },
73 [PAGE_TWO]: {
74 Items: [
75 { skuName: 'o3 0416 Outp glbl', unitOfMeasure: '1K', retailPrice: 0.008 },
76 {
77 skuName: 'o3-deep research 0626-inp-glbl',
78 unitOfMeasure: '1M',
79 retailPrice: 10,
80 },
81 ],
82 NextPageLink: null,
83 },
85const PRICING_PAGE =
86 '<td>GPT-5.4 (&lt;272k context length)</td><td>GPT-5.4 (&gt;272k context length)</td>'
87​
88const originalFetch = globalThis.fetch
89​
90afterEach(() => {
91 globalThis.fetch = originalFetch
92})
93​
94function stubFetch(
95 models: string,
96 urls: Array<string> = [],
97 pricingPage = PRICING_PAGE,
98 reasoning = REASONING,
99 prices:
100 | Record<string, unknown>
101 | 'throttle-page-2'
102 | 'throttle-page-2-once' = PRICES,
103) {
104 let pageTwoCalls = 0
105 globalThis.fetch = ((input: string, init?: RequestInit) => {
106 const url = String(input)
107 urls.push(url)
108 if (url === AZURE_MODELS_URL || url === AZURE_REASONING_URL) {
109 expect(new Headers(init?.headers).get('Accept')).toBe('text/markdown')
110 return Promise.resolve(
111 new Response(url === AZURE_MODELS_URL ? models : reasoning),
112 )
113 }
114 if (url === PAGE_TWO) pageTwoCalls++
115 if (
116 url === PAGE_TWO &&
117 (prices === 'throttle-page-2' ||
118 (prices === 'throttle-page-2-once' && pageTwoCalls === 1))
119 ) {
120 return Promise.resolve(
121 new Response('Too many requests at this point. Please retry later.', {
122 status: 429,
123 statusText: 'Too Many Requests',
124 }),
125 )
126 }
127 const priceDoc =
128 prices === 'throttle-page-2' || prices === 'throttle-page-2-once'
129 ? PRICES
130 : prices
131 if (url in priceDoc) return Promise.resolve(Response.json(priceDoc[url]))
132 if (url === AZURE_PRICING_PAGE_URL) {
133 return Promise.resolve(new Response(pricingPage))
134 }
135 if (url === AZURE_SPEC_URL) {
136 return Promise.resolve(Response.json(CHAT_SPEC))
137 }
138 return Promise.reject(new Error(`unexpected fetch: ${url}`))
139 }) as typeof fetch
141​
142describe('azure', () => {
143 it('lists the tabulated models with facts, price, and sources', async () => {
144 stubFetch(MODELS)
145 const { models, docsFailures } = await provider.listModels({})
146​
147 expect(models.map((model) => [model.rawId, model.activity])).toEqual([
148 ['o3', 'chat'],
149 ['gpt-image-2', 'image'],
150 // Named in prose and metered: kept, with no facts. `o9` is dropped.
151 ['o3-deep-research', null],
152 ])
153 const o3 = models[0]
154 expect(o3).toMatchObject({
155 contextWindow: 200_000,
156 maxOutput: 100_000,
157 modalities: { input: ['text', 'image'], output: null },
158 capabilities: [
159 'reasoning',
160 'tools',
161 'structured_outputs',
162 'response_format',
163 ],
164 schemaEndpointId: 'chat/completions',
165 reasoning: {
166 mode: 'effort',
167 mandatory: null,
168 efforts: ['low', 'medium', 'high'],
169 },
170 requestMap: {
171 thinking: {
172 on: { reasoning_effort: 'high' },
173 off: null,
174 },
175 maxTokensField: 'max_completion_tokens',
176 reasoningEffort: true,
177 },
178 pricing: {
179 tables: { rate: { base: { input_tokens: 2e-6, output_tokens: 8e-6 } } },
180 },
181 })
182 expect(o3?.factSources?.pricing?.sourceUrl).toBe(AZURE_PRICES_URL)
183 expect(o3?.factSources?.maxOutput?.sourceUrl).toBe(AZURE_MODELS_URL)
184 expect(models[1]?.pricing).toBeNull()
185 expect(docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
186 })
187​
188 /** Advance the price-list retry sleeps without waiting on the clock. */
189 async function flushed<T>(promise: Promise<T>): Promise<T> {
190 void promise.catch(() => undefined)
191 await vi.runAllTimersAsync()
192 return promise
193 }
194​
195 it('retries a 429 on a later retail prices page and keeps the price', async () => {
196 const urls: Array<string> = []
197 stubFetch(MODELS, urls, PRICING_PAGE, REASONING, 'throttle-page-2-once')
198 vi.useFakeTimers()
199 try {
200 const { models, docsFailures } = await flushed(provider.listModels({}))
201​
202 expect(urls.filter((url) => url === PAGE_TWO)).toHaveLength(2)
203 expect(docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
204 expect(models[0]).toMatchObject({
205 pricing: {
206 tables: {
207 rate: { base: { input_tokens: 2e-6, output_tokens: 8e-6 } },
208 },
209 },
210 })
211 expect(models[0]?.absent).toBeUndefined()
212 } finally {
213 vi.useRealTimers()
214 }
215 })
216​
217 it('keeps the poll when every retry of a later retail prices page is throttled', async () => {
218 const urls: Array<string> = []
219 stubFetch(MODELS, urls, PRICING_PAGE, REASONING, 'throttle-page-2')
220 vi.useFakeTimers()
221 try {
222 const { models, docsFailures } = await flushed(provider.listModels({}))
223​
224 expect(urls.filter((url) => url === PAGE_TWO)).toHaveLength(5)
225 expect(models.map((model) => model.rawId)).toEqual(['o3', 'gpt-image-2'])
226 expect(models[0]).toMatchObject({
227 contextWindow: 200_000,
228 reasoning: {
229 mode: 'effort',
230 mandatory: null,
231 efforts: ['low', 'medium', 'high'],
232 },
233 absent: { pricing: 'unavailable' },
234 })
235 expect(models[0]?.pricing).toBeNull()
236 expect(docsFailures).toMatchObject({ failed: 1, skipped: 0 })
237 expect(docsFailures?.first).toHaveLength(1)
238 expect(docsFailures?.first[0]?.source).toBe(AZURE_PRICES_URL)
239 expect(docsFailures?.first[0]?.error).toContain(
240 `fetch failed after 5 attempts: ${PAGE_TWO} → 429 Too Many Requests`,
241 )
242 } finally {
243 vi.useRealTimers()
244 }
245 })
246​
247 it('reports a docs failure when the pricing page labels no threshold', async () => {
248 stubFetch(MODELS, [], '<td>GPT-5.4 Global</td>')
249 const { models, docsFailures } = await provider.listModels({})
250​
251 expect(models.map((model) => model.rawId)).toEqual(['o3', 'gpt-image-2'])
252 expect(models[0]?.absent).toEqual({ pricing: 'unavailable' })
253 expect(docsFailures?.first[0]?.error).toContain(
254 'labels no context-length threshold',
255 )
256 })
257​
258 it('throws when the reasoning article states no effort rules', async () => {
259 stubFetch(
260 MODELS,
261 [],
262 PRICING_PAGE,
263 '| **Feature** | **o3** |\n| --- |\n| **Reasoning effort** | ✅ |\n',
264 )
265 await expect(provider.listModels({})).rejects.toThrow(
266 'effort options did not parse',
267 )
268 })
269​
270 it('throws when the models article tabulates nothing', async () => {
271 stubFetch('::: zone pivot="azure-openai"\n\nNo tables.\n')
272 await expect(provider.listModels({})).rejects.toThrow('parsed 0 model rows')
273 })
274​
275 it("fetches Azure's own v1 spec and classifies its chat routes", async () => {
276 const urls: Array<string> = []
277 stubFetch(MODELS, urls)
278 const spec = await provider.fetchSpec({})
279​
280 expect(urls).toEqual([AZURE_SPEC_URL])
281 expect(spec.sources[0]?.url).toBe(AZURE_SPEC_URL)
282 expect(spec.specRevision).toBe(spec.sources[0]?.hash)
283 expect(provider.classify('/responses', {})).toBe('chat')
284 expect(provider.classify('/fine_tuning/jobs', {})).toBeNull()
285 })
286})