@sixb/azure-ai-foundry 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +218 -0
- package/dist/accounting.d.ts +5 -0
- package/dist/accounting.d.ts.map +1 -0
- package/dist/catalog.d.ts +29 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/chat-accounting.d.ts +4 -0
- package/dist/chat-accounting.d.ts.map +1 -0
- package/dist/chat-request.d.ts +18 -0
- package/dist/chat-request.d.ts.map +1 -0
- package/dist/diagnostics.d.ts +10 -0
- package/dist/diagnostics.d.ts.map +1 -0
- package/dist/discovery.d.ts +63 -0
- package/dist/discovery.d.ts.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1898 -0
- package/dist/index.js.map +25 -0
- package/dist/messages-accounting.d.ts +5 -0
- package/dist/messages-accounting.d.ts.map +1 -0
- package/dist/messages-request.d.ts +11 -0
- package/dist/messages-request.d.ts.map +1 -0
- package/dist/messages-schema.d.ts +4 -0
- package/dist/messages-schema.d.ts.map +1 -0
- package/dist/provider.d.ts +64 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/publisher.d.ts +7 -0
- package/dist/publisher.d.ts.map +1 -0
- package/dist/request.d.ts +20 -0
- package/dist/request.d.ts.map +1 -0
- package/dist/resolution.d.ts +36 -0
- package/dist/resolution.d.ts.map +1 -0
- package/dist/structured-output.d.ts +4 -0
- package/dist/structured-output.d.ts.map +1 -0
- package/dist/transport.d.ts +30 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/tsconfig.json +5 -0
- package/dist/util.d.ts +6 -0
- package/dist/util.d.ts.map +1 -0
- package/package.json +54 -0
- package/src/accounting.ts +117 -0
- package/src/catalog.ts +328 -0
- package/src/chat-accounting.ts +134 -0
- package/src/chat-request.ts +161 -0
- package/src/diagnostics.ts +34 -0
- package/src/discovery.ts +385 -0
- package/src/index.ts +17 -0
- package/src/messages-accounting.ts +105 -0
- package/src/messages-request.ts +164 -0
- package/src/messages-schema.ts +101 -0
- package/src/provider.ts +416 -0
- package/src/publisher.ts +34 -0
- package/src/request.ts +266 -0
- package/src/resolution.ts +179 -0
- package/src/structured-output.ts +135 -0
- package/src/transport.ts +268 -0
- package/src/util.ts +16 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1898 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/provider.ts
|
|
3
|
+
import {
|
|
4
|
+
assertJsonObject,
|
|
5
|
+
ModelCatalogUnavailableError as ModelCatalogUnavailableError3,
|
|
6
|
+
ModelProviderError as ModelProviderError4,
|
|
7
|
+
UnsupportedModelFeatureError as UnsupportedModelFeatureError5
|
|
8
|
+
} from "@sixb/core/models";
|
|
9
|
+
import { chatEvents } from "@sixb/model-protocols/chat";
|
|
10
|
+
import { messagesEvents } from "@sixb/model-protocols/messages";
|
|
11
|
+
import { responsesEvents } from "@sixb/model-protocols/responses";
|
|
12
|
+
|
|
13
|
+
// src/accounting.ts
|
|
14
|
+
import {
|
|
15
|
+
defineModelRateCard,
|
|
16
|
+
estimateModelReservation,
|
|
17
|
+
rateModelCall
|
|
18
|
+
} from "@sixb/core/models";
|
|
19
|
+
import { responsesUsage } from "@sixb/model-protocols/responses";
|
|
20
|
+
|
|
21
|
+
// src/util.ts
|
|
22
|
+
import { isJsonObject } from "@sixb/core/models";
|
|
23
|
+
var PREFIX = "[SixbAzureAIFoundry]";
|
|
24
|
+
function object(value) {
|
|
25
|
+
return isJsonObject(value) ? value : undefined;
|
|
26
|
+
}
|
|
27
|
+
function positiveInteger(value, field) {
|
|
28
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {
|
|
29
|
+
throw new TypeError(`${PREFIX} ${field} must be a positive safe integer.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function counter(value) {
|
|
33
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// src/accounting.ts
|
|
37
|
+
function foundryUsage(raw, reliableReasoning) {
|
|
38
|
+
const usage = responsesUsage(raw);
|
|
39
|
+
const { reasoningOutputTokens, ...totals } = usage;
|
|
40
|
+
const cached = usage.cacheReadInputTokens;
|
|
41
|
+
const input = usage.inputTokens;
|
|
42
|
+
const output = usage.outputTokens;
|
|
43
|
+
const knownReasoning = reasoningOutputTokens !== undefined && output !== undefined && reasoningOutputTokens <= output && (reliableReasoning === true || reliableReasoning === undefined && reasoningOutputTokens > 0);
|
|
44
|
+
return {
|
|
45
|
+
...totals,
|
|
46
|
+
...object(raw?.input_tokens_details)?.cache_write_tokens === 0 ? { cacheWriteInputTokens: 0 } : {},
|
|
47
|
+
...input !== undefined && cached !== undefined && cached <= input && onlyTokenMeters(raw) ? { uncachedInputTokens: input - cached } : {},
|
|
48
|
+
...knownReasoning ? { reasoningOutputTokens } : {},
|
|
49
|
+
...knownReasoning && reasoningOutputTokens !== undefined && output !== undefined && reasoningOutputTokens <= output && onlyTokenMeters(raw) ? { textOutputTokens: output - reasoningOutputTokens } : {}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function foundryEstimator(card, request, modelName, modelVersion, aliases) {
|
|
53
|
+
return tokenEstimator(card, request, ["temperature", "top_p", "metadata"], onlyTokenMeters, modelName, modelVersion, aliases);
|
|
54
|
+
}
|
|
55
|
+
function tokenEstimator(card, request, requestKeys, tokenMeters, modelName, modelVersion, aliases) {
|
|
56
|
+
const rateCard = card && defineModelRateCard(card);
|
|
57
|
+
const fixed = Object.keys(request ?? {}).every((key) => requestKeys.includes(key));
|
|
58
|
+
return {
|
|
59
|
+
estimateReservation: (tokens) => fixed ? estimateModelReservation({ ...tokens, rateCard }) : undefined,
|
|
60
|
+
estimate: ({ usage, responseModelId, route }) => {
|
|
61
|
+
const actual = route?.modelId ?? responseModelId;
|
|
62
|
+
if (!fixed || !tokenMeters(usage.raw) || modelName && actual && !(aliases ?? [modelName, `${modelName}-${modelVersion}`]).includes(actual))
|
|
63
|
+
return { status: "unpriceable", reason: "missing-rate-card" };
|
|
64
|
+
return rateModelCall({ usage, rateCard });
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function onlyTokenMeters(raw) {
|
|
69
|
+
if (!raw)
|
|
70
|
+
return true;
|
|
71
|
+
if (Object.keys(raw).some((key) => ![
|
|
72
|
+
"input_tokens",
|
|
73
|
+
"output_tokens",
|
|
74
|
+
"total_tokens",
|
|
75
|
+
"input_tokens_details",
|
|
76
|
+
"output_tokens_details"
|
|
77
|
+
].includes(key)))
|
|
78
|
+
return false;
|
|
79
|
+
return Object.entries(object(raw.input_tokens_details) ?? {}).every(([key, value]) => key === "cached_tokens" || key === "cache_write_tokens" && value === 0) && Object.keys(object(raw.output_tokens_details) ?? {}).every((key) => key === "reasoning_tokens");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// src/catalog.ts
|
|
83
|
+
import {
|
|
84
|
+
defineLanguageModel,
|
|
85
|
+
defineModelRateCard as defineModelRateCard2,
|
|
86
|
+
MODEL_REASONING_EFFORTS,
|
|
87
|
+
ModelCatalogUnavailableError
|
|
88
|
+
} from "@sixb/core/models";
|
|
89
|
+
|
|
90
|
+
// src/publisher.ts
|
|
91
|
+
var publishers = {
|
|
92
|
+
openai: { id: "openai", name: "OpenAI" },
|
|
93
|
+
anthropic: { id: "anthropic", name: "Anthropic" },
|
|
94
|
+
deepseek: { id: "deepseek", name: "DeepSeek" },
|
|
95
|
+
meta: { id: "meta", name: "Meta" },
|
|
96
|
+
microsoft: { id: "microsoft", name: "Microsoft" },
|
|
97
|
+
mistralai: { id: "mistral", name: "Mistral AI" },
|
|
98
|
+
moonshotai: { id: "moonshotai", name: "Moonshot AI" },
|
|
99
|
+
zai: { id: "zai", name: "Z.ai" },
|
|
100
|
+
xai: { id: "spacexai", name: "xAI" },
|
|
101
|
+
fireworks: { id: "fireworks-ai", name: "Fireworks" },
|
|
102
|
+
fireworksai: { id: "fireworks-ai", name: "Fireworks" }
|
|
103
|
+
};
|
|
104
|
+
function azurePublisher(name) {
|
|
105
|
+
const key = name.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
106
|
+
return Object.hasOwn(publishers, key) ? publishers[key] : { id: name.toLowerCase().replace(/\s+/g, "-"), name };
|
|
107
|
+
}
|
|
108
|
+
function fireworksPublisher(family) {
|
|
109
|
+
if (typeof family !== "string")
|
|
110
|
+
return;
|
|
111
|
+
const group = family.split("-")[0];
|
|
112
|
+
if (group === "glm")
|
|
113
|
+
return publishers.zai;
|
|
114
|
+
if (group === "kimi")
|
|
115
|
+
return publishers.moonshotai;
|
|
116
|
+
if (group === "deepseek")
|
|
117
|
+
return publishers.deepseek;
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// src/transport.ts
|
|
122
|
+
import { ModelProviderError as ModelProviderError2 } from "@sixb/core/models";
|
|
123
|
+
|
|
124
|
+
// src/diagnostics.ts
|
|
125
|
+
import { ModelProviderError } from "@sixb/core/models";
|
|
126
|
+
|
|
127
|
+
class RequestDiagnostics {
|
|
128
|
+
secrets = new Set;
|
|
129
|
+
add(value) {
|
|
130
|
+
if (value.trim())
|
|
131
|
+
this.secrets.add(value.trim());
|
|
132
|
+
}
|
|
133
|
+
text(value) {
|
|
134
|
+
for (const secret of [...this.secrets].sort((a, b) => b.length - a.length))
|
|
135
|
+
value = value.replaceAll(secret, "[REDACTED]");
|
|
136
|
+
return value;
|
|
137
|
+
}
|
|
138
|
+
providerError(error) {
|
|
139
|
+
return new ModelProviderError(this.text(error.message), error.providerId, error.modelId, {
|
|
140
|
+
status: error.status,
|
|
141
|
+
retryable: error.retryable,
|
|
142
|
+
retryAfterMs: error.retryAfterMs,
|
|
143
|
+
code: error.code === undefined ? undefined : this.text(error.code),
|
|
144
|
+
requestId: error.requestId === undefined ? undefined : this.text(error.requestId)
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
failure(error) {
|
|
148
|
+
if (error instanceof ModelProviderError)
|
|
149
|
+
return this.providerError(error);
|
|
150
|
+
const sanitized = new Error(this.text(error instanceof Error ? error.message : String(error)));
|
|
151
|
+
sanitized.name = error instanceof Error ? this.text(error.name) : "Error";
|
|
152
|
+
return sanitized;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// src/transport.ts
|
|
157
|
+
class FoundryTransport {
|
|
158
|
+
diagnostics = new WeakMap;
|
|
159
|
+
baseUrl;
|
|
160
|
+
projectUrl;
|
|
161
|
+
options;
|
|
162
|
+
constructor(options) {
|
|
163
|
+
if (!URL.canParse(options.endpoint))
|
|
164
|
+
throw new TypeError(`${PREFIX} endpoint must be a valid project URL.`);
|
|
165
|
+
const url = new URL(options.endpoint);
|
|
166
|
+
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
167
|
+
throw new TypeError(`${PREFIX} endpoint must be an HTTP(S) project URL without credentials, query, or fragment.`);
|
|
168
|
+
}
|
|
169
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
170
|
+
if (!/^\/api\/projects\/[^/]+$/.test(path))
|
|
171
|
+
throw new TypeError(`${PREFIX} endpoint must be a Foundry project URL: https://<resource>.services.ai.azure.com/api/projects/<project>.`);
|
|
172
|
+
this.projectUrl = `${url.origin}${path}`;
|
|
173
|
+
this.baseUrl = `${this.projectUrl}/openai/v1`;
|
|
174
|
+
if (typeof options.apiKey !== "function" && (typeof options.apiKey !== "string" || !options.apiKey.trim()))
|
|
175
|
+
throw new TypeError(`${PREFIX} apiKey is required.`);
|
|
176
|
+
if (options.maxRetries !== undefined && (!Number.isSafeInteger(options.maxRetries) || options.maxRetries < 0)) {
|
|
177
|
+
throw new TypeError(`${PREFIX} maxRetries must be a nonnegative safe integer.`);
|
|
178
|
+
}
|
|
179
|
+
positiveInteger(options.maxRetryDelayMs, "maxRetryDelayMs");
|
|
180
|
+
this.options = {
|
|
181
|
+
...options,
|
|
182
|
+
headers: typeof options.headers === "function" ? options.headers : { ...options.headers }
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
async post(body, signal, providerId, modelId, protocol = "responses") {
|
|
186
|
+
const url = this.url(protocol);
|
|
187
|
+
const diagnostics = new RequestDiagnostics;
|
|
188
|
+
for (let attempt = 0;; attempt++) {
|
|
189
|
+
signal.throwIfAborted();
|
|
190
|
+
const headers = await this.headers(signal, diagnostics, protocol === "messages" ? "x-api-key" : "api-key");
|
|
191
|
+
headers.set("content-type", "application/json");
|
|
192
|
+
headers.set("accept", "text/event-stream");
|
|
193
|
+
if (protocol === "messages")
|
|
194
|
+
headers.set("anthropic-version", "2023-06-01");
|
|
195
|
+
signal.throwIfAborted();
|
|
196
|
+
const response = await abortable(async () => {
|
|
197
|
+
const result = await this.fetch(url, {
|
|
198
|
+
method: "POST",
|
|
199
|
+
redirect: "error",
|
|
200
|
+
headers,
|
|
201
|
+
body,
|
|
202
|
+
signal
|
|
203
|
+
});
|
|
204
|
+
if (signal.aborted)
|
|
205
|
+
result.body?.cancel(signal.reason).catch(() => {});
|
|
206
|
+
return result;
|
|
207
|
+
}, signal).catch((error) => {
|
|
208
|
+
if (signal.aborted)
|
|
209
|
+
throw signal.reason;
|
|
210
|
+
throw diagnostics.failure(error);
|
|
211
|
+
});
|
|
212
|
+
this.diagnostics.set(response, diagnostics);
|
|
213
|
+
if (signal.aborted) {
|
|
214
|
+
response.body?.cancel(signal.reason).catch(() => {});
|
|
215
|
+
signal.throwIfAborted();
|
|
216
|
+
}
|
|
217
|
+
if (response.ok)
|
|
218
|
+
return response;
|
|
219
|
+
const error = this.redactError(response, await httpError(response, providerId, modelId, signal));
|
|
220
|
+
if (!error.retryable || attempt >= (this.options.maxRetries ?? 2))
|
|
221
|
+
throw error;
|
|
222
|
+
await wait(Math.min(error.retryAfterMs ?? 250 * 2 ** attempt, this.options.maxRetryDelayMs ?? 60000), signal);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
redactText(response, value) {
|
|
226
|
+
return value === undefined ? undefined : this.diagnostics.get(response)?.text(value) ?? value;
|
|
227
|
+
}
|
|
228
|
+
redactError(response, error) {
|
|
229
|
+
return this.diagnostics.get(response).providerError(error);
|
|
230
|
+
}
|
|
231
|
+
redactFailure(response, error) {
|
|
232
|
+
return this.diagnostics.get(response).failure(error);
|
|
233
|
+
}
|
|
234
|
+
async headers(signal, diagnostics, keyHeader = "api-key") {
|
|
235
|
+
const headers = new Headers(await resolve(this.options.headers, signal));
|
|
236
|
+
for (const value of headers.values())
|
|
237
|
+
diagnostics.add(value);
|
|
238
|
+
for (const reserved of ["authorization", "api-key", "x-api-key"])
|
|
239
|
+
if (headers.has(reserved))
|
|
240
|
+
throw new TypeError(`${PREFIX} Use apiKey instead of '${reserved}' headers.`);
|
|
241
|
+
const key = await resolve(this.options.apiKey, signal);
|
|
242
|
+
if (typeof key !== "string" || !key.trim())
|
|
243
|
+
throw new TypeError(`${PREFIX} apiKey must resolve to a nonempty string.`);
|
|
244
|
+
diagnostics.add(key);
|
|
245
|
+
headers.set(keyHeader, key);
|
|
246
|
+
return headers;
|
|
247
|
+
}
|
|
248
|
+
fetch(url, init) {
|
|
249
|
+
return (this.options.fetch ?? fetch)(url, init);
|
|
250
|
+
}
|
|
251
|
+
url(protocol) {
|
|
252
|
+
if (protocol === "responses")
|
|
253
|
+
return `${this.baseUrl}/responses`;
|
|
254
|
+
if (protocol === "chat")
|
|
255
|
+
return `${this.baseUrl}/chat/completions`;
|
|
256
|
+
return `${new URL(this.baseUrl).origin}/anthropic/v1/messages`;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function requestId(response) {
|
|
260
|
+
return response.headers.get("apim-request-id") ?? response.headers.get("x-request-id") ?? response.headers.get("request-id") ?? undefined;
|
|
261
|
+
}
|
|
262
|
+
async function resolve(source, signal) {
|
|
263
|
+
signal.throwIfAborted();
|
|
264
|
+
if (typeof source !== "function")
|
|
265
|
+
return source;
|
|
266
|
+
return abortable(() => source(signal), signal);
|
|
267
|
+
}
|
|
268
|
+
function abortable(operation, signal) {
|
|
269
|
+
return new Promise((resolve, reject) => {
|
|
270
|
+
signal.throwIfAborted();
|
|
271
|
+
const abort = () => {
|
|
272
|
+
signal.removeEventListener("abort", abort);
|
|
273
|
+
reject(signal.reason);
|
|
274
|
+
};
|
|
275
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
276
|
+
Promise.resolve().then(() => {
|
|
277
|
+
signal.throwIfAborted();
|
|
278
|
+
return operation();
|
|
279
|
+
}).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
async function httpError(response, providerId, modelId, signal) {
|
|
283
|
+
let message = `Provider request failed with HTTP ${response.status}.`;
|
|
284
|
+
let code;
|
|
285
|
+
const reader = response.body?.getReader();
|
|
286
|
+
if (reader) {
|
|
287
|
+
const cancel = () => {
|
|
288
|
+
reader.cancel(signal.reason).catch(() => {});
|
|
289
|
+
};
|
|
290
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
291
|
+
const chunks = [];
|
|
292
|
+
let length = 0;
|
|
293
|
+
try {
|
|
294
|
+
while (length < 8192) {
|
|
295
|
+
signal.throwIfAborted();
|
|
296
|
+
const { value, done } = await abortable(() => reader.read(), signal);
|
|
297
|
+
if (done)
|
|
298
|
+
break;
|
|
299
|
+
const part = value.subarray(0, 8192 - length);
|
|
300
|
+
chunks.push(part);
|
|
301
|
+
length += part.length;
|
|
302
|
+
}
|
|
303
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
304
|
+
const error = object(object(parsed)?.error);
|
|
305
|
+
if (typeof error?.message === "string")
|
|
306
|
+
message = error.message;
|
|
307
|
+
if (typeof error?.code === "string")
|
|
308
|
+
code = error.code;
|
|
309
|
+
else if (typeof error?.type === "string")
|
|
310
|
+
code = error.type;
|
|
311
|
+
} catch {} finally {
|
|
312
|
+
signal.removeEventListener("abort", cancel);
|
|
313
|
+
reader.cancel().catch(() => {});
|
|
314
|
+
reader.releaseLock();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
signal.throwIfAborted();
|
|
318
|
+
const delay = response.headers.get("retry-after-ms") ?? response.headers.get("x-ms-retry-after-ms");
|
|
319
|
+
const retry = response.headers.get("retry-after");
|
|
320
|
+
const ms = delay !== null ? Number(delay) : retry !== null ? Number.isFinite(Number(retry)) ? Number(retry) * 1000 : Date.parse(retry) - Date.now() : undefined;
|
|
321
|
+
return new ModelProviderError2(`${PREFIX} ${message}`, providerId, modelId, {
|
|
322
|
+
status: response.status,
|
|
323
|
+
requestId: requestId(response),
|
|
324
|
+
code,
|
|
325
|
+
retryable: response.status === 408 || response.status === 429 || response.status >= 500,
|
|
326
|
+
...ms !== undefined && Number.isFinite(ms) && ms >= 0 ? { retryAfterMs: Math.ceil(ms) } : {}
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
async function wait(ms, signal) {
|
|
330
|
+
signal.throwIfAborted();
|
|
331
|
+
await new Promise((resolve, reject) => {
|
|
332
|
+
const abort = () => {
|
|
333
|
+
clearTimeout(timer);
|
|
334
|
+
reject(signal.reason);
|
|
335
|
+
};
|
|
336
|
+
const timer = setTimeout(() => {
|
|
337
|
+
signal.removeEventListener("abort", abort);
|
|
338
|
+
resolve();
|
|
339
|
+
}, ms);
|
|
340
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/catalog.ts
|
|
345
|
+
var url = "https://models.dev/api.json";
|
|
346
|
+
|
|
347
|
+
class RemoteModelsDevCatalog {
|
|
348
|
+
snapshot = [];
|
|
349
|
+
loadedAt = 0;
|
|
350
|
+
pending;
|
|
351
|
+
options;
|
|
352
|
+
constructor(options = {}) {
|
|
353
|
+
this.options = { ...options };
|
|
354
|
+
for (const [key, value] of Object.entries({
|
|
355
|
+
ttlMs: this.options.ttlMs,
|
|
356
|
+
timeoutMs: this.options.timeoutMs
|
|
357
|
+
}))
|
|
358
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value < (key === "ttlMs" ? 0 : 1)))
|
|
359
|
+
throw new TypeError(`${PREFIX} Invalid catalog ${key}.`);
|
|
360
|
+
}
|
|
361
|
+
invalidate() {
|
|
362
|
+
this.loadedAt = 0;
|
|
363
|
+
}
|
|
364
|
+
async get(name, offline = false) {
|
|
365
|
+
return (await this.lookup(offline))(name);
|
|
366
|
+
}
|
|
367
|
+
async lookup(offline = false) {
|
|
368
|
+
const models = offline ? this.snapshot : await this.load();
|
|
369
|
+
return (name) => {
|
|
370
|
+
const matches = models.filter((m) => m.catalogProvider === "azure" && m.modelName.toLowerCase() === name.toLowerCase());
|
|
371
|
+
if (matches.length)
|
|
372
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
373
|
+
if (!/^FW-/i.test(name))
|
|
374
|
+
return;
|
|
375
|
+
const identity = normalizeFireworksVersion(name.slice(3).toLowerCase());
|
|
376
|
+
const fallback = models.filter((m) => {
|
|
377
|
+
if (m.catalogProvider !== "fireworks-ai")
|
|
378
|
+
return false;
|
|
379
|
+
const suffix = /^accounts\/fireworks\/(?:models|routers)\/([^/]+)$/.exec(m.modelName.toLowerCase())?.[1];
|
|
380
|
+
return suffix !== undefined && !/(?:^|-)latest$/.test(suffix) && normalizeFireworksVersion(suffix) === identity;
|
|
381
|
+
});
|
|
382
|
+
return fallback.length === 1 ? fallback[0] : undefined;
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
load() {
|
|
386
|
+
if (this.loadedAt && Date.now() - this.loadedAt < (this.options.ttlMs ?? 3600000))
|
|
387
|
+
return Promise.resolve(this.snapshot);
|
|
388
|
+
this.pending ??= this.fetchModels().then((models) => {
|
|
389
|
+
this.snapshot = Object.freeze(models);
|
|
390
|
+
this.loadedAt = Date.now();
|
|
391
|
+
return this.snapshot;
|
|
392
|
+
}).finally(() => {
|
|
393
|
+
this.pending = undefined;
|
|
394
|
+
});
|
|
395
|
+
return this.pending;
|
|
396
|
+
}
|
|
397
|
+
async fetchModels() {
|
|
398
|
+
const signal = AbortSignal.timeout(this.options.timeoutMs ?? 1e4);
|
|
399
|
+
let text;
|
|
400
|
+
try {
|
|
401
|
+
const response = await abortable(() => (this.options.fetch ?? fetch)(url, { signal, redirect: "error" }), signal);
|
|
402
|
+
if (!response.ok || !response.body)
|
|
403
|
+
throw new Error(`HTTP ${response.status}`);
|
|
404
|
+
const reader = response.body.getReader();
|
|
405
|
+
const chunks = [];
|
|
406
|
+
let bytes = 0;
|
|
407
|
+
try {
|
|
408
|
+
for (;; ) {
|
|
409
|
+
const chunk = await abortable(() => reader.read(), signal);
|
|
410
|
+
if (chunk.done)
|
|
411
|
+
break;
|
|
412
|
+
bytes += chunk.value.length;
|
|
413
|
+
if (bytes > 32 * 1024 * 1024)
|
|
414
|
+
throw new Error("Catalog exceeds 32 MiB");
|
|
415
|
+
chunks.push(chunk.value);
|
|
416
|
+
}
|
|
417
|
+
text = Buffer.concat(chunks).toString();
|
|
418
|
+
} finally {
|
|
419
|
+
reader.cancel().catch(() => {});
|
|
420
|
+
reader.releaseLock();
|
|
421
|
+
}
|
|
422
|
+
} catch (cause) {
|
|
423
|
+
throw new ModelCatalogUnavailableError(`${PREFIX} models.dev catalog unavailable.`, { cause });
|
|
424
|
+
}
|
|
425
|
+
const root = object(JSON.parse(text));
|
|
426
|
+
if (!object(object(root?.azure)?.models))
|
|
427
|
+
throw new TypeError(`${PREFIX} models.dev response is missing azure.models.`);
|
|
428
|
+
return ["azure", "fireworks-ai"].flatMap((catalogProvider) => {
|
|
429
|
+
const providerData = root?.[catalogProvider];
|
|
430
|
+
if (providerData === undefined)
|
|
431
|
+
return [];
|
|
432
|
+
const models = object(object(providerData)?.models);
|
|
433
|
+
if (!models)
|
|
434
|
+
throw new TypeError(`${PREFIX} models.dev response is missing ${catalogProvider}.models.`);
|
|
435
|
+
return Object.entries(models).flatMap(([id, value]) => {
|
|
436
|
+
const raw = object(value);
|
|
437
|
+
if (!raw || raw.id !== id)
|
|
438
|
+
throw new TypeError(`${PREFIX} Invalid models.dev model identity.`);
|
|
439
|
+
const modalities = object(raw.modalities);
|
|
440
|
+
if (!strings(modalities?.output).includes("text"))
|
|
441
|
+
return [];
|
|
442
|
+
const limits = object(raw.limit);
|
|
443
|
+
const provider = object(raw.provider);
|
|
444
|
+
const protocol = catalogProvider === "fireworks-ai" ? "chat" : provider?.npm === "@ai-sdk/anthropic" ? "messages" : provider?.shape === "completions" || provider?.npm === "@ai-sdk/openai-compatible" ? "chat" : undefined;
|
|
445
|
+
return [
|
|
446
|
+
{
|
|
447
|
+
catalogProvider,
|
|
448
|
+
modelName: id,
|
|
449
|
+
protocol,
|
|
450
|
+
rateCard: rates(object(raw.cost), protocol),
|
|
451
|
+
definition: defineLanguageModel({
|
|
452
|
+
kind: "language",
|
|
453
|
+
providerId: "azure-ai-foundry",
|
|
454
|
+
modelId: id,
|
|
455
|
+
...typeof raw.name === "string" ? { name: raw.name } : {},
|
|
456
|
+
...catalogProvider === "fireworks-ai" ? { publisher: fireworksPublisher(raw.family) } : {},
|
|
457
|
+
contextWindow: limit(limits?.context),
|
|
458
|
+
maxInputTokens: limit(limits?.input),
|
|
459
|
+
maxOutputTokens: limit(limits?.output),
|
|
460
|
+
capabilities: {
|
|
461
|
+
...typeof raw.tool_call === "boolean" ? { localTools: raw.tool_call } : {},
|
|
462
|
+
...typeof raw.structured_output === "boolean" ? { nativeStructuredOutput: raw.structured_output } : {},
|
|
463
|
+
reasoning: reasoning(raw.reasoning, raw.reasoning_options),
|
|
464
|
+
...Array.isArray(modalities?.input) ? {
|
|
465
|
+
inputMediaTypes: strings(modalities?.input).flatMap((m) => m === "image" ? ["image/png", "image/jpeg", "image/webp", "image/gif"] : m === "pdf" ? ["application/pdf"] : [])
|
|
466
|
+
} : {}
|
|
467
|
+
}
|
|
468
|
+
})
|
|
469
|
+
}
|
|
470
|
+
];
|
|
471
|
+
});
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
function normalizeFireworksVersion(id) {
|
|
476
|
+
return id.replace(/(\d)p(?=\d)/g, "$1.");
|
|
477
|
+
}
|
|
478
|
+
function strings(value) {
|
|
479
|
+
return Array.isArray(value) ? value.filter((s) => typeof s === "string") : [];
|
|
480
|
+
}
|
|
481
|
+
function limit(value) {
|
|
482
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
|
|
483
|
+
}
|
|
484
|
+
function reasoning(supported, value) {
|
|
485
|
+
if (supported === false)
|
|
486
|
+
return false;
|
|
487
|
+
if (supported !== true && !Array.isArray(value))
|
|
488
|
+
return;
|
|
489
|
+
const options = Array.isArray(value) ? value.map(object).filter((o) => o !== undefined) : [];
|
|
490
|
+
const efforts = options.filter((o) => o?.type === "effort").flatMap((o) => strings(o?.values));
|
|
491
|
+
const budget = options.find((o) => o?.type === "budget_tokens");
|
|
492
|
+
return {
|
|
493
|
+
...options.some((o) => o?.type === "toggle") || efforts.includes("none") ? { canDisable: true } : {},
|
|
494
|
+
...efforts.length ? { efforts: MODEL_REASONING_EFFORTS.filter((e) => efforts.includes(e)) } : {},
|
|
495
|
+
...budget ? {
|
|
496
|
+
budgetTokens: {
|
|
497
|
+
...limit(budget.min) ? { min: limit(budget.min) } : {},
|
|
498
|
+
...limit(budget.max) ? { max: limit(budget.max) } : {}
|
|
499
|
+
}
|
|
500
|
+
} : {}
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
function rates(raw, protocol) {
|
|
504
|
+
const card = parseRates(raw);
|
|
505
|
+
if (protocol !== "messages" || card?.cacheWriteInput === undefined)
|
|
506
|
+
return card;
|
|
507
|
+
const { cacheWriteInput, ...rest } = card;
|
|
508
|
+
return defineModelRateCard2({ ...rest, cacheWriteInput5m: cacheWriteInput });
|
|
509
|
+
}
|
|
510
|
+
function parseRates(raw) {
|
|
511
|
+
if (!raw || raw.tiers === undefined)
|
|
512
|
+
return flatRates(raw);
|
|
513
|
+
const { tiers, context_over_200k: legacy, ...base } = raw;
|
|
514
|
+
const card = flatRates(base);
|
|
515
|
+
if (!card || !Array.isArray(tiers))
|
|
516
|
+
return;
|
|
517
|
+
const parsed = [];
|
|
518
|
+
for (const value of tiers) {
|
|
519
|
+
const entry = object(value);
|
|
520
|
+
if (!entry)
|
|
521
|
+
return;
|
|
522
|
+
const { tier, ...prices } = entry;
|
|
523
|
+
const threshold = object(tier);
|
|
524
|
+
const size = threshold?.size;
|
|
525
|
+
const tierCard = flatRates(prices);
|
|
526
|
+
if (!tierCard || !threshold || Object.keys(threshold).some((k) => k !== "type" && k !== "size") || threshold.type !== undefined && threshold.type !== "context" || typeof size !== "number" || !Number.isSafeInteger(size) || size < 0 || size >= Number.MAX_SAFE_INTEGER)
|
|
527
|
+
return;
|
|
528
|
+
parsed.push({ size, card: tierCard });
|
|
529
|
+
}
|
|
530
|
+
parsed.sort((a, b) => a.size - b.size);
|
|
531
|
+
if (new Set(parsed.map((t) => t.size)).size !== parsed.length)
|
|
532
|
+
return;
|
|
533
|
+
const keys = ["input", "output", "cacheReadInput", "cacheWriteInput"];
|
|
534
|
+
if (legacy !== undefined) {
|
|
535
|
+
const mirror = flatRates(object(legacy));
|
|
536
|
+
if (!mirror || parsed.length !== 1 || parsed[0].size < 200000 || keys.some((k) => mirror[k] !== parsed[0].card[k]))
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
if (parsed.some((t) => keys.some((k) => card[k] === undefined !== (t.card[k] === undefined))))
|
|
540
|
+
return;
|
|
541
|
+
const price = (key) => {
|
|
542
|
+
const basePrice = card[key];
|
|
543
|
+
if (basePrice === undefined || !parsed.length)
|
|
544
|
+
return basePrice;
|
|
545
|
+
if (typeof basePrice !== "string")
|
|
546
|
+
return;
|
|
547
|
+
return {
|
|
548
|
+
default: basePrice,
|
|
549
|
+
tiers: parsed.map((t, i) => ({
|
|
550
|
+
minTokens: t.size + 1,
|
|
551
|
+
...parsed[i + 1] ? { maxTokens: parsed[i + 1].size + 1 } : {},
|
|
552
|
+
price: String(t.card[key])
|
|
553
|
+
}))
|
|
554
|
+
};
|
|
555
|
+
};
|
|
556
|
+
return defineModelRateCard2({
|
|
557
|
+
currency: "USD",
|
|
558
|
+
unit: "million-tokens",
|
|
559
|
+
input: price("input"),
|
|
560
|
+
output: price("output"),
|
|
561
|
+
...card.cacheReadInput === undefined ? {} : { cacheReadInput: price("cacheReadInput") },
|
|
562
|
+
...card.cacheWriteInput === undefined ? {} : { cacheWriteInput: price("cacheWriteInput") }
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
function flatRates(raw) {
|
|
566
|
+
if (!raw)
|
|
567
|
+
return;
|
|
568
|
+
if (Object.keys(raw).some((k) => !["input", "output", "cache_read", "cache_write"].includes(k)))
|
|
569
|
+
return;
|
|
570
|
+
const decimal = (v) => (typeof v === "number" || typeof v === "string") && /^\d+(\.\d+)?$/.test(String(v)) ? String(v) : undefined;
|
|
571
|
+
const input = decimal(raw.input), output = decimal(raw.output);
|
|
572
|
+
if (input === undefined || output === undefined)
|
|
573
|
+
return;
|
|
574
|
+
const read = decimal(raw.cache_read), write = decimal(raw.cache_write);
|
|
575
|
+
if (raw.cache_read !== undefined && read === undefined || raw.cache_write !== undefined && write === undefined)
|
|
576
|
+
return;
|
|
577
|
+
return defineModelRateCard2({
|
|
578
|
+
currency: "USD",
|
|
579
|
+
unit: "million-tokens",
|
|
580
|
+
input,
|
|
581
|
+
output,
|
|
582
|
+
...read === undefined ? {} : { cacheReadInput: read },
|
|
583
|
+
...write === undefined ? {} : { cacheWriteInput: write }
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// src/chat-accounting.ts
|
|
588
|
+
function foundryChatUsage(raw, reliableReasoning) {
|
|
589
|
+
const input = counter(raw?.prompt_tokens);
|
|
590
|
+
const output = counter(raw?.completion_tokens);
|
|
591
|
+
const read = counter(object(raw?.prompt_tokens_details)?.cached_tokens);
|
|
592
|
+
const reported = reasoningTokens(raw);
|
|
593
|
+
const reasoning = reported !== undefined && reported !== false && (reliableReasoning === true || reliableReasoning === undefined && reported > 0) ? reported : undefined;
|
|
594
|
+
const known = tokenMeters(raw);
|
|
595
|
+
return {
|
|
596
|
+
...input === undefined ? {} : { inputTokens: input },
|
|
597
|
+
...output === undefined ? {} : { outputTokens: output },
|
|
598
|
+
...read === undefined ? {} : { cacheReadInputTokens: read },
|
|
599
|
+
...object(raw?.prompt_tokens_details)?.cache_write_tokens === 0 ? { cacheWriteInputTokens: 0 } : {},
|
|
600
|
+
...input !== undefined && read !== undefined && read <= input && known ? { uncachedInputTokens: input - read } : {},
|
|
601
|
+
...reasoning === undefined ? {} : { reasoningOutputTokens: reasoning },
|
|
602
|
+
...output !== undefined && reasoning !== undefined && reasoning <= output && known ? { textOutputTokens: output - reasoning } : {},
|
|
603
|
+
...raw ? { raw } : {}
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
function foundryChatEstimator(card, request, modelName, modelVersion, aliases) {
|
|
607
|
+
const estimator = tokenEstimator(card, request, ["temperature", "top_p", "metadata"], tokenMeters, modelName, modelVersion, aliases);
|
|
608
|
+
return {
|
|
609
|
+
estimateReservation: estimator.estimateReservation,
|
|
610
|
+
estimate: (input) => estimator.estimate({
|
|
611
|
+
...input,
|
|
612
|
+
usage: { ...foundryChatUsage(input.usage.raw, false), ...input.usage }
|
|
613
|
+
})
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
function tokenMeters(raw) {
|
|
617
|
+
if (!raw)
|
|
618
|
+
return true;
|
|
619
|
+
if (reasoningTokens(raw) === false)
|
|
620
|
+
return false;
|
|
621
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
622
|
+
if (["prompt_tokens", "completion_tokens", "total_tokens"].includes(key)) {
|
|
623
|
+
if (counter(value) === undefined)
|
|
624
|
+
return false;
|
|
625
|
+
} else if (key === "prompt_tokens_details" || key === "completion_tokens_details" || key === "output_tokens_details") {
|
|
626
|
+
if (value === null)
|
|
627
|
+
continue;
|
|
628
|
+
const details = object(value);
|
|
629
|
+
if (!details)
|
|
630
|
+
return false;
|
|
631
|
+
for (const [meter, count] of Object.entries(details)) {
|
|
632
|
+
if (key === "prompt_tokens_details" && meter === "cached_tokens" || key !== "prompt_tokens_details" && meter === "reasoning_tokens") {
|
|
633
|
+
if (counter(count) === undefined)
|
|
634
|
+
return false;
|
|
635
|
+
} else if (key === "prompt_tokens_details" && meter === "image_tokens") {
|
|
636
|
+
const image = counter(count);
|
|
637
|
+
const input = counter(raw.prompt_tokens);
|
|
638
|
+
if (image === undefined || input === undefined || image > input)
|
|
639
|
+
return false;
|
|
640
|
+
} else if (![
|
|
641
|
+
"audio_tokens",
|
|
642
|
+
...key === "prompt_tokens_details" ? ["cache_write_tokens"] : ["accepted_prediction_tokens", "rejected_prediction_tokens"]
|
|
643
|
+
].includes(meter) || count !== 0)
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
} else if (key !== "reasoning_tokens")
|
|
647
|
+
return false;
|
|
648
|
+
}
|
|
649
|
+
return true;
|
|
650
|
+
}
|
|
651
|
+
function reasoningTokens(raw) {
|
|
652
|
+
let result;
|
|
653
|
+
for (const value of [
|
|
654
|
+
object(raw?.completion_tokens_details)?.reasoning_tokens,
|
|
655
|
+
object(raw?.output_tokens_details)?.reasoning_tokens,
|
|
656
|
+
raw?.reasoning_tokens
|
|
657
|
+
]) {
|
|
658
|
+
if (value === undefined)
|
|
659
|
+
continue;
|
|
660
|
+
const count = counter(value);
|
|
661
|
+
const output = counter(raw?.completion_tokens);
|
|
662
|
+
if (count === undefined || output === undefined || count > output || result !== undefined && result !== count)
|
|
663
|
+
return false;
|
|
664
|
+
result = count;
|
|
665
|
+
}
|
|
666
|
+
return result;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// src/chat-request.ts
|
|
670
|
+
import {
|
|
671
|
+
modelReasoningSupportIssue as modelReasoningSupportIssue2,
|
|
672
|
+
UnsupportedModelFeatureError as UnsupportedModelFeatureError2
|
|
673
|
+
} from "@sixb/core/models";
|
|
674
|
+
import { chatInput } from "@sixb/model-protocols/chat";
|
|
675
|
+
|
|
676
|
+
// src/request.ts
|
|
677
|
+
import {
|
|
678
|
+
isJsonObject as isJsonObject3,
|
|
679
|
+
modelReasoningSupportIssue,
|
|
680
|
+
UnsupportedModelFeatureError
|
|
681
|
+
} from "@sixb/core/models";
|
|
682
|
+
import { responsesInput } from "@sixb/model-protocols/responses";
|
|
683
|
+
|
|
684
|
+
// src/structured-output.ts
|
|
685
|
+
import { isJsonObject as isJsonObject2 } from "@sixb/core/models";
|
|
686
|
+
var KEYWORDS = new Set([
|
|
687
|
+
"type",
|
|
688
|
+
"description",
|
|
689
|
+
"title",
|
|
690
|
+
"properties",
|
|
691
|
+
"required",
|
|
692
|
+
"additionalProperties",
|
|
693
|
+
"items",
|
|
694
|
+
"enum",
|
|
695
|
+
"anyOf",
|
|
696
|
+
"$ref",
|
|
697
|
+
"$defs",
|
|
698
|
+
"definitions"
|
|
699
|
+
]);
|
|
700
|
+
var TYPES = new Set(["object", "array", "string", "number", "integer", "boolean", "null"]);
|
|
701
|
+
function foundryOutputSchema(schema) {
|
|
702
|
+
let root;
|
|
703
|
+
try {
|
|
704
|
+
root = JSON.parse(JSON.stringify(schema));
|
|
705
|
+
} catch {
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
if (!isJsonObject2(root))
|
|
709
|
+
return;
|
|
710
|
+
const wire = root;
|
|
711
|
+
const counted = new Set;
|
|
712
|
+
const validated = new Map;
|
|
713
|
+
let properties = 0;
|
|
714
|
+
const reference = (ref) => {
|
|
715
|
+
if (ref === "#")
|
|
716
|
+
return wire;
|
|
717
|
+
if (!ref.startsWith("#/"))
|
|
718
|
+
return;
|
|
719
|
+
let value = wire;
|
|
720
|
+
for (const segment of ref.slice(2).split("/")) {
|
|
721
|
+
const key = segment.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
722
|
+
if (!isJsonObject2(value) || !Object.hasOwn(value, key))
|
|
723
|
+
return;
|
|
724
|
+
value = value[key];
|
|
725
|
+
}
|
|
726
|
+
return isJsonObject2(value) ? value : undefined;
|
|
727
|
+
};
|
|
728
|
+
const walk = (value, depth, active) => {
|
|
729
|
+
if (!isJsonObject2(value))
|
|
730
|
+
return false;
|
|
731
|
+
if (active.has(value))
|
|
732
|
+
return value.type === "object" || value.type === "array";
|
|
733
|
+
if (validated.get(value)?.has(depth))
|
|
734
|
+
return true;
|
|
735
|
+
if (Object.keys(value).some((key) => !KEYWORDS.has(key)))
|
|
736
|
+
return false;
|
|
737
|
+
for (const key of ["description", "title"]) {
|
|
738
|
+
if (value[key] !== undefined && typeof value[key] !== "string")
|
|
739
|
+
return false;
|
|
740
|
+
}
|
|
741
|
+
const next = new Set(active).add(value);
|
|
742
|
+
if (value.$ref !== undefined) {
|
|
743
|
+
if (typeof value.$ref !== "string" || !walk(reference(value.$ref), depth, next))
|
|
744
|
+
return false;
|
|
745
|
+
}
|
|
746
|
+
const types = typeof value.type === "string" ? [value.type] : value.type;
|
|
747
|
+
if (types !== undefined && (!Array.isArray(types) || types.length === 0 || types.some((t) => typeof t !== "string" || !TYPES.has(t)) || Array.isArray(value.type) && (types.length !== 2 || !types.includes("null") || new Set(types).size !== 2)))
|
|
748
|
+
return false;
|
|
749
|
+
const objectType = Array.isArray(types) && types.includes("object");
|
|
750
|
+
const arrayType = Array.isArray(types) && types.includes("array");
|
|
751
|
+
const level = depth + (objectType || arrayType ? 1 : 0);
|
|
752
|
+
if (level > 5)
|
|
753
|
+
return false;
|
|
754
|
+
if (objectType) {
|
|
755
|
+
if (!isJsonObject2(value.properties) || value.additionalProperties !== false || !Array.isArray(value.required))
|
|
756
|
+
return false;
|
|
757
|
+
const keys = Object.keys(value.properties);
|
|
758
|
+
const required = value.required;
|
|
759
|
+
if (required.length !== keys.length || new Set(required).size !== keys.length || keys.some((key) => !required.includes(key)))
|
|
760
|
+
return false;
|
|
761
|
+
if (!counted.has(value)) {
|
|
762
|
+
counted.add(value);
|
|
763
|
+
properties += keys.length;
|
|
764
|
+
}
|
|
765
|
+
if (properties > 100 || !Object.values(value.properties).every((child) => walk(child, level, next)))
|
|
766
|
+
return false;
|
|
767
|
+
} else if (value.properties !== undefined || value.required !== undefined || value.additionalProperties !== undefined)
|
|
768
|
+
return false;
|
|
769
|
+
if (arrayType && !walk(value.items, level, next))
|
|
770
|
+
return false;
|
|
771
|
+
if (!arrayType && value.items !== undefined)
|
|
772
|
+
return false;
|
|
773
|
+
if (value.anyOf !== undefined && (!Array.isArray(value.anyOf) || value.anyOf.length === 0 || !value.anyOf.every((child) => walk(child, level, next))))
|
|
774
|
+
return false;
|
|
775
|
+
if (value.type === undefined && value.$ref === undefined && value.anyOf === undefined)
|
|
776
|
+
return false;
|
|
777
|
+
if (value.enum !== undefined && (!Array.isArray(value.enum) || value.enum.length === 0 || value.enum.some((entry) => typeof entry === "object" && entry !== null)))
|
|
778
|
+
return false;
|
|
779
|
+
for (const key of ["$defs", "definitions"]) {
|
|
780
|
+
const definitions = value[key];
|
|
781
|
+
if (definitions !== undefined && (!isJsonObject2(definitions) || !Object.values(definitions).every((child) => walk(child, 0, next))))
|
|
782
|
+
return false;
|
|
783
|
+
}
|
|
784
|
+
const depths = validated.get(value) ?? new Set;
|
|
785
|
+
depths.add(depth);
|
|
786
|
+
validated.set(value, depths);
|
|
787
|
+
return true;
|
|
788
|
+
};
|
|
789
|
+
return wire.type === "object" && wire.anyOf === undefined && walk(wire, 0, new Set) ? schema : undefined;
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// src/request.ts
|
|
793
|
+
var SUMMARY_MODELS = new Set(["gpt-5", "gpt-5-mini", "gpt-5-nano", "o3", "o4-mini"]);
|
|
794
|
+
var RESERVED = new Set([
|
|
795
|
+
"model",
|
|
796
|
+
"input",
|
|
797
|
+
"instructions",
|
|
798
|
+
"tools",
|
|
799
|
+
"tool_choice",
|
|
800
|
+
"parallel_tool_calls",
|
|
801
|
+
"stream",
|
|
802
|
+
"store",
|
|
803
|
+
"background",
|
|
804
|
+
"conversation",
|
|
805
|
+
"previous_response_id",
|
|
806
|
+
"include",
|
|
807
|
+
"reasoning",
|
|
808
|
+
"text",
|
|
809
|
+
"max_output_tokens",
|
|
810
|
+
"truncation"
|
|
811
|
+
]);
|
|
812
|
+
function validateOptions(options) {
|
|
813
|
+
positiveInteger(options.maxOutputTokens, "maxOutputTokens");
|
|
814
|
+
positiveInteger(options.maxInputFileBytes, "maxInputFileBytes");
|
|
815
|
+
for (const key of Object.keys(options.request ?? {})) {
|
|
816
|
+
if (RESERVED.has(key))
|
|
817
|
+
throw new TypeError(`${PREFIX} Request option '${key}' is owned by the adapter.`);
|
|
818
|
+
}
|
|
819
|
+
if (options.encryptedReasoning !== undefined && typeof options.encryptedReasoning !== "boolean")
|
|
820
|
+
throw new TypeError(`${PREFIX} encryptedReasoning must be boolean.`);
|
|
821
|
+
if (options.reasoningSummary !== undefined && options.reasoningSummary !== false && !["auto", "concise", "detailed"].includes(options.reasoningSummary))
|
|
822
|
+
throw new TypeError(`${PREFIX} Invalid reasoningSummary.`);
|
|
823
|
+
}
|
|
824
|
+
function responsesRequest(request, definition, options, scope, deployment) {
|
|
825
|
+
const max = prepareRequest(request, definition, options, scope);
|
|
826
|
+
const input = responsesInput(request.messages, definition.providerId).map((item) => {
|
|
827
|
+
if (!isJsonObject3(item))
|
|
828
|
+
return item;
|
|
829
|
+
const content = Array.isArray(item.content) ? item.content.map((part) => {
|
|
830
|
+
if (isJsonObject3(part) && part.type === "input_file" && part.file_data && !part.filename)
|
|
831
|
+
return { ...part, filename: "document.pdf" };
|
|
832
|
+
return part;
|
|
833
|
+
}) : undefined;
|
|
834
|
+
return {
|
|
835
|
+
...item,
|
|
836
|
+
...content ? { content } : {},
|
|
837
|
+
...item.role !== undefined ? { type: "message" } : {}
|
|
838
|
+
};
|
|
839
|
+
});
|
|
840
|
+
const caps = definition.capabilities;
|
|
841
|
+
if (request.tools.length && caps.localTools !== true)
|
|
842
|
+
throw new UnsupportedModelFeatureError(`${PREFIX} Configure localTools capability for this deployment before using tools.`);
|
|
843
|
+
const schema = request.responseFormat && foundryOutputSchema(request.responseFormat.schema);
|
|
844
|
+
if (request.responseFormat && (caps.nativeStructuredOutput !== true || !schema)) {
|
|
845
|
+
throw new UnsupportedModelFeatureError(`${PREFIX} Structured output requires a declared capability and an Azure-compatible strict schema (100 properties, five levels, closed objects, all properties required).`);
|
|
846
|
+
}
|
|
847
|
+
const reasoning = request.reasoning;
|
|
848
|
+
const summary = options.reasoningSummary ?? (reasoning !== "none" && caps.reasoning && deployment?.modelPublisher.toLowerCase() === "openai" && SUMMARY_MODELS.has(deployment.modelName.toLowerCase()) ? "auto" : undefined);
|
|
849
|
+
if (reasoning !== undefined && reasoning !== "provider-default") {
|
|
850
|
+
const issue = modelReasoningSupportIssue(caps.reasoning, reasoning);
|
|
851
|
+
if (typeof reasoning !== "string" || caps.reasoning === undefined || issue) {
|
|
852
|
+
throw new UnsupportedModelFeatureError(`${PREFIX} ${issue ?? "Responses reasoning requires declared named efforts; exact token budgets are unsupported"}.`);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
if (summary && (!caps.reasoning || typeof caps.reasoning !== "object"))
|
|
856
|
+
throw new UnsupportedModelFeatureError(`${PREFIX} Reasoning summaries require a declared reasoning capability.`);
|
|
857
|
+
const tools = request.tools.map((tool) => ({
|
|
858
|
+
type: "function",
|
|
859
|
+
name: tool.name,
|
|
860
|
+
description: tool.description,
|
|
861
|
+
parameters: tool.inputSchema,
|
|
862
|
+
strict: caps.nativeStructuredOutput === true && foundryOutputSchema(tool.inputSchema) !== undefined
|
|
863
|
+
}));
|
|
864
|
+
return {
|
|
865
|
+
...options.request,
|
|
866
|
+
model: definition.modelId,
|
|
867
|
+
input,
|
|
868
|
+
stream: true,
|
|
869
|
+
store: false,
|
|
870
|
+
...options.encryptedReasoning === false ? {} : { include: ["reasoning.encrypted_content"] },
|
|
871
|
+
...max === undefined ? {} : { max_output_tokens: max },
|
|
872
|
+
...tools.length ? {
|
|
873
|
+
tools,
|
|
874
|
+
tool_choice: "auto",
|
|
875
|
+
parallel_tool_calls: !schema && !tools.some((t) => t.strict) && caps.parallelToolCalls === true
|
|
876
|
+
} : {},
|
|
877
|
+
...reasoning !== undefined && reasoning !== "provider-default" || summary ? {
|
|
878
|
+
reasoning: {
|
|
879
|
+
...reasoning === undefined || reasoning === "provider-default" ? {} : { effort: reasoning },
|
|
880
|
+
...summary ? { summary } : {}
|
|
881
|
+
}
|
|
882
|
+
} : {},
|
|
883
|
+
...schema && request.responseFormat ? {
|
|
884
|
+
text: {
|
|
885
|
+
format: {
|
|
886
|
+
type: "json_schema",
|
|
887
|
+
name: request.responseFormat.name,
|
|
888
|
+
schema,
|
|
889
|
+
strict: true,
|
|
890
|
+
...request.responseFormat.description === undefined ? {} : { description: request.responseFormat.description }
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
} : {}
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
function prepareRequest(request, definition, options, scope, remotePdf = false) {
|
|
897
|
+
positiveInteger(request.maxOutputTokens, "maxOutputTokens");
|
|
898
|
+
validateMessages(request.messages, definition, options.maxInputFileBytes ?? 20 * 1024 * 1024, scope, remotePdf);
|
|
899
|
+
const limits = [
|
|
900
|
+
definition.maxOutputTokens,
|
|
901
|
+
options.maxOutputTokens,
|
|
902
|
+
request.maxOutputTokens
|
|
903
|
+
].filter((n) => n !== undefined);
|
|
904
|
+
return limits.length ? Math.min(...limits) : undefined;
|
|
905
|
+
}
|
|
906
|
+
function validateMessages(messages, definition, budget, scope, remotePdf = false) {
|
|
907
|
+
let bytes = 0;
|
|
908
|
+
for (const message of messages) {
|
|
909
|
+
if (message.role === "system") {
|
|
910
|
+
checkScope(message.providerData?.[definition.providerId], scope);
|
|
911
|
+
continue;
|
|
912
|
+
}
|
|
913
|
+
for (const part of message.content) {
|
|
914
|
+
if (part.type === "provider-state") {
|
|
915
|
+
if (part.providerId === definition.providerId)
|
|
916
|
+
checkScope(part.data, scope);
|
|
917
|
+
continue;
|
|
918
|
+
}
|
|
919
|
+
checkScope(part.providerData?.[definition.providerId], scope);
|
|
920
|
+
if (part.type !== "file")
|
|
921
|
+
continue;
|
|
922
|
+
const allowed = definition.capabilities.inputMediaTypes;
|
|
923
|
+
const media = part.mediaType;
|
|
924
|
+
if (!["application/pdf", "image/png", "image/jpeg", "image/webp", "image/gif"].includes(media) || !(allowed === "any" || allowed?.some((type) => type === media || type === "image/*" && media.startsWith("image/")))) {
|
|
925
|
+
throw new UnsupportedModelFeatureError(`${PREFIX} Input media '${media}' is not supported by this deployment's configured capabilities.`);
|
|
926
|
+
}
|
|
927
|
+
if (part.data.username || part.data.password)
|
|
928
|
+
throw new TypeError(`${PREFIX} File URLs must not contain credentials.`);
|
|
929
|
+
if (part.data.protocol !== "data:") {
|
|
930
|
+
if (!remotePdf && media === "application/pdf" || !["https:", "http:"].includes(part.data.protocol))
|
|
931
|
+
throw new UnsupportedModelFeatureError(`${PREFIX} ${remotePdf ? "Use inline base64 or HTTP(S) images/PDFs." : "Use an inline base64 PDF or an HTTP(S)/base64 image."}`);
|
|
932
|
+
continue;
|
|
933
|
+
}
|
|
934
|
+
const match = /^data:([^;,]+);base64,([A-Za-z0-9+/]*={0,2})$/.exec(part.data.href);
|
|
935
|
+
if (!match || match[1] !== media || !match[2] || match[2].length % 4 !== 0)
|
|
936
|
+
throw new TypeError(`${PREFIX} File data must be canonical base64 with a matching media type.`);
|
|
937
|
+
const data = match[2];
|
|
938
|
+
bytes += data.length / 4 * 3 - (data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0);
|
|
939
|
+
if (bytes > budget)
|
|
940
|
+
throw new RangeError(`${PREFIX} Inline files exceed maxInputFileBytes (${budget}).`);
|
|
941
|
+
if (Buffer.from(data, "base64").toString("base64") !== data)
|
|
942
|
+
throw new TypeError(`${PREFIX} File data must use canonical base64.`);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
function checkScope(data, scope) {
|
|
947
|
+
if (data !== undefined && object(data)?.scope !== scope) {
|
|
948
|
+
throw new UnsupportedModelFeatureError(`${PREFIX} Replay state belongs to a different endpoint, deployment, or protocol.`);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
// src/chat-request.ts
|
|
953
|
+
var RESERVED2 = new Set([
|
|
954
|
+
"model",
|
|
955
|
+
"messages",
|
|
956
|
+
"stream",
|
|
957
|
+
"stream_options",
|
|
958
|
+
"n",
|
|
959
|
+
"tools",
|
|
960
|
+
"tool_choice",
|
|
961
|
+
"parallel_tool_calls",
|
|
962
|
+
"functions",
|
|
963
|
+
"function_call",
|
|
964
|
+
"response_format",
|
|
965
|
+
"max_tokens",
|
|
966
|
+
"max_completion_tokens",
|
|
967
|
+
"reasoning_effort",
|
|
968
|
+
"thinking",
|
|
969
|
+
"reasoning",
|
|
970
|
+
"modalities",
|
|
971
|
+
"audio",
|
|
972
|
+
"store"
|
|
973
|
+
]);
|
|
974
|
+
function validateChatOptions(options) {
|
|
975
|
+
positiveInteger(options.maxOutputTokens, "maxOutputTokens");
|
|
976
|
+
positiveInteger(options.maxInputFileBytes, "maxInputFileBytes");
|
|
977
|
+
for (const key of Object.keys(options.request ?? {}))
|
|
978
|
+
if (RESERVED2.has(key))
|
|
979
|
+
throw new TypeError(`${PREFIX} Chat request option '${key}' is owned by the adapter.`);
|
|
980
|
+
for (const [key, allowed] of [
|
|
981
|
+
["profile", ["openai", "deepseek"]],
|
|
982
|
+
["systemRole", ["system", "developer"]],
|
|
983
|
+
["maxTokensParameter", ["max_completion_tokens", "max_tokens"]],
|
|
984
|
+
["reasoningReplay", ["omit", "tool-continuation"]]
|
|
985
|
+
]) {
|
|
986
|
+
if (options[key] !== undefined && !allowed.some((value) => value === options[key]))
|
|
987
|
+
throw new TypeError(`${PREFIX} Invalid Chat ${key}.`);
|
|
988
|
+
}
|
|
989
|
+
if (options.includeUsage !== undefined && typeof options.includeUsage !== "boolean")
|
|
990
|
+
throw new TypeError(`${PREFIX} includeUsage must be boolean.`);
|
|
991
|
+
}
|
|
992
|
+
function foundryChatRequest(request, definition, options, scope) {
|
|
993
|
+
const max = prepareRequest(request, definition, options, scope);
|
|
994
|
+
const profile = options.profile ?? "openai";
|
|
995
|
+
if (profile !== "deepseek" && options.reasoningReplay === "tool-continuation")
|
|
996
|
+
throw new UnsupportedModelFeatureError2(`${PREFIX} Reasoning-content replay requires the DeepSeek Chat profile.`);
|
|
997
|
+
const caps = definition.capabilities;
|
|
998
|
+
if (request.tools.length && caps.localTools !== true)
|
|
999
|
+
throw new UnsupportedModelFeatureError2(`${PREFIX} Configure localTools capability before using Chat tools.`);
|
|
1000
|
+
const reasoning = request.reasoning;
|
|
1001
|
+
const explicitReasoning = reasoning !== undefined && reasoning !== "provider-default";
|
|
1002
|
+
if (explicitReasoning) {
|
|
1003
|
+
const issue = modelReasoningSupportIssue2(caps.reasoning, reasoning);
|
|
1004
|
+
if (issue || caps.reasoning === undefined || typeof reasoning !== "string")
|
|
1005
|
+
throw new UnsupportedModelFeatureError2(`${PREFIX} ${issue ?? "Chat reasoning requires declared named efforts; exact budgets are unsupported"}.`);
|
|
1006
|
+
}
|
|
1007
|
+
const schema = request.responseFormat && foundryOutputSchema(request.responseFormat.schema);
|
|
1008
|
+
if (request.responseFormat && (profile === "deepseek" || caps.nativeStructuredOutput !== true || !schema))
|
|
1009
|
+
throw new UnsupportedModelFeatureError2(`${PREFIX} Chat structured output requires verified OpenAI-compatible strict-schema support. DeepSeek JSON mode is not strict schema decoding.`);
|
|
1010
|
+
const tools = request.tools.map((tool) => ({
|
|
1011
|
+
type: "function",
|
|
1012
|
+
function: {
|
|
1013
|
+
name: tool.name,
|
|
1014
|
+
description: tool.description,
|
|
1015
|
+
parameters: tool.inputSchema,
|
|
1016
|
+
...profile === "openai" ? {
|
|
1017
|
+
strict: caps.nativeStructuredOutput === true && foundryOutputSchema(tool.inputSchema) !== undefined
|
|
1018
|
+
} : {}
|
|
1019
|
+
}
|
|
1020
|
+
}));
|
|
1021
|
+
return {
|
|
1022
|
+
...options.request,
|
|
1023
|
+
model: definition.modelId,
|
|
1024
|
+
messages: chatInput(request.messages, {
|
|
1025
|
+
providerId: definition.providerId,
|
|
1026
|
+
errorPrefix: PREFIX,
|
|
1027
|
+
systemRole: options.systemRole,
|
|
1028
|
+
reasoningReplay: options.reasoningReplay
|
|
1029
|
+
}),
|
|
1030
|
+
stream: true,
|
|
1031
|
+
...options.includeUsage === false ? {} : { stream_options: { include_usage: true } },
|
|
1032
|
+
...max === undefined ? {} : { [options.maxTokensParameter ?? "max_completion_tokens"]: max },
|
|
1033
|
+
...explicitReasoning && typeof reasoning === "string" ? { reasoning_effort: reasoning } : {},
|
|
1034
|
+
...tools.length ? {
|
|
1035
|
+
tools,
|
|
1036
|
+
tool_choice: "auto",
|
|
1037
|
+
...profile === "openai" ? {
|
|
1038
|
+
parallel_tool_calls: !schema && !tools.some((tool) => tool.function.strict) && caps.parallelToolCalls === true
|
|
1039
|
+
} : {}
|
|
1040
|
+
} : {},
|
|
1041
|
+
...schema && request.responseFormat ? {
|
|
1042
|
+
response_format: {
|
|
1043
|
+
type: "json_schema",
|
|
1044
|
+
json_schema: {
|
|
1045
|
+
name: request.responseFormat.name,
|
|
1046
|
+
schema,
|
|
1047
|
+
strict: true,
|
|
1048
|
+
...request.responseFormat.description ? { description: request.responseFormat.description } : {}
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
} : {}
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
// src/discovery.ts
|
|
1056
|
+
import {
|
|
1057
|
+
ModelCatalogUnavailableError as ModelCatalogUnavailableError2,
|
|
1058
|
+
ModelProviderError as ModelProviderError3
|
|
1059
|
+
} from "@sixb/core/models";
|
|
1060
|
+
class FoundryDeployments {
|
|
1061
|
+
providerId;
|
|
1062
|
+
transport;
|
|
1063
|
+
settings;
|
|
1064
|
+
cached;
|
|
1065
|
+
expiresAt = 0;
|
|
1066
|
+
pending;
|
|
1067
|
+
constructor(providerId, transport, discovery = {}) {
|
|
1068
|
+
this.providerId = providerId;
|
|
1069
|
+
this.transport = transport;
|
|
1070
|
+
for (const key of [
|
|
1071
|
+
"ttlMs",
|
|
1072
|
+
"timeoutMs",
|
|
1073
|
+
"maxPages",
|
|
1074
|
+
"maxDeployments",
|
|
1075
|
+
"maxResponseBytes"
|
|
1076
|
+
])
|
|
1077
|
+
positiveInteger(discovery[key], `discovery.${key}`);
|
|
1078
|
+
this.settings = {
|
|
1079
|
+
url: `${transport.projectUrl}/deployments?api-version=v1`,
|
|
1080
|
+
ttlMs: discovery.ttlMs ?? 60 * 60 * 1000,
|
|
1081
|
+
timeoutMs: discovery.timeoutMs ?? 5000,
|
|
1082
|
+
maxPages: discovery.maxPages ?? 100,
|
|
1083
|
+
maxDeployments: discovery.maxDeployments ?? 1e4,
|
|
1084
|
+
maxResponseBytes: discovery.maxResponseBytes ?? 4 * 1024 * 1024
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
async list(refresh = false) {
|
|
1088
|
+
return (await this.load(refresh)).records;
|
|
1089
|
+
}
|
|
1090
|
+
async resolve(name, offline) {
|
|
1091
|
+
const snapshot = offline ? this.cached : await this.load();
|
|
1092
|
+
const deployment = snapshot?.byName.get(name);
|
|
1093
|
+
if (!snapshot || !deployment)
|
|
1094
|
+
throw this.invalid(`Deployment '${name}' was not found in ${offline ? "cached project deployments; resolve online first" : "this project"}.`);
|
|
1095
|
+
return {
|
|
1096
|
+
deployment,
|
|
1097
|
+
discoveredAt: snapshot.fetchedAt
|
|
1098
|
+
};
|
|
1099
|
+
}
|
|
1100
|
+
load(refresh = false) {
|
|
1101
|
+
if (this.pending)
|
|
1102
|
+
return this.pending;
|
|
1103
|
+
if (!refresh && this.cached && Date.now() < this.expiresAt)
|
|
1104
|
+
return Promise.resolve(this.cached);
|
|
1105
|
+
this.pending = this.fetchSnapshot().then((snapshot) => {
|
|
1106
|
+
this.cached = snapshot;
|
|
1107
|
+
this.expiresAt = Date.now() + this.settings.ttlMs;
|
|
1108
|
+
return snapshot;
|
|
1109
|
+
}).catch((error) => {
|
|
1110
|
+
this.expiresAt = 0;
|
|
1111
|
+
throw error;
|
|
1112
|
+
}).finally(() => {
|
|
1113
|
+
this.pending = undefined;
|
|
1114
|
+
});
|
|
1115
|
+
return this.pending;
|
|
1116
|
+
}
|
|
1117
|
+
async fetchSnapshot() {
|
|
1118
|
+
const settings = this.settings;
|
|
1119
|
+
const diagnostics = new RequestDiagnostics;
|
|
1120
|
+
const controller = new AbortController;
|
|
1121
|
+
const timer = setTimeout(() => controller.abort(new DOMException("Discovery timed out", "TimeoutError")), settings.timeoutMs);
|
|
1122
|
+
const { signal } = controller;
|
|
1123
|
+
const records = [];
|
|
1124
|
+
const byName = new Map;
|
|
1125
|
+
const seen = new Set;
|
|
1126
|
+
const budget = { bytes: settings.maxResponseBytes };
|
|
1127
|
+
let url = settings.url;
|
|
1128
|
+
let entries = 0;
|
|
1129
|
+
try {
|
|
1130
|
+
while (url !== undefined) {
|
|
1131
|
+
const pageUrl = this.pageUrl(url, settings.url);
|
|
1132
|
+
if (seen.has(pageUrl))
|
|
1133
|
+
throw this.invalid("Deployment pagination repeated a page.");
|
|
1134
|
+
if (seen.size >= settings.maxPages)
|
|
1135
|
+
throw this.invalid("Deployment pagination exceeded maxPages.");
|
|
1136
|
+
seen.add(pageUrl);
|
|
1137
|
+
const response = await this.fetchPage(pageUrl, signal, diagnostics);
|
|
1138
|
+
const text = await this.readPage(response, budget, signal);
|
|
1139
|
+
let value;
|
|
1140
|
+
try {
|
|
1141
|
+
value = JSON.parse(text);
|
|
1142
|
+
} catch (cause) {
|
|
1143
|
+
throw this.invalid("Deployment response is not valid JSON.", cause);
|
|
1144
|
+
}
|
|
1145
|
+
const page = object(value);
|
|
1146
|
+
if (!page || !Array.isArray(page.value))
|
|
1147
|
+
throw this.invalid("Deployment response is missing its value array.");
|
|
1148
|
+
entries += page.value.length;
|
|
1149
|
+
if (entries > settings.maxDeployments)
|
|
1150
|
+
throw this.invalid("Deployment response exceeded maxDeployments.");
|
|
1151
|
+
for (const item of page.value) {
|
|
1152
|
+
const raw = object(item);
|
|
1153
|
+
if (!raw || typeof raw.type !== "string" || !raw.type.trim())
|
|
1154
|
+
throw this.invalid("Deployment record is missing its type.");
|
|
1155
|
+
if (raw.type !== "ModelDeployment")
|
|
1156
|
+
continue;
|
|
1157
|
+
const record = deploymentRecord(raw, (message) => this.invalid(message));
|
|
1158
|
+
if (byName.has(record.name))
|
|
1159
|
+
throw this.invalid(`Duplicate deployment '${record.name}'; deployment names must be unique across project connections.`);
|
|
1160
|
+
records.push(record);
|
|
1161
|
+
byName.set(record.name, record);
|
|
1162
|
+
}
|
|
1163
|
+
if (page.nextLink !== undefined && (typeof page.nextLink !== "string" || !page.nextLink.trim()))
|
|
1164
|
+
throw this.invalid("Deployment nextLink must be a nonempty URL.");
|
|
1165
|
+
url = typeof page.nextLink === "string" ? this.pageUrl(page.nextLink, pageUrl) : undefined;
|
|
1166
|
+
}
|
|
1167
|
+
return { records: Object.freeze(records), byName, fetchedAt: new Date().toISOString() };
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
if (error instanceof ModelCatalogUnavailableError2)
|
|
1170
|
+
throw new ModelCatalogUnavailableError2(diagnostics.text(error.message), {
|
|
1171
|
+
cause: diagnostics.failure(error.cause)
|
|
1172
|
+
});
|
|
1173
|
+
throw diagnostics.failure(error);
|
|
1174
|
+
} finally {
|
|
1175
|
+
clearTimeout(timer);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
pageUrl(link, initial) {
|
|
1179
|
+
let url;
|
|
1180
|
+
try {
|
|
1181
|
+
url = new URL(link, initial);
|
|
1182
|
+
} catch (cause) {
|
|
1183
|
+
throw this.invalid("Invalid deployment nextLink.", cause);
|
|
1184
|
+
}
|
|
1185
|
+
const base = new URL(initial);
|
|
1186
|
+
if (url.origin !== base.origin || url.pathname !== base.pathname || url.username || url.password || url.hash)
|
|
1187
|
+
throw this.invalid("Deployment nextLink must stay on the same project deployments endpoint.");
|
|
1188
|
+
if (!url.searchParams.has("api-version"))
|
|
1189
|
+
url.searchParams.set("api-version", "v1");
|
|
1190
|
+
if (url.searchParams.getAll("api-version").length !== 1 || url.searchParams.get("api-version") !== "v1")
|
|
1191
|
+
throw this.invalid("Deployment nextLink must use api-version=v1.");
|
|
1192
|
+
url.searchParams.sort();
|
|
1193
|
+
return url.href;
|
|
1194
|
+
}
|
|
1195
|
+
async fetchPage(url, signal, diagnostics) {
|
|
1196
|
+
let headers;
|
|
1197
|
+
try {
|
|
1198
|
+
headers = await this.transport.headers(signal, diagnostics);
|
|
1199
|
+
} catch (cause) {
|
|
1200
|
+
throw this.unavailable(cause);
|
|
1201
|
+
}
|
|
1202
|
+
headers.set("accept", "application/json");
|
|
1203
|
+
let response;
|
|
1204
|
+
try {
|
|
1205
|
+
response = await abortable(async () => {
|
|
1206
|
+
const result = await this.transport.fetch(url, { headers, signal, redirect: "error" });
|
|
1207
|
+
if (signal.aborted)
|
|
1208
|
+
result.body?.cancel().catch(() => {});
|
|
1209
|
+
return result;
|
|
1210
|
+
}, signal);
|
|
1211
|
+
} catch (cause) {
|
|
1212
|
+
throw this.unavailable(cause);
|
|
1213
|
+
}
|
|
1214
|
+
if (response.status !== 200) {
|
|
1215
|
+
response.body?.cancel().catch(() => {});
|
|
1216
|
+
throw this.unavailable(new ModelProviderError3(`${PREFIX} Deployment discovery failed with HTTP ${response.status}.`, this.providerId, "catalog", { status: response.status, requestId: requestId(response) }));
|
|
1217
|
+
}
|
|
1218
|
+
return response;
|
|
1219
|
+
}
|
|
1220
|
+
async readPage(response, budget, signal) {
|
|
1221
|
+
if (!response.body)
|
|
1222
|
+
throw this.invalid("Deployment response has no body.");
|
|
1223
|
+
const reader = response.body.getReader();
|
|
1224
|
+
const cancel = () => {
|
|
1225
|
+
reader.cancel(signal.reason).catch(() => {});
|
|
1226
|
+
};
|
|
1227
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
1228
|
+
const chunks = [];
|
|
1229
|
+
try {
|
|
1230
|
+
for (;; ) {
|
|
1231
|
+
const chunk = await abortable(() => reader.read(), signal).catch((cause) => {
|
|
1232
|
+
throw this.unavailable(cause);
|
|
1233
|
+
});
|
|
1234
|
+
if (signal.aborted)
|
|
1235
|
+
throw this.unavailable(signal.reason);
|
|
1236
|
+
if (chunk.done)
|
|
1237
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
1238
|
+
budget.bytes -= chunk.value.byteLength;
|
|
1239
|
+
if (budget.bytes < 0)
|
|
1240
|
+
throw this.invalid("Deployment response exceeded maxResponseBytes.");
|
|
1241
|
+
chunks.push(chunk.value);
|
|
1242
|
+
}
|
|
1243
|
+
} finally {
|
|
1244
|
+
signal.removeEventListener("abort", cancel);
|
|
1245
|
+
reader.cancel().catch(() => {});
|
|
1246
|
+
reader.releaseLock();
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
invalid(message, cause) {
|
|
1250
|
+
return new ModelProviderError3(`${PREFIX} ${message}`, this.providerId, "catalog", { cause });
|
|
1251
|
+
}
|
|
1252
|
+
unavailable(cause) {
|
|
1253
|
+
return new ModelCatalogUnavailableError2(`${PREFIX} Project deployment catalog unavailable.`, {
|
|
1254
|
+
cause
|
|
1255
|
+
});
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
var BOOLEAN_KEYS = [
|
|
1259
|
+
"responses",
|
|
1260
|
+
"messages",
|
|
1261
|
+
"chatCompletion",
|
|
1262
|
+
"chat_completion",
|
|
1263
|
+
"completion",
|
|
1264
|
+
"embeddings",
|
|
1265
|
+
"jsonObjectResponse",
|
|
1266
|
+
"assistants"
|
|
1267
|
+
];
|
|
1268
|
+
function deploymentRecord(raw, invalid) {
|
|
1269
|
+
const required = (value, field) => {
|
|
1270
|
+
if (typeof value !== "string" || !value.trim())
|
|
1271
|
+
throw invalid(`Deployment ${field} must be a nonempty string.`);
|
|
1272
|
+
return value;
|
|
1273
|
+
};
|
|
1274
|
+
const capabilities = object(raw.capabilities);
|
|
1275
|
+
if (!capabilities || Object.values(capabilities).some((value) => typeof value !== "string"))
|
|
1276
|
+
throw invalid("Deployment capabilities must contain string values.");
|
|
1277
|
+
const sku = object(raw.sku);
|
|
1278
|
+
if (!sku)
|
|
1279
|
+
throw invalid("Deployment sku must be an object.");
|
|
1280
|
+
for (const key of ["family", "size", "tier"])
|
|
1281
|
+
if (sku[key] !== undefined && typeof sku[key] !== "string")
|
|
1282
|
+
throw invalid(`Deployment sku.${key} must be a string.`);
|
|
1283
|
+
if (sku.capacity !== undefined && (typeof sku.capacity !== "number" || !Number.isSafeInteger(sku.capacity) || sku.capacity < 0))
|
|
1284
|
+
throw invalid("Deployment sku.capacity must be a nonnegative safe integer.");
|
|
1285
|
+
if (typeof raw.modelVersion !== "string")
|
|
1286
|
+
throw invalid("Deployment modelVersion must be a string.");
|
|
1287
|
+
const strings = Object.fromEntries(Object.entries(capabilities).map(([key, value]) => [key, String(value)]));
|
|
1288
|
+
for (const key of BOOLEAN_KEYS)
|
|
1289
|
+
if (strings[key] !== undefined && !["true", "false"].includes(strings[key]))
|
|
1290
|
+
throw invalid(`Deployment capability '${key}' must be 'true' or 'false'.`);
|
|
1291
|
+
if (strings.chatCompletion !== undefined && strings.chat_completion !== undefined && strings.chatCompletion !== strings.chat_completion)
|
|
1292
|
+
throw invalid("Deployment has contradictory Chat capability aliases.");
|
|
1293
|
+
for (const key of ["maxContextToken", "maxOutputToken"]) {
|
|
1294
|
+
if (strings[key] !== undefined && (!/^[1-9]\d*$/.test(strings[key]) || !Number.isSafeInteger(Number(strings[key]))))
|
|
1295
|
+
throw invalid(`Deployment capability '${key}' must be a positive safe integer string.`);
|
|
1296
|
+
}
|
|
1297
|
+
const name = required(raw.name, "name");
|
|
1298
|
+
if (name !== name.trim())
|
|
1299
|
+
throw invalid("Deployment name must not contain surrounding whitespace.");
|
|
1300
|
+
return Object.freeze({
|
|
1301
|
+
name,
|
|
1302
|
+
modelName: required(raw.modelName, "modelName"),
|
|
1303
|
+
modelVersion: raw.modelVersion,
|
|
1304
|
+
modelPublisher: required(raw.modelPublisher, "modelPublisher"),
|
|
1305
|
+
...raw.connectionName === undefined ? {} : { connectionName: required(raw.connectionName, "connectionName") },
|
|
1306
|
+
capabilities: Object.freeze(strings),
|
|
1307
|
+
sku: Object.freeze({
|
|
1308
|
+
name: required(sku.name, "sku.name"),
|
|
1309
|
+
...typeof sku.capacity === "number" ? { capacity: sku.capacity } : {},
|
|
1310
|
+
...typeof sku.family === "string" ? { family: sku.family } : {},
|
|
1311
|
+
...typeof sku.size === "string" ? { size: sku.size } : {},
|
|
1312
|
+
...typeof sku.tier === "string" ? { tier: sku.tier } : {}
|
|
1313
|
+
})
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
// src/messages-accounting.ts
|
|
1318
|
+
function foundryMessagesUsage(raw) {
|
|
1319
|
+
const uncached = counter(raw.input_tokens);
|
|
1320
|
+
const read = counter(raw.cache_read_input_tokens);
|
|
1321
|
+
const creation = object(raw.cache_creation);
|
|
1322
|
+
const five = counter(creation?.ephemeral_5m_input_tokens);
|
|
1323
|
+
const hour = counter(creation?.ephemeral_1h_input_tokens);
|
|
1324
|
+
const write = counter(raw.cache_creation_input_tokens) ?? (five !== undefined && hour !== undefined ? five + hour : undefined);
|
|
1325
|
+
const output = counter(raw.output_tokens);
|
|
1326
|
+
const thinking = counter(object(raw.output_tokens_details)?.thinking_tokens);
|
|
1327
|
+
const input = uncached !== undefined && read !== undefined && write !== undefined ? uncached + read + write : undefined;
|
|
1328
|
+
return {
|
|
1329
|
+
...input === undefined ? {} : { inputTokens: input },
|
|
1330
|
+
...uncached === undefined ? {} : { uncachedInputTokens: uncached },
|
|
1331
|
+
...read === undefined ? {} : { cacheReadInputTokens: read },
|
|
1332
|
+
...write === undefined ? {} : { cacheWriteInputTokens: write },
|
|
1333
|
+
...five === undefined && write !== 0 ? {} : { cacheWrite5mInputTokens: five ?? 0 },
|
|
1334
|
+
...hour === undefined && write !== 0 ? {} : { cacheWrite1hInputTokens: hour ?? 0 },
|
|
1335
|
+
...output === undefined ? {} : { outputTokens: output },
|
|
1336
|
+
...thinking === undefined ? {} : { reasoningOutputTokens: thinking },
|
|
1337
|
+
...output !== undefined && thinking !== undefined && thinking <= output ? { textOutputTokens: output - thinking } : {},
|
|
1338
|
+
raw
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1341
|
+
function foundryMessagesEstimator(card, request, modelName, modelVersion, aliases) {
|
|
1342
|
+
const estimator = tokenEstimator(card, request, ["temperature", "top_p", "top_k", "metadata", "stop_sequences", "cache_control"], tokenMeters2, modelName, modelVersion, aliases ?? (modelName ? [modelName] : undefined));
|
|
1343
|
+
const cache = object(request?.cache_control);
|
|
1344
|
+
if (!cache)
|
|
1345
|
+
return estimator;
|
|
1346
|
+
const ttl = cache.ttl ?? "5m";
|
|
1347
|
+
const writeRate = ttl === "1h" ? card?.cacheWriteInput1h : card?.cacheWriteInput5m;
|
|
1348
|
+
const unknownWriteRate = writeRate === undefined && card?.cacheWriteInput === undefined;
|
|
1349
|
+
return {
|
|
1350
|
+
...estimator,
|
|
1351
|
+
estimateReservation: (tokens) => unknownWriteRate ? undefined : estimator.estimateReservation?.(tokens)
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
function tokenMeters2(raw) {
|
|
1355
|
+
if (!raw)
|
|
1356
|
+
return true;
|
|
1357
|
+
const numeric = [
|
|
1358
|
+
"input_tokens",
|
|
1359
|
+
"output_tokens",
|
|
1360
|
+
"cache_read_input_tokens",
|
|
1361
|
+
"cache_creation_input_tokens"
|
|
1362
|
+
];
|
|
1363
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
1364
|
+
if (numeric.includes(key)) {
|
|
1365
|
+
if (counter(value) === undefined)
|
|
1366
|
+
return false;
|
|
1367
|
+
} else if (key === "cache_creation" || key === "output_tokens_details") {
|
|
1368
|
+
const details = object(value);
|
|
1369
|
+
const allowed = key === "cache_creation" ? ["ephemeral_5m_input_tokens", "ephemeral_1h_input_tokens"] : ["thinking_tokens"];
|
|
1370
|
+
if (!details || Object.entries(details).some(([k, v]) => !allowed.includes(k) || counter(v) === undefined))
|
|
1371
|
+
return false;
|
|
1372
|
+
} else if (key === "server_tool_use") {
|
|
1373
|
+
const tools = object(value);
|
|
1374
|
+
if (!tools || Object.entries(tools).some(([k, v]) => !["web_search_requests", "web_fetch_requests"].includes(k) || v !== 0))
|
|
1375
|
+
return false;
|
|
1376
|
+
} else if (key === "service_tier" && value === "standard") {} else
|
|
1377
|
+
return false;
|
|
1378
|
+
}
|
|
1379
|
+
return true;
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
// src/messages-request.ts
|
|
1383
|
+
import {
|
|
1384
|
+
modelReasoningSupportIssue as modelReasoningSupportIssue3,
|
|
1385
|
+
UnsupportedModelFeatureError as UnsupportedModelFeatureError3
|
|
1386
|
+
} from "@sixb/core/models";
|
|
1387
|
+
import { messagesInput } from "@sixb/model-protocols/messages";
|
|
1388
|
+
|
|
1389
|
+
// src/messages-schema.ts
|
|
1390
|
+
import { isJsonObject as isJsonObject4 } from "@sixb/core/models";
|
|
1391
|
+
var KEYS = new Set([
|
|
1392
|
+
"type",
|
|
1393
|
+
"title",
|
|
1394
|
+
"description",
|
|
1395
|
+
"properties",
|
|
1396
|
+
"required",
|
|
1397
|
+
"additionalProperties",
|
|
1398
|
+
"items",
|
|
1399
|
+
"enum",
|
|
1400
|
+
"const",
|
|
1401
|
+
"anyOf",
|
|
1402
|
+
"format"
|
|
1403
|
+
]);
|
|
1404
|
+
var TYPES2 = new Set(["object", "array", "string", "number", "integer", "boolean", "null"]);
|
|
1405
|
+
var FORMATS = new Set([
|
|
1406
|
+
"date-time",
|
|
1407
|
+
"time",
|
|
1408
|
+
"date",
|
|
1409
|
+
"duration",
|
|
1410
|
+
"email",
|
|
1411
|
+
"hostname",
|
|
1412
|
+
"uri",
|
|
1413
|
+
"ipv4",
|
|
1414
|
+
"ipv6",
|
|
1415
|
+
"uuid"
|
|
1416
|
+
]);
|
|
1417
|
+
function messagesOutputSchema(schema) {
|
|
1418
|
+
const active = new Set;
|
|
1419
|
+
const walk = (value) => {
|
|
1420
|
+
if (!isJsonObject4(value) || active.has(value))
|
|
1421
|
+
return false;
|
|
1422
|
+
if (Object.keys(value).some((key) => !KEYS.has(key)))
|
|
1423
|
+
return false;
|
|
1424
|
+
active.add(value);
|
|
1425
|
+
try {
|
|
1426
|
+
for (const key of ["title", "description"])
|
|
1427
|
+
if (value[key] !== undefined && typeof value[key] !== "string")
|
|
1428
|
+
return false;
|
|
1429
|
+
const types = typeof value.type === "string" ? [value.type] : value.type;
|
|
1430
|
+
if (types !== undefined && (!Array.isArray(types) || !types.length || types.some((type) => typeof type !== "string" || !TYPES2.has(type))))
|
|
1431
|
+
return false;
|
|
1432
|
+
if (value.anyOf !== undefined && (!Array.isArray(value.anyOf) || !value.anyOf.length || !value.anyOf.every(walk)))
|
|
1433
|
+
return false;
|
|
1434
|
+
if (types === undefined && value.anyOf === undefined && value.const === undefined && value.enum === undefined)
|
|
1435
|
+
return false;
|
|
1436
|
+
if (Array.isArray(types) && types.includes("object")) {
|
|
1437
|
+
if (!isJsonObject4(value.properties) || value.additionalProperties !== false)
|
|
1438
|
+
return false;
|
|
1439
|
+
if (value.required !== undefined && (!Array.isArray(value.required) || value.required.some((key) => typeof key !== "string" || !Object.hasOwn(value.properties, key))))
|
|
1440
|
+
return false;
|
|
1441
|
+
if (!Object.values(value.properties).every(walk))
|
|
1442
|
+
return false;
|
|
1443
|
+
} else if (value.properties !== undefined || value.required !== undefined || value.additionalProperties !== undefined)
|
|
1444
|
+
return false;
|
|
1445
|
+
if (Array.isArray(types) && types.includes("array")) {
|
|
1446
|
+
if (!walk(value.items))
|
|
1447
|
+
return false;
|
|
1448
|
+
} else if (value.items !== undefined)
|
|
1449
|
+
return false;
|
|
1450
|
+
if (value.format !== undefined && (typeof value.format !== "string" || !FORMATS.has(value.format)))
|
|
1451
|
+
return false;
|
|
1452
|
+
if (value.enum !== undefined && (!Array.isArray(value.enum) || !value.enum.length || value.enum.some((entry) => typeof entry === "object" && entry !== null)))
|
|
1453
|
+
return false;
|
|
1454
|
+
if (value.const !== undefined && typeof value.const === "object" && value.const !== null)
|
|
1455
|
+
return false;
|
|
1456
|
+
return true;
|
|
1457
|
+
} finally {
|
|
1458
|
+
active.delete(value);
|
|
1459
|
+
}
|
|
1460
|
+
};
|
|
1461
|
+
return schema.type === "object" && walk(schema) ? schema : undefined;
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// src/messages-request.ts
|
|
1465
|
+
var RESERVED3 = new Set([
|
|
1466
|
+
"model",
|
|
1467
|
+
"messages",
|
|
1468
|
+
"system",
|
|
1469
|
+
"tools",
|
|
1470
|
+
"tool_choice",
|
|
1471
|
+
"stream",
|
|
1472
|
+
"max_tokens",
|
|
1473
|
+
"thinking",
|
|
1474
|
+
"output_config",
|
|
1475
|
+
"output_format",
|
|
1476
|
+
"disable_parallel_tool_use",
|
|
1477
|
+
"container",
|
|
1478
|
+
"mcp_servers",
|
|
1479
|
+
"context_management"
|
|
1480
|
+
]);
|
|
1481
|
+
function validateMessagesOptions(options) {
|
|
1482
|
+
positiveInteger(options.maxOutputTokens, "maxOutputTokens");
|
|
1483
|
+
positiveInteger(options.maxInputFileBytes, "maxInputFileBytes");
|
|
1484
|
+
if (options.thinkingMode !== undefined && !["adaptive", "manual"].includes(options.thinkingMode))
|
|
1485
|
+
throw new TypeError(`${PREFIX} thinkingMode must be adaptive or manual.`);
|
|
1486
|
+
for (const key of Object.keys(options.request ?? {}))
|
|
1487
|
+
if (RESERVED3.has(key))
|
|
1488
|
+
throw new TypeError(`${PREFIX} Messages request option '${key}' is owned by the adapter.`);
|
|
1489
|
+
const cache = options.request?.cache_control;
|
|
1490
|
+
if (cache !== undefined) {
|
|
1491
|
+
const value = object(cache);
|
|
1492
|
+
if (!value || value.type !== "ephemeral" || value.ttl !== undefined && !["5m", "1h"].includes(String(value.ttl)) || Object.keys(value).some((key) => !["type", "ttl"].includes(key)))
|
|
1493
|
+
throw new TypeError(`${PREFIX} cache_control must be ephemeral with an optional 5m or 1h ttl.`);
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
function foundryMessagesRequest(request, definition, options, scope) {
|
|
1497
|
+
const max = prepareRequest(request, definition, options, scope, true);
|
|
1498
|
+
let conversation = false;
|
|
1499
|
+
for (const message of request.messages) {
|
|
1500
|
+
if (message.role === "system" && conversation)
|
|
1501
|
+
throw new UnsupportedModelFeatureError3(`${PREFIX} Messages system instructions must precede the conversation.`);
|
|
1502
|
+
if (message.role !== "system")
|
|
1503
|
+
conversation = true;
|
|
1504
|
+
}
|
|
1505
|
+
if (max === undefined)
|
|
1506
|
+
throw new TypeError(`${PREFIX} Native Messages requires maxOutputTokens in the definition, binding, or request.`);
|
|
1507
|
+
const caps = definition.capabilities;
|
|
1508
|
+
if (request.tools.length && caps.localTools !== true)
|
|
1509
|
+
throw new UnsupportedModelFeatureError3(`${PREFIX} Configure localTools capability before using Messages tools.`);
|
|
1510
|
+
const schema = request.responseFormat && messagesOutputSchema(request.responseFormat.schema);
|
|
1511
|
+
if (request.responseFormat && (caps.nativeStructuredOutput !== true || !schema))
|
|
1512
|
+
throw new UnsupportedModelFeatureError3(`${PREFIX} Messages structured output requires a declared capability and a supported closed-object Claude schema.`);
|
|
1513
|
+
const thinking = reasoningRequest(request, definition, options, max);
|
|
1514
|
+
if (thinking.thinking && object(thinking.thinking)?.type !== "disabled" && ["temperature", "top_p", "top_k"].some((key) => options.request?.[key] !== undefined))
|
|
1515
|
+
throw new UnsupportedModelFeatureError3(`${PREFIX} Explicit sampling controls cannot be combined with Messages thinking.`);
|
|
1516
|
+
const mapped = messagesInput(request.messages, definition.providerId, PREFIX);
|
|
1517
|
+
const output = {
|
|
1518
|
+
...thinking.effort === undefined ? {} : { effort: thinking.effort },
|
|
1519
|
+
...schema ? { format: { type: "json_schema", schema } } : {}
|
|
1520
|
+
};
|
|
1521
|
+
return {
|
|
1522
|
+
...options.request,
|
|
1523
|
+
model: definition.modelId,
|
|
1524
|
+
messages: mapped.messages,
|
|
1525
|
+
...mapped.system.length ? { system: mapped.system } : {},
|
|
1526
|
+
stream: true,
|
|
1527
|
+
max_tokens: max,
|
|
1528
|
+
...thinking.thinking ? { thinking: thinking.thinking } : {},
|
|
1529
|
+
...Object.keys(output).length ? { output_config: output } : {},
|
|
1530
|
+
...request.tools.length ? {
|
|
1531
|
+
tools: request.tools.map((tool) => ({
|
|
1532
|
+
name: tool.name,
|
|
1533
|
+
description: tool.description,
|
|
1534
|
+
input_schema: tool.inputSchema,
|
|
1535
|
+
...caps.nativeStructuredOutput === true && messagesOutputSchema(tool.inputSchema) ? { strict: true } : {}
|
|
1536
|
+
})),
|
|
1537
|
+
tool_choice: { type: "auto", disable_parallel_tool_use: caps.parallelToolCalls !== true }
|
|
1538
|
+
} : {}
|
|
1539
|
+
};
|
|
1540
|
+
}
|
|
1541
|
+
function reasoningRequest(request, definition, options, max) {
|
|
1542
|
+
const reasoning = request.reasoning;
|
|
1543
|
+
if (reasoning === undefined || reasoning === "provider-default")
|
|
1544
|
+
return {};
|
|
1545
|
+
const caps = definition.capabilities.reasoning;
|
|
1546
|
+
const issue = modelReasoningSupportIssue3(caps, reasoning);
|
|
1547
|
+
if (caps === undefined || issue)
|
|
1548
|
+
throw new UnsupportedModelFeatureError3(`${PREFIX} ${issue ?? "Configure reasoning capabilities for this deployment"}.`);
|
|
1549
|
+
if (reasoning === "none") {
|
|
1550
|
+
return {
|
|
1551
|
+
thinking: { type: "disabled" }
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
if (typeof reasoning === "string") {
|
|
1555
|
+
if (reasoning === "minimal" || options.thinkingMode === "manual")
|
|
1556
|
+
throw new UnsupportedModelFeatureError3(`${PREFIX} Named efforts require an adaptive-thinking Claude offering.`);
|
|
1557
|
+
return { thinking: { type: "adaptive" }, effort: reasoning };
|
|
1558
|
+
}
|
|
1559
|
+
if (options.thinkingMode === "adaptive")
|
|
1560
|
+
throw new UnsupportedModelFeatureError3(`${PREFIX} This Claude offering only supports adaptive thinking, not manual budgets.`);
|
|
1561
|
+
if (reasoning.budgetTokens < 1024 || reasoning.budgetTokens >= max)
|
|
1562
|
+
throw new UnsupportedModelFeatureError3(`${PREFIX} Messages reasoning budget must be at least 1024 and below maxOutputTokens (${max}).`);
|
|
1563
|
+
return { thinking: { type: "enabled", budget_tokens: reasoning.budgetTokens } };
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
// src/resolution.ts
|
|
1567
|
+
import {
|
|
1568
|
+
defineLanguageModel as defineLanguageModel2,
|
|
1569
|
+
defineModelRateCard as defineModelRateCard3,
|
|
1570
|
+
UnsupportedModelFeatureError as UnsupportedModelFeatureError4
|
|
1571
|
+
} from "@sixb/core/models";
|
|
1572
|
+
function resolveModel(input) {
|
|
1573
|
+
const { deployment, options } = input;
|
|
1574
|
+
const metadata = deployment ? {
|
|
1575
|
+
publisher: deployment.modelPublisher,
|
|
1576
|
+
modelName: deployment.modelName,
|
|
1577
|
+
modelVersion: deployment.modelVersion,
|
|
1578
|
+
sku: deployment.sku.name,
|
|
1579
|
+
deployment,
|
|
1580
|
+
discoveredAt: input.discoveredAt
|
|
1581
|
+
} : {};
|
|
1582
|
+
const entry = input.catalogModel;
|
|
1583
|
+
const deploymentPublisher = deployment && azurePublisher(deployment.modelPublisher);
|
|
1584
|
+
const publisher = deploymentPublisher?.id === "fireworks-ai" ? entry?.definition.publisher ?? deploymentPublisher : deploymentPublisher ?? entry?.definition.publisher;
|
|
1585
|
+
const protocol = input.protocol ?? entry?.protocol ?? (deployment?.capabilities.responses === "true" ? "responses" : deployment?.capabilities.chatCompletion === "true" || deployment?.capabilities.chat_completion === "true" ? "chat" : deployment?.capabilities.messages === "true" ? "messages" : "responses");
|
|
1586
|
+
if (protocol === "messages" && deployment?.connectionName)
|
|
1587
|
+
throw new UnsupportedModelFeatureError4(`${PREFIX} Native Messages cannot route a deployment from a project connection; use the owning resource's project URL and API key.`);
|
|
1588
|
+
const flag = deployment?.capabilities[protocol === "chat" ? "chatCompletion" : protocol] ?? (protocol === "chat" ? deployment?.capabilities.chat_completion : undefined);
|
|
1589
|
+
if (flag === "false")
|
|
1590
|
+
throw new UnsupportedModelFeatureError4(`${PREFIX} Deployment '${input.modelId}' reports that ${protocol === "chat" ? "Chat" : protocol === "responses" ? "Responses" : "Messages"} is unsupported.`);
|
|
1591
|
+
const definition = defineLanguageModel2({
|
|
1592
|
+
...entry?.definition,
|
|
1593
|
+
publisher,
|
|
1594
|
+
via: "Azure AI Foundry",
|
|
1595
|
+
...options.definition,
|
|
1596
|
+
kind: "language",
|
|
1597
|
+
providerId: input.providerId,
|
|
1598
|
+
modelId: input.modelId,
|
|
1599
|
+
capabilities: {
|
|
1600
|
+
...entry?.definition.capabilities,
|
|
1601
|
+
...options.definition?.capabilities
|
|
1602
|
+
}
|
|
1603
|
+
});
|
|
1604
|
+
return {
|
|
1605
|
+
protocol,
|
|
1606
|
+
definition: deployment ? effectiveDefinition(definition, protocol, options) : defineLanguageModel2({
|
|
1607
|
+
kind: "language",
|
|
1608
|
+
providerId: input.providerId,
|
|
1609
|
+
modelId: input.modelId,
|
|
1610
|
+
publisher: definition.publisher,
|
|
1611
|
+
via: definition.via,
|
|
1612
|
+
capabilities: {}
|
|
1613
|
+
}),
|
|
1614
|
+
metadata: Object.freeze({
|
|
1615
|
+
...metadata,
|
|
1616
|
+
...entry ? {
|
|
1617
|
+
catalog: Object.freeze({
|
|
1618
|
+
provider: entry.catalogProvider,
|
|
1619
|
+
modelId: entry.modelName,
|
|
1620
|
+
source: "https://models.dev/api.json",
|
|
1621
|
+
pricing: "reference"
|
|
1622
|
+
})
|
|
1623
|
+
} : {}
|
|
1624
|
+
}),
|
|
1625
|
+
rateCard: options.rateCard ? defineModelRateCard3(options.rateCard) : entry?.rateCard,
|
|
1626
|
+
aliases: Object.freeze([
|
|
1627
|
+
...new Set([
|
|
1628
|
+
input.modelId,
|
|
1629
|
+
...entry ? [entry.modelName] : [],
|
|
1630
|
+
...metadata.modelName ? [
|
|
1631
|
+
metadata.modelName,
|
|
1632
|
+
...metadata.modelVersion && protocol !== "messages" ? [`${metadata.modelName}-${metadata.modelVersion}`] : []
|
|
1633
|
+
] : []
|
|
1634
|
+
])
|
|
1635
|
+
])
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
function effectiveDefinition(definition, protocol, options) {
|
|
1639
|
+
const caps = definition.capabilities;
|
|
1640
|
+
const media = caps.inputMediaTypes;
|
|
1641
|
+
const supported = [
|
|
1642
|
+
"image/png",
|
|
1643
|
+
"image/jpeg",
|
|
1644
|
+
"image/webp",
|
|
1645
|
+
"image/gif",
|
|
1646
|
+
...protocol === "chat" ? [] : ["application/pdf"]
|
|
1647
|
+
];
|
|
1648
|
+
let reasoning = caps.reasoning;
|
|
1649
|
+
if (reasoning) {
|
|
1650
|
+
const { budgetTokens, efforts, ...rest } = reasoning;
|
|
1651
|
+
const max = Math.min(definition.maxOutputTokens ?? Infinity, options.maxOutputTokens ?? Infinity) - 1;
|
|
1652
|
+
const min = Math.max(1024, budgetTokens?.min ?? 0);
|
|
1653
|
+
const budgetMax = Math.min(max, budgetTokens?.max ?? Infinity);
|
|
1654
|
+
reasoning = {
|
|
1655
|
+
...rest,
|
|
1656
|
+
...efforts && !(protocol === "messages" && options.thinkingMode === "manual") ? { efforts: efforts.filter((effort) => protocol !== "messages" || effort !== "minimal") } : {},
|
|
1657
|
+
...budgetTokens && protocol === "messages" && options.thinkingMode !== "adaptive" && budgetMax >= min ? { budgetTokens: { min, ...Number.isFinite(budgetMax) ? { max: budgetMax } : {} } } : {}
|
|
1658
|
+
};
|
|
1659
|
+
}
|
|
1660
|
+
return defineLanguageModel2({
|
|
1661
|
+
...definition,
|
|
1662
|
+
capabilities: {
|
|
1663
|
+
...caps,
|
|
1664
|
+
...media === undefined ? {} : {
|
|
1665
|
+
inputMediaTypes: supported.filter((type) => media === "any" || media.includes(type) || type.startsWith("image/") && media.includes("image/*"))
|
|
1666
|
+
},
|
|
1667
|
+
...reasoning === undefined ? {} : { reasoning },
|
|
1668
|
+
...protocol === "chat" && options.profile === "deepseek" ? { nativeStructuredOutput: false } : {},
|
|
1669
|
+
...caps.providerExecutedTools ? { providerExecutedTools: false } : {}
|
|
1670
|
+
}
|
|
1671
|
+
});
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
// src/provider.ts
|
|
1675
|
+
function createAzureAIFoundry(options) {
|
|
1676
|
+
const transport = new FoundryTransport(options);
|
|
1677
|
+
const providerId = options.providerId ?? "azure-ai-foundry";
|
|
1678
|
+
if (!providerId.trim())
|
|
1679
|
+
throw new TypeError(`${PREFIX} providerId must not be empty.`);
|
|
1680
|
+
const deployments = new FoundryDeployments(providerId, transport, options.discovery);
|
|
1681
|
+
const modelCatalog = new RemoteModelsDevCatalog(options.catalog);
|
|
1682
|
+
const model = (protocol, deploymentName, modelOptions) => {
|
|
1683
|
+
if (!deploymentName.trim() || deploymentName !== deploymentName.trim())
|
|
1684
|
+
throw new TypeError(`${PREFIX} deploymentName must be nonempty without surrounding whitespace.`);
|
|
1685
|
+
return new FoundryModel(protocol, transport, deployments, providerId, deploymentName, modelOptions, modelCatalog);
|
|
1686
|
+
};
|
|
1687
|
+
const responses = (name, options = {}) => model("responses", name, options);
|
|
1688
|
+
const messages = (name, options = {}) => model("messages", name, options);
|
|
1689
|
+
const chat = (name, options = {}) => model("chat", name, options);
|
|
1690
|
+
const list = async (protocol, refresh = false) => {
|
|
1691
|
+
if (refresh)
|
|
1692
|
+
modelCatalog.invalidate();
|
|
1693
|
+
const records = await deployments.list(refresh);
|
|
1694
|
+
const lookup = records.length ? await modelCatalog.lookup() : undefined;
|
|
1695
|
+
const results = [];
|
|
1696
|
+
for (const deployment of records) {
|
|
1697
|
+
const name = deployment.name;
|
|
1698
|
+
try {
|
|
1699
|
+
const profile = resolveModel({
|
|
1700
|
+
providerId,
|
|
1701
|
+
modelId: name,
|
|
1702
|
+
protocol,
|
|
1703
|
+
options: {},
|
|
1704
|
+
deployment,
|
|
1705
|
+
catalogModel: lookup?.(deployment.modelName)
|
|
1706
|
+
});
|
|
1707
|
+
const flags = deployment.capabilities;
|
|
1708
|
+
const supported = profile.metadata.catalog || (profile.protocol === "responses" ? flags?.responses === "true" : profile.protocol === "chat" ? flags?.chatCompletion === "true" || flags?.chat_completion === "true" : flags?.messages === "true");
|
|
1709
|
+
if (supported)
|
|
1710
|
+
results.push(profile.definition);
|
|
1711
|
+
} catch (error) {
|
|
1712
|
+
if (!(error instanceof UnsupportedModelFeatureError5))
|
|
1713
|
+
throw error;
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
return Object.freeze(results);
|
|
1717
|
+
};
|
|
1718
|
+
const catalog = {
|
|
1719
|
+
get: async (name, options) => (await list(options?.protocol)).find((d) => d.modelId === name),
|
|
1720
|
+
list: (options) => list(options?.protocol),
|
|
1721
|
+
refresh: (options) => list(options?.protocol, true),
|
|
1722
|
+
deployments: () => deployments.list()
|
|
1723
|
+
};
|
|
1724
|
+
const auto = (name, options = {}) => model(undefined, name, options);
|
|
1725
|
+
return Object.assign(auto, { providerId, catalog, responses, messages, chat });
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
class FoundryModel {
|
|
1729
|
+
requestedProtocol;
|
|
1730
|
+
transport;
|
|
1731
|
+
deployments;
|
|
1732
|
+
providerId;
|
|
1733
|
+
modelId;
|
|
1734
|
+
modelCatalog;
|
|
1735
|
+
resolution;
|
|
1736
|
+
profile;
|
|
1737
|
+
estimator;
|
|
1738
|
+
#execution;
|
|
1739
|
+
#pendingExecution;
|
|
1740
|
+
get protocol() {
|
|
1741
|
+
return this.#execution?.profile.protocol ?? this.profile.protocol;
|
|
1742
|
+
}
|
|
1743
|
+
get definition() {
|
|
1744
|
+
return this.#execution?.profile.definition ?? this.profile.definition;
|
|
1745
|
+
}
|
|
1746
|
+
get metadata() {
|
|
1747
|
+
return this.#execution?.profile.metadata ?? this.profile.metadata;
|
|
1748
|
+
}
|
|
1749
|
+
get costEstimator() {
|
|
1750
|
+
return this.#execution?.estimator ?? this.estimator;
|
|
1751
|
+
}
|
|
1752
|
+
options;
|
|
1753
|
+
scope;
|
|
1754
|
+
reliableReasoning;
|
|
1755
|
+
constructor(requestedProtocol, transport, deployments, providerId, modelId, options, modelCatalog, resolution) {
|
|
1756
|
+
this.requestedProtocol = requestedProtocol;
|
|
1757
|
+
this.transport = transport;
|
|
1758
|
+
this.deployments = deployments;
|
|
1759
|
+
this.providerId = providerId;
|
|
1760
|
+
this.modelId = modelId;
|
|
1761
|
+
this.modelCatalog = modelCatalog;
|
|
1762
|
+
this.resolution = resolution;
|
|
1763
|
+
if (options.request !== undefined)
|
|
1764
|
+
assertJsonObject(options.request, `${PREFIX} request options`);
|
|
1765
|
+
if (options.rateCard && options.costEstimator)
|
|
1766
|
+
throw new TypeError(`${PREFIX} Configure either rateCard or costEstimator, not both.`);
|
|
1767
|
+
if (options.reasoningUsage !== undefined && !["reported", "unknown"].includes(options.reasoningUsage))
|
|
1768
|
+
throw new TypeError(`${PREFIX} Invalid reasoningUsage.`);
|
|
1769
|
+
this.profile = resolveModel({
|
|
1770
|
+
providerId,
|
|
1771
|
+
modelId,
|
|
1772
|
+
protocol: requestedProtocol,
|
|
1773
|
+
options,
|
|
1774
|
+
...this.resolution
|
|
1775
|
+
});
|
|
1776
|
+
const protocol = this.profile.protocol;
|
|
1777
|
+
if (protocol === "messages")
|
|
1778
|
+
validateMessagesOptions(options);
|
|
1779
|
+
else if (protocol === "chat")
|
|
1780
|
+
validateChatOptions(options);
|
|
1781
|
+
else
|
|
1782
|
+
validateOptions(options);
|
|
1783
|
+
const { costEstimator, ...serializable } = options;
|
|
1784
|
+
this.options = {
|
|
1785
|
+
...structuredClone(serializable),
|
|
1786
|
+
...costEstimator ? { costEstimator } : {}
|
|
1787
|
+
};
|
|
1788
|
+
this.scope = JSON.stringify([
|
|
1789
|
+
protocol === "messages" ? transport.url(protocol) : transport.baseUrl,
|
|
1790
|
+
this.protocol,
|
|
1791
|
+
modelId
|
|
1792
|
+
]);
|
|
1793
|
+
this.reliableReasoning = options.reasoningUsage === "unknown" ? false : options.reasoningUsage === "reported" || this.metadata.publisher?.toLowerCase() === "openai" ? true : undefined;
|
|
1794
|
+
this.estimator = options.costEstimator ?? (protocol === "messages" ? foundryMessagesEstimator : protocol === "chat" ? foundryChatEstimator : foundryEstimator)(this.profile.rateCard, this.options.request, this.metadata.modelName, this.metadata.modelVersion, this.profile.aliases);
|
|
1795
|
+
Object.freeze(this);
|
|
1796
|
+
}
|
|
1797
|
+
async resolve(options) {
|
|
1798
|
+
if (this.resolution)
|
|
1799
|
+
return this;
|
|
1800
|
+
const resolution = await this.deployments.resolve(this.modelId, options?.offline === true);
|
|
1801
|
+
let catalogModel;
|
|
1802
|
+
try {
|
|
1803
|
+
catalogModel = await this.modelCatalog.get(resolution.deployment.modelName, options?.offline);
|
|
1804
|
+
} catch (error) {
|
|
1805
|
+
if (!(error instanceof ModelCatalogUnavailableError3))
|
|
1806
|
+
throw error;
|
|
1807
|
+
catalogModel = await this.modelCatalog.get(resolution.deployment.modelName, true);
|
|
1808
|
+
if (!catalogModel && !this.options.definition)
|
|
1809
|
+
throw error;
|
|
1810
|
+
}
|
|
1811
|
+
return new FoundryModel(this.requestedProtocol, this.transport, this.deployments, this.providerId, this.modelId, this.options, this.modelCatalog, {
|
|
1812
|
+
...resolution,
|
|
1813
|
+
catalogModel
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
async stream(request) {
|
|
1817
|
+
request.signal.throwIfAborted();
|
|
1818
|
+
if (!this.resolution) {
|
|
1819
|
+
this.#pendingExecution ??= this.resolve().then((model) => {
|
|
1820
|
+
this.#execution = model;
|
|
1821
|
+
return model;
|
|
1822
|
+
}).catch((error) => {
|
|
1823
|
+
this.#pendingExecution = undefined;
|
|
1824
|
+
throw error;
|
|
1825
|
+
});
|
|
1826
|
+
const model = await abortable(() => this.#pendingExecution, request.signal);
|
|
1827
|
+
return model.stream(request);
|
|
1828
|
+
}
|
|
1829
|
+
const body = this.protocol === "messages" ? foundryMessagesRequest(request, this.definition, this.options, this.scope) : this.protocol === "chat" ? foundryChatRequest(request, this.definition, this.options, this.scope) : responsesRequest(request, this.definition, this.options, this.scope, this.resolution?.deployment);
|
|
1830
|
+
const response = await this.transport.post(JSON.stringify(body), request.signal, this.providerId, this.modelId, this.protocol);
|
|
1831
|
+
const id = this.transport.redactText(response, requestId(response));
|
|
1832
|
+
if (!response.body)
|
|
1833
|
+
throw new ModelProviderError4(`${PREFIX} Provider returned an empty streaming response.`, this.providerId, this.modelId, { requestId: id, status: response.status });
|
|
1834
|
+
const streamOptions = {
|
|
1835
|
+
providerId: this.providerId,
|
|
1836
|
+
modelId: this.modelId,
|
|
1837
|
+
requestId: id,
|
|
1838
|
+
errorPrefix: PREFIX
|
|
1839
|
+
};
|
|
1840
|
+
return {
|
|
1841
|
+
events: this.events(this.protocol === "messages" ? messagesEvents(response.body, request.signal, {
|
|
1842
|
+
...streamOptions,
|
|
1843
|
+
usage: foundryMessagesUsage
|
|
1844
|
+
}) : this.protocol === "chat" ? chatEvents(response.body, request.signal, {
|
|
1845
|
+
...streamOptions,
|
|
1846
|
+
usage: (raw) => foundryChatUsage(raw, this.reliableReasoning)
|
|
1847
|
+
}) : responsesEvents(response.body, request.signal, {
|
|
1848
|
+
...streamOptions,
|
|
1849
|
+
usage: (raw) => foundryUsage(raw, this.reliableReasoning),
|
|
1850
|
+
finishMetadata: (response) => {
|
|
1851
|
+
const metadata = {};
|
|
1852
|
+
for (const key of [
|
|
1853
|
+
"content_filters",
|
|
1854
|
+
"prompt_filter_results",
|
|
1855
|
+
"incomplete_details"
|
|
1856
|
+
]) {
|
|
1857
|
+
if (response[key] !== undefined)
|
|
1858
|
+
metadata[key] = response[key];
|
|
1859
|
+
}
|
|
1860
|
+
return {
|
|
1861
|
+
providerData: { [this.providerId]: metadata },
|
|
1862
|
+
...typeof response.model === "string" ? { route: { modelId: response.model } } : {}
|
|
1863
|
+
};
|
|
1864
|
+
}
|
|
1865
|
+
}), response)
|
|
1866
|
+
};
|
|
1867
|
+
}
|
|
1868
|
+
async* events(source, response) {
|
|
1869
|
+
try {
|
|
1870
|
+
for await (const event of source) {
|
|
1871
|
+
if (event.type === "error" && event.error instanceof ModelProviderError4) {
|
|
1872
|
+
yield { ...event, error: this.transport.redactError(response, event.error) };
|
|
1873
|
+
} else if (event.type === "provider-state" && event.providerId === this.providerId) {
|
|
1874
|
+
yield { ...event, data: { ...object(event.data), scope: this.scope } };
|
|
1875
|
+
} else if ("providerData" in event && event.providerData?.[this.providerId]) {
|
|
1876
|
+
yield {
|
|
1877
|
+
...event,
|
|
1878
|
+
providerData: {
|
|
1879
|
+
...event.providerData,
|
|
1880
|
+
[this.providerId]: {
|
|
1881
|
+
...object(event.providerData[this.providerId]),
|
|
1882
|
+
scope: this.scope
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
};
|
|
1886
|
+
} else
|
|
1887
|
+
yield event;
|
|
1888
|
+
}
|
|
1889
|
+
} catch (error) {
|
|
1890
|
+
throw this.transport.redactFailure(response, error);
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
export {
|
|
1895
|
+
createAzureAIFoundry
|
|
1896
|
+
};
|
|
1897
|
+
|
|
1898
|
+
//# debugId=6D364F59E216D99A64756E2164756E21
|