@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/src/transport.ts
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { ModelProviderError } from "@sixb/core/models"
|
|
2
|
+
import { RequestDiagnostics } from "./diagnostics"
|
|
3
|
+
import { object, PREFIX, positiveInteger } from "./util"
|
|
4
|
+
|
|
5
|
+
export type ValueSource<T> = T | ((signal: AbortSignal) => T | Promise<T>)
|
|
6
|
+
export type FoundryProtocol = "responses" | "messages" | "chat"
|
|
7
|
+
|
|
8
|
+
export interface TransportOptions {
|
|
9
|
+
readonly endpoint: string
|
|
10
|
+
readonly apiKey: ValueSource<string | undefined>
|
|
11
|
+
readonly headers?: ValueSource<Readonly<Record<string, string>>>
|
|
12
|
+
readonly fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>
|
|
13
|
+
readonly maxRetries?: number
|
|
14
|
+
readonly maxRetryDelayMs?: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class FoundryTransport {
|
|
18
|
+
private readonly diagnostics = new WeakMap<Response, RequestDiagnostics>()
|
|
19
|
+
readonly baseUrl: string
|
|
20
|
+
readonly projectUrl: string
|
|
21
|
+
private readonly options: TransportOptions
|
|
22
|
+
|
|
23
|
+
constructor(options: TransportOptions) {
|
|
24
|
+
if (!URL.canParse(options.endpoint))
|
|
25
|
+
throw new TypeError(`${PREFIX} endpoint must be a valid project URL.`)
|
|
26
|
+
const url = new URL(options.endpoint)
|
|
27
|
+
if (
|
|
28
|
+
!["https:", "http:"].includes(url.protocol) ||
|
|
29
|
+
url.username ||
|
|
30
|
+
url.password ||
|
|
31
|
+
url.search ||
|
|
32
|
+
url.hash
|
|
33
|
+
) {
|
|
34
|
+
throw new TypeError(
|
|
35
|
+
`${PREFIX} endpoint must be an HTTP(S) project URL without credentials, query, or fragment.`
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
const path = url.pathname.replace(/\/+$/, "")
|
|
39
|
+
if (!/^\/api\/projects\/[^/]+$/.test(path))
|
|
40
|
+
throw new TypeError(
|
|
41
|
+
`${PREFIX} endpoint must be a Foundry project URL: https://<resource>.services.ai.azure.com/api/projects/<project>.`
|
|
42
|
+
)
|
|
43
|
+
this.projectUrl = `${url.origin}${path}`
|
|
44
|
+
this.baseUrl = `${this.projectUrl}/openai/v1`
|
|
45
|
+
if (
|
|
46
|
+
typeof options.apiKey !== "function" &&
|
|
47
|
+
(typeof options.apiKey !== "string" || !options.apiKey.trim())
|
|
48
|
+
)
|
|
49
|
+
throw new TypeError(`${PREFIX} apiKey is required.`)
|
|
50
|
+
if (
|
|
51
|
+
options.maxRetries !== undefined &&
|
|
52
|
+
(!Number.isSafeInteger(options.maxRetries) || options.maxRetries < 0)
|
|
53
|
+
) {
|
|
54
|
+
throw new TypeError(`${PREFIX} maxRetries must be a nonnegative safe integer.`)
|
|
55
|
+
}
|
|
56
|
+
positiveInteger(options.maxRetryDelayMs, "maxRetryDelayMs")
|
|
57
|
+
this.options = {
|
|
58
|
+
...options,
|
|
59
|
+
headers: typeof options.headers === "function" ? options.headers : { ...options.headers },
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async post(
|
|
64
|
+
body: string,
|
|
65
|
+
signal: AbortSignal,
|
|
66
|
+
providerId: string,
|
|
67
|
+
modelId: string,
|
|
68
|
+
protocol: FoundryProtocol = "responses"
|
|
69
|
+
): Promise<Response> {
|
|
70
|
+
const url = this.url(protocol)
|
|
71
|
+
const diagnostics = new RequestDiagnostics()
|
|
72
|
+
for (let attempt = 0; ; attempt++) {
|
|
73
|
+
signal.throwIfAborted()
|
|
74
|
+
const headers = await this.headers(
|
|
75
|
+
signal,
|
|
76
|
+
diagnostics,
|
|
77
|
+
protocol === "messages" ? "x-api-key" : "api-key"
|
|
78
|
+
)
|
|
79
|
+
headers.set("content-type", "application/json")
|
|
80
|
+
headers.set("accept", "text/event-stream")
|
|
81
|
+
if (protocol === "messages") headers.set("anthropic-version", "2023-06-01")
|
|
82
|
+
signal.throwIfAborted()
|
|
83
|
+
// Ambiguous network failures and accepted streams are never automatically replayed.
|
|
84
|
+
const response = await abortable(async () => {
|
|
85
|
+
const result = await this.fetch(url, {
|
|
86
|
+
method: "POST",
|
|
87
|
+
// Redirects can forward API keys and prompt bodies to another origin.
|
|
88
|
+
redirect: "error",
|
|
89
|
+
headers,
|
|
90
|
+
body,
|
|
91
|
+
signal,
|
|
92
|
+
})
|
|
93
|
+
// An injected fetch can finish after the caller has already cancelled.
|
|
94
|
+
if (signal.aborted) void result.body?.cancel(signal.reason).catch(() => {})
|
|
95
|
+
return result
|
|
96
|
+
}, signal).catch((error: unknown) => {
|
|
97
|
+
if (signal.aborted) throw signal.reason
|
|
98
|
+
throw diagnostics.failure(error)
|
|
99
|
+
})
|
|
100
|
+
this.diagnostics.set(response, diagnostics)
|
|
101
|
+
if (signal.aborted) {
|
|
102
|
+
void response.body?.cancel(signal.reason).catch(() => {})
|
|
103
|
+
signal.throwIfAborted()
|
|
104
|
+
}
|
|
105
|
+
if (response.ok) return response
|
|
106
|
+
const error = this.redactError(
|
|
107
|
+
response,
|
|
108
|
+
await httpError(response, providerId, modelId, signal)
|
|
109
|
+
)
|
|
110
|
+
if (!error.retryable || attempt >= (this.options.maxRetries ?? 2)) throw error
|
|
111
|
+
await wait(
|
|
112
|
+
Math.min(error.retryAfterMs ?? 250 * 2 ** attempt, this.options.maxRetryDelayMs ?? 60_000),
|
|
113
|
+
signal
|
|
114
|
+
)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
redactText(response: Response, value: string | undefined): string | undefined {
|
|
119
|
+
return value === undefined ? undefined : (this.diagnostics.get(response)?.text(value) ?? value)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
redactError(response: Response, error: ModelProviderError): ModelProviderError {
|
|
123
|
+
return this.diagnostics.get(response)!.providerError(error)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
redactFailure(response: Response, error: unknown): unknown {
|
|
127
|
+
return this.diagnostics.get(response)!.failure(error)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async headers(
|
|
131
|
+
signal: AbortSignal,
|
|
132
|
+
diagnostics: RequestDiagnostics,
|
|
133
|
+
keyHeader: "api-key" | "x-api-key" = "api-key"
|
|
134
|
+
): Promise<Headers> {
|
|
135
|
+
const headers = new Headers(await resolve(this.options.headers, signal))
|
|
136
|
+
for (const value of headers.values()) diagnostics.add(value)
|
|
137
|
+
for (const reserved of ["authorization", "api-key", "x-api-key"])
|
|
138
|
+
if (headers.has(reserved))
|
|
139
|
+
throw new TypeError(`${PREFIX} Use apiKey instead of '${reserved}' headers.`)
|
|
140
|
+
const key = await resolve(this.options.apiKey, signal)
|
|
141
|
+
if (typeof key !== "string" || !key.trim())
|
|
142
|
+
throw new TypeError(`${PREFIX} apiKey must resolve to a nonempty string.`)
|
|
143
|
+
diagnostics.add(key)
|
|
144
|
+
headers.set(keyHeader, key)
|
|
145
|
+
return headers
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
fetch(url: string, init: RequestInit): Promise<Response> {
|
|
149
|
+
return (this.options.fetch ?? fetch)(url, init)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
url(protocol: FoundryProtocol): string {
|
|
153
|
+
if (protocol === "responses") return `${this.baseUrl}/responses`
|
|
154
|
+
if (protocol === "chat") return `${this.baseUrl}/chat/completions`
|
|
155
|
+
return `${new URL(this.baseUrl).origin}/anthropic/v1/messages`
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function requestId(response: Response): string | undefined {
|
|
160
|
+
return (
|
|
161
|
+
response.headers.get("apim-request-id") ??
|
|
162
|
+
response.headers.get("x-request-id") ??
|
|
163
|
+
response.headers.get("request-id") ??
|
|
164
|
+
undefined
|
|
165
|
+
)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function resolve<T>(
|
|
169
|
+
source: ValueSource<T> | undefined,
|
|
170
|
+
signal: AbortSignal
|
|
171
|
+
): Promise<T | undefined> {
|
|
172
|
+
signal.throwIfAborted()
|
|
173
|
+
if (typeof source !== "function") return source
|
|
174
|
+
return abortable(() => (source as (signal: AbortSignal) => T | Promise<T>)(signal), signal)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Bound credential/transport work even when an injected implementation ignores the signal. */
|
|
178
|
+
export function abortable<T>(operation: () => T | Promise<T>, signal: AbortSignal): Promise<T> {
|
|
179
|
+
return new Promise<T>((resolve, reject) => {
|
|
180
|
+
signal.throwIfAborted()
|
|
181
|
+
const abort = () => {
|
|
182
|
+
signal.removeEventListener("abort", abort)
|
|
183
|
+
reject(signal.reason)
|
|
184
|
+
}
|
|
185
|
+
signal.addEventListener("abort", abort, { once: true })
|
|
186
|
+
Promise.resolve()
|
|
187
|
+
.then(() => {
|
|
188
|
+
signal.throwIfAborted()
|
|
189
|
+
return operation()
|
|
190
|
+
})
|
|
191
|
+
.then(resolve, reject)
|
|
192
|
+
.finally(() => signal.removeEventListener("abort", abort))
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function httpError(
|
|
197
|
+
response: Response,
|
|
198
|
+
providerId: string,
|
|
199
|
+
modelId: string,
|
|
200
|
+
signal: AbortSignal
|
|
201
|
+
): Promise<ModelProviderError> {
|
|
202
|
+
let message = `Provider request failed with HTTP ${response.status}.`
|
|
203
|
+
let code: string | undefined
|
|
204
|
+
const reader = response.body?.getReader()
|
|
205
|
+
if (reader) {
|
|
206
|
+
const cancel = () => {
|
|
207
|
+
void reader.cancel(signal.reason).catch(() => {})
|
|
208
|
+
}
|
|
209
|
+
signal.addEventListener("abort", cancel, { once: true })
|
|
210
|
+
const chunks: Uint8Array[] = []
|
|
211
|
+
let length = 0
|
|
212
|
+
try {
|
|
213
|
+
while (length < 8_192) {
|
|
214
|
+
signal.throwIfAborted()
|
|
215
|
+
const { value, done } = await abortable(() => reader.read(), signal)
|
|
216
|
+
if (done) break
|
|
217
|
+
const part = value.subarray(0, 8_192 - length)
|
|
218
|
+
chunks.push(part)
|
|
219
|
+
length += part.length
|
|
220
|
+
}
|
|
221
|
+
const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8"))
|
|
222
|
+
const error = object(object(parsed)?.error)
|
|
223
|
+
if (typeof error?.message === "string") message = error.message
|
|
224
|
+
if (typeof error?.code === "string") code = error.code
|
|
225
|
+
else if (typeof error?.type === "string") code = error.type
|
|
226
|
+
} catch {
|
|
227
|
+
// Arbitrary/partial error bodies stay private; the HTTP status remains actionable.
|
|
228
|
+
} finally {
|
|
229
|
+
signal.removeEventListener("abort", cancel)
|
|
230
|
+
void reader.cancel().catch(() => {})
|
|
231
|
+
reader.releaseLock()
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
signal.throwIfAborted()
|
|
235
|
+
const delay =
|
|
236
|
+
response.headers.get("retry-after-ms") ?? response.headers.get("x-ms-retry-after-ms")
|
|
237
|
+
const retry = response.headers.get("retry-after")
|
|
238
|
+
const ms =
|
|
239
|
+
delay !== null
|
|
240
|
+
? Number(delay)
|
|
241
|
+
: retry !== null
|
|
242
|
+
? Number.isFinite(Number(retry))
|
|
243
|
+
? Number(retry) * 1_000
|
|
244
|
+
: Date.parse(retry) - Date.now()
|
|
245
|
+
: undefined
|
|
246
|
+
return new ModelProviderError(`${PREFIX} ${message}`, providerId, modelId, {
|
|
247
|
+
status: response.status,
|
|
248
|
+
requestId: requestId(response),
|
|
249
|
+
code,
|
|
250
|
+
retryable: response.status === 408 || response.status === 429 || response.status >= 500,
|
|
251
|
+
...(ms !== undefined && Number.isFinite(ms) && ms >= 0 ? { retryAfterMs: Math.ceil(ms) } : {}),
|
|
252
|
+
})
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function wait(ms: number, signal: AbortSignal): Promise<void> {
|
|
256
|
+
signal.throwIfAborted()
|
|
257
|
+
await new Promise<void>((resolve, reject) => {
|
|
258
|
+
const abort = () => {
|
|
259
|
+
clearTimeout(timer)
|
|
260
|
+
reject(signal.reason)
|
|
261
|
+
}
|
|
262
|
+
const timer = setTimeout(() => {
|
|
263
|
+
signal.removeEventListener("abort", abort)
|
|
264
|
+
resolve()
|
|
265
|
+
}, ms)
|
|
266
|
+
signal.addEventListener("abort", abort, { once: true })
|
|
267
|
+
})
|
|
268
|
+
}
|
package/src/util.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { isJsonObject, type JsonObject } from "@sixb/core/models"
|
|
2
|
+
|
|
3
|
+
export const PREFIX = "[SixbAzureAIFoundry]"
|
|
4
|
+
|
|
5
|
+
export function object(value: unknown): JsonObject | undefined {
|
|
6
|
+
return isJsonObject(value) ? value : undefined
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function positiveInteger(value: number | undefined, field: string): void {
|
|
10
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {
|
|
11
|
+
throw new TypeError(`${PREFIX} ${field} must be a positive safe integer.`)
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function counter(value: unknown): number | undefined {
|
|
15
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined
|
|
16
|
+
}
|