@shop-os/modelkit 0.21.0 → 0.22.0

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/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { ImageModel, experimental_generateVideo, generateText as generateText$1, LanguageModel, FlexibleSchema, InferSchema, ToolSet, Output, streamText as streamText$1, JSONValue, generateObject as generateObject$1, streamObject as streamObject$1, LanguageModelUsage, ProviderMetadata } from 'ai';
1
+ import { ImageModel, experimental_generateVideo, FinishReason, generateText as generateText$1, LanguageModel, FlexibleSchema, InferSchema, ToolSet, Output, streamText as streamText$1, JSONValue, generateObject as generateObject$1, streamObject as streamObject$1, LanguageModelUsage, ProviderMetadata } from 'ai';
2
2
  export * from 'ai';
3
3
  export { Warning as AiWarning } from 'ai';
4
4
  import { z } from 'zod';
@@ -1211,6 +1211,8 @@ interface ModelKitErrorInit {
1211
1211
  body?: ProviderErrorBody;
1212
1212
  cause?: unknown;
1213
1213
  retryable?: boolean;
1214
+ finishReason?: FinishReason;
1215
+ usage?: UsageEvent;
1214
1216
  }
1215
1217
  declare class ModelKitError extends Error {
1216
1218
  readonly code: ModelKitErrorCode;
@@ -1219,7 +1221,11 @@ declare class ModelKitError extends Error {
1219
1221
  readonly status: number | undefined;
1220
1222
  readonly body: ProviderErrorBody | undefined;
1221
1223
  readonly retryable: boolean;
1224
+ readonly finishReason: FinishReason | undefined;
1225
+ /** Set when the provider billed a call that still failed; never sent to `onUsage`. */
1226
+ readonly usage: UsageEvent | undefined;
1222
1227
  constructor(init: ModelKitErrorInit);
1228
+ withUsage(usage: UsageEvent): ModelKitError;
1223
1229
  }
1224
1230
  declare function isModelKitError(err: unknown): err is ModelKitError;
1225
1231
 
@@ -2259,6 +2265,12 @@ interface RetryOptions {
2259
2265
  maxDelayMs?: number;
2260
2266
  factor?: number;
2261
2267
  signal?: AbortSignal;
2268
+ /** A separate, jittered schedule and budget for `rate_limited` errors; other errors keep the one above. */
2269
+ rateLimited?: {
2270
+ attempts: number;
2271
+ baseDelayMs: number;
2272
+ maxDelayMs: number;
2273
+ };
2262
2274
  }
2263
2275
  declare function withRetry<T>(fn: (attempt: number) => Promise<T>, opts?: RetryOptions): Promise<T>;
2264
2276
  declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ImageModel, experimental_generateVideo, generateText as generateText$1, LanguageModel, FlexibleSchema, InferSchema, ToolSet, Output, streamText as streamText$1, JSONValue, generateObject as generateObject$1, streamObject as streamObject$1, LanguageModelUsage, ProviderMetadata } from 'ai';
1
+ import { ImageModel, experimental_generateVideo, FinishReason, generateText as generateText$1, LanguageModel, FlexibleSchema, InferSchema, ToolSet, Output, streamText as streamText$1, JSONValue, generateObject as generateObject$1, streamObject as streamObject$1, LanguageModelUsage, ProviderMetadata } from 'ai';
2
2
  export * from 'ai';
3
3
  export { Warning as AiWarning } from 'ai';
4
4
  import { z } from 'zod';
@@ -1211,6 +1211,8 @@ interface ModelKitErrorInit {
1211
1211
  body?: ProviderErrorBody;
1212
1212
  cause?: unknown;
1213
1213
  retryable?: boolean;
1214
+ finishReason?: FinishReason;
1215
+ usage?: UsageEvent;
1214
1216
  }
