@broberg/ai-sdk 0.66.1 → 0.68.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.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  resolveModel,
12
12
  resolveTier,
13
13
  setAvailability
14
- } from "./chunk-HM3AYPWH.js";
14
+ } from "./chunk-ZI3RWAUY.js";
15
15
  import {
16
16
  DEFAULT_CLIP_SEC,
17
17
  MEDIA_PRICING,
@@ -23,11 +23,11 @@ import {
23
23
  listMediaPrices,
24
24
  pricingFreshness,
25
25
  pricingGeneratedAt
26
- } from "./chunk-D53S242W.js";
26
+ } from "./chunk-Z22SM5JD.js";
27
27
  import {
28
28
  PRICING,
29
29
  getPrice
30
- } from "./chunk-BWBRED4O.js";
30
+ } from "./chunk-QDYSNEGE.js";
31
31
 
32
32
  // src/search/brave.ts
33
33
  async function braveSearch(req, apiKey, f) {
@@ -1769,7 +1769,60 @@ function deepseekAdapter(config = {}) {
1769
1769
  });
1770
1770
  }
1771
1771
 
1772
+ // src/providers/pronunciation.ts
1773
+ function xmlEscape(s) {
1774
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1775
+ }
1776
+ function escapeRegex(s) {
1777
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1778
+ }
1779
+ function assertPronunciations(list, provider) {
1780
+ for (const p of list ?? []) {
1781
+ if (!p.word.trim()) {
1782
+ throw new Error(`${provider} adapter: a pronunciation entry has an empty "word".`);
1783
+ }
1784
+ if (p.alias !== void 0 && p.ipa !== void 0) {
1785
+ throw new Error(
1786
+ `${provider} adapter: pronunciation "${p.word}" sets BOTH alias and ipa. They are different instructions \u2014 alias says it differently, ipa says it in phonemes. Pick one.`
1787
+ );
1788
+ }
1789
+ if (p.alias === void 0 && p.ipa === void 0) {
1790
+ throw new Error(
1791
+ `${provider} adapter: pronunciation "${p.word}" sets neither alias nor ipa, so there is nothing to say instead.`
1792
+ );
1793
+ }
1794
+ }
1795
+ }
1796
+ function applyPronunciations(haystack, list, render, escape = (s) => s) {
1797
+ const entries = (list ?? []).filter((p) => p.word.trim().length > 0);
1798
+ if (entries.length === 0) return haystack;
1799
+ const sorted = [...entries].sort((a, b) => escape(b.word).length - escape(a.word).length);
1800
+ const byLower = /* @__PURE__ */ new Map();
1801
+ for (const p of sorted) {
1802
+ const k = escape(p.word).toLowerCase();
1803
+ if (!byLower.has(k)) byLower.set(k, p);
1804
+ }
1805
+ const alternation = sorted.map((p) => escapeRegex(escape(p.word))).join("|");
1806
+ const re = new RegExp(`(?<!\\w)(${alternation})(?!\\w)`, "gi");
1807
+ return haystack.replace(re, (matched, _g1, offset) => {
1808
+ const entry = byLower.get(matched.toLowerCase());
1809
+ if (!entry) return matched;
1810
+ if (!entry.matchInCompounds) {
1811
+ if (haystack[offset - 1] === "-" || haystack[offset + matched.length] === "-") return matched;
1812
+ }
1813
+ return render(entry, matched);
1814
+ });
1815
+ }
1816
+
1772
1817
  // src/providers/mistral.ts
1818
+ var MISTRAL_TTS_DEFAULT_MODEL = "voxtral-mini-tts-3-0";
1819
+ var MISTRAL_TTS_MIME = {
1820
+ mp3: "audio/mpeg",
1821
+ wav: "audio/wav",
1822
+ pcm: "audio/pcm",
1823
+ flac: "audio/flac",
1824
+ opus: "audio/ogg"
1825
+ };
1773
1826
  function mistralAdapter(config = {}) {
1774
1827
  const baseUrl = config.baseUrl ?? DEFAULT_BASE_URLS.mistral;
1775
1828
  const base = makeOpenAICompatibleAdapter({ name: "mistral", baseUrl, apiKey: config.apiKey, fetch: config.fetch, supportsPromptCacheKey: true, supportsPrefix: true, supportsReasoningEffort: true });
@@ -1909,6 +1962,52 @@ function mistralAdapter(config = {}) {
1909
1962
  }
1910
1963
  return { text: data.text ?? "", usage };
1911
1964
  }
