@broberg/ai-sdk 0.78.5 → 0.78.7

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.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { U as Usage, C as CostSink, T as Tier, a as ChatResult, b as ChatStreamEvent, c as TranslateResult, I as ImageResult, A as AnimateResult, d as TrainStyleResult, E as EmbeddingResult, e as TranscribeResult, O as OcrResult, M as ModerationResult, J as JudgeResult, V as VectorizeResult, P as PodcastResult, B as BatchRequestItem, f as TierSpec, g as BatchJob, h as BatchResultItem, i as ProviderAdapter, j as ToolCall, k as Tool, l as Transport, m as Capability, R as Region, n as BudgetConfig, o as BudgetStore } from './registry-UIY_A6GR.js';
2
- export { p as AlignedWordTimings, q as AvailabilitySource, r as AvailabilityStatus, s as AzureWordBoundary, t as CallOptions, u as ChatRequest, v as ContentPart, D as DialogueRequest, w as DialogueTurn, x as EmbeddingRequest, y as ImageRequest, z as JudgeAnswer, F as JudgeChoiceAnswer, G as JudgeNoulAnswer, H as JudgeQuestion, K as JudgeScoreAnswer, L as LATEST, N as LatestEntry, Q as LoraWeight, S as Message, W as ModelStatus, X as ModelUnavailableError, Y as ModerationItem, Z as ModerationRequest, _ as OcrPage, $ as OcrRequest, a0 as ResolveOptions, a1 as ResolveResult, a2 as Role, a3 as TierDescription, a4 as TrainStyleRequest, a5 as TranscribeRequest, a6 as TtsRequest, a7 as WordTiming, a8 as alignWordTimings, a9 as classifyRegionName, aa as describeTier, ab as listLatest, ac as listModels, ad as regionOfHost, ae as regionOfProvider, af as resolveLatest, ag as resolveModel } from './registry-UIY_A6GR.js';
1
+ import { U as Usage, C as CostSink, T as Tier, a as ChatResult, b as ChatStreamEvent, c as TranslateResult, I as ImageResult, A as AnimateResult, d as TrainStyleResult, E as EmbeddingResult, e as TranscribeResult, O as OcrResult, M as ModerationResult, J as JudgeResult, V as VectorizeResult, P as PodcastResult, B as BatchRequestItem, f as TierSpec, g as BatchJob, h as BatchResultItem, i as ProviderAdapter, j as ToolCall, k as Tool, l as Transport, m as Capability, R as Region, n as BudgetConfig, o as BudgetStore } from './registry-C65-nbWA.js';
2
+ export { p as AlignedWordTimings, q as AvailabilitySource, r as AvailabilityStatus, s as AzureWordBoundary, t as CallOptions, u as ChatRequest, v as ContentPart, D as DialogueRequest, w as DialogueTurn, x as EmbeddingRequest, y as ImageRequest, z as JudgeAnswer, F as JudgeChoiceAnswer, G as JudgeNoulAnswer, H as JudgeQuestion, K as JudgeScoreAnswer, L as LATEST, N as LatestEntry, Q as LoraWeight, S as Message, W as ModelStatus, X as ModelUnavailableError, Y as ModerationItem, Z as ModerationRequest, _ as OcrPage, $ as OcrRequest, a0 as ResolveOptions, a1 as ResolveResult, a2 as Role, a3 as TierDescription, a4 as TrainStyleRequest, a5 as TranscribeRequest, a6 as TranscriptCorrection, a7 as TtsRequest, a8 as WordTiming, a9 as alignWordTimings, aa as classifyRegionName, ab as describeTier, ac as listLatest, ad as listModels, ae as regionOfHost, af as regionOfProvider, ag as resolveLatest, ah as resolveModel } from './registry-C65-nbWA.js';
3
3
  import { z } from 'zod';
4
4
  export { CheapestQuery, CheapestResult, CheapestRow, DEFAULT_CLIP_SEC, MEDIA_PRICING_CHECKED_AT, MediaPrice, MediaUnit, PRICING_STALE_AFTER_DAYS, PriceKind, PricingFreshness, UnitFreshness, UpstreamStatus, cheapestModels, classifyKind, getMediaPrice, listMediaPrices, pricingFreshness, pricingGeneratedAt } from './pricing.js';
5
5
 
@@ -341,6 +341,7 @@ declare const INPUT_LIMITS: {
341
341
  readonly stateItems: 10000;
342
342
  readonly scriptLines: 10000;
343
343
  readonly pronunciations: 10000;
344
+ readonly corrections: 10000;
344
345
  };
