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

azure.ts

181 lines5.6 KB

1/**
2 * Azure OpenAI. Models and their facts come from two Microsoft Learn
3 * articles, prices from the Azure Retail Prices API, and schemas from the
4 * v1 OpenAPI document in Azure's REST API specs repo. All four are public.
5 * Deployment lists on a resource need a key and are not called.
6 */
7import {
8 AZURE_MODELS_URL,
9 AZURE_REASONING_URL,
10 azureChatMaxTokensField,
11 azureModelInfo,
12 parseAzureEffortRules,
13 parseAzureFeatureMatrix,
14 parseAzureModels,
15} from '../azure-models.ts'
16import {
17 AZURE_PRICES_URL,
18 azureMetered,
19 azureModelPricing,
20 fetchAzurePrices,
21} from '../azure-pricing.ts'
22import {
23 assertParsed,
24 cachedDocs,
25 docsReport,
26 docsRun,
27 tryDocs,
28 unavailable,
29} from '../model-facts.ts'
30import { classifyOpenAiCompat } from '../openai-compat.ts'
31import { fetchOpenApi, fetchText, sha256Text } from '../types.ts'
32import type {
33 ListModelsResult,
34 ProviderConfig,
35 ProviderSecrets,
36 SpecFetchResult,
37} from '../types.ts'
38​
39export const AZURE_SPEC_URL =
40 'https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/ai/data-plane/OpenAI.v1/azure-v1-v1-generated.json'
41​
42/** A Learn article as markdown, parsed, with the hash of what was read. */
43function learnDoc<T>(
44 kv: KVNamespace | undefined,
45 url: string,
46 parse: (markdown: string) => Map<string, T>,
47): Promise<{ rows: Record<string, T>; hash: string }> {
48 return cachedDocs(kv, url, async () => {
49 const markdown = await fetchText(url, {
50 headers: { Accept: 'text/markdown' },
51 })
52 const rows = parse(markdown)
53 assertParsed(rows, `azure ${url}`)
54 return { rows: Object.fromEntries(rows), hash: await sha256Text(markdown) }
55 })
57​
58async function listModels(
59 _env: ProviderSecrets,
60 kv?: KVNamespace,
61): Promise<ListModelsResult> {
62 const docs = docsRun()
63 const [models, reasoning, prices, chatTokens] = await Promise.all([
64 learnDoc(kv, AZURE_MODELS_URL, parseAzureModels),
65 cachedDocs(kv, AZURE_REASONING_URL, async () => {
66 const markdown = await fetchText(AZURE_REASONING_URL, {
67 headers: { Accept: 'text/markdown' },
68 })
69 const matrix = parseAzureFeatureMatrix(markdown)
70 assertParsed(matrix, `azure ${AZURE_REASONING_URL}`)
71 return {
72 rows: Object.fromEntries(matrix),
73 rules: parseAzureEffortRules(markdown),
74 columnIds: [...matrix.keys()],
75 hash: await sha256Text(markdown),
76 }
77 }),
78 // One throttled page throws. That keeps the stored cards; the next
79 // poll is the retry. The models article stays outside this wrapper.
80 tryDocs(docs, AZURE_PRICES_URL, (cached) =>
81 cached(kv, AZURE_PRICES_URL, fetchAzurePrices),
82 ),
83 cachedDocs(kv, AZURE_SPEC_URL, async () => {
84 const { spec, hash } = await fetchOpenApi(AZURE_SPEC_URL)
85 return { maxTokensField: azureChatMaxTokensField(spec), hash }
86 }),
87 ])
88 const hashes = { models: models.hash, reasoning: reasoning.hash }
89 const columnIds = new Set(reasoning.columnIds)
90 const tabulated = Object.values(models.rows)
91 .filter((row) => row.tabulated)
92 .map((row) => row.rawId)
93 return {
94 models: Object.values(models.rows)
95 .filter(
96 (row) =>
97 row.tabulated ||
98 (prices !== null &&
99 azureMetered(prices.meters, row.rawId, tabulated)),
100 )
101 .map((row) => {
102 const info = azureModelInfo(row, reasoning.rows[row.rawId], hashes, {
103 rules: reasoning.rules,
104 columnIds,
105 chatMaxTokens: chatTokens.maxTokensField,
106 })
107 if (row.activity !== 'chat') return info
108 if (!prices) return { ...info, ...unavailable('pricing') }
109 const priced = azureModelPricing(prices, row.rawId, row.version)
110 return {
111 ...info,
112 ...priced,
113 factSources: { ...info.factSources, ...priced.factSources },
114 }
115 }),
116 docsFailures: docsReport(docs),
117 }
119​
120async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
121 const { spec, hash } = await fetchOpenApi(AZURE_SPEC_URL)
122 return {
123 specs: [spec],
124 sources: [{ url: AZURE_SPEC_URL, hash }],
125 outputStrategy: 'post-200',
126 // Floating `main` URL: the document hash is the revision id.
127 specRevision: hash,
128 }
130​
131export const provider: ProviderConfig = {
132 id: 'azure',
133 // Azure OpenAI serves OpenAI models under OpenAI's ids; an id with no
134 // OpenAI row simply stays unlinked.
135 upstreamModelIdentity: (rawId) => ({
136 providerNamespace: 'openai',
137 rawId,
138 source: {
139 derivation: 'docs-derived',
140 sourceUrl: AZURE_MODELS_URL,
141 path: 'model id',
142 },
143 }),
144 displayName: 'Azure OpenAI',
145 specSourceUrl: AZURE_SPEC_URL,
146 modelsEndpoint: AZURE_MODELS_URL,
147 defaultDerivation: 'upstream-spec',
148 // Azure's v1 data plane: https://{resource}.openai.azure.com/openai/v1.
149 // Either an `api-key` header or a Microsoft Entra bearer token.
150 connect: {
151 servers: [
152 {
153 url: 'https://{resource}.openai.azure.com/openai/v1',
154 variables: {
155 resource: {
156 default: 'my-resource',
157 description: 'The Azure OpenAI resource name.',
158 },
159 },
160 },
161 ],
162 securitySchemes: {
163 apiKey: {
164 type: 'apiKey',
165 in: 'header',
166 name: 'api-key',
167 description: 'An Azure OpenAI resource key.',
168 },
169 bearerAuth: {
170 type: 'http',
171 scheme: 'bearer',
172 description:
173 'A Microsoft Entra token for https://cognitiveservices.azure.com/.default as `Authorization: Bearer <token>`.',
174 },
175 },
176 security: [{ apiKey: [] }, { bearerAuth: [] }],
177 },
178 fetchSpec,
179 listModels,
180 classify: classifyOpenAiCompat,