@enlitt/sdk 0.0.0-stage → 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/CHANGELOG.md +35 -0
- package/LICENSE +21 -0
- package/README.md +63 -2
- package/dist/browser/auth.d.cts +44 -0
- package/dist/browser/auth.d.ts +45 -0
- package/dist/browser/auth.d.ts.map +1 -0
- package/dist/browser.cjs +35 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +12 -0
- package/dist/browser.d.ts +13 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +32 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-2BGWYTJM.cjs +1097 -0
- package/dist/chunk-2BGWYTJM.cjs.map +1 -0
- package/dist/chunk-6OWXYBBT.cjs +146 -0
- package/dist/chunk-6OWXYBBT.cjs.map +1 -0
- package/dist/chunk-NI6WH5FI.js +33 -0
- package/dist/chunk-NI6WH5FI.js.map +1 -0
- package/dist/chunk-O6ASIA3X.js +866 -0
- package/dist/chunk-O6ASIA3X.js.map +1 -0
- package/dist/chunk-PPOUNWNA.cjs +895 -0
- package/dist/chunk-PPOUNWNA.cjs.map +1 -0
- package/dist/chunk-UVZMKGIL.js +1091 -0
- package/dist/chunk-UVZMKGIL.js.map +1 -0
- package/dist/chunk-V5TCSQ7C.js +143 -0
- package/dist/chunk-V5TCSQ7C.js.map +1 -0
- package/dist/chunk-YPA4R65T.cjs +35 -0
- package/dist/chunk-YPA4R65T.cjs.map +1 -0
- package/dist/core/errors.d.cts +262 -0
- package/dist/core/errors.d.ts +263 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/index.d.cts +24 -0
- package/dist/core/index.d.ts +25 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/premium.d.cts +230 -0
- package/dist/core/premium.d.ts +231 -0
- package/dist/core/premium.d.ts.map +1 -0
- package/dist/core/session.d.cts +122 -0
- package/dist/core/session.d.ts +123 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/sse.d.cts +79 -0
- package/dist/core/sse.d.ts +80 -0
- package/dist/core/sse.d.ts.map +1 -0
- package/dist/core/transport.d.cts +223 -0
- package/dist/core/transport.d.ts +224 -0
- package/dist/core/transport.d.ts.map +1 -0
- package/dist/core/usage.d.cts +35 -0
- package/dist/core/usage.d.ts +36 -0
- package/dist/core/usage.d.ts.map +1 -0
- package/dist/core.cjs +77 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.js +4 -0
- package/dist/core.js.map +1 -0
- package/dist/index.cjs +4 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +16 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/openai/client.d.cts +72 -0
- package/dist/openai/client.d.ts +73 -0
- package/dist/openai/client.d.ts.map +1 -0
- package/dist/openai/index.d.cts +2 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/media.d.cts +108 -0
- package/dist/openai/media.d.ts +109 -0
- package/dist/openai/media.d.ts.map +1 -0
- package/dist/openai.cjs +623 -0
- package/dist/openai.cjs.map +1 -0
- package/dist/openai.js +617 -0
- package/dist/openai.js.map +1 -0
- package/dist/server/callback.d.cts +107 -0
- package/dist/server/callback.d.ts +108 -0
- package/dist/server/callback.d.ts.map +1 -0
- package/dist/server/client-sign-in.d.cts +77 -0
- package/dist/server/client-sign-in.d.ts +78 -0
- package/dist/server/client-sign-in.d.ts.map +1 -0
- package/dist/server/index.d.cts +20 -0
- package/dist/server/index.d.ts +21 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/secrets.d.cts +46 -0
- package/dist/server/secrets.d.ts +47 -0
- package/dist/server/secrets.d.ts.map +1 -0
- package/dist/server-unavailable.cjs +8 -0
- package/dist/server-unavailable.cjs.map +1 -0
- package/dist/server-unavailable.d.cts +10 -0
- package/dist/server-unavailable.d.ts +11 -0
- package/dist/server-unavailable.d.ts.map +1 -0
- package/dist/server-unavailable.js +6 -0
- package/dist/server-unavailable.js.map +1 -0
- package/dist/server.cjs +880 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.js +795 -0
- package/dist/server.js.map +1 -0
- package/dist/vercel/index.d.cts +17 -0
- package/dist/vercel/index.d.ts +18 -0
- package/dist/vercel/index.d.ts.map +1 -0
- package/dist/vercel/language-model.d.cts +146 -0
- package/dist/vercel/language-model.d.ts +147 -0
- package/dist/vercel/language-model.d.ts.map +1 -0
- package/dist/vercel/premium-language-model.d.cts +127 -0
- package/dist/vercel/premium-language-model.d.ts +128 -0
- package/dist/vercel/premium-language-model.d.ts.map +1 -0
- package/dist/vercel/premium-media-model.d.cts +101 -0
- package/dist/vercel/premium-media-model.d.ts +102 -0
- package/dist/vercel/premium-media-model.d.ts.map +1 -0
- package/dist/vercel/standard-language-model.d.cts +104 -0
- package/dist/vercel/standard-language-model.d.ts +105 -0
- package/dist/vercel/standard-language-model.d.ts.map +1 -0
- package/dist/vercel.cjs +22 -0
- package/dist/vercel.cjs.map +1 -0
- package/dist/vercel.js +5 -0
- package/dist/vercel.js.map +1 -0
- package/package.json +139 -3
package/dist/openai.js
ADDED
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
import { createSseEventStream } from './chunk-V5TCSQ7C.js';
|
|
2
|
+
import { EnlittConfigurationError, createInternalClient, requestEnlitt, EnlittError, readEnlittJson, assertCallerMetadata, assertNanoUsd, generateRandomCallId, assertCallId, assertReportingDeadlineMs, runPremiumCharge, isCancellation } from './chunk-O6ASIA3X.js';
|
|
3
|
+
import { ENLITT_STANDARD_MODEL, validateOpenAIResponse, validateEnlittStandardRequest, validateResponseStreamEvent } from '@enlitt/protocol';
|
|
4
|
+
export { ENLITT_STANDARD_MODEL } from '@enlitt/protocol';
|
|
5
|
+
|
|
6
|
+
function createMediaMethods(client, provider) {
|
|
7
|
+
return {
|
|
8
|
+
images: {
|
|
9
|
+
generate: async (body, options) => {
|
|
10
|
+
validateRequestOptions(options);
|
|
11
|
+
assertPremiumModel(body, provider);
|
|
12
|
+
if (typeof body.model !== "string" || body.model.length === 0) {
|
|
13
|
+
throw new EnlittConfigurationError(
|
|
14
|
+
"images.generate() through Enlitt requires a model name, so the operation names the model it paid for."
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
if (body.stream === true) {
|
|
18
|
+
throw new EnlittConfigurationError("Streaming image generation is not supported through Enlitt.");
|
|
19
|
+
}
|
|
20
|
+
const method = requireMethod(provider?.images?.generate, "images.generate");
|
|
21
|
+
const { enlitt: _removed, ...request } = body;
|
|
22
|
+
return runMediaCall(client, body, options, {
|
|
23
|
+
kind: "image",
|
|
24
|
+
request,
|
|
25
|
+
invoke: () => method.call(provider.images, request, options),
|
|
26
|
+
facts: imageUsageFacts
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
audio: {
|
|
31
|
+
speech: {
|
|
32
|
+
create: async (body, options) => {
|
|
33
|
+
validateRequestOptions(options);
|
|
34
|
+
assertPremiumModel(body, provider);
|
|
35
|
+
const method = requireMethod(provider?.audio?.speech?.create, "audio.speech.create");
|
|
36
|
+
const { enlitt: _removed, ...request } = body;
|
|
37
|
+
return runMediaCall(client, body, options, {
|
|
38
|
+
kind: "speech",
|
|
39
|
+
request,
|
|
40
|
+
characters: [...request.input].length,
|
|
41
|
+
// The `Response` body is the caller's; the adapter never reads it.
|
|
42
|
+
invoke: () => method.call(provider.audio.speech, request, options),
|
|
43
|
+
facts: () => ({})
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
transcriptions: {
|
|
48
|
+
create: async (body, options) => {
|
|
49
|
+
validateRequestOptions(options);
|
|
50
|
+
assertPremiumModel(body, provider);
|
|
51
|
+
if (body.stream === true) {
|
|
52
|
+
throw new EnlittConfigurationError("Streaming transcription is not supported through Enlitt.");
|
|
53
|
+
}
|
|
54
|
+
const method = requireMethod(provider?.audio?.transcriptions?.create, "audio.transcriptions.create");
|
|
55
|
+
const { enlitt: _removed, ...request } = body;
|
|
56
|
+
return runMediaCall(client, body, options, {
|
|
57
|
+
kind: "transcription",
|
|
58
|
+
request,
|
|
59
|
+
invoke: () => method.call(provider.audio.transcriptions, request, options),
|
|
60
|
+
facts: () => ({})
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function assertPremiumModel(body, provider) {
|
|
68
|
+
if (body.model === ENLITT_STANDARD_MODEL) {
|
|
69
|
+
throw new EnlittConfigurationError(
|
|
70
|
+
`Enlitt has no standard image or audio model; "${ENLITT_STANDARD_MODEL}" is a language model only.`
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
if (provider === void 0) {
|
|
74
|
+
throw new EnlittConfigurationError("A premium OpenAI model requires an OpenAI client passed to enlitt().");
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function requireMethod(method, name) {
|
|
78
|
+
if (typeof method !== "function") {
|
|
79
|
+
throw new EnlittConfigurationError(`The OpenAI client passed to enlitt() does not expose ${name}().`);
|
|
80
|
+
}
|
|
81
|
+
return method;
|
|
82
|
+
}
|
|
83
|
+
async function runMediaCall(client, body, options, spec) {
|
|
84
|
+
const call = readCallOptions(body, "premium");
|
|
85
|
+
const price = call.price;
|
|
86
|
+
const signal = options?.signal;
|
|
87
|
+
const request = {
|
|
88
|
+
maxCharge: call.maxCharge,
|
|
89
|
+
provider: { id: "openai", model: String(body.model) },
|
|
90
|
+
callId: call.idempotencyKey,
|
|
91
|
+
...call.reportingDeadlineMs !== void 0 ? { reportingDeadlineMs: call.reportingDeadlineMs } : {},
|
|
92
|
+
...call.metadata !== void 0 ? { metadata: call.metadata } : {},
|
|
93
|
+
...signal !== void 0 ? { signal } : {}
|
|
94
|
+
};
|
|
95
|
+
return runPremiumCharge(client, request, async (charge, operation) => {
|
|
96
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
97
|
+
let result;
|
|
98
|
+
try {
|
|
99
|
+
result = await spec.invoke();
|
|
100
|
+
} catch (thrown) {
|
|
101
|
+
const endedAt2 = /* @__PURE__ */ new Date();
|
|
102
|
+
const canceled = isCancellation(thrown, signal);
|
|
103
|
+
if (canceled) {
|
|
104
|
+
charge(await evaluatePrice(client, price, buildContext(spec, "canceled", void 0, startedAt, endedAt2, operation)));
|
|
105
|
+
}
|
|
106
|
+
operation.describe({
|
|
107
|
+
timing: { startedAt: startedAt.toISOString(), endedAt: endedAt2.toISOString() },
|
|
108
|
+
delivery: { outputStarted: false, outputCompleted: false },
|
|
109
|
+
errorCategory: canceled ? "canceled" : "provider"
|
|
110
|
+
});
|
|
111
|
+
throw thrown;
|
|
112
|
+
}
|
|
113
|
+
const endedAt = /* @__PURE__ */ new Date();
|
|
114
|
+
charge(await evaluatePrice(client, price, buildContext(spec, "completed", result, startedAt, endedAt, operation)));
|
|
115
|
+
operation.describe({
|
|
116
|
+
timing: { startedAt: startedAt.toISOString(), endedAt: endedAt.toISOString() },
|
|
117
|
+
delivery: { outputStarted: true, outputCompleted: true },
|
|
118
|
+
...spec.facts(result)
|
|
119
|
+
});
|
|
120
|
+
return result;
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
function buildContext(spec, status, result, startedAt, endedAt, operation) {
|
|
124
|
+
const base = {
|
|
125
|
+
status,
|
|
126
|
+
startedAt,
|
|
127
|
+
endedAt,
|
|
128
|
+
durationMs: endedAt.getTime() - startedAt.getTime(),
|
|
129
|
+
effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd
|
|
130
|
+
};
|
|
131
|
+
if (spec.kind === "speech") {
|
|
132
|
+
return { ...base, kind: "speech", request: spec.request, characters: spec.characters };
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
...base,
|
|
136
|
+
kind: spec.kind,
|
|
137
|
+
request: spec.request,
|
|
138
|
+
...result !== void 0 ? { response: result } : {}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function imageUsageFacts(result) {
|
|
142
|
+
const usage = result?.usage;
|
|
143
|
+
if (usage === void 0) return {};
|
|
144
|
+
return { usage: { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens } };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/openai/client.ts
|
|
148
|
+
var RESPONSES_PATH = "/v1/responses";
|
|
149
|
+
var STANDARD_FIELDS = /* @__PURE__ */ new Set(["model", "input", "instructions", "max_output_tokens", "tools", "tool_choice", "stream", "metadata", "enlitt"]);
|
|
150
|
+
function enlitt(first = {}, second = {}) {
|
|
151
|
+
const looksLikeClient = hasResponsesProperty(first);
|
|
152
|
+
let provider;
|
|
153
|
+
let options;
|
|
154
|
+
if (looksLikeClient) {
|
|
155
|
+
if (!isOpenAIClient(first)) {
|
|
156
|
+
throw new EnlittConfigurationError("The OpenAI client must expose responses.create().");
|
|
157
|
+
}
|
|
158
|
+
provider = first;
|
|
159
|
+
options = second;
|
|
160
|
+
} else {
|
|
161
|
+
options = first;
|
|
162
|
+
}
|
|
163
|
+
const client = createInternalClient(options);
|
|
164
|
+
return {
|
|
165
|
+
// Premium-only image and audio methods (owner decision 2026-11-15).
|
|
166
|
+
...createMediaMethods(client, provider),
|
|
167
|
+
responses: {
|
|
168
|
+
create: (body, requestOptions) => {
|
|
169
|
+
validateRequestOptions(requestOptions);
|
|
170
|
+
return body.model === ENLITT_STANDARD_MODEL ? createStandardResponse(client, body, requestOptions) : createPremiumResponse(client, provider, body, requestOptions);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function hasResponsesProperty(value) {
|
|
176
|
+
return typeof value === "object" && value !== null && "responses" in value;
|
|
177
|
+
}
|
|
178
|
+
function isOpenAIClient(value) {
|
|
179
|
+
if (!hasResponsesProperty(value)) return false;
|
|
180
|
+
const responses = value.responses;
|
|
181
|
+
return typeof responses === "object" && responses !== null && typeof responses.create === "function";
|
|
182
|
+
}
|
|
183
|
+
function validateRequestOptions(options) {
|
|
184
|
+
if (options === void 0) return;
|
|
185
|
+
for (const key of Object.keys(options)) {
|
|
186
|
+
if (key !== "signal" && key !== "timeout") {
|
|
187
|
+
throw new EnlittConfigurationError(`OpenAI request option "${key}" is not supported by the Enlitt adapter.`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (options.timeout !== void 0 && (!Number.isSafeInteger(options.timeout) || options.timeout <= 0)) {
|
|
191
|
+
throw new EnlittConfigurationError("OpenAI request option timeout must be a positive safe integer.");
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function readCallOptions(body, mode) {
|
|
195
|
+
const input = body.enlitt ?? {};
|
|
196
|
+
const known = /* @__PURE__ */ new Set(["idempotencyKey", "maxCharge", "price", "reportingDeadlineMs", "metadata"]);
|
|
197
|
+
for (const key of Object.keys(input)) {
|
|
198
|
+
if (!known.has(key)) throw new EnlittConfigurationError(`enlitt.${key} is not a recognized Enlitt option.`);
|
|
199
|
+
}
|
|
200
|
+
if (mode === "standard" && (input.maxCharge !== void 0 || input.price !== void 0 || input.reportingDeadlineMs !== void 0)) {
|
|
201
|
+
throw new EnlittConfigurationError("maxCharge, price, and reportingDeadlineMs are premium-only options.");
|
|
202
|
+
}
|
|
203
|
+
const idempotencyKey = input.idempotencyKey === void 0 ? generateRandomCallId() : assertCallId(input.idempotencyKey);
|
|
204
|
+
const metadata = input.metadata === void 0 ? void 0 : assertCallerMetadata(input.metadata, "enlitt.metadata");
|
|
205
|
+
if (mode === "standard") return { idempotencyKey, metadata };
|
|
206
|
+
const price = input.price;
|
|
207
|
+
if (price !== void 0 && typeof price !== "string" && typeof price !== "function") {
|
|
208
|
+
throw new EnlittConfigurationError("enlitt.price must be a canonical NANOUSD string or a function.");
|
|
209
|
+
}
|
|
210
|
+
const constantPrice = typeof price === "string" ? assertNanoUsd(price, "enlitt.price") : price;
|
|
211
|
+
const maxCharge = input.maxCharge === void 0 ? typeof constantPrice === "string" ? constantPrice : void 0 : assertNanoUsd(input.maxCharge, "enlitt.maxCharge");
|
|
212
|
+
if (maxCharge === void 0) {
|
|
213
|
+
throw new EnlittConfigurationError("A premium call requires enlitt.maxCharge, or a constant enlitt.price.");
|
|
214
|
+
}
|
|
215
|
+
if (typeof constantPrice === "string" && BigInt(constantPrice) > BigInt(maxCharge)) {
|
|
216
|
+
throw new EnlittConfigurationError("enlitt.price cannot exceed enlitt.maxCharge.");
|
|
217
|
+
}
|
|
218
|
+
const reportingDeadlineMs = input.reportingDeadlineMs === void 0 ? void 0 : assertReportingDeadlineMs(input.reportingDeadlineMs, "enlitt.reportingDeadlineMs");
|
|
219
|
+
return { idempotencyKey, metadata, maxCharge, price: constantPrice, reportingDeadlineMs };
|
|
220
|
+
}
|
|
221
|
+
function timedSignal(options) {
|
|
222
|
+
if (options?.timeout === void 0) return { ...options?.signal !== void 0 ? { signal: options.signal } : {}, cleanup: () => void 0 };
|
|
223
|
+
const controller = new AbortController();
|
|
224
|
+
const abort = () => controller.abort(options.signal?.reason);
|
|
225
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
226
|
+
const timer = setTimeout(() => controller.abort(new DOMException("The request timed out.", "AbortError")), options.timeout);
|
|
227
|
+
return {
|
|
228
|
+
signal: controller.signal,
|
|
229
|
+
cleanup() {
|
|
230
|
+
clearTimeout(timer);
|
|
231
|
+
options.signal?.removeEventListener("abort", abort);
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
async function createStandardResponse(client, body, options) {
|
|
236
|
+
const call = readCallOptions(body, "standard");
|
|
237
|
+
const request = buildStandardRequest(body, call.metadata);
|
|
238
|
+
const timed = timedSignal(options);
|
|
239
|
+
try {
|
|
240
|
+
const response = await requestEnlitt(client, {
|
|
241
|
+
path: RESPONSES_PATH,
|
|
242
|
+
body: request,
|
|
243
|
+
callId: call.idempotencyKey,
|
|
244
|
+
accept: body.stream === true ? "text/event-stream" : "application/json",
|
|
245
|
+
...timed.signal !== void 0 ? { signal: timed.signal } : {}
|
|
246
|
+
});
|
|
247
|
+
if (body.stream === true) {
|
|
248
|
+
if (response.body === null) throw new EnlittError("malformed_response", "Enlitt's streaming response carried no body.");
|
|
249
|
+
return mapStandardStream(response.body, () => timed.cleanup());
|
|
250
|
+
}
|
|
251
|
+
const parsed = validateOpenAIResponse(await readEnlittJson(response), { mode: "tolerant" });
|
|
252
|
+
if (!parsed.ok) throw malformed(parsed.error.message, parsed.error.param);
|
|
253
|
+
return mapStandardResponse(parsed.value);
|
|
254
|
+
} finally {
|
|
255
|
+
if (body.stream !== true) timed.cleanup();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
function buildStandardRequest(body, metadata) {
|
|
259
|
+
for (const key of Object.keys(body)) {
|
|
260
|
+
if (!STANDARD_FIELDS.has(key)) throw new EnlittConfigurationError(`OpenAI field "${key}" is not supported by Enlitt's standard route.`);
|
|
261
|
+
}
|
|
262
|
+
const messages = [];
|
|
263
|
+
if (body.instructions !== void 0 && body.instructions !== null) {
|
|
264
|
+
if (typeof body.instructions !== "string") throw new EnlittConfigurationError("Standard instructions must be a string.");
|
|
265
|
+
messages.push({ role: "system", content: body.instructions });
|
|
266
|
+
}
|
|
267
|
+
messages.push(...mapInput(body.input));
|
|
268
|
+
const draft = { model: ENLITT_STANDARD_MODEL, messages };
|
|
269
|
+
if (body.max_output_tokens !== void 0 && body.max_output_tokens !== null) draft.max_output_tokens = body.max_output_tokens;
|
|
270
|
+
if (body.stream === true) draft.stream = true;
|
|
271
|
+
if (metadata !== void 0) draft.metadata = metadata;
|
|
272
|
+
if (body.metadata !== void 0 && body.metadata !== null) {
|
|
273
|
+
if (metadata !== void 0) throw new EnlittConfigurationError("Supply metadata under enlitt.metadata, not both metadata locations.");
|
|
274
|
+
draft.metadata = assertCallerMetadata(body.metadata, "metadata");
|
|
275
|
+
}
|
|
276
|
+
if (body.tool_choice !== void 0 && body.tool_choice !== "auto" && body.tool_choice !== "none") {
|
|
277
|
+
throw new EnlittConfigurationError("Standard tool_choice supports only auto or none.");
|
|
278
|
+
}
|
|
279
|
+
if (body.tools !== void 0 && body.tool_choice !== "none") {
|
|
280
|
+
draft.tools = body.tools.map((tool, index) => {
|
|
281
|
+
const value = tool;
|
|
282
|
+
if (value.type !== "function") throw new EnlittConfigurationError(`tools[${index}] must be a function tool.`);
|
|
283
|
+
if (value.strict !== void 0) throw new EnlittConfigurationError(`tools[${index}].strict is not supported.`);
|
|
284
|
+
return { name: value.name, ...value.description !== void 0 ? { description: value.description } : {}, input_schema: value.parameters };
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
const validated = validateEnlittStandardRequest(draft);
|
|
288
|
+
if (!validated.ok) throw new EnlittConfigurationError(`${validated.error.message} (${validated.error.param})`);
|
|
289
|
+
return validated.value;
|
|
290
|
+
}
|
|
291
|
+
function mapInput(input) {
|
|
292
|
+
if (typeof input === "string") return [{ role: "user", content: [{ type: "text", text: input }] }];
|
|
293
|
+
if (!Array.isArray(input)) throw new EnlittConfigurationError("Standard input must be a string or an array of supported input items.");
|
|
294
|
+
return input.map((item, index) => {
|
|
295
|
+
if (typeof item !== "object" || item === null) throw new EnlittConfigurationError(`input[${index}] is not supported.`);
|
|
296
|
+
const value = item;
|
|
297
|
+
if (value.type === "function_call") {
|
|
298
|
+
return { role: "assistant", tool_calls: [{ id: String(value.call_id), name: String(value.name), arguments: String(value.arguments) }] };
|
|
299
|
+
}
|
|
300
|
+
if (value.type === "function_call_output") {
|
|
301
|
+
if (typeof value.output !== "string") throw new EnlittConfigurationError(`input[${index}].output must be a string.`);
|
|
302
|
+
return { role: "tool", tool_call_id: String(value.call_id), content: value.output };
|
|
303
|
+
}
|
|
304
|
+
const role = value.role;
|
|
305
|
+
if (role !== "user" && role !== "system" && role !== "developer" && role !== "assistant") {
|
|
306
|
+
throw new EnlittConfigurationError(`input[${index}].role is not supported.`);
|
|
307
|
+
}
|
|
308
|
+
const content = value.content;
|
|
309
|
+
if (role === "system" || role === "developer") {
|
|
310
|
+
if (typeof content !== "string") throw new EnlittConfigurationError(`input[${index}].content must be a string.`);
|
|
311
|
+
return { role: "system", content };
|
|
312
|
+
}
|
|
313
|
+
if (role === "assistant") {
|
|
314
|
+
if (typeof content !== "string") throw new EnlittConfigurationError(`input[${index}].content must be a string.`);
|
|
315
|
+
return { role: "assistant", content };
|
|
316
|
+
}
|
|
317
|
+
const parts = typeof content === "string" ? [{ type: "input_text", text: content }] : content;
|
|
318
|
+
if (!Array.isArray(parts)) throw new EnlittConfigurationError(`input[${index}].content is not supported.`);
|
|
319
|
+
return {
|
|
320
|
+
role: "user",
|
|
321
|
+
content: parts.map((part, partIndex) => {
|
|
322
|
+
const p = part;
|
|
323
|
+
if (p.type === "input_text" && typeof p.text === "string") return { type: "text", text: p.text };
|
|
324
|
+
if (p.type === "input_image" && typeof p.image_url === "string") {
|
|
325
|
+
const match = /^data:(image\/(?:png|jpeg));base64,(.+)$/.exec(p.image_url);
|
|
326
|
+
return match ? { type: "image", source: { type: "base64", media_type: match[1], data: match[2] } } : { type: "image", source: { type: "url", url: p.image_url } };
|
|
327
|
+
}
|
|
328
|
+
throw new EnlittConfigurationError(`input[${index}].content[${partIndex}] is not supported.`);
|
|
329
|
+
})
|
|
330
|
+
};
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
function mapStandardResponse(value) {
|
|
334
|
+
const known = value.output.filter((item) => !("unknown" in item));
|
|
335
|
+
const output = known.map((item) => item.type === "message" ? { ...item, content: item.content.filter((part) => !("unknown" in part)).map((part) => ({ ...part, annotations: [] })) } : item);
|
|
336
|
+
return {
|
|
337
|
+
id: value.id,
|
|
338
|
+
access_programs: null,
|
|
339
|
+
created_at: value.created_at,
|
|
340
|
+
...value.completed_at !== void 0 ? { completed_at: value.completed_at } : {},
|
|
341
|
+
output_text: value.output_text ?? output.flatMap((item) => item.type === "message" ? item.content.flatMap((part) => "text" in part ? [part.text] : []) : []).join(""),
|
|
342
|
+
error: value.error,
|
|
343
|
+
incomplete_details: value.incomplete_details,
|
|
344
|
+
instructions: null,
|
|
345
|
+
metadata: value.metadata,
|
|
346
|
+
model: ENLITT_STANDARD_MODEL,
|
|
347
|
+
object: "response",
|
|
348
|
+
output,
|
|
349
|
+
parallel_tool_calls: false,
|
|
350
|
+
temperature: null,
|
|
351
|
+
tool_choice: "auto",
|
|
352
|
+
tools: [],
|
|
353
|
+
top_p: null,
|
|
354
|
+
status: value.status === "other" ? "failed" : value.status,
|
|
355
|
+
usage: value.usage
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
async function* mapStandardStream(stream, cleanup) {
|
|
359
|
+
let previous;
|
|
360
|
+
let previousJson;
|
|
361
|
+
let sawTerminal = false;
|
|
362
|
+
try {
|
|
363
|
+
for await (const framed of createSseEventStream(stream)) {
|
|
364
|
+
if (sawTerminal) throw malformed("a stream event followed the terminal event", "body");
|
|
365
|
+
let json;
|
|
366
|
+
try {
|
|
367
|
+
json = JSON.parse(framed.data);
|
|
368
|
+
} catch {
|
|
369
|
+
throw malformed("stream event was not valid JSON", "body");
|
|
370
|
+
}
|
|
371
|
+
const parsed = validateResponseStreamEvent(json, { mode: "tolerant" });
|
|
372
|
+
if (!parsed.ok) throw malformed(parsed.error.message, parsed.error.param);
|
|
373
|
+
const event = parsed.value;
|
|
374
|
+
const eventJson = JSON.stringify(event);
|
|
375
|
+
if (previous === void 0) {
|
|
376
|
+
if (event.type !== "response.created") {
|
|
377
|
+
throw malformed('the first stream event was not "response.created"', "body");
|
|
378
|
+
}
|
|
379
|
+
} else if (event.sequence_number === previous.sequence_number) {
|
|
380
|
+
if (eventJson === previousJson) continue;
|
|
381
|
+
throw malformed("two stream events reused a sequence number with different content", "body");
|
|
382
|
+
} else if (event.sequence_number !== previous.sequence_number + 1) {
|
|
383
|
+
throw malformed("stream event sequence numbers were not contiguous", "body");
|
|
384
|
+
}
|
|
385
|
+
previous = event;
|
|
386
|
+
previousJson = eventJson;
|
|
387
|
+
if ("unknown" in event) continue;
|
|
388
|
+
const mapped = mapStandardEvent(event);
|
|
389
|
+
if (mapped !== void 0) yield mapped;
|
|
390
|
+
sawTerminal = event.type === "response.completed" || event.type === "response.incomplete" || event.type === "response.failed";
|
|
391
|
+
}
|
|
392
|
+
if (!sawTerminal) throw malformed("the stream ended without a terminal event", "body");
|
|
393
|
+
} finally {
|
|
394
|
+
cleanup();
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
function mapStandardEvent(event) {
|
|
398
|
+
if ("response" in event) return { ...event, response: mapStandardResponse(event.response) };
|
|
399
|
+
if ("item" in event) {
|
|
400
|
+
if ("unknown" in event.item) return void 0;
|
|
401
|
+
const item = event.item.type === "message" ? { ...event.item, content: event.item.content.filter((part) => !("unknown" in part)).map((part) => ({ ...part, annotations: [] })) } : event.item;
|
|
402
|
+
return { ...event, item };
|
|
403
|
+
}
|
|
404
|
+
if ("part" in event) {
|
|
405
|
+
if ("unknown" in event.part) return void 0;
|
|
406
|
+
return { ...event, part: { ...event.part, annotations: [] } };
|
|
407
|
+
}
|
|
408
|
+
return event;
|
|
409
|
+
}
|
|
410
|
+
function malformed(message, param) {
|
|
411
|
+
return new EnlittError("malformed_response", `Enlitt's response could not be validated: ${message} (${param}).`);
|
|
412
|
+
}
|
|
413
|
+
async function createPremiumResponse(client, provider, body, options) {
|
|
414
|
+
if (provider === void 0) throw new EnlittConfigurationError("A premium OpenAI model requires an OpenAI client passed to enlitt().");
|
|
415
|
+
if (typeof body.model !== "string" || body.model.length === 0) throw new EnlittConfigurationError("A premium OpenAI call requires a model name.");
|
|
416
|
+
if (body.background === true) throw new EnlittConfigurationError("Background OpenAI responses are not supported.");
|
|
417
|
+
const call = readCallOptions(body, "premium");
|
|
418
|
+
const { enlitt: _removed, ...providerBody } = body;
|
|
419
|
+
const request = {
|
|
420
|
+
maxCharge: call.maxCharge,
|
|
421
|
+
provider: { id: "openai", model: body.model },
|
|
422
|
+
callId: call.idempotencyKey,
|
|
423
|
+
...call.reportingDeadlineMs !== void 0 ? { reportingDeadlineMs: call.reportingDeadlineMs } : {},
|
|
424
|
+
...call.metadata !== void 0 ? { metadata: call.metadata } : {},
|
|
425
|
+
...options?.signal !== void 0 ? { signal: options.signal } : {}
|
|
426
|
+
};
|
|
427
|
+
return body.stream === true ? wrapPremiumStream(client, provider, request, call.price, providerBody, options) : wrapPremiumResponse(client, provider, request, call.price, providerBody, options);
|
|
428
|
+
}
|
|
429
|
+
var TerminalResponse = class extends Error {
|
|
430
|
+
constructor(result, canceled) {
|
|
431
|
+
super();
|
|
432
|
+
this.result = result;
|
|
433
|
+
this.name = canceled ? "AbortError" : "TerminalResponse";
|
|
434
|
+
}
|
|
435
|
+
result;
|
|
436
|
+
};
|
|
437
|
+
async function wrapPremiumResponse(client, provider, request, price, body, options) {
|
|
438
|
+
try {
|
|
439
|
+
return await runPremiumCharge(client, request, async (charge, operation) => {
|
|
440
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
441
|
+
let response;
|
|
442
|
+
try {
|
|
443
|
+
response = await provider.responses.create(body, options);
|
|
444
|
+
} catch (error) {
|
|
445
|
+
if (isCancellation(error, request.signal)) {
|
|
446
|
+
const endedAt2 = /* @__PURE__ */ new Date();
|
|
447
|
+
charge(await evaluatePrice(
|
|
448
|
+
client,
|
|
449
|
+
price,
|
|
450
|
+
contextForEvents(
|
|
451
|
+
void 0,
|
|
452
|
+
void 0,
|
|
453
|
+
startedAt,
|
|
454
|
+
endedAt2,
|
|
455
|
+
operation,
|
|
456
|
+
void 0,
|
|
457
|
+
"canceled"
|
|
458
|
+
)
|
|
459
|
+
));
|
|
460
|
+
describe(operation, startedAt, endedAt2, void 0, "canceled");
|
|
461
|
+
}
|
|
462
|
+
throw error;
|
|
463
|
+
}
|
|
464
|
+
const endedAt = /* @__PURE__ */ new Date();
|
|
465
|
+
const canceled = response.status === "cancelled";
|
|
466
|
+
if (response.status !== "failed") charge(await evaluatePrice(client, price, contextForResponse(response, startedAt, endedAt, operation, canceled)));
|
|
467
|
+
describe(operation, startedAt, endedAt, response, response.status === "failed" ? "provider" : canceled ? "canceled" : void 0);
|
|
468
|
+
if (response.status === "failed" || canceled) throw new TerminalResponse(response, canceled);
|
|
469
|
+
return response;
|
|
470
|
+
});
|
|
471
|
+
} catch (thrown) {
|
|
472
|
+
if (thrown instanceof TerminalResponse) return thrown.result;
|
|
473
|
+
throw thrown;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
async function wrapPremiumStream(client, provider, request, price, body, options) {
|
|
477
|
+
let expose;
|
|
478
|
+
let rejectExpose;
|
|
479
|
+
const exposed = new Promise((resolve, reject) => {
|
|
480
|
+
expose = resolve;
|
|
481
|
+
rejectExpose = reject;
|
|
482
|
+
});
|
|
483
|
+
let wasExposed = false;
|
|
484
|
+
void runPremiumCharge(client, request, async (charge, operation) => {
|
|
485
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
486
|
+
let source;
|
|
487
|
+
try {
|
|
488
|
+
source = await provider.responses.create(body, options);
|
|
489
|
+
} catch (error) {
|
|
490
|
+
if (isCancellation(error, request.signal)) {
|
|
491
|
+
const endedAt = /* @__PURE__ */ new Date();
|
|
492
|
+
charge(await evaluatePrice(
|
|
493
|
+
client,
|
|
494
|
+
price,
|
|
495
|
+
contextForEvents(
|
|
496
|
+
typeof price === "function" ? [] : void 0,
|
|
497
|
+
void 0,
|
|
498
|
+
startedAt,
|
|
499
|
+
endedAt,
|
|
500
|
+
operation,
|
|
501
|
+
void 0,
|
|
502
|
+
"canceled"
|
|
503
|
+
)
|
|
504
|
+
));
|
|
505
|
+
describe(operation, startedAt, endedAt, void 0, "canceled");
|
|
506
|
+
}
|
|
507
|
+
rejectExpose(error);
|
|
508
|
+
throw error;
|
|
509
|
+
}
|
|
510
|
+
let settle;
|
|
511
|
+
let fail;
|
|
512
|
+
const terminal = new Promise((resolve, reject) => {
|
|
513
|
+
settle = resolve;
|
|
514
|
+
fail = reject;
|
|
515
|
+
});
|
|
516
|
+
wasExposed = true;
|
|
517
|
+
expose(streamWithSettlement(source, price, client, charge, operation, startedAt, settle, fail, request.signal));
|
|
518
|
+
return terminal;
|
|
519
|
+
}).catch((error) => {
|
|
520
|
+
if (!wasExposed) rejectExpose(error);
|
|
521
|
+
});
|
|
522
|
+
return exposed;
|
|
523
|
+
}
|
|
524
|
+
async function* streamWithSettlement(source, price, client, charge, operation, startedAt, settle, fail, signal) {
|
|
525
|
+
const events = typeof price === "function" ? [] : void 0;
|
|
526
|
+
let terminal = false;
|
|
527
|
+
let firstTokenAt;
|
|
528
|
+
try {
|
|
529
|
+
for await (const event of source) {
|
|
530
|
+
events?.push(event);
|
|
531
|
+
if (firstTokenAt === void 0 && (event.type === "response.output_text.delta" || event.type === "response.function_call_arguments.delta")) firstTokenAt = /* @__PURE__ */ new Date();
|
|
532
|
+
yield event;
|
|
533
|
+
if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
534
|
+
terminal = true;
|
|
535
|
+
const endedAt = /* @__PURE__ */ new Date();
|
|
536
|
+
charge(await evaluatePrice(client, price, contextForEvents(events, event.response.usage, startedAt, endedAt, operation, firstTokenAt, "completed")));
|
|
537
|
+
describe(operation, startedAt, endedAt, event.response);
|
|
538
|
+
settle();
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
if (event.type === "response.failed") {
|
|
542
|
+
terminal = true;
|
|
543
|
+
describe(operation, startedAt, /* @__PURE__ */ new Date(), event.response, "provider");
|
|
544
|
+
fail(new Error("OpenAI response failed"));
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
terminal = true;
|
|
549
|
+
fail(new Error("OpenAI stream ended without a terminal event"));
|
|
550
|
+
} catch (error) {
|
|
551
|
+
if (!terminal) {
|
|
552
|
+
terminal = true;
|
|
553
|
+
const endedAt = /* @__PURE__ */ new Date();
|
|
554
|
+
if (isCancellation(error, signal)) {
|
|
555
|
+
charge(await evaluatePrice(
|
|
556
|
+
client,
|
|
557
|
+
price,
|
|
558
|
+
contextForEvents(events, void 0, startedAt, endedAt, operation, firstTokenAt, "canceled")
|
|
559
|
+
));
|
|
560
|
+
describe(operation, startedAt, endedAt, void 0, "canceled");
|
|
561
|
+
} else {
|
|
562
|
+
describe(operation, startedAt, endedAt, void 0, "provider");
|
|
563
|
+
}
|
|
564
|
+
fail(error);
|
|
565
|
+
}
|
|
566
|
+
throw error;
|
|
567
|
+
} finally {
|
|
568
|
+
if (!terminal) {
|
|
569
|
+
const endedAt = /* @__PURE__ */ new Date();
|
|
570
|
+
charge(await evaluatePrice(client, price, contextForEvents(events, void 0, startedAt, endedAt, operation, firstTokenAt, "canceled")));
|
|
571
|
+
describe(operation, startedAt, endedAt, void 0, "canceled");
|
|
572
|
+
fail(new DOMException("OpenAI stream canceled", "AbortError"));
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
function contextForResponse(response, startedAt, endedAt, operation, canceled) {
|
|
577
|
+
return { status: canceled ? "canceled" : "completed", response, ...response.usage !== void 0 ? { usage: response.usage } : {}, startedAt, endedAt, durationMs: endedAt.getTime() - startedAt.getTime(), effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd };
|
|
578
|
+
}
|
|
579
|
+
function contextForEvents(events, usage, startedAt, endedAt, operation, firstTokenAt, status) {
|
|
580
|
+
return { status, ...events !== void 0 ? { events } : {}, ...usage !== void 0 ? { usage } : {}, startedAt, endedAt, durationMs: endedAt.getTime() - startedAt.getTime(), ...firstTokenAt !== void 0 ? { timeToFirstTokenMs: firstTokenAt.getTime() - startedAt.getTime() } : {}, effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd };
|
|
581
|
+
}
|
|
582
|
+
async function evaluatePrice(client, price, context) {
|
|
583
|
+
if (price === void 0) return "0";
|
|
584
|
+
if (typeof price === "string") return price;
|
|
585
|
+
try {
|
|
586
|
+
return assertNanoUsd(await price(context), "price() result");
|
|
587
|
+
} catch (error) {
|
|
588
|
+
client.onTerminalReportError?.(error instanceof EnlittError ? error : new EnlittConfigurationError(`The price function failed, so the call was charged "0": ${error instanceof Error ? error.message : String(error)}`));
|
|
589
|
+
return "0";
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
function describe(operation, startedAt, endedAt, response, errorCategory) {
|
|
593
|
+
const usage = response?.usage;
|
|
594
|
+
operation.describe({
|
|
595
|
+
timing: { startedAt: startedAt.toISOString(), endedAt: endedAt.toISOString() },
|
|
596
|
+
delivery: { outputStarted: response !== void 0, outputCompleted: response !== void 0 && response.status !== "failed" },
|
|
597
|
+
...response?.id !== void 0 ? { providerResponseId: response.id } : {},
|
|
598
|
+
...usage !== void 0 ? {
|
|
599
|
+
usage: {
|
|
600
|
+
inputTokens: usage.input_tokens,
|
|
601
|
+
outputTokens: usage.output_tokens,
|
|
602
|
+
...usage.input_tokens_details?.cached_tokens !== void 0 ? { cachedInputTokens: usage.input_tokens_details.cached_tokens } : {},
|
|
603
|
+
...usage.output_tokens_details?.reasoning_tokens !== void 0 ? { reasoningTokens: usage.output_tokens_details.reasoning_tokens } : {}
|
|
604
|
+
}
|
|
605
|
+
} : {},
|
|
606
|
+
...errorCategory !== void 0 ? { errorCategory } : {}
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
function perToken(rates) {
|
|
610
|
+
const input = BigInt(assertNanoUsd(rates.input, "perToken input rate"));
|
|
611
|
+
const output = BigInt(assertNanoUsd(rates.output, "perToken output rate"));
|
|
612
|
+
return (context) => (input * BigInt(context.usage?.input_tokens ?? 0) + output * BigInt(context.usage?.output_tokens ?? 0)).toString();
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
export { enlitt, perToken };
|
|
616
|
+
//# sourceMappingURL=openai.js.map
|
|
617
|
+
//# sourceMappingURL=openai.js.map
|