345
346
  declare const tierSpecSchema: z.ZodObject<{
346
347
  provider: z.ZodString;
@@ -820,6 +821,10 @@ declare const transcribeInputSchema: z.ZodObject<{
820
821
  language: z.ZodOptional<z.ZodString>;
821
822
  durationSec: z.ZodOptional<z.ZodNumber>;
822
823
  phrases: z.ZodOptional<z.ZodArray<z.ZodString>>;
824
+ corrections: z.ZodOptional<z.ZodArray<z.ZodObject<{
825
+ from: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
826
+ to: z.ZodString;
827
+ }, z.core.$strip>>>;
823
828
  timestamps: z.ZodOptional<z.ZodUnion<readonly [z.ZodEnum<{
824
829
  word: "word";
825
830
  segment: "segment";
@@ -1525,6 +1530,10 @@ interface OpenAICompatibleConfig {
1525
1530
  /** F074.3 — this provider accepts `reasoning_effort` (Mistral). Anywhere else a
1526
1531
  * reasoningEffort is REFUSED, like `prefix`: a dropped flag reads as obeyed. */
1527
1532
  supportsReasoningEffort?: boolean;
1533
+ /** F101 — this provider takes reasoning as an OBJECT, `reasoning:{effort}` or
1534
+ * `reasoning:{enabled:false}` (OpenRouter), not Mistral's flat `reasoning_effort`.
1535
+ * A reasoningEffort is mapped onto it instead of being refused. */
1536
+ reasoningObject?: boolean;
1528
1537
  }
1529
1538
  declare function makeOpenAICompatibleAdapter(config: OpenAICompatibleConfig): ProviderAdapter;
1530
1539
 
@@ -1596,8 +1605,8 @@ declare const falStubAdapter: ProviderAdapter;
1596
1605
  * wires the live adapters. */
1597
1606
  declare const stubProviders: Record<string, ProviderAdapter>;
1598
1607
 
1599
- declare const VERSION: "0.78.5";
1600
- declare const SDK_TAG: "@broberg/ai-sdk@0.78.5";
1608
+ declare const VERSION: "0.78.7";
1609
+ declare const SDK_TAG: "@broberg/ai-sdk@0.78.7";
1601
1610
 
1602
1611
  /** Built-in defaults. Every entry is overridable via AiConfig.defaults or a
1603
1612
  * per-call override.
package/dist/index.js CHANGED
@@ -1059,6 +1059,9 @@ function mapAnthropicStop(reason) {
1059
1059
 
1060
1060
  // src/providers/openai-compatible.ts
1061
1061
  var REASONS_BY_DEFAULT = /* @__PURE__ */ new Set(["mistral-large-4", "mistral-large-4-0"]);
1062
+ function openrouterDefaultReasoning(model) {
1063
+ return model.startsWith("deepseek/deepseek-v4") && model.includes("flash") ? "none" : void 0;
1064
+ }
1062
1065
  function autoCacheKey(messages) {
1063
1066
  const system = messages.find((m) => m.role === "system");
1064
1067
  if (!system || typeof system.content !== "string" || system.content.length < 200) return void 0;
@@ -1166,11 +1169,17 @@ function buildChatBody(req, config) {
1166
1169
  if (req.maxTokens !== void 0) body.max_tokens = req.maxTokens;
1167
1170
  if (req.temperature !== void 0) body.temperature = req.temperature;
1168
1171
  if (req.responseFormat === "json") body.response_format = { type: "json_object" };
1169
- if (req.reasoningEffort !== void 0 && !config.supportsReasoningEffort) {
1170
- throw new Error(`${config.name} adapter: reasoningEffort is a Mistral option and is not supported here`);
1172
+ if (req.reasoningEffort !== void 0 && !config.supportsReasoningEffort && !config.reasoningObject) {
1173
+ throw new Error(`${config.name} adapter: reasoningEffort is a Mistral/OpenRouter option and is not supported here`);
1174
+ }
1175
+ if (config.reasoningObject) {
1176
+ const eff = req.reasoningEffort ?? openrouterDefaultReasoning(req.spec.model);
1177
+ if (eff === "none") body.reasoning = { enabled: false };
1178
+ else if (eff !== void 0) body.reasoning = { effort: eff };
1179
+ } else {
1180
+ const effort = req.reasoningEffort ?? (config.supportsReasoningEffort && REASONS_BY_DEFAULT.has(req.spec.model) ? "low" : void 0);
1181
+ if (effort !== void 0) body.reasoning_effort = effort;
1171
1182
  }
1172
- const effort = req.reasoningEffort ?? (config.supportsReasoningEffort && REASONS_BY_DEFAULT.has(req.spec.model) ? "low" : void 0);
1173
- if (effort !== void 0) body.reasoning_effort = effort;
1174
1183
  if (config.supportsPromptCacheKey && req.promptCache !== false) {
1175
1184
  const k = req.promptCacheKey ?? autoCacheKey(req.messages);
1176
1185
  if (k !== void 0) body.prompt_cache_key = k;
@@ -1208,6 +1217,11 @@ function makeOpenAICompatibleAdapter(config) {
1208
1217
  const toolCalls = msg?.tool_calls?.map(
1209
1218
  (tc) => fromProviderToolCall(tc, "openai")
1210
1219
  );
1220
+ if (text.length === 0 && !(toolCalls && toolCalls.length > 0) && hasReasoning(msg)) {
1221
+ throw new Error(
1222
+ `${config.name} chat: the model spent its whole output budget thinking and returned no answer (${data.usage?.completion_tokens ?? "?"} completion tokens, empty content). Raise maxTokens, or bound the thinking with reasoningEffort ("low" or "none").`
1223
+ );
1224
+ }
1211
1225
  const cachedIn = data.usage?.prompt_tokens_details?.cached_tokens;
1212
1226
  const usage = freshUsage({
1213
1227
  provider: config.name,
@@ -1266,6 +1280,8 @@ function makeOpenAICompatibleAdapter(config) {
1266
1280
  });
1267
1281
  const toolAcc = /* @__PURE__ */ new Map();
1268
1282
  let finishReason = null;
1283
+ let sawReasoning = false;
1284
+ let emittedText = false;
1269
1285
  for await (const data of stream) {
1270
1286
  let chunk;
1271
1287
  try {
@@ -1276,10 +1292,14 @@ function makeOpenAICompatibleAdapter(config) {
1276
1292
  const choice = chunk.choices?.[0];
1277
1293
  if (choice) {
1278
1294
  const delta = choice.delta ?? {};
1295
+ if (hasReasoning(delta)) sawReasoning = true;
1279
1296
  const piece = contentToText(delta.content);
1280
1297
  if (piece.length > 0) {
1281
1298
  const out = stripStreamPrefix(piece);
1282
- if (out.length > 0) yield { type: "text", delta: out };
1299
+ if (out.length > 0) {
1300
+ emittedText = true;
1301
+ yield { type: "text", delta: out };
1302
+ }
1283
1303
  }
1284
1304
  for (const tc of delta.tool_calls ?? []) {
1285
1305
  const idx = tc.index ?? 0;
@@ -1323,7 +1343,8 @@ function makeOpenAICompatibleAdapter(config) {
1323
1343
  }
1324
1344
  yield { type: "tool_call", id: t.id, name: t.name, args };
1325
1345
  }
1326
- yield { type: "finish", reason: mapFinishReason(finishReason) };
1346
+ const reason = mapFinishReason(finishReason);
1347
+ yield { type: "finish", reason: sawReasoning && !emittedText && toolAcc.size === 0 && reason !== "tool_calls" ? "length" : reason };
1327
1348
  }
1328
1349
  return {
1329
1350
  name: config.name,
@@ -1344,6 +1365,11 @@ function contentToText(content) {
1344
1365
  }
1345
1366
  return "";
1346
1367
  }
1368
+ function hasReasoning(m) {
1369
+ if (!m) return false;
1370
+ if (typeof m.reasoning === "string" && m.reasoning.length > 0) return true;
1371
+ return Array.isArray(m.reasoning_details) && m.reasoning_details.length > 0;
1372
+ }
1347
1373
  function mapFinishReason(reason) {
1348
1374
  switch (reason) {
1349
1375
  case "tool_calls":
@@ -1743,7 +1769,9 @@ function openrouterAdapter(config = {}) {
1743
1769
  fetch: config.fetch,
1744
1770
  // OpenRouter returns ground-truth usage.cost (USD) when usage:{include:true}
1745
1771
  // is set — use it over the local pricing-table estimate (F010).
1746
- costFromResponseField: true
1772
+ costFromResponseField: true,
1773
+ // F101 — OpenRouter takes reasoning as an object ({effort} / {enabled:false}).
1774
+ reasoningObject: true
1747
1775
  });
1748
1776
  async function image(req) {
1749
1777
  const apiKey = config.apiKey ?? env().OPENROUTER_API_KEY;
@@ -3760,6 +3788,32 @@ async function resolveAudio(audio, fetchImpl = fetch) {
3760
3788
  if (!res.ok) throw new Error(`transcribe: failed to fetch audio (${res.status})`);
3761
3789
  return new Uint8Array(await res.arrayBuffer());
3762
3790
  }
3791
+ function applyTranscriptCorrections(result, corrections) {
3792
+ if (!corrections || corrections.length === 0) return result;
3793
+ const to = /* @__PURE__ */ new Map();
3794
+ for (const c of corrections) {
3795
+ for (const f of Array.isArray(c.from) ? c.from : [c.from]) {
3796
+ const k = f.toLowerCase();
3797
+ if (!to.has(k)) to.set(k, c.to);
3798
+ }
3799
+ }
3800
+ const keys = [...to.keys()].sort((a, b) => b.length - a.length);
3801
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3802
+ const re = new RegExp(`(?<![\\p{L}\\p{N}])(?:${keys.map(esc).join("|")})(?![\\p{L}\\p{N}])`, "giu");
3803
+ const counts = /* @__PURE__ */ new Map();
3804
+ const fix = (s, count) => s.replace(re, (m) => {
3805
+ const out2 = to.get(m.toLowerCase()) ?? m;
3806
+ if (count) counts.set(out2, (counts.get(out2) ?? 0) + 1);
3807
+ return out2;
3808
+ });
3809
+ const text = fix(result.text, true);
3810
+ if (counts.size === 0) return result;
3811
+ const out = { ...result, text };
3812
+ if (result.segments) out.segments = result.segments.map((s) => ({ ...s, text: fix(s.text, false) }));
3813
+ if (result.words) out.words = result.words.map((w) => ({ ...w, word: fix(w.word, false) }));
3814
+ out.correctionsApplied = [...counts.entries()].map(([t, count]) => ({ to: t, count }));
3815
+ return out;
3816
+ }
3763
3817
 
3764
3818
  // src/capabilities/contracts/index.ts
3765
3819
  var RAW_SNIPPET_CHARS = 200;
@@ -4288,7 +4342,8 @@ var INPUT_LIMITS = {
4288
4342
  judgeEntryItems: 1e3,
4289
4343
  stateItems: 1e4,
4290
4344
  scriptLines: 1e4,
4291
- pronunciations: 1e4
4345
+ pronunciations: 1e4,
4346
+ corrections: 1e4
4292
4347
  };
4293
4348
  var L = INPUT_LIMITS;
4294
4349
  var transportSchema = z.enum(["http", "subprocess"]);
@@ -4466,6 +4521,10 @@ var embeddingInputSchema = z.object({
4466
4521
  text: z.union([z.string(), z.array(z.string()).max(L.texts)]),
4467
4522
  ...callOptions
4468
4523
  });
4524
+ var correctionSchema = z.object({
4525
+ from: z.union([z.string().min(1).max(200), z.array(z.string().min(1).max(200)).min(1).max(100)]),
4526
+ to: z.string().min(1).max(200)
4527
+ });
4469
4528
  var transcribeInputSchema = z.object({
4470
4529
  /** Audio URL or raw bytes. */
4471
4530
  audio: z.union([z.string(), z.instanceof(Uint8Array)]),
@@ -4474,6 +4533,9 @@ var transcribeInputSchema = z.object({
4474
4533
  durationSec: z.number().positive().optional(),
4475
4534
  /** Bias toward brand/jargon terms (Azure phraseList, F029.3); others ignore it. */
4476
4535
  phrases: z.array(z.string()).max(L.phrases).optional(),
4536
+ /** F102 — fix what the provider mis-hears, AFTER it answers: whole-word, case-insensitive,
4537
+ * consumer-owned. Works on every provider. `phrases` is only best-effort (measured no effect). */
4538
+ corrections: z.array(correctionSchema).max(L.corrections).optional(),
4477
4539
  /** Opt-in timestamps (F036) — a single granularity or an array. Omit → the
4478
4540
  * current { text, usage } shape, unchanged. Pass ["word","segment"] for both.
4479
4541
  * Supported by Whisper (openai) + Azure fast-transcription (F036.1); other
@@ -4609,8 +4671,8 @@ var aiConfigSchema = z.object({
4609
4671
  import { randomUUID } from "crypto";
4610
4672
 
4611
4673
  // src/version.ts
4612
- var VERSION = "0.78.5";
4613
- var SDK_TAG = "@broberg/ai-sdk@0.78.5";
4674
+ var VERSION = "0.78.7";
4675
+ var SDK_TAG = "@broberg/ai-sdk@0.78.7";
4614
4676
 
4615
4677
  // src/cost/sinks/upmetrics.ts
4616
4678
  function isRetryableStatus(status) {
@@ -5600,7 +5662,8 @@ function createAI(config = {}) {
5600
5662
  const adapter = pickProvider(spec.provider);
5601
5663
  if (!adapter.transcribe) throw new Error(`createAI: provider "${spec.provider}" does not support transcribe`);
5602
5664
  const timestamps = input.timestamps === void 0 ? void 0 : Array.isArray(input.timestamps) ? input.timestamps : [input.timestamps];
5603
- return adapter.transcribe({ audio, language: input.language, durationSec: input.durationSec, phrases: input.phrases, timestamps, spec });
5665
+ const r = await adapter.transcribe({ audio, language: input.language, durationSec: input.durationSec, phrases: input.phrases, timestamps, spec });
5666
+ return applyTranscriptCorrections(r, input.corrections);
5604
5667
  }
5605
5668
  });
5606
5669
  },