@broberg/ai-sdk 0.14.0 → 0.16.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.ts CHANGED
@@ -170,6 +170,16 @@ interface ImageRequest {
170
170
  finetune?: string;
171
171
  /** F023 — how strongly the finetune is applied (BFL finetune_strength, ~0–2). */
172
172
  finetuneStrength?: number;
173
+ /** F023.5 — 1–8 reference photos of a subject (URL or raw bytes). Routes to the
174
+ * EU-resident BFL FLUX 2 multi-reference endpoint — generate a likeness with NO
175
+ * training step. Bytes are base64-inlined into the EU call (no cross-region fetch). */
176
+ referenceImages?: (string | Uint8Array)[];
177
+ /** F023.5 — fixed seed for reproducible output (BFL). */
178
+ seed?: number;
179
+ /** F023.5 — output container (BFL FLUX 2): "jpeg" | "png" | "webp". Default jpeg. */
180
+ outputFormat?: "jpeg" | "png" | "webp";
181
+ /** F023.5 — BFL content-moderation strictness, 0 (strict) … 6 (lax). Default 2. */
182
+ safetyTolerance?: number;
173
183
  /** F021.4 — re-roll once with a fresh seed if fal's safety-checker false-positives
174
184
  * and returns a black image (has_nsfw_concepts). fal only. */
175
185
  retryOnBlack?: boolean;
@@ -952,6 +962,15 @@ declare const imageInputSchema: z.ZodObject<{
952
962
  finetune: z.ZodOptional<z.ZodString>;
953
963
  /** F023 — BFL finetune_strength (~0–2; higher = stronger likeness). */
954
964
  finetuneStrength: z.ZodOptional<z.ZodNumber>;
965
+ /** F023.5 — 1–8 reference photos (URL or raw bytes) → EU-resident BFL FLUX 2
966
+ * multi-reference generation (likeness, no training step). */
967
+ referenceImages: z.ZodOptional<z.ZodArray<z.ZodUnion<[z.ZodString, z.ZodType<Uint8Array<ArrayBuffer>, z.ZodTypeDef, Uint8Array<ArrayBuffer>>]>, "many">>;
968
+ /** F023.5 — fixed seed for reproducible output (BFL). */
969
+ seed: z.ZodOptional<z.ZodNumber>;
970
+ /** F023.5 — output container (BFL FLUX 2). Default jpeg. */
971
+ outputFormat: z.ZodOptional<z.ZodEnum<["jpeg", "png", "webp"]>>;
972
+ /** F023.5 — BFL content-moderation strictness, 0 (strict) … 6 (lax). Default 2. */
973
+ safetyTolerance: z.ZodOptional<z.ZodNumber>;
955
974
  /** F021.4 — re-roll once if fal returns a black image (NSFW false-positive). */
956
975
  retryOnBlack: z.ZodOptional<z.ZodBoolean>;
957
976
  }, "strip", z.ZodTypeAny, {
@@ -961,7 +980,10 @@ declare const imageInputSchema: z.ZodObject<{
961
980
  path: string;
962
981
  scale?: number | undefined;
963
982
  }[] | undefined;
983
+ seed?: number | undefined;
964
984
  lora?: string | undefined;
985
+ width?: number | undefined;
986
+ height?: number | undefined;
965
987
  tier?: "fast" | "smart" | "powerful" | "cheap" | "vision" | "video" | "embedding" | undefined;
966
988
  override?: {
967
989
  provider?: string | undefined;
@@ -974,10 +996,11 @@ declare const imageInputSchema: z.ZodObject<{
974
996
  transport: "http" | "subprocess";
975
997
  })[] | undefined;
976
998
  labels?: Record<string, string> | undefined;
977
- width?: number | undefined;
978
- height?: number | undefined;
979
999
  finetune?: string | undefined;
980
1000
  finetuneStrength?: number | undefined;
1001
+ referenceImages?: (string | Uint8Array<ArrayBuffer>)[] | undefined;
1002
+ outputFormat?: "jpeg" | "png" | "webp" | undefined;
1003
+ safetyTolerance?: number | undefined;
981
1004
  retryOnBlack?: boolean | undefined;
982
1005
  }, {
983
1006
  prompt: string;
@@ -986,7 +1009,10 @@ declare const imageInputSchema: z.ZodObject<{
986
1009
  path: string;
987
1010
  scale?: number | undefined;
988
1011
  }[] | undefined;
1012
+ seed?: number | undefined;
989
1013
  lora?: string | undefined;
1014
+ width?: number | undefined;
1015
+ height?: number | undefined;
990
1016
  tier?: "fast" | "smart" | "powerful" | "cheap" | "vision" | "video" | "embedding" | undefined;
991
1017
  override?: {
992
1018
  provider?: string | undefined;
@@ -999,10 +1025,11 @@ declare const imageInputSchema: z.ZodObject<{
999
1025
  transport: "http" | "subprocess";
1000
1026
  })[] | undefined;
1001
1027
  labels?: Record<string, string> | undefined;
1002
- width?: number | undefined;
1003
- height?: number | undefined;
1004
1028
  finetune?: string | undefined;
1005
1029
  finetuneStrength?: number | undefined;
1030
+ referenceImages?: (string | Uint8Array<ArrayBuffer>)[] | undefined;
1031
+ outputFormat?: "jpeg" | "png" | "webp" | undefined;
1032
+ safetyTolerance?: number | undefined;
1006
1033
  retryOnBlack?: boolean | undefined;
1007
1034
  }>;
1008
1035
  declare const trainStyleInputSchema: z.ZodObject<{
@@ -1706,6 +1733,19 @@ interface BflAdapterConfig {
1706
1733
  /** Override the per-image USD price (else the built-in finetuned-inference estimate). */
1707
1734
  pricePerImage?: number;
1708
1735
  }
1736
+ /** Remaining BFL account credits + their USD value (1 credit = $0.01). */
1737
+ interface BflCredits {
1738
+ credits: number;
1739
+ usd: number;
1740
+ }
1741
+ /** F023.6 — check the BFL account's remaining credit balance (`GET /v1/credits`).
1742
+ * Account-level (region-independent); EU-pinned by default for consistency. Use it
1743
+ * for budget-gating before a generate call: `if ((await bflCredits()).usd < 1) …`. */
1744
+ declare function bflCredits(opts?: {
1745
+ apiKey?: string;
1746
+ baseUrl?: string;
1747
+ fetch?: typeof fetch;
1748
+ }): Promise<BflCredits>;
1709
1749
  declare function bflAdapter(config?: BflAdapterConfig): ProviderAdapter;
1710
1750
 
1711
1751
  interface OpenAICompatibleConfig {
@@ -1741,8 +1781,8 @@ declare const falStubAdapter: ProviderAdapter;
1741
1781
  * wires the live adapters. */
1742
1782
  declare const stubProviders: Record<string, ProviderAdapter>;
1743
1783
 
1744
- declare const VERSION: "0.14.0";
1745
- declare const SDK_TAG: "@broberg/ai-sdk@0.14.0";
1784
+ declare const VERSION: "0.16.0";
1785
+ declare const SDK_TAG: "@broberg/ai-sdk@0.16.0";
1746
1786
 
1747
1787
  /** Built-in defaults. Every entry is overridable via AiConfig.defaults or a
1748
1788
  * per-call override. Model IDs are current at scaffold time; callers pin their
@@ -1968,4 +2008,4 @@ interface StreamTransportRequest extends TransportRequest {
1968
2008
  */
1969
2009
  declare function streamTransport(req: StreamTransportRequest): AsyncIterable<string>;
1970
2010
 
1971
- export { type AiClient, type AiConfig, type BatchJob, type BatchRequestItem, type BatchResultItem, type BflAdapterConfig, type BudgetConfig, BudgetExceededError, BudgetGuard, type BudgetStore, type CallOptions, type Capability, type ChatInput, type ChatRequest, type ChatResult, type ChatStreamEvent, type ClassifyInput, type ClassifyResult, type ContentPart, type Contracts, type CostSink, type CostSummary, DEFAULT_TIER_MAP, type DesignInput, type DesignResult, type DialogueRequest, type DialogueTurn, type DiscordSinkConfig, ELEVENLABS_DANISH_VOICES, type EmbeddingInput, type EmbeddingRequest, type EmbeddingResult, type ExtractInput, type ExtractResult, type FalAdapterConfig, type HttpResponse, type ImageInput, type ImageRequest, type ImageResult, type LoraWeight, type Message, type MockupInput, type MockupResult, type ModerationInput, type ModerationItem, type ModerationRequest, type ModerationResult, type OcrInput, type OcrPage, type OcrRequest, type OcrResult, type OpenAICompatibleConfig, type PodcastInput, type PodcastResult, type PricingEntry, type ProviderAdapter, type RefreshOptions, type RefreshResult, type RerankInput, type RerankResult, type Role, SDK_TAG, type SqliteBudgetStoreConfig, type SqliteSinkConfig, StreamHttpError, type SubprocessResponse, type Tier, type TierSpec, type Tool, type ToolCall, type TrainStyleInput, type TrainStyleRequest, type TrainStyleResult, type TranscribeInput, type TranscribeRequest, type TranscribeResult, type TranslateInput, type TranslateResult, type Transport, type TransportRequest, type TransportResponse, type TtsInput, type TtsRequest, type UpmetricsSinkConfig, type Usage, VERSION, type VideoInput, type VisionInput, aiConfigSchema, anthropicAdapter, anthropicApiAdapter, anthropicSubprocessAdapter, bflAdapter, chatInputSchema, computeCost, createAI, deepinfraAdapter, defaultProviders, discordSink, elevenlabsAdapter, embeddingInputSchema, falAdapter, falStubAdapter, freshUsage, fromProviderToolCall, geminiAdapter, getCostSummary, getPrice, httpTransport, imageInputSchema, makeContracts, makeOpenAICompatibleAdapter, messageSchema, mistralAdapter, multiSink, noopSink, openaiAdapter, openaiStubAdapter, openrouterAdapter, parseClaudeCliJson, parseJsonLoose, refreshAvailability, resetRefreshState, resetRegistry, resolveTier, resolveVoice, sqliteBudgetStore, sqliteSink, streamTransport, stubProviders, subprocessTransport, tierSpecSchema, toProviderTools, toolSchema, translateInputSchema, upmetricsSink, visionInputSchema };
2011
+ export { type AiClient, type AiConfig, type BatchJob, type BatchRequestItem, type BatchResultItem, type BflAdapterConfig, type BflCredits, type BudgetConfig, BudgetExceededError, BudgetGuard, type BudgetStore, type CallOptions, type Capability, type ChatInput, type ChatRequest, type ChatResult, type ChatStreamEvent, type ClassifyInput, type ClassifyResult, type ContentPart, type Contracts, type CostSink, type CostSummary, DEFAULT_TIER_MAP, type DesignInput, type DesignResult, type DialogueRequest, type DialogueTurn, type DiscordSinkConfig, ELEVENLABS_DANISH_VOICES, type EmbeddingInput, type EmbeddingRequest, type EmbeddingResult, type ExtractInput, type ExtractResult, type FalAdapterConfig, type HttpResponse, type ImageInput, type ImageRequest, type ImageResult, type LoraWeight, type Message, type MockupInput, type MockupResult, type ModerationInput, type ModerationItem, type ModerationRequest, type ModerationResult, type OcrInput, type OcrPage, type OcrRequest, type OcrResult, type OpenAICompatibleConfig, type PodcastInput, type PodcastResult, type PricingEntry, type ProviderAdapter, type RefreshOptions, type RefreshResult, type RerankInput, type RerankResult, type Role, SDK_TAG, type SqliteBudgetStoreConfig, type SqliteSinkConfig, StreamHttpError, type SubprocessResponse, type Tier, type TierSpec, type Tool, type ToolCall, type TrainStyleInput, type TrainStyleRequest, type TrainStyleResult, type TranscribeInput, type TranscribeRequest, type TranscribeResult, type TranslateInput, type TranslateResult, type Transport, type TransportRequest, type TransportResponse, type TtsInput, type TtsRequest, type UpmetricsSinkConfig, type Usage, VERSION, type VideoInput, type VisionInput, aiConfigSchema, anthropicAdapter, anthropicApiAdapter, anthropicSubprocessAdapter, bflAdapter, bflCredits, chatInputSchema, computeCost, createAI, deepinfraAdapter, defaultProviders, discordSink, elevenlabsAdapter, embeddingInputSchema, falAdapter, falStubAdapter, freshUsage, fromProviderToolCall, geminiAdapter, getCostSummary, getPrice, httpTransport, imageInputSchema, makeContracts, makeOpenAICompatibleAdapter, messageSchema, mistralAdapter, multiSink, noopSink, openaiAdapter, openaiStubAdapter, openrouterAdapter, parseClaudeCliJson, parseJsonLoose, refreshAvailability, resetRefreshState, resetRegistry, resolveTier, resolveVoice, sqliteBudgetStore, sqliteSink, streamTransport, stubProviders, subprocessTransport, tierSpecSchema, toProviderTools, toolSchema, translateInputSchema, upmetricsSink, visionInputSchema };
package/dist/index.js CHANGED
@@ -1575,11 +1575,24 @@ function buildZip(files) {
1575
1575
 
1576
1576
  // src/providers/bfl.ts
1577
1577
  var EU_BASE = "https://api.eu.bfl.ai";
1578
+ var BFL_CREDIT_USD = 0.01;
1578
1579
  var BFL_IMAGE_PRICE = 0.06;
1579
1580
  var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
1580
1581
  function gcd(a, b) {
1581
1582
  return b === 0 ? a : gcd(b, a % b);
1582
1583
  }
1584
+ async function bflCredits(opts = {}) {
1585
+ const apiKey = opts.apiKey ?? process.env.BFL_API_KEY;
1586
+ if (!apiKey) throw new Error("bflCredits: BFL_API_KEY not set");
1587
+ const doFetch = opts.fetch ?? fetch;
1588
+ const res = await doFetch(`${opts.baseUrl ?? EU_BASE}/v1/credits`, { headers: { "x-key": apiKey } });
1589
+ if (!res.ok) {
1590
+ throw new Error(`bflCredits ${res.status}: ${(await res.text().catch(() => "")).slice(0, 200)}`);
1591
+ }
1592
+ const data = await res.json();
1593
+ const credits = typeof data.credits === "number" ? data.credits : 0;
1594
+ return { credits, usd: credits * BFL_CREDIT_USD };
1595
+ }
1583
1596
  function bflAdapter(config = {}) {
1584
1597
  const doFetch = config.fetch ?? fetch;
1585
1598
  const base = config.baseUrl ?? EU_BASE;
@@ -1589,22 +1602,30 @@ function bflAdapter(config = {}) {
1589
1602
  async function image(req) {
1590
1603
  const apiKey = resolveKey();
1591
1604
  if (!apiKey) throw new Error("bfl adapter: BFL_API_KEY not set");
1592
- if (!req.finetune) {
1605
+ const headers = { "content-type": "application/json", "x-key": apiKey };
1606
+ const body = { prompt: req.prompt };
1607
+ if (req.referenceImages?.length) {
1608
+ req.referenceImages.forEach((img, i) => {
1609
+ body[i === 0 ? "input_image" : `input_image_${i + 1}`] = toBflImage(img);
1610
+ });
1611
+ if (req.width) body.width = req.width;
1612
+ if (req.height) body.height = req.height;
1613
+ if (req.seed !== void 0) body.seed = req.seed;
1614
+ body.output_format = req.outputFormat ?? "jpeg";
1615
+ body.safety_tolerance = req.safetyTolerance ?? 2;
1616
+ } else if (req.finetune) {
1617
+ body.finetune_id = req.finetune;
1618
+ if (req.finetuneStrength !== void 0) body.finetune_strength = req.finetuneStrength;
1619
+ if (req.width && req.height) {
1620
+ const g = gcd(req.width, req.height) || 1;
1621
+ body.aspect_ratio = `${req.width / g}:${req.height / g}`;
1622
+ }
1623
+ } else {
1593
1624
  throw new Error(
1594
- "bfl adapter: requires a finetune id \u2014 call ai.image({ finetune, override: { provider: 'bfl' } }). Train the subject once in the BFL dashboard (dashboard.bfl.ai) \u2014 finetune-create is not in the public API."
1625
+ "bfl adapter: requires referenceImages (FLUX 2 multi-reference) or a finetune id. ai.image({ referenceImages: [...] }) needs no training; ai.image({ finetune }) uses a subject trained once in the BFL dashboard (dashboard.bfl.ai \u2014 finetune-create is not in the public API)."
1595
1626
  );
1596
1627
  }
1597
- const headers = { "content-type": "application/json", "x-key": apiKey };
1598
- const body = {
1599
- finetune_id: req.finetune,
1600
- prompt: req.prompt
1601
- };
1602
- if (req.finetuneStrength !== void 0) body.finetune_strength = req.finetuneStrength;
1603
- if (req.width && req.height) {
1604
- const g = gcd(req.width, req.height) || 1;
1605
- body.aspect_ratio = `${req.width / g}:${req.height / g}`;
1606
- }
1607
- const submitRes = await doFetch(`${base}/v1/flux-pro-1.1-ultra-finetuned`, {
1628
+ const submitRes = await doFetch(`${base}/v1/${req.spec.model}`, {
1608
1629
  method: "POST",
1609
1630
  headers,
1610
1631
  body: JSON.stringify(body)
@@ -1623,9 +1644,15 @@ function bflAdapter(config = {}) {
1623
1644
  inputTokens: 0,
1624
1645
  outputTokens: 0
1625
1646
  });
1626
- usage.costUsd = config.pricePerImage ?? BFL_IMAGE_PRICE;
1647
+ usage.costUsd = typeof submit.cost === "number" ? submit.cost * BFL_CREDIT_USD : config.pricePerImage ?? BFL_IMAGE_PRICE;
1627
1648
  return { url: sample, usage };
1628
1649
  }
1650
+ function toBflImage(img) {
1651
+ if (typeof img !== "string") return Buffer.from(img).toString("base64");
1652
+ if (/^https?:\/\//i.test(img)) return img;
1653
+ const comma = img.startsWith("data:") ? img.indexOf(",") : -1;
1654
+ return comma >= 0 ? img.slice(comma + 1) : img;
1655
+ }
1629
1656
  async function poll(id, apiKey) {
1630
1657
  const headers = { "x-key": apiKey };
1631
1658
  const deadline = Date.now() + timeoutMs;
@@ -1979,6 +2006,15 @@ var imageInputSchema = z.object({
1979
2006
  finetune: z.string().optional(),
1980
2007
  /** F023 — BFL finetune_strength (~0–2; higher = stronger likeness). */
1981
2008
  finetuneStrength: z.number().min(0).max(2).optional(),
2009
+ /** F023.5 — 1–8 reference photos (URL or raw bytes) → EU-resident BFL FLUX 2
2010
+ * multi-reference generation (likeness, no training step). */
2011
+ referenceImages: z.array(z.union([z.string(), z.instanceof(Uint8Array)])).min(1).max(8).optional(),
2012
+ /** F023.5 — fixed seed for reproducible output (BFL). */
2013
+ seed: z.number().int().optional(),
2014
+ /** F023.5 — output container (BFL FLUX 2). Default jpeg. */
2015
+ outputFormat: z.enum(["jpeg", "png", "webp"]).optional(),
2016
+ /** F023.5 — BFL content-moderation strictness, 0 (strict) … 6 (lax). Default 2. */
2017
+ safetyTolerance: z.number().int().min(0).max(6).optional(),
1982
2018
  /** F021.4 — re-roll once if fal returns a black image (NSFW false-positive). */
1983
2019
  retryOnBlack: z.boolean().optional(),
1984
2020
  ...callOptions
@@ -2066,6 +2102,11 @@ var DEFAULT_BFL_FINETUNE_SPEC = {
2066
2102
  model: "flux-pro-1.1-ultra-finetuned",
2067
2103
  transport: "http"
2068
2104
  };
2105
+ var DEFAULT_BFL_REFERENCE_SPEC = {
2106
+ provider: "bfl",
2107
+ model: "flux-2-max",
2108
+ transport: "http"
2109
+ };
2069
2110
  var DEFAULT_OCR_SPEC = { provider: "mistral", model: "mistral-ocr-latest", transport: "http" };
2070
2111
  var DEFAULT_MODERATION_SPEC = { provider: "mistral", model: "mistral-moderation-latest", transport: "http" };
2071
2112
  var DEFAULT_PODCAST_SPEC = { provider: "elevenlabs", model: "eleven_v3", transport: "http" };
@@ -2312,7 +2353,7 @@ function createAI(config = {}) {
2312
2353
  ...input.loras ?? [],
2313
2354
  ...input.lora ? [{ path: input.lora }] : []
2314
2355
  ];
2315
- const base = input.finetune ? DEFAULT_BFL_FINETUNE_SPEC : loras.length > 0 ? DEFAULT_LORA_IMAGE_SPEC : DEFAULT_IMAGE_SPEC;
2356
+ const base = input.referenceImages?.length ? DEFAULT_BFL_REFERENCE_SPEC : input.finetune ? DEFAULT_BFL_FINETUNE_SPEC : loras.length > 0 ? DEFAULT_LORA_IMAGE_SPEC : DEFAULT_IMAGE_SPEC;
2316
2357
  return runCapability({
2317
2358
  primary: { ...base, ...input.override },
2318
2359
  fallback: input.fallback,
@@ -2333,6 +2374,10 @@ function createAI(config = {}) {
2333
2374
  loras: loras.length ? loras : void 0,
2334
2375
  finetune: input.finetune,
2335
2376
  finetuneStrength: input.finetuneStrength,
2377
+ referenceImages: input.referenceImages,
2378
+ seed: input.seed,
2379
+ outputFormat: input.outputFormat,
2380
+ safetyTolerance: input.safetyTolerance,
2336
2381
  retryOnBlack: input.retryOnBlack
2337
2382
  });
2338
2383
  }
@@ -2588,8 +2633,8 @@ var stubProviders = {
2588
2633
  };
2589
2634
 
2590
2635
  // src/version.ts
2591
- var VERSION = "0.14.0";
2592
- var SDK_TAG = "@broberg/ai-sdk@0.14.0";
2636
+ var VERSION = "0.16.0";
2637
+ var SDK_TAG = "@broberg/ai-sdk@0.16.0";
2593
2638
 
2594
2639
  // src/availability/refresh.ts
2595
2640
  var NOT_REFRESHED = { refreshed: false, checked: 0, markedUnavailable: [] };
@@ -2876,6 +2921,7 @@ export {
2876
2921
  anthropicApiAdapter,
2877
2922
  anthropicSubprocessAdapter,
2878
2923
  bflAdapter,
2924
+ bflCredits,
2879
2925
  chatInputSchema,
2880
2926
  computeCost,
2881
2927
  createAI,