1215
1217
  declare class ModelKitError extends Error {
1216
1218
  readonly code: ModelKitErrorCode;
@@ -1219,7 +1221,11 @@ declare class ModelKitError extends Error {
1219
1221
  readonly status: number | undefined;
1220
1222
  readonly body: ProviderErrorBody | undefined;
1221
1223
  readonly retryable: boolean;
1224
+ readonly finishReason: FinishReason | undefined;
1225
+ /** Set when the provider billed a call that still failed; never sent to `onUsage`. */
1226
+ readonly usage: UsageEvent | undefined;
1222
1227
  constructor(init: ModelKitErrorInit);
1228
+ withUsage(usage: UsageEvent): ModelKitError;
1223
1229
  }
1224
1230
  declare function isModelKitError(err: unknown): err is ModelKitError;
1225
1231
 
@@ -2259,6 +2265,12 @@ interface RetryOptions {
2259
2265
  maxDelayMs?: number;
2260
2266
  factor?: number;
2261
2267
  signal?: AbortSignal;
2268
+ /** A separate, jittered schedule and budget for `rate_limited` errors; other errors keep the one above. */
2269
+ rateLimited?: {
2270
+ attempts: number;
2271
+ baseDelayMs: number;
2272
+ maxDelayMs: number;
2273
+ };
2262
2274
  }
2263
2275
  declare function withRetry<T>(fn: (attempt: number) => Promise<T>, opts?: RetryOptions): Promise<T>;
2264
2276
  declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
package/dist/index.js CHANGED
@@ -10,13 +10,16 @@ function hasAwsCredentials(aws) {
10
10
  }
11
11
 
12
12
  // src/errors.ts
13
- var ModelKitError = class extends Error {
13
+ var ModelKitError = class _ModelKitError extends Error {
14
14
  code;
15
15
  provider;
16
16
  model;
17
17
  status;
18
18
  body;
19
19
  retryable;
20
+ finishReason;
21
+ /** Set when the provider billed a call that still failed; never sent to `onUsage`. */
22
+ usage;
20
23
  constructor(init) {
21
24
  super(init.message, { cause: init.cause });
22
25
  this.name = "ModelKitError";
@@ -26,6 +29,25 @@ var ModelKitError = class extends Error {
26
29
  this.status = init.status;
27
30
  this.body = init.body;
28
31
  this.retryable = init.retryable ?? defaultRetryable(init.code);
32
+ this.finishReason = init.finishReason;
33
+ this.usage = init.usage;
34
+ }
35
+ withUsage(usage5) {
36
+ const init = {
37
+ code: this.code,
38
+ message: this.message,
39
+ cause: this.cause,
40
+ retryable: this.retryable,
41
+ usage: usage5
42
+ };
43
+ if (this.provider !== void 0) init.provider = this.provider;
44
+ if (this.model !== void 0) init.model = this.model;
45
+ if (this.status !== void 0) init.status = this.status;
46
+ if (this.body !== void 0) init.body = this.body;
47
+ if (this.finishReason !== void 0) init.finishReason = this.finishReason;
48
+ const copy = new _ModelKitError(init);
49
+ if (this.stack !== void 0) copy.stack = this.stack;
50
+ return copy;
29
51
  }
30
52
  };
31
53
  function defaultRetryable(code) {
@@ -9248,19 +9270,42 @@ async function withRetry(fn, opts = {}) {
9248
9270
  const base = opts.baseDelayMs ?? 1e3;
9249
9271
  const max = opts.maxDelayMs ?? 1e4;
9250
9272
  const factor = opts.factor ?? 2;
9273
+ const rateLimited = opts.rateLimited;
9274
+ let limitedFailures = 0;
9275
+ let otherFailures = 0;
9251
9276
  let last;
9252
- for (let attempt = 1; attempt <= attempts; attempt++) {
9277
+ const ceiling = attempts + (rateLimited?.attempts ?? 0);
9278
+ for (let attempt = 1; attempt <= ceiling; attempt++) {
9253
9279
  if (opts.signal?.aborted) throw throwAborted();
9254
9280
  try {
9255
9281
  return await fn(attempt);
9256
9282
  } catch (cause) {
9257
- last = cause instanceof Error ? cause : new Error(String(cause), { cause });
9258
- if (attempt === attempts || !shouldRetry(last) || opts.signal?.aborted) throw cause;
9259
- await sleep(Math.min(max, base * factor ** (attempt - 1)), opts.signal);
9283
+ last = cause;
9284
+ const err = cause instanceof Error ? cause : new Error(String(cause), { cause });
9285
+ if (!shouldRetry(err) || opts.signal?.aborted) throw cause;
9286
+ let delay;
9287
+ if (rateLimited !== void 0 && err instanceof ModelKitError && err.code === "rate_limited") {
9288
+ limitedFailures += 1;
9289
+ if (limitedFailures >= rateLimited.attempts) throw cause;
9290
+ delay = jitter(
9291
+ Math.min(
9292
+ rateLimited.maxDelayMs,
9293
+ rateLimited.baseDelayMs * factor ** (limitedFailures - 1)
9294
+ )
9295
+ );
9296
+ } else {
9297
+ otherFailures += 1;
9298
+ if (otherFailures >= attempts) throw cause;
9299
+ delay = Math.min(max, base * factor ** (otherFailures - 1));
9300
+ }
9301
+ await sleep(delay, opts.signal);
9260
9302
  }
9261
9303
  }
9262
9304
  throw last;
9263
9305
  }
9306
+ function jitter(ms) {
9307
+ return Math.round(ms * (0.75 + Math.random() * 0.25));
9308
+ }
9264
9309
  function combineSignals(a, b) {
9265
9310
  return a && b ? AbortSignal.any([a, b]) : a ?? b;
9266
9311
  }
@@ -14040,6 +14085,12 @@ async function fishFetch(ctx, path, init) {
14040
14085
  if (!res.ok) throw classifyHttpError(res.status, await readBody(res), "fish", ctx.model.id);
14041
14086
  return res;
14042
14087
  }
14088
+ var FISH_RATE_LIMIT = { attempts: 6, baseDelayMs: 2e3, maxDelayMs: 2e4 };
14089
+ function fishRetryOptions(ctx) {
14090
+ const options = mediaRetryOptions(ctx.call, ctx.signal);
14091
+ if (ctx.call.maxRetries !== void 0) return options;
14092
+ return { ...options, rateLimited: FISH_RATE_LIMIT };
14093
+ }
14043
14094
  function usage3(ctx) {
14044
14095
  return {
14045
14096
  model: ctx.model.id,
@@ -14063,23 +14114,20 @@ async function generateSpeech2(req, ctx) {
14063
14114
  body.reference_id = checkVoiceId2(ctx, req.customVoice ? "customVoice" : "voice", voice);
14064
14115
  }
14065
14116
  if (req.language !== void 0) body.language = req.language;
14066
- const { bytes, mime } = await withRetry(
14067
- async () => {
14068
- const res = await fishFetch(ctx, "/v1/tts", {
14069
- method: "POST",
14070
- headers: { "Content-Type": "application/json", model: ctx.model.providerModelId },
14071
- body: JSON.stringify(body)
14072
- });
14073
- let audio;
14074
- try {
14075
- audio = new Uint8Array(await res.arrayBuffer());
14076
- } catch (cause) {
14077
- throw classifyThrown("fish", cause, ctx.model.id);
14078
- }
14079
- return { bytes: audio, mime: audioMime2(res, format) };
14080
- },
14081
- mediaRetryOptions(ctx.call, ctx.signal)
14082
- );
14117
+ const { bytes, mime } = await withRetry(async () => {
14118
+ const res = await fishFetch(ctx, "/v1/tts", {
14119
+ method: "POST",
14120
+ headers: { "Content-Type": "application/json", model: ctx.model.providerModelId },
14121
+ body: JSON.stringify(body)
14122
+ });
14123
+ let audio;
14124
+ try {
14125
+ audio = new Uint8Array(await res.arrayBuffer());
14126
+ } catch (cause) {
14127
+ throw classifyThrown("fish", cause, ctx.model.id);
14128
+ }
14129
+ return { bytes: audio, mime: audioMime2(res, format) };
14130
+ }, fishRetryOptions(ctx));
14083
14131
  if (bytes.byteLength === 0)
14084
14132
  throw fishError(ctx, "provider_rejected", "Fish TTS returned no audio");
14085
14133
  return { audio: { bytes, mime }, usage: usage3(ctx) };
@@ -14155,7 +14203,7 @@ async function createVoice2(req, ctx) {
14155
14203
  const form = await cloneForm2(req, ctx);
14156
14204
  const res = await withRetry(
14157
14205
  () => onlyRateLimitRetries2(() => fishFetch(ctx, "/model", { method: "POST", body: form })),
14158
- mediaRetryOptions(ctx.call, ctx.signal)
14206
+ fishRetryOptions(ctx)
14159
14207
  );
14160
14208
  const raw = await readBody(res);
14161
14209
  const parsed = createdModelSchema.safeParse(raw);
@@ -14192,17 +14240,14 @@ async function designVoice(req, ctx) {
14192
14240
  if (req.language !== void 0) body.language = req.language;
14193
14241
  if (req.count !== void 0) body.n = req.count;
14194
14242
  if (req.seed !== void 0) body.seed = req.seed;
14195
- const raw = await withRetry(
14196
- async () => {
14197
- const res = await fishFetch(ctx, "/v1/voice-design", {
14198
- method: "POST",
14199
- headers: { "Content-Type": "application/json", model: ctx.model.providerModelId },
14200
- body: JSON.stringify(body)
14201
- });
14202
- return readBody(res);
14203
- },
14204
- mediaRetryOptions(ctx.call, ctx.signal)
14205
- );
14243
+ const raw = await withRetry(async () => {
14244
+ const res = await fishFetch(ctx, "/v1/voice-design", {
14245
+ method: "POST",
14246
+ headers: { "Content-Type": "application/json", model: ctx.model.providerModelId },
14247
+ body: JSON.stringify(body)
14248
+ });
14249
+ return readBody(res);
14250
+ }, fishRetryOptions(ctx));
14206
14251
  const parsed = designSchema.safeParse(raw);
14207
14252
  if (!parsed.success) {
14208
14253
  throw fishError(ctx, "provider_rejected", "Fish voice design returned no candidates");
@@ -14220,27 +14265,24 @@ async function deleteVoice2(req, ctx) {
14220
14265
  checkRow2(ctx, "voice-clone");
14221
14266
  const id = encodeURIComponent(checkVoiceId2(ctx, "voiceId", req.voiceId));
14222
14267
  let attempts = 0;
14223
- await withRetry(
14224
- async () => {
14225
- attempts += 1;
14226
- try {
14227
- await fishFetch(ctx, `/model/${id}`, { method: "DELETE" });
14228
- } catch (cause) {
14229
- if (!isModelKitError(cause) || cause.status !== 404) throw cause;
14230
- if (attempts > 1) return;
14231
- throw new ModelKitError({
14232
- code: "provider_rejected",
14233
- message: `Fish has no voice ${req.voiceId} under this key set; delete with the tier that created it`,
14234
- provider: "fish",
14235
- model: ctx.model.id,
14236
- status: 404,
14237
- cause,
14238
- retryable: false
14239
- });
14240
- }
14241
- },
14242
- mediaRetryOptions(ctx.call, ctx.signal)
14243
- );
14268
+ await withRetry(async () => {
14269
+ attempts += 1;
14270
+ try {
14271
+ await fishFetch(ctx, `/model/${id}`, { method: "DELETE" });
14272
+ } catch (cause) {
14273
+ if (!isModelKitError(cause) || cause.status !== 404) throw cause;
14274
+ if (attempts > 1) return;
14275
+ throw new ModelKitError({
14276
+ code: "provider_rejected",
14277
+ message: `Fish has no voice ${req.voiceId} under this key set; delete with the tier that created it`,
14278
+ provider: "fish",
14279
+ model: ctx.model.id,
14280
+ status: 404,
14281
+ cause,
14282
+ retryable: false
14283
+ });
14284
+ }
14285
+ }, fishRetryOptions(ctx));
14244
14286
  }
14245
14287
  var fishAdapter = {
14246
14288
  id: "fish",
@@ -15198,6 +15240,21 @@ function extractBlockReason(cause) {
15198
15240
  current = parsed.data.cause ?? null;
15199
15241
  }
15200
15242
  }
15243
+ function billedTokens(model, usage5) {
15244
+ const inputTokens = usage5?.inputTokens;
15245
+ const outputTokens = usage5?.outputTokens;
15246
+ if (inputTokens === void 0 && outputTokens === void 0) return void 0;
15247
+ const event = {
15248
+ model,
15249
+ provider: "google-image",
15250
+ modality: "TEXT",
15251
+ unit: "tokens",
15252
+ quantity: (inputTokens ?? 0) + (outputTokens ?? 0)
15253
+ };
15254
+ if (inputTokens !== void 0) event.inputTokens = inputTokens;
15255
+ if (outputTokens !== void 0) event.outputTokens = outputTokens;
15256
+ return event;
15257
+ }
15201
15258
  function toProviderError(cause, ctx) {
15202
15259
  const blockReason = extractBlockReason(cause);
15203
15260
  if (blockReason) {
@@ -15269,14 +15326,22 @@ function createGoogleImageAdapter(deps = defaultGoogleImageDeps) {
15269
15326
  const images = (result.files ?? []).filter((file) => file.mediaType.startsWith("image/")).map((file) => ({ bytes: file.uint8Array, mime: file.mediaType }));
15270
15327
  if (images.length === 0) {
15271
15328
  const filtered = result.finishReason === "content-filter" || result.finishReason === "other";
15272
- throw new ModelKitError({
15329
+ const init = {
15273
15330
  code: filtered ? "content_blocked" : "provider_rejected",
15274
15331
  message: `google-image returned no image (finishReason: ${result.finishReason}). ${result.text}`.trim(),
15275
15332
  provider: "google-image",
15276
15333
  model: ctx.model.id,
15277
- body: { finishReason: result.finishReason ?? null, text: result.text ?? "" },
15334
+ body: {
15335
+ finishReason: result.finishReason ?? null,
15336
+ rawFinishReason: result.rawFinishReason ?? null,
15337
+ text: result.text ?? ""
15338
+ },
15278
15339
  retryable: false
15279
- });
15340
+ };
15341
+ if (result.finishReason !== void 0) init.finishReason = result.finishReason;
15342
+ const billed = billedTokens(ctx.model.id, result.usage);
15343
+ if (billed !== void 0) init.usage = billed;
15344
+ throw new ModelKitError(init);
15280
15345
  }
15281
15346
  const usage5 = {
15282
15347
  model: ctx.model.id,
@@ -20471,6 +20536,11 @@ function createModelKit(config, adapters) {
20471
20536
  };
20472
20537
  return startedAt === void 0 ? stamped : timed(stamped, startedAt);
20473
20538
  }
20539
+ function billedFailure(ctx, err, billed, startedAt) {
20540
+ return err.withUsage(
20541
+ timed({ ...billed, model: ctx.model.id, ...keySourceField(ctx.keySource) }, startedAt)
20542
+ );
20543
+ }
20474
20544
  function textTimed(event, stepCount, startedAt) {
20475
20545
  return stepCount === 1 ? timed(event, startedAt) : event;
20476
20546
  }
@@ -20755,7 +20825,14 @@ function createModelKit(config, adapters) {
20755
20825
  model: model.id
20756
20826
  });
20757
20827
  const startedAt = Date.now();
20758
- const result = await adapter.generateImage(request, ctx);
20828
+ let result;
20829
+ try {
20830
+ result = await adapter.generateImage(request, ctx);
20831
+ } catch (err) {
20832
+ if (isModelKitError(err) && err.usage !== void 0)
20833
+ throw billedFailure(ctx, err, err.usage, startedAt);
20834
+ throw err;
20835
+ }
20759
20836
  const usage5 = rowUsage(ctx, result.usage, startedAt);
20760
20837
  await emit(usage5);
20761
20838
  const images = result.images.map(toGeneratedImage);