@use-lattice/litmus 0.121.3

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.
Files changed (199) hide show
  1. package/LICENSE +19 -0
  2. package/dist/src/accounts-Bt1oJb1Z.cjs +219 -0
  3. package/dist/src/accounts-DjOU8Rm3.js +178 -0
  4. package/dist/src/agentic-utils-D03IiXQc.js +153 -0
  5. package/dist/src/agentic-utils-Dh7xaMQM.cjs +180 -0
  6. package/dist/src/agents-C6BIMlZa.js +231 -0
  7. package/dist/src/agents-DvIpNX1L.cjs +666 -0
  8. package/dist/src/agents-ZP0RP9vV.cjs +231 -0
  9. package/dist/src/agents-maJXdjbR.js +665 -0
  10. package/dist/src/aimlapi-BTbQjG2E.cjs +30 -0
  11. package/dist/src/aimlapi-CwMxqfXP.js +30 -0
  12. package/dist/src/audio-BBUdvsde.cjs +97 -0
  13. package/dist/src/audio-D5DPZ7I-.js +97 -0
  14. package/dist/src/base-BEysXrkq.cjs +222 -0
  15. package/dist/src/base-C451JQfq.js +193 -0
  16. package/dist/src/blobs-BY8MDmpo.js +230 -0
  17. package/dist/src/blobs-BgcNn97m.cjs +256 -0
  18. package/dist/src/cache-BBE_lsTA.cjs +4 -0
  19. package/dist/src/cache-BkrqU5Ba.js +237 -0
  20. package/dist/src/cache-DsCxFlsZ.cjs +297 -0
  21. package/dist/src/chat-CPJWDP6a.cjs +289 -0
  22. package/dist/src/chat-CXX3xzkk.cjs +811 -0
  23. package/dist/src/chat-CcDgZFJ4.js +787 -0
  24. package/dist/src/chat-Dz5ZeGO2.js +289 -0
  25. package/dist/src/chatkit-Dw0mKkML.cjs +1158 -0
  26. package/dist/src/chatkit-swAIVuea.js +1157 -0
  27. package/dist/src/chunk-DEq-mXcV.js +15 -0
  28. package/dist/src/claude-agent-sdk-BXZJtOg6.js +379 -0
  29. package/dist/src/claude-agent-sdk-CkfyjDoG.cjs +383 -0
  30. package/dist/src/cloudflare-ai-BzpJcqUH.js +161 -0
  31. package/dist/src/cloudflare-ai-Cmy_R1y2.cjs +161 -0
  32. package/dist/src/cloudflare-gateway-B9tVQKok.cjs +272 -0
  33. package/dist/src/cloudflare-gateway-DrD3ew3H.js +272 -0
  34. package/dist/src/codex-sdk-Dezj9Nwm.js +1056 -0
  35. package/dist/src/codex-sdk-Dl9D4k5B.cjs +1060 -0
  36. package/dist/src/cometapi-C-9YvCHC.js +54 -0
  37. package/dist/src/cometapi-DHgDKoO2.cjs +54 -0
  38. package/dist/src/completion-B8Ctyxpr.js +120 -0
  39. package/dist/src/completion-Cxrt08sj.cjs +131 -0
  40. package/dist/src/createHash-BwgE13yv.cjs +27 -0
  41. package/dist/src/createHash-DmPQkvBh.js +15 -0
  42. package/dist/src/docker-BiqcTwLv.js +80 -0
  43. package/dist/src/docker-C7tEJnP-.cjs +80 -0
  44. package/dist/src/esm-C62Zofr1.cjs +409 -0
  45. package/dist/src/esm-DMVc93eh.js +379 -0
  46. package/dist/src/evalResult-C3NJPQOo.cjs +301 -0
  47. package/dist/src/evalResult-C7JJAPBb.js +295 -0
  48. package/dist/src/evalResult-DoVTZZWI.cjs +2 -0
  49. package/dist/src/extractor-DnMD3fwt.cjs +391 -0
  50. package/dist/src/extractor-DtlL28vL.js +374 -0
  51. package/dist/src/fetch-BTxakTSg.cjs +1133 -0
  52. package/dist/src/fetch-DQckpUFz.js +928 -0
  53. package/dist/src/fileExtensions-DnqA1y9x.js +85 -0
  54. package/dist/src/fileExtensions-bYh77CN8.cjs +114 -0
  55. package/dist/src/genaiTracer-CyZrmaK0.cjs +268 -0
  56. package/dist/src/genaiTracer-D3fD9dNV.js +256 -0
  57. package/dist/src/graders-BNscxFrU.js +13644 -0
  58. package/dist/src/graders-D2oE9Msq.js +2 -0
  59. package/dist/src/graders-c0Ez_w-9.cjs +2 -0
  60. package/dist/src/graders-d0F2M3e9.cjs +14056 -0
  61. package/dist/src/image-0ZhE0VlR.cjs +280 -0
  62. package/dist/src/image-CWE1pdNv.js +257 -0
  63. package/dist/src/image-D9ZK6hwL.js +163 -0
  64. package/dist/src/image-DKZgZITg.cjs +163 -0
  65. package/dist/src/index.cjs +11366 -0
  66. package/dist/src/index.d.cts +19640 -0
  67. package/dist/src/index.d.ts +19641 -0
  68. package/dist/src/index.js +11306 -0
  69. package/dist/src/invariant-Ddh24eXh.js +25 -0
  70. package/dist/src/invariant-kfQ8Bu82.cjs +30 -0
  71. package/dist/src/knowledgeBase-BgPyGFUd.cjs +122 -0
  72. package/dist/src/knowledgeBase-DyHilYaP.js +122 -0
  73. package/dist/src/litellm-CyMeneHS.js +135 -0
  74. package/dist/src/litellm-DWDF73yF.cjs +135 -0
  75. package/dist/src/logger-C40ZGil9.js +717 -0
  76. package/dist/src/logger-DyfK9PBt.cjs +917 -0
  77. package/dist/src/luma-ray-BAU9X_ep.cjs +315 -0
  78. package/dist/src/luma-ray-nwVseBbv.js +313 -0
  79. package/dist/src/messages-B5ADWTTv.js +245 -0
  80. package/dist/src/messages-BCnZfqrS.cjs +257 -0
  81. package/dist/src/meteor-DLZZ3osF.cjs +134 -0
  82. package/dist/src/meteor-DUiCJRC-.js +134 -0
  83. package/dist/src/modelslab-00cveB8L.cjs +163 -0
  84. package/dist/src/modelslab-D9sCU_L7.js +163 -0
  85. package/dist/src/nova-reel-CTapvqYH.js +276 -0
  86. package/dist/src/nova-reel-DlWuuroF.cjs +278 -0
  87. package/dist/src/nova-sonic-5UPWfeMv.cjs +363 -0
  88. package/dist/src/nova-sonic-BhSwQNym.js +363 -0
  89. package/dist/src/openai-BWrJK9d8.cjs +52 -0
  90. package/dist/src/openai-DumO8WQn.js +47 -0
  91. package/dist/src/openclaw-B8brrjC_.cjs +577 -0
  92. package/dist/src/openclaw-Bkayww9q.js +571 -0
  93. package/dist/src/opencode-sdk-7xjoDNiM.cjs +562 -0
  94. package/dist/src/opencode-sdk-SGwAPxht.js +558 -0
  95. package/dist/src/otlpReceiver-CoAHfAN9.cjs +15 -0
  96. package/dist/src/otlpReceiver-oO3EQwI9.js +14 -0
  97. package/dist/src/providerRegistry-4yjhaEM8.js +45 -0
  98. package/dist/src/providerRegistry-DhV4rJIc.cjs +50 -0
  99. package/dist/src/providers-B5RJVG-7.cjs +33609 -0
  100. package/dist/src/providers-BdmZCLzV.js +33262 -0
  101. package/dist/src/providers-CxtRxn8e.js +2 -0
  102. package/dist/src/providers-DnQLNbx1.cjs +3 -0
  103. package/dist/src/pythonUtils-BD0druiM.cjs +275 -0
  104. package/dist/src/pythonUtils-IBhn5YGR.js +249 -0
  105. package/dist/src/quiverai-BDOwZBsM.cjs +213 -0
  106. package/dist/src/quiverai-D3JTF5lD.js +213 -0
  107. package/dist/src/responses-B2LCDCXZ.js +667 -0
  108. package/dist/src/responses-BvNm4Xv9.cjs +685 -0
  109. package/dist/src/rubyUtils-B0NwnfpY.cjs +245 -0
  110. package/dist/src/rubyUtils-BroxzZ7c.cjs +2 -0
  111. package/dist/src/rubyUtils-hqVw5UvJ.js +222 -0
  112. package/dist/src/sagemaker-Cno2V-Sx.js +689 -0
  113. package/dist/src/sagemaker-fV_KUgs5.cjs +691 -0
  114. package/dist/src/server-BOuAXb06.cjs +238 -0
  115. package/dist/src/server-CtI-EWzm.cjs +2 -0
  116. package/dist/src/server-Cy3DZymt.js +189 -0
  117. package/dist/src/slack-CP8xBePa.js +135 -0
  118. package/dist/src/slack-DSQ1yXVb.cjs +135 -0
  119. package/dist/src/store-BwDDaBjb.cjs +246 -0
  120. package/dist/src/store-DcbLC593.cjs +2 -0
  121. package/dist/src/store-IGpqMIkv.js +240 -0
  122. package/dist/src/tables-3Q2cL7So.cjs +373 -0
  123. package/dist/src/tables-Bi2fjr4W.js +288 -0
  124. package/dist/src/telemetry-Bg2WqF79.js +161 -0
  125. package/dist/src/telemetry-D0x6u5kX.cjs +166 -0
  126. package/dist/src/telemetry-DXNimrI0.cjs +2 -0
  127. package/dist/src/text-B_UCRPp2.js +22 -0
  128. package/dist/src/text-CW1cyrwj.cjs +33 -0
  129. package/dist/src/tokenUsageUtils-NYT-WKS6.js +138 -0
  130. package/dist/src/tokenUsageUtils-bVa1ga6f.cjs +173 -0
  131. package/dist/src/transcription-Cl_W16Pr.js +122 -0
  132. package/dist/src/transcription-yt1EecY8.cjs +124 -0
  133. package/dist/src/transform-BCtGrl_W.cjs +228 -0
  134. package/dist/src/transform-Bv6gG2MJ.cjs +1688 -0
  135. package/dist/src/transform-CY1wbpRy.js +1507 -0
  136. package/dist/src/transform-DU8rUL9P.cjs +2 -0
  137. package/dist/src/transform-yWaShiKr.js +216 -0
  138. package/dist/src/transformersAvailability-BGkzavwb.js +35 -0
  139. package/dist/src/transformersAvailability-DKoRtQLy.cjs +35 -0
  140. package/dist/src/types-5aqHpBwE.cjs +3769 -0
  141. package/dist/src/types-Bn6D9c4U.js +3300 -0
  142. package/dist/src/util-BkKlTkI2.js +293 -0
  143. package/dist/src/util-CTh0bfOm.cjs +1119 -0
  144. package/dist/src/util-D17oBwo7.cjs +328 -0
  145. package/dist/src/util-DsS_-v4p.js +613 -0
  146. package/dist/src/util-DuntT1Ga.js +951 -0
  147. package/dist/src/util-aWjdCYMI.cjs +667 -0
  148. package/dist/src/utils-CisQwpjA.js +94 -0
  149. package/dist/src/utils-yWamDvmz.cjs +123 -0
  150. package/dist/tsconfig.tsbuildinfo +1 -0
  151. package/drizzle/0000_lush_hellion.sql +36 -0
  152. package/drizzle/0001_wide_calypso.sql +3 -0
  153. package/drizzle/0002_tidy_juggernaut.sql +1 -0
  154. package/drizzle/0003_lively_naoko.sql +8 -0
  155. package/drizzle/0004_minor_peter_quill.sql +19 -0
  156. package/drizzle/0005_silky_millenium_guard.sql +2 -0
  157. package/drizzle/0006_harsh_caretaker.sql +42 -0
  158. package/drizzle/0007_cloudy_wong.sql +1 -0
  159. package/drizzle/0008_broad_boomer.sql +2 -0
  160. package/drizzle/0009_strong_marten_broadcloak.sql +19 -0
  161. package/drizzle/0010_needy_bishop.sql +11 -0
  162. package/drizzle/0011_moaning_millenium_guard.sql +1 -0
  163. package/drizzle/0012_late_marten_broadcloak.sql +2 -0
  164. package/drizzle/0013_previous_dormammu.sql +9 -0
  165. package/drizzle/0014_lazy_captain_universe.sql +2 -0
  166. package/drizzle/0015_zippy_wallop.sql +29 -0
  167. package/drizzle/0016_jazzy_zemo.sql +2 -0
  168. package/drizzle/0017_reflective_praxagora.sql +4 -0
  169. package/drizzle/0018_fat_vanisher.sql +22 -0
  170. package/drizzle/0019_new_clint_barton.sql +8 -0
  171. package/drizzle/0020_skinny_maverick.sql +1 -0
  172. package/drizzle/0021_mysterious_madelyne_pryor.sql +13 -0
  173. package/drizzle/0022_sleepy_ultimo.sql +25 -0
  174. package/drizzle/0023_wooden_mandrill.sql +2 -0
  175. package/drizzle/AGENTS.md +68 -0
  176. package/drizzle/CLAUDE.md +1 -0
  177. package/drizzle/meta/0000_snapshot.json +221 -0
  178. package/drizzle/meta/0001_snapshot.json +214 -0
  179. package/drizzle/meta/0002_snapshot.json +221 -0
  180. package/drizzle/meta/0005_snapshot.json +369 -0
  181. package/drizzle/meta/0006_snapshot.json +638 -0
  182. package/drizzle/meta/0007_snapshot.json +640 -0
  183. package/drizzle/meta/0008_snapshot.json +649 -0
  184. package/drizzle/meta/0009_snapshot.json +554 -0
  185. package/drizzle/meta/0010_snapshot.json +619 -0
  186. package/drizzle/meta/0011_snapshot.json +627 -0
  187. package/drizzle/meta/0012_snapshot.json +639 -0
  188. package/drizzle/meta/0013_snapshot.json +717 -0
  189. package/drizzle/meta/0014_snapshot.json +717 -0
  190. package/drizzle/meta/0015_snapshot.json +897 -0
  191. package/drizzle/meta/0016_snapshot.json +1031 -0
  192. package/drizzle/meta/0018_snapshot.json +1210 -0
  193. package/drizzle/meta/0019_snapshot.json +1165 -0
  194. package/drizzle/meta/0020_snapshot.json +1232 -0
  195. package/drizzle/meta/0021_snapshot.json +1311 -0
  196. package/drizzle/meta/0022_snapshot.json +1481 -0
  197. package/drizzle/meta/0023_snapshot.json +1496 -0
  198. package/drizzle/meta/_journal.json +174 -0
  199. package/package.json +240 -0
