@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,689 @@
1
+ import { b as getEnvInt, r as logger, x as getEnvString, y as getEnvFloat } from "./logger-C40ZGil9.js";
2
+ import { n as transform } from "./transform-yWaShiKr.js";
3
+ import { t as telemetry } from "./telemetry-Bg2WqF79.js";
4
+ import { z } from "zod";
5
+ import crypto from "crypto";
6
+ //#region src/providers/sagemaker.ts
7
+ /**
8
+ * Sleep utility function for implementing delays
9
+ * @param ms Milliseconds to sleep
10
+ * @returns Promise that resolves after the specified delay
11
+ */
12
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
13
+ const SUPPORTED_MODEL_TYPES = [
14
+ "openai",
15
+ "llama",
16
+ "huggingface",
17
+ "jumpstart",
18
+ "custom"
19
+ ];
20
+ /**
21
+ * Zod schema for validating SageMaker options
22
+ */
23
+ const SageMakerConfigSchema = z.strictObject({
24
+ accessKeyId: z.string().optional(),
25
+ profile: z.string().optional(),
26
+ region: z.string().optional(),
27
+ secretAccessKey: z.string().optional(),
28
+ sessionToken: z.string().optional(),
29
+ endpoint: z.string().optional(),
30
+ contentType: z.string().optional(),
31
+ acceptType: z.string().optional(),
32
+ maxTokens: z.number().optional(),
33
+ temperature: z.number().optional(),
34
+ topP: z.number().optional(),
35
+ stopSequences: z.array(z.string()).optional(),
36
+ delay: z.number().optional(),
37
+ transform: z.string().optional(),
38
+ modelType: z.enum(SUPPORTED_MODEL_TYPES).optional(),
39
+ responseFormat: z.strictObject({
40
+ type: z.string().optional(),
41
+ path: z.string().optional()
42
+ }).optional(),
43
+ basePath: z.string().optional()
44
+ });
45
+ /**
46
+ * Base class for SageMaker providers with common functionality
47
+ */
48
+ var SageMakerGenericProvider = class {
49
+ env;
50
+ sagemakerRuntime;
51
+ config;
52
+ endpointName;
53
+ delay;
54
+ transform;
55
+ providerId;
56
+ constructor(endpointName, options) {
57
+ const { config, id, env, delay, transform } = options;
58
+ this.env = env;
59
+ this.endpointName = endpointName;
60
+ try {
61
+ SageMakerConfigSchema.parse(config);
62
+ } catch (error) {
63
+ logger.warn(`Error validating SageMaker config\nConfig: ${JSON.stringify(config)}\n${error instanceof z.ZodError ? z.prettifyError(error) : error}`);
64
+ }
65
+ this.config = config ?? {};
66
+ this.delay = delay || this.config.delay;
67
+ this.transform = transform || this.config.transform;
68
+ this.providerId = id;
69
+ telemetry.record("feature_used", { feature: "sagemaker" });
70
+ }
71
+ id() {
72
+ return this.providerId || `sagemaker:${this.endpointName}`;
73
+ }
74
+ toString() {
75
+ return `[Amazon SageMaker Provider ${this.endpointName}]`;
76
+ }
77
+ /**
78
+ * Get AWS credentials from config or environment
79
+ */
80
+ async getCredentials() {
81
+ if (this.config.accessKeyId && this.config.secretAccessKey) {
82
+ logger.debug("Using explicit credentials from config");
83
+ return {
84
+ accessKeyId: this.config.accessKeyId,
85
+ secretAccessKey: this.config.secretAccessKey,
86
+ sessionToken: this.config.sessionToken
87
+ };
88
+ }
89
+ if (this.config.profile) {
90
+ logger.debug(`Using AWS profile: ${this.config.profile}`);
91
+ try {
92
+ const { fromSSO } = await import("@aws-sdk/credential-provider-sso");
93
+ return fromSSO({ profile: this.config.profile });
94
+ } catch {
95
+ throw new Error(`Failed to load AWS SSO profile. Please install @aws-sdk/credential-provider-sso`);
96
+ }
97
+ }
98
+ logger.debug("Using default AWS credentials from environment");
99
+ }
100
+ /**
101
+ * Initialize and return the SageMaker runtime client
102
+ */
103
+ async getSageMakerRuntimeInstance() {
104
+ if (!this.sagemakerRuntime) try {
105
+ const { SageMakerRuntimeClient } = await import("@aws-sdk/client-sagemaker-runtime");
106
+ const credentials = await this.getCredentials();
107
+ this.sagemakerRuntime = new SageMakerRuntimeClient({
108
+ region: this.getRegion(),
109
+ maxAttempts: getEnvInt("AWS_SAGEMAKER_MAX_RETRIES", 3),
110
+ retryMode: "adaptive",
111
+ ...credentials ? { credentials } : {}
112
+ });
113
+ logger.debug(`SageMaker client initialized for region ${this.getRegion()}`);
114
+ } catch {
115
+ throw new Error("The @aws-sdk/client-sagemaker-runtime package is required. Please install it with: npm install @aws-sdk/client-sagemaker-runtime");
116
+ }
117
+ return this.sagemakerRuntime;
118
+ }
119
+ /**
120
+ * Get AWS region from config or environment
121
+ */
122
+ getRegion() {
123
+ return this.config?.region || this.env?.AWS_REGION || getEnvString("AWS_REGION") || getEnvString("AWS_DEFAULT_REGION") || "us-east-1";
124
+ }
125
+ /**
126
+ * Get SageMaker endpoint name
127
+ */
128
+ getEndpointName() {
129
+ return this.config?.endpoint || this.endpointName;
130
+ }
131
+ /**
132
+ * Get content type for request
133
+ */
134
+ getContentType() {
135
+ return this.config?.contentType || "application/json";
136
+ }
137
+ /**
138
+ * Get accept type for response
139
+ */
140
+ getAcceptType() {
141
+ return this.config?.acceptType || "application/json";
142
+ }
143
+ /**
144
+ * Apply transformation to a prompt if a transform function is specified
145
+ * @param prompt The original prompt to transform
146
+ * @param context Optional context information for the transformation
147
+ * @returns The transformed prompt, or the original if no transformation is applied
148
+ */
149
+ async applyTransformation(prompt, context) {
150
+ if (!this.transform) return prompt;
151
+ try {
152
+ const transformContext = {
153
+ vars: context?.vars || {},
154
+ prompt: context?.prompt || { raw: prompt },
155
+ uuid: `sagemaker-${this.endpointName}-${Date.now()}`
156
+ };
157
+ const transformFn = this.transform || context?.originalProvider?.transform;
158
+ if (!transformFn) return prompt;
159
+ logger.debug(`Applying transform to prompt for SageMaker endpoint ${this.getEndpointName()}`);
160
+ if (typeof transformFn === "string" && !transformFn.startsWith("file://")) try {
161
+ if (transformFn.includes("=>")) {
162
+ const result = new Function("prompt", "context", `try { return (${transformFn})(prompt, context); } catch(e) { throw new Error("Transform function error: " + e.message); }`)(prompt, transformContext);
163
+ if (result === void 0 || result === null) {
164
+ logger.debug("Transform function returned null or undefined, using original prompt");
165
+ return prompt;
166
+ }
167
+ if (typeof result === "string") return result;
168
+ else if (typeof result === "object") return JSON.stringify(result);
169
+ else return String(result);
170
+ } else {
171
+ const result = new Function("prompt", "context", `try { ${transformFn} } catch(e) { throw new Error("Transform function error: " + e.message); }`)(prompt, transformContext);
172
+ if (result === void 0 || result === null) {
173
+ logger.debug("Transform function returned null or undefined, using original prompt");
174
+ return prompt;
175
+ }
176
+ if (typeof result === "string") return result;
177
+ else if (typeof result === "object") return JSON.stringify(result);
178
+ else return String(result);
179
+ }
180
+ } catch (transformError) {
181
+ logger.error(`Error executing inline transform: ${transformError}`);
182
+ }
183
+ else try {
184
+ const { TransformInputType } = await import("./transform-yWaShiKr.js").then((n) => n.r);
185
+ const transformed = await transform(transformFn, prompt, transformContext, false, TransformInputType.OUTPUT);
186
+ if (transformed === void 0 || transformed === null) {
187
+ logger.debug("Transform function returned null or undefined, using original prompt");
188
+ return prompt;
189
+ }
190
+ if (typeof transformed === "string") return transformed;
191
+ else if (typeof transformed === "object") return JSON.stringify(transformed);
192
+ else return String(transformed);
193
+ } catch (transformError) {
194
+ logger.error(`Error using transform utility: ${transformError}`);
195
+ }
196
+ logger.warn(`Transform did not produce a valid result, using original prompt`);
197
+ return prompt;
198
+ } catch (_) {
199
+ logger.error(`Error applying transform to prompt: ${_}`);
200
+ return prompt;
201
+ }
202
+ }
203
+ /**
204
+ * Extracts data from a response using a path expression
205
+ * Supports JavaScript expressions and file-based transforms
206
+ */
207
+ async extractFromPath(responseJson, pathExpression) {
208
+ if (!pathExpression) return responseJson;
209
+ try {
210
+ if (pathExpression.startsWith("file://")) try {
211
+ const { TransformInputType } = await import("./transform-yWaShiKr.js").then((n) => n.r);
212
+ const transformedResult = await transform(pathExpression, responseJson, { prompt: {} }, false, TransformInputType.OUTPUT);
213
+ return transformedResult !== void 0 && transformedResult !== null ? transformedResult : responseJson;
214
+ } catch (error) {
215
+ logger.warn(`Failed to transform response using file: ${error}`);
216
+ return responseJson;
217
+ }
218
+ try {
219
+ const result = new Function("json", `try { return ${pathExpression}; } catch(e) { return undefined; }`)(responseJson);
220
+ if (result === void 0) {
221
+ logger.warn(`Path expression "${pathExpression}" did not match any data in the response`);
222
+ logger.debug(`Response JSON structure: ${JSON.stringify(responseJson).substring(0, 200)}...`);
223
+ return responseJson;
224
+ }
225
+ return result;
226
+ } catch (error) {
227
+ logger.warn(`Failed to evaluate expression "${pathExpression}": ${error}`);
228
+ return responseJson;
229
+ }
230
+ } catch (error) {
231
+ logger.warn(`Failed to extract data using path expression "${pathExpression}": ${error}`);
232
+ logger.debug(`Response JSON structure: ${JSON.stringify(responseJson).substring(0, 200)}...`);
233
+ return responseJson;
234
+ }
235
+ }
236
+ };
237
+ /**
238
+ * Provider for text generation with SageMaker endpoints
239
+ */
240
+ var SageMakerCompletionProvider = class extends SageMakerGenericProvider {
241
+ modelType;
242
+ constructor(endpointName, options) {
243
+ super(endpointName, options);
244
+ this.modelType = this.parseModelType(options.config?.modelType);
245
+ }
246
+ /**
247
+ * Model type must be specified within the id or the `config.modelType` field.
248
+ */
249
+ parseModelType(modelType) {
250
+ const match = this.id().match(/^sagemaker:(?<modelType>.+):.+$/);
251
+ if (match) {
252
+ const modelTypeFromId = match.groups.modelType;
253
+ if (SUPPORTED_MODEL_TYPES.includes(modelTypeFromId)) return modelTypeFromId;
254
+ else throw new Error(`Invalid model type "${modelTypeFromId}" in provider ID. Valid types are: ${SUPPORTED_MODEL_TYPES.join(", ")}`);
255
+ }
256
+ if (modelType) if (SUPPORTED_MODEL_TYPES.includes(modelType)) return modelType;
257
+ else throw new Error(`Invalid model type "${modelType}" in \`config.modelType\`. Valid types are: ${SUPPORTED_MODEL_TYPES.join(", ")}`);
258
+ throw new Error("Model type must be set either in `config.modelType` or as part of the Provider ID, for example: \"sagemaker:<model_type>:<endpoint>\"");
259
+ }
260
+ /**
261
+ * Format the request payload based on model type
262
+ */
263
+ formatPayload(prompt) {
264
+ const maxTokens = this.config.maxTokens ?? getEnvInt("AWS_SAGEMAKER_MAX_TOKENS") ?? 1024;
265
+ const temperature = typeof this.config.temperature === "number" ? this.config.temperature : getEnvFloat("AWS_SAGEMAKER_TEMPERATURE") ?? .7;
266
+ const topP = typeof this.config.topP === "number" ? this.config.topP : getEnvFloat("AWS_SAGEMAKER_TOP_P") ?? 1;
267
+ const stopSequences = this.config.stopSequences || [];
268
+ let payload;
269
+ logger.debug(`Formatting payload for model type: ${this.modelType}`);
270
+ switch (this.modelType) {
271
+ case "openai":
272
+ try {
273
+ const messages = JSON.parse(prompt);
274
+ if (Array.isArray(messages)) payload = {
275
+ messages,
276
+ max_tokens: maxTokens,
277
+ temperature,
278
+ top_p: topP,
279
+ stop: stopSequences.length > 0 ? stopSequences : void 0
280
+ };
281
+ else throw new Error("Not valid messages format");
282
+ } catch {
283
+ payload = {
284
+ prompt,
285
+ max_tokens: maxTokens,
286
+ temperature,
287
+ top_p: topP,
288
+ stop: stopSequences.length > 0 ? stopSequences : void 0
289
+ };
290
+ }
291
+ break;
292
+ case "llama":
293
+ try {
294
+ const messages = JSON.parse(prompt);
295
+ if (Array.isArray(messages)) payload = {
296
+ inputs: messages,
297
+ parameters: {
298
+ max_new_tokens: maxTokens,
299
+ temperature,
300
+ top_p: topP,
301
+ stop: stopSequences.length > 0 ? stopSequences : void 0
302
+ }
303
+ };
304
+ else throw new Error("Not valid messages format");
305
+ } catch {
306
+ payload = {
307
+ inputs: prompt,
308
+ parameters: {
309
+ max_new_tokens: maxTokens,
310
+ temperature,
311
+ top_p: topP,
312
+ stop: stopSequences.length > 0 ? stopSequences : void 0
313
+ }
314
+ };
315
+ }
316
+ break;
317
+ case "jumpstart":
318
+ payload = {
319
+ inputs: prompt,
320
+ parameters: {
321
+ max_new_tokens: maxTokens,
322
+ temperature,
323
+ top_p: topP,
324
+ do_sample: temperature > 0
325
+ }
326
+ };
327
+ break;
328
+ case "huggingface":
329
+ payload = {
330
+ inputs: prompt,
331
+ parameters: {
332
+ max_new_tokens: maxTokens,
333
+ temperature,
334
+ top_p: topP,
335
+ do_sample: temperature > 0,
336
+ return_full_text: false
337
+ }
338
+ };
339
+ break;
340
+ default:
341
+ try {
342
+ payload = JSON.parse(prompt);
343
+ } catch {
344
+ payload = { prompt };
345
+ }
346
+ break;
347
+ }
348
+ return JSON.stringify(payload);
349
+ }
350
+ /**
351
+ * Parse the response from SageMaker endpoint
352
+ */
353
+ async parseResponse(responseBody) {
354
+ let responseJson;
355
+ logger.debug(`Parsing response for model type: ${this.modelType}`);
356
+ try {
357
+ responseJson = JSON.parse(responseBody);
358
+ } catch {
359
+ logger.debug("Response is not JSON, returning as-is");
360
+ return responseBody;
361
+ }
362
+ if (this.config.responseFormat?.path) try {
363
+ const pathExpression = this.config.responseFormat.path;
364
+ return await this.extractFromPath(responseJson, pathExpression);
365
+ } catch (error) {
366
+ logger.warn(`Failed to extract from path: ${this.config.responseFormat.path}, Error: ${error}`);
367
+ logger.debug(`Response JSON structure: ${JSON.stringify(responseJson).substring(0, 200)}...`);
368
+ return responseJson;
369
+ }
370
+ if (responseJson.generated_text) {
371
+ logger.debug("Detected JumpStart model response format with generated_text field");
372
+ return responseJson.generated_text;
373
+ }
374
+ switch (this.modelType) {
375
+ case "openai": return responseJson.choices?.[0]?.message?.content || responseJson.choices?.[0]?.text || responseJson.generation || responseJson;
376
+ case "llama": return responseJson.generation || responseJson.choices?.[0]?.message?.content || responseJson.choices?.[0]?.text || responseJson;
377
+ case "huggingface": return Array.isArray(responseJson) ? responseJson[0]?.generated_text || responseJson[0] : responseJson.generated_text || responseJson;
378
+ case "jumpstart": return responseJson.generated_text || responseJson;
379
+ default: return responseJson.output || responseJson.generation || responseJson.response || responseJson.text || responseJson.generated_text || responseJson.choices?.[0]?.message?.content || responseJson.choices?.[0]?.text || responseJson;
380
+ }
381
+ }
382
+ /**
383
+ * Generate a consistent cache key for SageMaker requests
384
+ * Uses crypto.createHash to generate a shorter, more efficient key
385
+ */
386
+ getCacheKey(prompt) {
387
+ const configForKey = {
388
+ endpoint: this.getEndpointName(),
389
+ modelType: this.config.modelType,
390
+ contentType: this.getContentType(),
391
+ acceptType: this.getAcceptType(),
392
+ maxTokens: this.config.maxTokens,
393
+ temperature: this.config.temperature,
394
+ topP: this.config.topP,
395
+ region: this.getRegion()
396
+ };
397
+ const configStr = JSON.stringify(configForKey);
398
+ const promptHash = crypto.createHash("sha256").update(prompt).digest("hex").substring(0, 16);
399
+ const configHash = crypto.createHash("sha256").update(configStr).digest("hex").substring(0, 8);
400
+ return `sagemaker:v1:${this.getEndpointName()}:${promptHash}:${configHash}`;
401
+ }
402
+ /**
403
+ * Invoke SageMaker endpoint for text generation with caching, delay support, and transformations
404
+ */
405
+ async callApi(prompt, context, _options) {
406
+ const { isCacheEnabled, getCache } = await import("./cache-BkrqU5Ba.js").then((n) => n.t);
407
+ const delayMs = context?.originalProvider?.delay || this.delay;
408
+ const transformedPrompt = await this.applyTransformation(prompt, context);
409
+ const isTransformed = transformedPrompt !== prompt;
410
+ if (isTransformed) {
411
+ logger.debug(`Prompt transformed for SageMaker endpoint ${this.getEndpointName()}`);
412
+ logger.debug(`Original: ${prompt.substring(0, 100)}${prompt.length > 100 ? "..." : ""}`);
413
+ logger.debug(`Transformed: ${transformedPrompt.substring(0, 100)}${transformedPrompt.length > 100 ? "..." : ""}`);
414
+ }
415
+ const bustCache = context?.bustCache ?? context?.debug === true;
416
+ if (isCacheEnabled() && !bustCache) {
417
+ const cacheKey = this.getCacheKey(transformedPrompt);
418
+ const cachedResult = await (getCache ? getCache() : await import("./cache-BkrqU5Ba.js").then((n) => n.t).then((m) => m.getCache())).get(cacheKey);
419
+ if (cachedResult) {
420
+ logger.debug(`Using cached SageMaker response for ${this.getEndpointName()}`);
421
+ try {
422
+ const parsedResult = JSON.parse(cachedResult);
423
+ if (parsedResult.tokenUsage) parsedResult.tokenUsage.cached = parsedResult.tokenUsage.total || 0;
424
+ if (isTransformed && parsedResult.metadata) {
425
+ parsedResult.metadata.transformed = true;
426
+ parsedResult.metadata.originalPrompt = prompt;
427
+ }
428
+ return {
429
+ ...parsedResult,
430
+ cached: true
431
+ };
432
+ } catch (_) {
433
+ logger.warn(`Failed to parse cached SageMaker response: ${_}`);
434
+ }
435
+ }
436
+ }
437
+ if (delayMs && delayMs > 0) {
438
+ logger.debug(`Applying delay of ${delayMs}ms before calling SageMaker endpoint ${this.getEndpointName()}`);
439
+ await sleep(delayMs);
440
+ }
441
+ const runtime = await this.getSageMakerRuntimeInstance();
442
+ const payload = this.formatPayload(transformedPrompt);
443
+ logger.debug(`Calling SageMaker endpoint ${this.getEndpointName()}`);
444
+ logger.debug(`With payload: ${payload.length > 1e3 ? payload.substring(0, 1e3) + "..." : payload}`);
445
+ try {
446
+ const { InvokeEndpointCommand } = await import("@aws-sdk/client-sagemaker-runtime");
447
+ const command = new InvokeEndpointCommand({
448
+ EndpointName: this.getEndpointName(),
449
+ ContentType: this.getContentType(),
450
+ Accept: this.getAcceptType(),
451
+ Body: payload
452
+ });
453
+ const startTime = Date.now();
454
+ const response = await runtime.send(command);
455
+ const _latency = Date.now() - startTime;
456
+ if (!response.Body) {
457
+ logger.error("No response body returned from SageMaker endpoint");
458
+ return { error: "No response body returned from SageMaker endpoint" };
459
+ }
460
+ const responseBody = new TextDecoder().decode(response.Body);
461
+ logger.debug(`SageMaker response (truncated): ${responseBody.length > 1e3 ? responseBody.substring(0, 1e3) + "..." : responseBody}`);
462
+ const output = await this.parseResponse(responseBody);
463
+ if (typeof output === "object" && output !== null && "code" in output) {
464
+ const code = output.code;
465
+ if (Number.isInteger(code) && code === 424) {
466
+ const errorMessage = `API Error: 424${output?.message ? ` ${output.message}` : ""}\n${JSON.stringify(output)}`;
467
+ logger.error(errorMessage);
468
+ return { error: errorMessage };
469
+ }
470
+ }
471
+ const promptTokens = Math.ceil(payload.length / 4);
472
+ const completionTokens = Math.ceil((typeof output === "string" ? output.length : 0) / 4);
473
+ const result = {
474
+ output,
475
+ raw: responseBody,
476
+ tokenUsage: {
477
+ prompt: promptTokens,
478
+ completion: completionTokens,
479
+ total: promptTokens + completionTokens,
480
+ cached: 0,
481
+ numRequests: 1
482
+ },
483
+ metadata: {
484
+ latencyMs: _latency,
485
+ modelType: this.config.modelType || "custom",
486
+ transformed: isTransformed,
487
+ originalPrompt: isTransformed ? prompt : void 0
488
+ }
489
+ };
490
+ if (isCacheEnabled() && !bustCache && result.output && !result.error) {
491
+ const cacheKey = this.getCacheKey(transformedPrompt);
492
+ const cache = getCache ? getCache() : await import("./cache-BkrqU5Ba.js").then((n) => n.t).then((m) => m.getCache());
493
+ const resultToCache = JSON.stringify(result);
494
+ try {
495
+ await cache.set(cacheKey, resultToCache);
496
+ logger.debug(`Stored SageMaker response in cache with key: ${cacheKey.substring(0, 100)}...`);
497
+ } catch (_) {
498
+ logger.warn(`Failed to store SageMaker response in cache: ${_}`);
499
+ }
500
+ }
501
+ return result;
502
+ } catch (error) {
503
+ logger.error(`SageMaker API error: ${error}`);
504
+ return { error: `SageMaker API error: ${error.message || String(error)}` };
505
+ }
506
+ }
507
+ };
508
+ /**
509
+ * Provider for embeddings with SageMaker endpoints
510
+ */
511
+ var SageMakerEmbeddingProvider = class extends SageMakerGenericProvider {
512
+ async callApi() {
513
+ throw new Error("callApi is not implemented for embedding provider. Use callEmbeddingApi instead.");
514
+ }
515
+ /**
516
+ * Generate a consistent cache key for SageMaker embedding requests
517
+ * Uses crypto.createHash to generate a shorter, more efficient key
518
+ */
519
+ getCacheKey(text) {
520
+ const configForKey = {
521
+ endpoint: this.getEndpointName(),
522
+ modelType: this.config.modelType,
523
+ contentType: this.getContentType(),
524
+ acceptType: this.getAcceptType(),
525
+ region: this.getRegion(),
526
+ responseFormat: this.config.responseFormat
527
+ };
528
+ const configStr = JSON.stringify(configForKey);
529
+ const textHash = crypto.createHash("sha256").update(text).digest("hex").substring(0, 16);
530
+ const configHash = crypto.createHash("sha256").update(configStr).digest("hex").substring(0, 8);
531
+ return `sagemaker:embedding:v1:${this.getEndpointName()}:${textHash}:${configHash}`;
532
+ }
533
+ /**
534
+ * Invoke SageMaker endpoint for embeddings with caching, delay support, and transformations
535
+ */
536
+ async callEmbeddingApi(text, context) {
537
+ const { isCacheEnabled, getCache } = await import("./cache-BkrqU5Ba.js").then((n) => n.t);
538
+ const delayMs = context?.originalProvider?.delay || this.delay;
539
+ const transformedText = await this.applyTransformation(text, context);
540
+ const isTransformed = transformedText !== text;
541
+ if (isTransformed) {
542
+ logger.debug(`Text transformed for SageMaker embedding endpoint ${this.getEndpointName()}`);
543
+ logger.debug(`Original: ${text.substring(0, 100)}${text.length > 100 ? "..." : ""}`);
544
+ logger.debug(`Transformed: ${transformedText.substring(0, 100)}${transformedText.length > 100 ? "..." : ""}`);
545
+ }
546
+ const bustCache = context?.debug === true;
547
+ if (isCacheEnabled() && !bustCache) {
548
+ const cacheKey = this.getCacheKey(transformedText);
549
+ const cachedResult = await (await getCache ? await getCache() : await import("./cache-BkrqU5Ba.js").then((n) => n.t).then((m) => m.getCache())).get(cacheKey);
550
+ if (cachedResult) {
551
+ logger.debug(`Using cached SageMaker embedding response for ${this.getEndpointName()}`);
552
+ try {
553
+ const parsedResult = JSON.parse(cachedResult);
554
+ if (parsedResult.tokenUsage) parsedResult.tokenUsage.cached = parsedResult.tokenUsage.prompt || 0;
555
+ return {
556
+ ...parsedResult,
557
+ cached: true
558
+ };
559
+ } catch (_) {
560
+ logger.warn(`Failed to parse cached SageMaker embedding response: ${_}`);
561
+ }
562
+ }
563
+ }
564
+ if (delayMs && delayMs > 0) {
565
+ logger.debug(`Applying delay of ${delayMs}ms before calling SageMaker embedding endpoint ${this.getEndpointName()}`);
566
+ await sleep(delayMs);
567
+ }
568
+ const runtime = await this.getSageMakerRuntimeInstance();
569
+ let payload;
570
+ const modelType = this.config.modelType || "custom";
571
+ logger.debug(`Formatting embedding payload for model type: ${modelType}`);
572
+ switch (modelType) {
573
+ case "openai":
574
+ payload = JSON.stringify({
575
+ input: transformedText,
576
+ model: "embedding"
577
+ });
578
+ break;
579
+ case "huggingface":
580
+ payload = JSON.stringify({ inputs: transformedText });
581
+ break;
582
+ default:
583
+ payload = JSON.stringify({
584
+ input: transformedText,
585
+ text: transformedText,
586
+ inputs: transformedText
587
+ });
588
+ break;
589
+ }
590
+ logger.debug(`Calling SageMaker embedding endpoint ${this.getEndpointName()}`);
591
+ logger.debug(`With payload: ${payload}`);
592
+ try {
593
+ const { InvokeEndpointCommand } = await import("@aws-sdk/client-sagemaker-runtime");
594
+ const command = new InvokeEndpointCommand({
595
+ EndpointName: this.getEndpointName(),
596
+ ContentType: this.getContentType(),
597
+ Accept: this.getAcceptType(),
598
+ Body: payload
599
+ });
600
+ const startTime = Date.now();
601
+ const response = await runtime.send(command);
602
+ Date.now() - startTime;
603
+ if (!response.Body) {
604
+ logger.error("No response body returned from SageMaker embedding endpoint");
605
+ return { error: "No response body returned from SageMaker embedding endpoint" };
606
+ }
607
+ const responseBody = new TextDecoder().decode(response.Body);
608
+ logger.debug(`SageMaker embedding response: ${responseBody.substring(0, 200)}...`);
609
+ let responseJson;
610
+ try {
611
+ responseJson = JSON.parse(responseBody);
612
+ } catch (_) {
613
+ return { error: `Failed to parse embedding response as JSON: ${_}` };
614
+ }
615
+ const embedding = responseJson.embedding || responseJson.embeddings || responseJson.data?.[0]?.embedding || (Array.isArray(responseJson) ? responseJson[0] : responseJson);
616
+ if (this.config.responseFormat?.path) try {
617
+ const pathExpression = this.config.responseFormat.path;
618
+ const extracted = await this.extractFromPath(responseJson, pathExpression);
619
+ if (Array.isArray(extracted) && extracted.every((val) => typeof val === "number")) {
620
+ const result = {
621
+ embedding: extracted,
622
+ tokenUsage: {
623
+ prompt: Math.ceil(text.length / 4),
624
+ cached: 0,
625
+ numRequests: 1
626
+ },
627
+ metadata: {
628
+ transformed: isTransformed,
629
+ originalText: isTransformed ? text : void 0
630
+ }
631
+ };
632
+ await this.cacheEmbeddingResult(result, transformedText, context, isTransformed, isTransformed ? text : void 0);
633
+ return result;
634
+ } else logger.warn("Extracted data is not a valid embedding array, trying other extraction methods");
635
+ } catch (error) {
636
+ logger.warn(`Failed to extract embedding from path expression: ${this.config.responseFormat.path}, Error: ${error}`);
637
+ logger.debug(`Response JSON structure: ${JSON.stringify(responseJson).substring(0, 200)}...`);
638
+ }
639
+ if (!embedding || !Array.isArray(embedding)) return { error: `Invalid embedding response format. Could not find embedding array in: ${JSON.stringify(responseJson).substring(0, 100)}...` };
640
+ const result = {
641
+ embedding,
642
+ tokenUsage: {
643
+ prompt: Math.ceil(text.length / 4),
644
+ cached: 0,
645
+ numRequests: 1
646
+ },
647
+ metadata: {
648
+ transformed: isTransformed,
649
+ originalText: isTransformed ? text : void 0
650
+ }
651
+ };
652
+ await this.cacheEmbeddingResult(result, transformedText, context, isTransformed, isTransformed ? text : void 0);
653
+ return result;
654
+ } catch (error) {
655
+ logger.error(`SageMaker embedding API error: ${error}`);
656
+ return { error: `SageMaker embedding API error: ${error.message || String(error)}` };
657
+ }
658
+ }
659
+ /**
660
+ * Helper method to cache embedding results
661
+ */
662
+ async cacheEmbeddingResult(result, text, context, isTransformed = false, originalText) {
663
+ const { isCacheEnabled, getCache } = await import("./cache-BkrqU5Ba.js").then((n) => n.t);
664
+ const bustCache = context?.debug === true;
665
+ if (isCacheEnabled() && !bustCache && result.embedding && !result.error) {
666
+ const cacheKey = this.getCacheKey(text);
667
+ const cache = await getCache ? await getCache() : await import("./cache-BkrqU5Ba.js").then((n) => n.t).then((m) => m.getCache());
668
+ if (isTransformed && originalText && !result.metadata) result.metadata = {
669
+ transformed: true,
670
+ originalText
671
+ };
672
+ else if (isTransformed && originalText && result.metadata) {
673
+ result.metadata.transformed = true;
674
+ result.metadata.originalText = originalText;
675
+ }
676
+ const resultToCache = JSON.stringify(result);
677
+ try {
678
+ await cache.set(cacheKey, resultToCache);
679
+ logger.debug(`Stored SageMaker embedding response in cache with key: ${cacheKey.substring(0, 100)}...`);
680
+ } catch (_) {
681
+ logger.warn(`Failed to store SageMaker embedding response in cache: ${_}`);
682
+ }
683
+ }
684
+ }
685
+ };
686
+ //#endregion
687
+ export { SageMakerCompletionProvider, SageMakerEmbeddingProvider };
688
+
689
+ //# sourceMappingURL=sagemaker-Cno2V-Sx.js.map