1965
+ async function tts(req) {
1966
+ if (req.wordTimings) {
1967
+ throw new Error("mistral tts: wordTimings is not available on Voxtral \u2014 route this call to azure for per-word timings.");
1968
+ }
1969
+ const format = req.format ?? "mp3";
1970
+ const mimeType = MISTRAL_TTS_MIME[format];
1971
+ if (!mimeType) {
1972
+ throw new Error(`mistral tts: format "${format}" is not one Voxtral produces \u2014 use ${Object.keys(MISTRAL_TTS_MIME).join(", ")}.`);
1973
+ }
1974
+ assertPronunciations(req.pronunciations, "mistral");
1975
+ for (const p of req.pronunciations ?? []) {
1976
+ if (p.ipa !== void 0) {
1977
+ throw new Error(
1978
+ `mistral tts: pronunciation "${p.word}" uses ipa, which this adapter does not map to Voxtral's phoneme_hints yet \u2014 use { alias } here, or route this call to azure.`
1979
+ );
1980
+ }
1981
+ }
1982
+ const input = applyPronunciations(req.text, req.pronunciations, (p) => p.alias);
1983
+ const model = /^voxtral-.*tts/.test(req.spec.model) ? req.spec.model : MISTRAL_TTS_DEFAULT_MODEL;
1984
+ const res = await fetchImpl(`${baseUrl}/audio/speech`, {
1985
+ method: "POST",
1986
+ headers: { "content-type": "application/json", authorization: `Bearer ${key()}` },
1987
+ body: JSON.stringify({ model, input, voice_id: req.voiceId, response_format: format })
1988
+ });
1989
+ if (!res.ok) {
1990
+ const body = await res.text().catch(() => "");
1991
+ throw new Error(`mistral tts ${res.status}: ${body.slice(0, 300)}`);
1992
+ }
1993
+ const data = await res.json();
1994
+ if (!data.audio_data) throw new Error("mistral tts: response carried no audio_data");
1995
+ const usage = freshUsage({
1996
+ provider: "mistral",
1997
+ region: regionOfHost(baseUrl),
1998
+ model,
1999
+ transport: "http",
2000
+ capability: "tts",
2001
+ inputTokens: 0,
2002
+ outputTokens: 0
2003
+ });
2004
+ const price = getMediaPrice("mistral", model);
2005
+ if (price) {
2006
+ usage.costUsd = input.length / 1e3 * price.usd;
2007
+ usage.costBasis = "computed";
2008
+ }
2009
+ return { audio: new Uint8Array(Buffer.from(data.audio_data, "base64")), mimeType, usage };
2010
+ }
1912
2011
  async function batchSubmit(req) {
1913
2012
  const jsonl = req.items.map(
1914
2013
  (it) => JSON.stringify({
@@ -1954,52 +2053,7 @@ function mistralAdapter(config = {}) {
1954
2053
  return { customId: row.custom_id ?? "", text: row.response?.body?.choices?.[0]?.message?.content ?? "" };
1955
2054
  });
1956
2055
  }
1957
- return { ...base, ocr, moderate, embedding, transcribe, batchSubmit, batchStatus, batchResults };
1958
- }
1959
-
1960
- // src/providers/pronunciation.ts
1961
- function xmlEscape(s) {
1962
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1963
- }
1964
- function escapeRegex(s) {
1965
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1966
- }
1967
- function assertPronunciations(list, provider) {
1968
- for (const p of list ?? []) {
1969
- if (!p.word.trim()) {
1970
- throw new Error(`${provider} adapter: a pronunciation entry has an empty "word".`);
1971
- }
1972
- if (p.alias !== void 0 && p.ipa !== void 0) {
1973
- throw new Error(
1974
- `${provider} adapter: pronunciation "${p.word}" sets BOTH alias and ipa. They are different instructions \u2014 alias says it differently, ipa says it in phonemes. Pick one.`
1975
- );
1976
- }
1977
- if (p.alias === void 0 && p.ipa === void 0) {
1978
- throw new Error(
1979
- `${provider} adapter: pronunciation "${p.word}" sets neither alias nor ipa, so there is nothing to say instead.`
1980
- );
1981
- }
1982
- }
1983
- }
1984
- function applyPronunciations(haystack, list, render, escape = (s) => s) {
1985
- const entries = (list ?? []).filter((p) => p.word.trim().length > 0);
1986
- if (entries.length === 0) return haystack;
1987
- const sorted = [...entries].sort((a, b) => escape(b.word).length - escape(a.word).length);
1988
- const byLower = /* @__PURE__ */ new Map();
1989
- for (const p of sorted) {
1990
- const k = escape(p.word).toLowerCase();
1991
- if (!byLower.has(k)) byLower.set(k, p);
1992
- }
1993
- const alternation = sorted.map((p) => escapeRegex(escape(p.word))).join("|");
1994
- const re = new RegExp(`(?<!\\w)(${alternation})(?!\\w)`, "gi");
1995
- return haystack.replace(re, (matched, _g1, offset) => {
1996
- const entry = byLower.get(matched.toLowerCase());
1997
- if (!entry) return matched;
1998
- if (!entry.matchInCompounds) {
1999
- if (haystack[offset - 1] === "-" || haystack[offset + matched.length] === "-") return matched;
2000
- }
2001
- return render(entry, matched);
2002
- });
2056
+ return { ...base, ocr, moderate, embedding, transcribe, tts, batchSubmit, batchStatus, batchResults };
2003
2057
  }
2004
2058
 
2005
2059
  // src/providers/elevenlabs.ts
@@ -2713,6 +2767,37 @@ function deeplAdapter(config = {}) {
2713
2767
  return { name: "deepl", translate };
2714
2768
  }
2715
2769
 
2770
+ // src/providers/system-one.ts
2771
+ function mapSystemOneAnswers(label, questions, wire) {
2772
+ const answers = {};
2773
+ for (const [id, q] of Object.entries(questions)) answers[id] = mapOne(label, id, q, wire?.[id]);
2774
+ return answers;
2775
+ }
2776
+ function mapOne(label, id, q, a) {
2777
+ if (!a) throw new Error(`${label}: no answer returned for question "${id}"`);
2778
+ const num = (v, field) => {
2779
+ if (typeof v !== "number") throw new Error(`${label}: "${id}" answer has no numeric ${field}`);
2780
+ return v;
2781
+ };
2782
+ if (q.type === "noul") return { type: "noul", noul: num(a.noul, "noul") };
2783
+ if (q.type === "choice") {
2784
+ if (typeof a.choice !== "string") throw new Error(`${label}: "${id}" answer has no choice`);
2785
+ return {
2786
+ type: "choice",
2787
+ choice: a.choice,
2788
+ probabilities: a.probabilities ?? {},
2789
+ confidence: num(a.confidence, "confidence")
2790
+ };
2791
+ }
2792
+ return {
2793
+ type: "score",
2794
+ score: num(a.score, "score"),
2795
+ probabilities: a.probabilities ?? {},
2796
+ legend: a.legend ?? {},
2797
+ confidence: num(a.confidence, "confidence")
2798
+ };
2799
+ }
2800
+
2716
2801
  // src/providers/typesafe.ts
2717
2802
  function typesafeAdapter(config = {}) {
2718
2803
  const fetchImpl = config.fetch ?? fetch;
@@ -2722,30 +2807,6 @@ function typesafeAdapter(config = {}) {
2722
2807
  if (!k) throw new Error("typesafe adapter: API key not set (env TYPESAFE_API_KEY)");
2723
2808
  return k;
2724
2809
  }
2725
- function mapAnswer(id, q, a) {
2726
- if (!a) throw new Error(`typesafe judge: no answer returned for question "${id}"`);
2727
- const num = (v, field) => {
2728
- if (typeof v !== "number") throw new Error(`typesafe judge: "${id}" answer has no numeric ${field}`);
2729
- return v;
2730
- };
2731
- if (q.type === "noul") return { type: "noul", noul: num(a.noul, "noul") };
2732
- if (q.type === "choice") {
2733
- if (typeof a.choice !== "string") throw new Error(`typesafe judge: "${id}" answer has no choice`);
2734
- return {
2735
- type: "choice",
2736
- choice: a.choice,
2737
- probabilities: a.probabilities ?? {},
2738
- confidence: num(a.confidence, "confidence")
2739
- };
2740
- }
2741
- return {
2742
- type: "score",
2743
- score: num(a.score, "score"),
2744
- probabilities: a.probabilities ?? {},
2745
- legend: a.legend ?? {},
2746
- confidence: num(a.confidence, "confidence")
2747
- };
2748
- }
2749
2810
  async function judge(req) {
2750
2811
  const apiKey = key();
2751
2812
  const res = await fetchImpl(`${base}/systemone`, {
@@ -2758,10 +2819,7 @@ function typesafeAdapter(config = {}) {
2758
2819
  throw new Error(`typesafe judge ${res.status}: ${errBody.slice(0, 300)}`);
2759
2820
  }
2760
2821
  const data = await res.json();
2761
- const answers = {};
2762
- for (const [id, q] of Object.entries(req.questions)) {
2763
- answers[id] = mapAnswer(id, q, data.answers?.[id]);
2764
- }
2822
+ const answers = mapSystemOneAnswers("typesafe judge", req.questions, data.answers);
2765
2823
  return {
2766
2824
  answers,
2767
2825
  usage: freshUsage({
@@ -2778,6 +2836,56 @@ function typesafeAdapter(config = {}) {
2778
2836
  return { name: "typesafe", judge };
2779
2837
  }
2780
2838
 
2839
+ // src/providers/microsoft-decision.ts
2840
+ var MICROSOFT_DECISION_DEFAULT_DEPLOYMENT = "decision-1-eu";
2841
+ function microsoftDecisionAdapter(config = {}) {
2842
+ const fetchImpl = config.fetch ?? fetch;
2843
+ function endpoint() {
2844
+ if (config.apiKey !== void 0 && config.endpoint === void 0) {
2845
+ throw new Error("microsoft-decision adapter: an explicit apiKey needs its own endpoint \u2014 pass both (never the env endpoint with a caller's key)");
2846
+ }
2847
+ const e = config.endpoint ?? process.env.AZURE_DECISION_ENDPOINT;
2848
+ if (!e) throw new Error("microsoft-decision adapter: endpoint not set (env AZURE_DECISION_ENDPOINT)");
2849
+ return e.replace(/\/$/, "");
2850
+ }
2851
+ function key() {
2852
+ const k = config.apiKey ?? process.env.AZURE_DECISION_API_KEY;
2853
+ if (!k) throw new Error("microsoft-decision adapter: API key not set (env AZURE_DECISION_API_KEY)");
2854
+ return k;
2855
+ }
2856
+ async function judge(req) {
2857
+ const url = `${endpoint()}/providers/microsoft/v1/systemone`;
2858
+ const apiKey = key();
2859
+ const deployment = config.deployment ?? process.env.AZURE_DECISION_DEPLOYMENT ?? MICROSOFT_DECISION_DEFAULT_DEPLOYMENT;
2860
+ const res = await fetchImpl(url, {
2861
+ method: "POST",
2862
+ headers: { "content-type": "application/json", "api-key": apiKey },
2863
+ body: JSON.stringify({ model: deployment, state: req.state, questions: req.questions })
2864
+ });
2865
+ if (!res.ok) {
2866
+ const errBody = await res.text().catch(() => "");
2867
+ throw new Error(`microsoft-decision judge ${res.status}: ${errBody.slice(0, 300)}`);
2868
+ }
2869
+ const data = await res.json();
2870
+ return {
2871
+ answers: mapSystemOneAnswers("microsoft-decision judge", req.questions, data.answers),
2872
+ usage: freshUsage({
2873
+ provider: "microsoft-decision",
2874
+ model: req.spec.model,
2875
+ // Measured per call: Azure names the region that served it ("Sweden Central").
2876
+ // A Foundry host (<resource>.cognitiveservices.azure.com) carries no region, so
2877
+ // without this header the honest answer is "unknown", never an assumed "eu".
2878
+ region: classifyRegionName(res.headers.get("x-ms-region")?.replace(/\s+/g, "") ?? void 0),
2879
+ transport: "http",
2880
+ capability: "judge",
2881
+ inputTokens: data.usage?.input_tokens ?? 0,
2882
+ outputTokens: data.usage?.output_tokens ?? 0
2883
+ })
2884
+ };
2885
+ }
2886
+ return { name: "microsoft-decision", judge };
2887
+ }
2888
+
2781
2889
  // src/providers/fal.ts
2782
2890
  import { deflateRawSync, crc32 } from "zlib";
2783
2891
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -3299,6 +3407,7 @@ var defaultProviders = {
3299
3407
  vertex: vertexAdapter(),
3300
3408
  deepl: deeplAdapter(),
3301
3409
  typesafe: typesafeAdapter(),
3410
+ "microsoft-decision": microsoftDecisionAdapter(),
3302
3411
  fal: falAdapter(),
3303
3412
  bfl: bflAdapter()
3304
3413
  };
@@ -4033,8 +4142,8 @@ var aiConfigSchema = z.object({
4033
4142
  import { randomUUID } from "crypto";
4034
4143
 
4035
4144
  // src/version.ts
4036
- var VERSION = "0.66.1";
4037
- var SDK_TAG = "@broberg/ai-sdk@0.66.1";
4145
+ var VERSION = "0.68.0";
4146
+ var SDK_TAG = "@broberg/ai-sdk@0.68.0";
4038
4147
 
4039
4148
  // src/cost/sinks/upmetrics.ts
4040
4149
  function isRetryableStatus(status) {
@@ -4359,6 +4468,15 @@ var DEFAULT_BFL_REFERENCE_SPEC = {
4359
4468
  var DEFAULT_OCR_SPEC = { provider: "mistral", model: "mistral-ocr-4-1", transport: "http" };
4360
4469
  var DEFAULT_MODERATION_SPEC = { provider: "mistral", model: "mistral-moderation-2603", transport: "http" };
4361
4470
  var DEFAULT_JUDGE_SPEC = { provider: "typesafe", model: "jev-1.13.0", transport: "http" };
4471
+ var EU_JUDGE_SPEC = { provider: "microsoft-decision", model: "microsoft-decision-1-v1", transport: "http" };
4472
+ var JUDGE_SPECS = { typesafe: DEFAULT_JUDGE_SPEC, "microsoft-decision": EU_JUDGE_SPEC };
4473
+ function judgeSpecFromEnv() {
4474
+ const v = process.env.AI_JUDGE_PROVIDER;
4475
+ if (v === void 0 || v === "") return DEFAULT_JUDGE_SPEC;
4476
+ const spec = JUDGE_SPECS[v];
4477
+ if (!spec) throw new Error(`createAI: AI_JUDGE_PROVIDER="${v}" is not a judge route \u2014 use ${Object.keys(JUDGE_SPECS).join(" or ")}`);
4478
+ return spec;
4479
+ }
4362
4480
  var DEFAULT_PODCAST_SPEC = { provider: "elevenlabs", model: "eleven_v3", transport: "http" };
4363
4481
  var DEFAULT_TTS_SPEC = { provider: "elevenlabs", model: "eleven_multilingual_v2", transport: "http" };
4364
4482
  var DEFAULT_BATCH_SPEC = { provider: "mistral", model: "mistral-small-2603", transport: "http" };
@@ -4372,6 +4490,7 @@ var ROUTED_SPECS = [
4372
4490
  DEFAULT_OCR_SPEC,
4373
4491
  DEFAULT_MODERATION_SPEC,
4374
4492
  DEFAULT_JUDGE_SPEC,
4493
+ EU_JUDGE_SPEC,
4375
4494
  DEFAULT_PODCAST_SPEC,
4376
4495
  DEFAULT_TTS_SPEC,
4377
4496
  DEFAULT_BATCH_SPEC,
@@ -4398,6 +4517,7 @@ function createAI(config = {}) {
4398
4517
  const cfg = aiConfigSchema.parse(config);
4399
4518
  if (cfg.byok) assertByokProviders(cfg.providers);
4400
4519
  const providers = cfg.providers ?? defaultProviders;
4520
+ const judgeSpec = judgeSpecFromEnv();
4401
4521
  const costSink = cfg.costSink === void 0 ? defaultCostSink(requireAgentName(cfg.agentName)) : cfg.costSink ?? void 0;
4402
4522
  const budget = cfg.budget ? new BudgetGuard(cfg.budget) : void 0;
4403
4523
  const estTokens = (s) => Math.ceil(s.length / 4);
@@ -4852,7 +4972,7 @@ function createAI(config = {}) {
4852
4972
  input = judgeInputSchema.parse(input);
4853
4973
  const stateText = typeof input.state === "string" ? input.state : JSON.stringify(input.state);
4854
4974
  return runCapability({
4855
- primary: withOverride(DEFAULT_JUDGE_SPEC, input.override, "judge"),
4975
+ primary: withOverride(judgeSpec, input.override, "judge"),
4856
4976
  fallback: input.fallback,
4857
4977
  capability: "judge",
4858
4978
  purpose: input.purpose,
@@ -5592,6 +5712,7 @@ export {
5592
5712
  INPUT_LIMITS,
5593
5713
  LOCALLY_PINNED_HOSTS,
5594
5714
  MEDIA_PRICING_CHECKED_AT,
5715
+ MICROSOFT_DECISION_DEFAULT_DEPLOYMENT,
5595
5716
  ModelUnavailableError,
5596
5717
  PRICING_STALE_AFTER_DAYS,
5597
5718
  SDK_TAG,
@@ -5650,6 +5771,7 @@ export {
5650
5771
  matchLabel,
5651
5772
  memorySearchCache,
5652
5773
  messageSchema,
5774
+ microsoftDecisionAdapter,
5653
5775
  mistralAdapter,
5654
5776
  mistralStubAdapter,
5655
5777
  multiSink,