@@ -0,0 +1,134 @@
1
+ import { t as invariant } from "./invariant-Ddh24eXh.js";
2
+ //#region src/assertions/meteor.ts
3
+ let PorterStemmer;
4
+ let WordNet;
5
+ async function ensureNaturalPackage() {
6
+ if (PorterStemmer && WordNet) return;
7
+ try {
8
+ const natural = await import("natural");
9
+ PorterStemmer = natural.PorterStemmer;
10
+ WordNet = natural.WordNet;
11
+ } catch (_err) {
12
+ throw new Error("The \"natural\" package is required for METEOR assertions. Install it with: npm install natural@^8.1.0");
13
+ }
14
+ }
15
+ function preprocessWord(word) {
16
+ return word.toLowerCase();
17
+ }
18
+ function generateEnums(candidate, reference, preprocess = preprocessWord) {
19
+ if (typeof candidate === "string") throw new TypeError(`"candidate" expects pre-tokenized candidate (string[]): ${candidate}`);
20
+ if (typeof reference === "string") throw new TypeError(`"reference" expects pre-tokenized reference (string[]): ${reference}`);
21
+ return [candidate.map((word, idx) => [idx, preprocess(word)]), reference.map((word, idx) => [idx, preprocess(word)])];
22
+ }
23
+ function matchExactEnums(enumCandidateList, enumReferenceList) {
24
+ const wordMatch = [];
25
+ const candidateCopy = [...enumCandidateList];
26
+ const referenceCopy = [...enumReferenceList];
27
+ for (let i = candidateCopy.length - 1; i >= 0; i--) for (let j = referenceCopy.length - 1; j >= 0; j--) if (candidateCopy[i][1] === referenceCopy[j][1]) {
28
+ wordMatch.push([candidateCopy[i][0], referenceCopy[j][0]]);
29
+ candidateCopy.splice(i, 1);
30
+ referenceCopy.splice(j, 1);
31
+ break;
32
+ }
33
+ return [
34
+ wordMatch,
35
+ candidateCopy,
36
+ referenceCopy
37
+ ];
38
+ }
39
+ async function matchStemEnums(enumCandidateList, enumReferenceList, stemmer) {
40
+ await ensureNaturalPackage();
41
+ invariant(PorterStemmer, "PorterStemmer should be loaded");
42
+ const actualStemmer = stemmer || PorterStemmer;
43
+ const candidateCopy = [...enumCandidateList];
44
+ const referenceCopy = [...enumReferenceList];
45
+ const candidateStems = candidateCopy.map(([idx, word]) => [idx, actualStemmer.stem(word)]);
46
+ const referenceStems = referenceCopy.map(([idx, word]) => [idx, actualStemmer.stem(word)]);
47
+ return matchExactEnums(candidateStems.map(([idx, stem]) => [idx, stem]), referenceStems.map(([idx, stem]) => [idx, stem]));
48
+ }
49
+ async function matchSynonymEnums(enumCandidateList, enumReferenceList, wordnet) {
50
+ await ensureNaturalPackage();
51
+ invariant(WordNet, "WordNet should be loaded");
52
+ const actualWordNet = wordnet || new WordNet();
53
+ const wordMatch = [];
54
+ const candidateCopy = [...enumCandidateList];
55
+ const referenceCopy = [...enumReferenceList];
56
+ for (let i = candidateCopy.length - 1; i >= 0; i--) {
57
+ const candidateWord = candidateCopy[i][1];
58
+ const candidateSynsets = await new Promise((resolve) => {
59
+ actualWordNet.lookup(candidateWord, (results) => resolve(results));
60
+ });
61
+ const candidateSynonymSet = new Set([candidateWord, ...candidateSynsets.flatMap((synset) => synset.synonyms.filter((syn) => !syn.includes("_")))]);
62
+ for (let j = referenceCopy.length - 1; j >= 0; j--) {
63
+ const referenceWord = referenceCopy[j][1];
64
+ if (candidateSynonymSet.has(referenceWord)) {
65
+ wordMatch.push([candidateCopy[i][0], referenceCopy[j][0]]);
66
+ candidateCopy.splice(i, 1);
67
+ referenceCopy.splice(j, 1);
68
+ break;
69
+ }
70
+ }
71
+ }
72
+ return [
73
+ wordMatch,
74
+ candidateCopy,
75
+ referenceCopy
76
+ ];
77
+ }
78
+ function countChunks(matches) {
79
+ if (matches.length === 0) return 0;
80
+ let chunks = 1;
81
+ for (let i = 0; i < matches.length - 1; i++) if (matches[i + 1][0] !== matches[i][0] + 1 || matches[i + 1][1] !== matches[i][1] + 1) chunks++;
82
+ return chunks;
83
+ }
84
+ async function calculateSingleMeteorScore(reference, candidate, alpha = .9, beta = 3, gamma = .5) {
85
+ const [enumCandidate, enumReference] = generateEnums(candidate, reference);
86
+ const translationLength = enumCandidate.length;
87
+ const referenceLength = enumReference.length;
88
+ const [exactMatches, remainingCandidate, remainingReference] = matchExactEnums(enumCandidate, enumReference);
89
+ const [stemMatches, remainingCandidateAfterStem, remainingReferenceAfterStem] = await matchStemEnums(remainingCandidate, remainingReference);
90
+ const [synonymMatches, ,] = await matchSynonymEnums(remainingCandidateAfterStem, remainingReferenceAfterStem);
91
+ const allMatches = [
92
+ ...exactMatches,
93
+ ...stemMatches,
94
+ ...synonymMatches
95
+ ].sort((a, b) => a[0] - b[0]);
96
+ const matchesCount = allMatches.length;
97
+ if (matchesCount === 0) return 0;
98
+ let fragFrac = 0;
99
+ let fmean = 0;
100
+ if (translationLength === 0 || referenceLength === 0 || matchesCount === 0) return 0;
101
+ const precision = matchesCount / translationLength;
102
+ const recall = matchesCount / referenceLength;
103
+ const denominator = alpha * precision + (1 - alpha) * recall;
104
+ if (denominator === 0) return 0;
105
+ fmean = precision * recall / denominator;
106
+ fragFrac = countChunks(allMatches) / matchesCount;
107
+ return (1 - gamma * Math.pow(fragFrac, beta)) * fmean;
108
+ }
109
+ async function calculateMeteorScore(candidate, references, alpha = .9, beta = 3, gamma = .5) {
110
+ if (!candidate || references.length === 0) throw new Error("Invalid inputs");
111
+ const scores = await Promise.all(references.map((reference) => calculateSingleMeteorScore(reference.split(/\s+/).map((word) => word.replace(/\.+$/, "")), candidate.split(/\s+/).map((word) => word.replace(/\.+$/, "")), alpha, beta, gamma)));
112
+ return Math.max(...scores);
113
+ }
114
+ async function handleMeteorAssertion({ assertion, inverse, outputString, renderedValue }) {
115
+ invariant(typeof renderedValue === "string" || Array.isArray(renderedValue) && renderedValue.every((v) => typeof v === "string"), "\"meteor\" assertion must have a string or array of strings value");
116
+ const references = Array.isArray(renderedValue) ? renderedValue : [renderedValue];
117
+ const meteorAssertion = assertion;
118
+ const alpha = meteorAssertion.alpha ?? .9;
119
+ const beta = meteorAssertion.beta ?? 3;
120
+ const gamma = meteorAssertion.gamma ?? .5;
121
+ const threshold = meteorAssertion.threshold ?? .5;
122
+ const score = await calculateMeteorScore(outputString, references, alpha, beta, gamma);
123
+ const pass = inverse ? score < threshold : score >= threshold;
124
+ return {
125
+ pass,
126
+ score: inverse ? 1 - score : score,
127
+ reason: pass ? "METEOR assertion passed" : `METEOR score ${score.toFixed(4)} did not meet threshold ${threshold}`,
128
+ assertion
129
+ };
130
+ }
131
+ //#endregion
132
+ export { handleMeteorAssertion };
133
+
134
+ //# sourceMappingURL=meteor-DUiCJRC-.js.map
@@ -0,0 +1,163 @@
1
+ const require_logger = require("./logger-DyfK9PBt.cjs");
2
+ const require_fetch = require("./fetch-BTxakTSg.cjs");
3
+ const require_cache = require("./cache-DsCxFlsZ.cjs");
4
+ const require_blobs = require("./blobs-BgcNn97m.cjs");
5
+ const require_extractor = require("./extractor-DnMD3fwt.cjs");
6
+ const require_text = require("./text-CW1cyrwj.cjs");
7
+ //#region src/providers/modelslab.ts
8
+ /**
9
+ * ModelsLab provider for text-to-image generation.
10
+ *
11
+ * Handles async polling: initial response may return {status: "processing"},
12
+ * in which case we poll the fetch endpoint until completion.
13
+ *
14
+ * API docs: https://docs.modelslab.com
15
+ *
16
+ * NOTE: ModelsLab uses key-in-body authentication (not Bearer header).
17
+ * The API key is sent as the "key" field in the JSON request body.
18
+ */
19
+ const MODELSLAB_BASE_URL = "https://modelslab.com/api/v6";
20
+ const POLL_INTERVAL_MS = 3e3;
21
+ const MAX_POLL_ATTEMPTS = 60;
22
+ var ModelsLabImageProvider = class {
23
+ modelName;
24
+ apiKey;
25
+ config;
26
+ constructor(modelName, options = {}) {
27
+ const { config, id, env } = options;
28
+ this.modelName = modelName;
29
+ this.apiKey = config?.apiKey || env?.MODELSLAB_API_KEY || require_logger.getEnvString("MODELSLAB_API_KEY");
30
+ const { apiKey: _apiKey, ...restConfig } = config ?? {};
31
+ this.config = restConfig;
32
+ this.id = id ? () => id : this.id;
33
+ }
34
+ id() {
35
+ return `modelslab:image:${this.modelName}`;
36
+ }
37
+ toString() {
38
+ return `[ModelsLab Image Provider ${this.modelName}]`;
39
+ }
40
+ async callApi(prompt, context, _callApiOptions) {
41
+ if (!this.apiKey) return { error: "ModelsLab API key is not set. Set the MODELSLAB_API_KEY environment variable or add `apiKey` to the provider config." };
42
+ const config = {
43
+ ...this.config,
44
+ ...context?.prompt?.config
45
+ };
46
+ const requestBody = {
47
+ key: this.apiKey,
48
+ model_id: this.modelName,
49
+ prompt,
50
+ width: config.width ?? 512,
51
+ height: config.height ?? 512,
52
+ num_inference_steps: config.num_inference_steps ?? 30,
53
+ guidance_scale: config.guidance_scale ?? 7.5,
54
+ samples: config.samples ?? 1,
55
+ safety_checker: config.safety_checker ?? "no",
56
+ enhance_prompt: config.enhance_prompt ?? "no"
57
+ };
58
+ if (config.negative_prompt) requestBody.negative_prompt = config.negative_prompt;
59
+ if (config.seed !== void 0) requestBody.seed = config.seed;
60
+ try {
61
+ require_logger.logger.debug("[ModelsLab] Image generation request", {
62
+ model: this.modelName,
63
+ prompt: require_text.ellipsize(prompt, 50)
64
+ });
65
+ const response = await require_cache.fetchWithCache(`${MODELSLAB_BASE_URL}/images/text2img`, {
66
+ method: "POST",
67
+ headers: { "Content-Type": "application/json" },
68
+ body: JSON.stringify(requestBody)
69
+ }, require_fetch.REQUEST_TIMEOUT_MS, "json", true);
70
+ let data = response.data;
71
+ let cached = response.cached;
72
+ if (data.status === "processing") {
73
+ const requestId = data.request_id ?? String(data.id);
74
+ require_logger.logger.debug("[ModelsLab] Image is processing, polling for result", {
75
+ model: this.modelName,
76
+ requestId
77
+ });
78
+ data = await this.pollForCompletion(requestId);
79
+ cached = false;
80
+ }
81
+ if (data.status === "error") return {
82
+ cached,
83
+ error: `ModelsLab API error: ${data.message || "Unknown error"}`
84
+ };
85
+ if (data.status === "success") {
86
+ if (!data.output || data.output.length === 0) return { error: "ModelsLab returned no image URLs" };
87
+ const imageUrl = data.output[0];
88
+ const { url: resolvedUrl, blobRef } = await this.maybeDownloadToBlob(imageUrl);
89
+ return {
90
+ output: `![${require_text.ellipsize(prompt.replace(/\r?\n|\r/g, " ").replace(/\[/g, "(").replace(/\]/g, ")"), 50)}](${resolvedUrl})`,
91
+ cached,
92
+ ...blobRef && { metadata: {
93
+ blobRef,
94
+ blobHash: blobRef.hash
95
+ } }
96
+ };
97
+ }
98
+ return { error: `Unexpected ModelsLab response status: ${data.status}` };
99
+ } catch (err) {
100
+ return { error: `ModelsLab API call error: ${String(err)}` };
101
+ }
102
+ }
103
+ async maybeDownloadToBlob(imageUrl) {
104
+ if (!require_extractor.isBlobStorageEnabled()) return { url: imageUrl };
105
+ try {
106
+ const response = await require_fetch.fetchWithProxy(imageUrl);
107
+ if (!response.ok) {
108
+ require_logger.logger.warn("[ModelsLab] Failed to download image for blob storage", {
109
+ url: imageUrl,
110
+ status: response.status
111
+ });
112
+ return { url: imageUrl };
113
+ }
114
+ const { ref } = await require_blobs.storeBlob(Buffer.from(await response.arrayBuffer()), response.headers.get("content-type")?.split(";")[0] || "image/png", {
115
+ location: "response.output",
116
+ kind: "image"
117
+ });
118
+ return {
119
+ url: ref.uri,
120
+ blobRef: ref
121
+ };
122
+ } catch (error) {
123
+ require_logger.logger.warn("[ModelsLab] Failed to store image as blob, using URL", {
124
+ url: imageUrl,
125
+ error: String(error)
126
+ });
127
+ return { url: imageUrl };
128
+ }
129
+ }
130
+ async pollForCompletion(requestId) {
131
+ const fetchUrl = `${MODELSLAB_BASE_URL}/images/fetch/${requestId}`;
132
+ for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
133
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
134
+ try {
135
+ const data = (await require_cache.fetchWithCache(fetchUrl, {
136
+ method: "POST",
137
+ headers: { "Content-Type": "application/json" },
138
+ body: JSON.stringify({ key: this.apiKey })
139
+ }, require_fetch.REQUEST_TIMEOUT_MS, "json", true)).data;
140
+ require_logger.logger.debug("[ModelsLab] Poll attempt", {
141
+ attempt: attempt + 1,
142
+ requestId,
143
+ status: data.status
144
+ });
145
+ if (data.status === "success" || data.status === "error") return data;
146
+ } catch (error) {
147
+ require_logger.logger.warn("[ModelsLab] Poll attempt failed", {
148
+ attempt: attempt + 1,
149
+ requestId,
150
+ error: String(error)
151
+ });
152
+ }
153
+ }
154
+ return {
155
+ status: "error",
156
+ message: `ModelsLab image generation timed out after ${MAX_POLL_ATTEMPTS * POLL_INTERVAL_MS / 1e3}s`
157
+ };
158
+ }
159
+ };
160
+ //#endregion
161
+ exports.ModelsLabImageProvider = ModelsLabImageProvider;
162
+
163
+ //# sourceMappingURL=modelslab-00cveB8L.cjs.map
@@ -0,0 +1,163 @@
1
+ import { r as logger, x as getEnvString } from "./logger-C40ZGil9.js";
2
+ import { h as REQUEST_TIMEOUT_MS, t as fetchWithProxy } from "./fetch-DQckpUFz.js";
3
+ import { r as fetchWithCache } from "./cache-BkrqU5Ba.js";
4
+ import { n as storeBlob } from "./blobs-BY8MDmpo.js";
5
+ import { n as isBlobStorageEnabled } from "./extractor-DtlL28vL.js";
6
+ import { t as ellipsize } from "./text-B_UCRPp2.js";
7
+ //#region src/providers/modelslab.ts
8
+ /**
9
+ * ModelsLab provider for text-to-image generation.
10
+ *
11
+ * Handles async polling: initial response may return {status: "processing"},
12
+ * in which case we poll the fetch endpoint until completion.
13
+ *
14
+ * API docs: https://docs.modelslab.com
15
+ *
16
+ * NOTE: ModelsLab uses key-in-body authentication (not Bearer header).
17
+ * The API key is sent as the "key" field in the JSON request body.
18
+ */
19
+ const MODELSLAB_BASE_URL = "https://modelslab.com/api/v6";
20
+ const POLL_INTERVAL_MS = 3e3;
21
+ const MAX_POLL_ATTEMPTS = 60;
22
+ var ModelsLabImageProvider = class {
23
+ modelName;
24
+ apiKey;
25
+ config;
26
+ constructor(modelName, options = {}) {
27
+ const { config, id, env } = options;
28
+ this.modelName = modelName;
29
+ this.apiKey = config?.apiKey || env?.MODELSLAB_API_KEY || getEnvString("MODELSLAB_API_KEY");
30
+ const { apiKey: _apiKey, ...restConfig } = config ?? {};
31
+ this.config = restConfig;
32
+ this.id = id ? () => id : this.id;
33
+ }
34
+ id() {
35
+ return `modelslab:image:${this.modelName}`;
36
+ }
37
+ toString() {
38
+ return `[ModelsLab Image Provider ${this.modelName}]`;
39
+ }
40
+ async callApi(prompt, context, _callApiOptions) {
41
+ if (!this.apiKey) return { error: "ModelsLab API key is not set. Set the MODELSLAB_API_KEY environment variable or add `apiKey` to the provider config." };
42
+ const config = {
43
+ ...this.config,
44
+ ...context?.prompt?.config
45
+ };
46
+ const requestBody = {
47
+ key: this.apiKey,
48
+ model_id: this.modelName,
49
+ prompt,
50
+ width: config.width ?? 512,
51
+ height: config.height ?? 512,
52
+ num_inference_steps: config.num_inference_steps ?? 30,
53
+ guidance_scale: config.guidance_scale ?? 7.5,
54
+ samples: config.samples ?? 1,
55
+ safety_checker: config.safety_checker ?? "no",
56
+ enhance_prompt: config.enhance_prompt ?? "no"
57
+ };
58
+ if (config.negative_prompt) requestBody.negative_prompt = config.negative_prompt;
59
+ if (config.seed !== void 0) requestBody.seed = config.seed;
60
+ try {
61
+ logger.debug("[ModelsLab] Image generation request", {
62
+ model: this.modelName,
63
+ prompt: ellipsize(prompt, 50)
64
+ });
65
+ const response = await fetchWithCache(`${MODELSLAB_BASE_URL}/images/text2img`, {
66
+ method: "POST",
67
+ headers: { "Content-Type": "application/json" },
68
+ body: JSON.stringify(requestBody)
69
+ }, REQUEST_TIMEOUT_MS, "json", true);
70
+ let data = response.data;
71
+ let cached = response.cached;
72
+ if (data.status === "processing") {
73
+ const requestId = data.request_id ?? String(data.id);
74
+ logger.debug("[ModelsLab] Image is processing, polling for result", {
75
+ model: this.modelName,
76
+ requestId
77
+ });
78
+ data = await this.pollForCompletion(requestId);
79
+ cached = false;
80
+ }
81
+ if (data.status === "error") return {
82
+ cached,
83
+ error: `ModelsLab API error: ${data.message || "Unknown error"}`
84
+ };
85
+ if (data.status === "success") {
86
+ if (!data.output || data.output.length === 0) return { error: "ModelsLab returned no image URLs" };
87
+ const imageUrl = data.output[0];
88
+ const { url: resolvedUrl, blobRef } = await this.maybeDownloadToBlob(imageUrl);
89
+ return {
90
+ output: `![${ellipsize(prompt.replace(/\r?\n|\r/g, " ").replace(/\[/g, "(").replace(/\]/g, ")"), 50)}](${resolvedUrl})`,
91
+ cached,
92
+ ...blobRef && { metadata: {
93
+ blobRef,
94
+ blobHash: blobRef.hash
95
+ } }
96
+ };
97
+ }
98
+ return { error: `Unexpected ModelsLab response status: ${data.status}` };
99
+ } catch (err) {
100
+ return { error: `ModelsLab API call error: ${String(err)}` };
101
+ }
102
+ }
103
+ async maybeDownloadToBlob(imageUrl) {
104
+ if (!isBlobStorageEnabled()) return { url: imageUrl };
105
+ try {
106
+ const response = await fetchWithProxy(imageUrl);
107
+ if (!response.ok) {
108
+ logger.warn("[ModelsLab] Failed to download image for blob storage", {
109
+ url: imageUrl,
110
+ status: response.status
111
+ });
112
+ return { url: imageUrl };
113
+ }
114
+ const { ref } = await storeBlob(Buffer.from(await response.arrayBuffer()), response.headers.get("content-type")?.split(";")[0] || "image/png", {
115
+ location: "response.output",
116
+ kind: "image"
117
+ });
118
+ return {
119
+ url: ref.uri,
120
+ blobRef: ref
121
+ };
122
+ } catch (error) {
123
+ logger.warn("[ModelsLab] Failed to store image as blob, using URL", {
124
+ url: imageUrl,
125
+ error: String(error)
126
+ });
127
+ return { url: imageUrl };
128
+ }
129
+ }
130
+ async pollForCompletion(requestId) {
131
+ const fetchUrl = `${MODELSLAB_BASE_URL}/images/fetch/${requestId}`;
132
+ for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
133
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
134
+ try {
135
+ const data = (await fetchWithCache(fetchUrl, {
136
+ method: "POST",
137
+ headers: { "Content-Type": "application/json" },
138
+ body: JSON.stringify({ key: this.apiKey })
139
+ }, REQUEST_TIMEOUT_MS, "json", true)).data;
140
+ logger.debug("[ModelsLab] Poll attempt", {
141
+ attempt: attempt + 1,
142
+ requestId,
143
+ status: data.status
144
+ });
145
+ if (data.status === "success" || data.status === "error") return data;
146
+ } catch (error) {
147
+ logger.warn("[ModelsLab] Poll attempt failed", {
148
+ attempt: attempt + 1,
149
+ requestId,
150
+ error: String(error)
151
+ });
152
+ }
153
+ }
154
+ return {
155
+ status: "error",
156
+ message: `ModelsLab image generation timed out after ${MAX_POLL_ATTEMPTS * POLL_INTERVAL_MS / 1e3}s`
157
+ };
158
+ }
159
+ };
160
+ //#endregion
161
+ export { ModelsLabImageProvider };
162
+
163
+ //# sourceMappingURL=modelslab-D9sCU_L7.js.map