@ampt/ai 2.0.0 → 2.0.2

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.cjs CHANGED
@@ -33,6 +33,205 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
33
33
  ));
34
34
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
35
 
36
+ // ../../node_modules/dread/configure.js
37
+ var require_configure = __commonJS({
38
+ "../../node_modules/dread/configure.js"(exports, module2) {
39
+ "use strict";
40
+ var assert = require("assert");
41
+ module2.exports = function configure(arg, current) {
42
+ if (arg.retries) {
43
+ if (arg.attempts) {
44
+ throw new Error("Specify attempts or retries, but not both");
45
+ }
46
+ arg.attempts = arg.retries + 1;
47
+ delete arg.retries;
48
+ }
49
+ const {
50
+ attempts = current.attempts,
51
+ backoff = current.backoff,
52
+ condition = current.condition,
53
+ timeout = current.timeout
54
+ } = arg;
55
+ assert(Number.isInteger(attempts) && attempts > 0, "attempts must be an integer > 0");
56
+ assert(typeof backoff === "function", "backoff must be a function");
57
+ assert(typeof condition === "function", "condition must be a function");
58
+ assert(timeout === void 0 || Number.isInteger(timeout), "timeout, if specified, must be a number");
59
+ arg.attempts = attempts;
60
+ arg.backoff = backoff;
61
+ arg.condition = condition;
62
+ arg.timeout = timeout;
63
+ return arg;
64
+ };
65
+ }
66
+ });
67
+
68
+ // ../../node_modules/dread/execute.js
69
+ var require_execute = __commonJS({
70
+ "../../node_modules/dread/execute.js"(exports, module2) {
71
+ "use strict";
72
+ var RETRYABLE = Symbol();
73
+ module2.exports = async function execute(task, { attempts, backoff, condition, timeout }) {
74
+ let number = 1, result, control, operationHandle, attemptHandle, delayHandle;
75
+ function abort(reason, retryable = true) {
76
+ if (result) {
77
+ return;
78
+ }
79
+ const error = typeof reason === "string" ? new Error(reason) : reason;
80
+ error[RETRYABLE] = retryable;
81
+ control(error);
82
+ }
83
+ const attempt = {
84
+ get attempt() {
85
+ return number;
86
+ },
87
+ get number() {
88
+ return number;
89
+ },
90
+ cancel(reason = "Attempt cancelled") {
91
+ abort(reason);
92
+ },
93
+ timeout(duration) {
94
+ clearTimeout(attemptHandle);
95
+ attemptHandle = setTimeout(function attemptTimeout() {
96
+ abort(`Attempt timed out after ${duration} ms`);
97
+ }, duration);
98
+ }
99
+ };
100
+ if (timeout) {
101
+ operationHandle = setTimeout(function operationTimeout() {
102
+ abort(`Operation timed out after ${timeout} ms`, false);
103
+ }, timeout);
104
+ }
105
+ for (; ; number += 1) {
106
+ try {
107
+ result = await Promise.race([
108
+ new Promise((_, reject) => {
109
+ control = reject;
110
+ }),
111
+ task(attempt)
112
+ ]);
113
+ return result;
114
+ } catch (error) {
115
+ const retryable = error[RETRYABLE];
116
+ delete error[RETRYABLE];
117
+ if (number < attempts) {
118
+ const shouldRetry = retryable === void 0 ? await condition(error) : retryable;
119
+ if (shouldRetry) {
120
+ const delay = await backoff(number, error);
121
+ await new Promise((resolve) => {
122
+ delayHandle = setTimeout(resolve, delay);
123
+ });
124
+ continue;
125
+ }
126
+ }
127
+ throw error;
128
+ } finally {
129
+ clearTimeout(delayHandle);
130
+ clearTimeout(attemptHandle);
131
+ clearTimeout(operationHandle);
132
+ }
133
+ }
134
+ };
135
+ }
136
+ });
137
+
138
+ // ../../node_modules/dread/backoff.js
139
+ var require_backoff = __commonJS({
140
+ "../../node_modules/dread/backoff.js"(exports, module2) {
141
+ "use strict";
142
+ var assert = require("assert");
143
+ var JitterType = Object.freeze({
144
+ NONE: "NONE",
145
+ // use full backoff
146
+ FULL: "FULL",
147
+ // random value between 0 and backoff
148
+ HALF: "HALF"
149
+ // random value between backoff/2 and backoff
150
+ });
151
+ function getJitter({ jitter = JitterType.FULL }) {
152
+ if (typeof jitter === "boolean") {
153
+ return jitter ? JitterType.FULL : JitterType.NONE;
154
+ }
155
+ return jitter.toUpperCase();
156
+ }
157
+ function backoff(number, base, factor, cap) {
158
+ return Math.min(base * Math.pow(factor, number), cap);
159
+ }
160
+ function exp(options = {}) {
161
+ const { base = 100, factor = 2, limit = 1e4 } = options;
162
+ assert(Number.isInteger(base), "base must be an integer");
163
+ assert(Number.isInteger(factor), "factor must be an integer");
164
+ assert(Number.isInteger(limit), "limit must be an integer");
165
+ const cap = limit || Number.MAX_SAFE_INTEGER;
166
+ const jitter = getJitter(options);
167
+ assert(typeof jitter === "string", "jitter must be string");
168
+ assert(jitter in JitterType, `invalid jitter value, use JitterType ${Object.keys(JitterType)}`);
169
+ switch (jitter) {
170
+ case JitterType.FULL:
171
+ return (number) => Math.round(Math.random() * backoff(number, base, factor, cap));
172
+ case JitterType.HALF:
173
+ return (number) => {
174
+ const halfBackoff = backoff(number, base, factor, cap) / 2;
175
+ return Math.round(halfBackoff + Math.random() * halfBackoff);
176
+ };
177
+ case JitterType.NONE:
178
+ default:
179
+ return (number) => Math.round(backoff(number, base, factor, cap));
180
+ }
181
+ }
182
+ module2.exports = { exp, JitterType };
183
+ }
184
+ });
185
+
186
+ // ../../node_modules/dread/condition.js
187
+ var require_condition = __commonJS({
188
+ "../../node_modules/dread/condition.js"(exports, module2) {
189
+ "use strict";
190
+ function prop(n14) {
191
+ return (err) => !!err[n14];
192
+ }
193
+ function is(t9) {
194
+ return (err) => err instanceof t9;
195
+ }
196
+ function code(v9) {
197
+ return (err) => err.code === v9;
198
+ }
199
+ function always() {
200
+ return () => true;
201
+ }
202
+ module2.exports = { prop, is, code, always };
203
+ }
204
+ });
205
+
206
+ // ../../node_modules/dread/dread.js
207
+ var require_dread = __commonJS({
208
+ "../../node_modules/dread/dread.js"(exports, module2) {
209
+ "use strict";
210
+ var configure = require_configure();
211
+ var execute = require_execute();
212
+ var { exp, JitterType } = require_backoff();
213
+ var { prop, is, code, always } = require_condition();
214
+ var defaults = {
215
+ attempts: 10,
216
+ condition: prop("retryable"),
217
+ backoff: exp(),
218
+ timeout: void 0
219
+ };
220
+ module2.exports = function dread2() {
221
+ let task, config = defaults;
222
+ for (const arg of arguments) {
223
+ if (typeof arg === "function") {
224
+ task = arg;
225
+ } else {
226
+ config = configure(arg, config);
227
+ }
228
+ }
229
+ return typeof task === "function" ? execute(task, config) : dread2.bind(null, config);
230
+ };
231
+ Object.assign(module2.exports, { prop, is, code, exp, always, JitterType });
232
+ }
233
+ });
234
+
36
235
  // ../../node_modules/@aws-sdk/util-config-provider/dist-es/booleanSelector.js
37
236
  var SelectorType, booleanSelector;
38
237
  var init_booleanSelector = __esm({
@@ -17857,6 +18056,7 @@ __export(src_exports, {
17857
18056
  ModelType: () => ModelType,
17858
18057
  buildPrompt: () => buildPrompt,
17859
18058
  chat: () => chat,
18059
+ embed: () => embed,
17860
18060
  getModelInfo: () => getModelInfo,
17861
18061
  invoke: () => invoke2,
17862
18062
  models: () => models,
@@ -17992,6 +18192,7 @@ var QuotaReader = class {
17992
18192
  };
17993
18193
 
17994
18194
  // ../../lib/aws/client.ts
18195
+ var import_dread = __toESM(require_dread(), 1);
17995
18196
  var import_node_crypto = require("crypto");
17996
18197
 
17997
18198
  // ../../node_modules/aws4fetch/dist/aws4fetch.esm.mjs
@@ -18267,6 +18468,21 @@ function guessServiceRegion(url, headers) {
18267
18468
  return [HOST_SERVICES[service] || service, region2];
18268
18469
  }
18269
18470
 
18471
+ // ../../lib/runtime-logging/index.ts
18472
+ function systemError(errOrMsg, _msg) {
18473
+ const err = typeof errOrMsg === "string" ? void 0 : errOrMsg;
18474
+ const msg = typeof errOrMsg === "string" ? errOrMsg : _msg;
18475
+ process.stdout.write(
18476
+ JSON.stringify({
18477
+ _slsLog: true,
18478
+ time: Date.now(),
18479
+ level: 50,
18480
+ msg,
18481
+ ...err && { err: { message: err.message, stack: err.stack, code: err.code, name: err.name } }
18482
+ }) + "\n"
18483
+ );
18484
+ }
18485
+
18270
18486
  // ../../lib/aws/credentials.ts
18271
18487
  var import_promises = require("timers/promises");
18272
18488
  var defaultProvider2;
@@ -18298,13 +18514,29 @@ async function loadCredentials() {
18298
18514
 
18299
18515
  // ../../lib/aws/client.ts
18300
18516
  var _client;
18517
+ var RetryableError = class extends Error {
18518
+ retryable = true;
18519
+ name = "RetryableError";
18520
+ };
18521
+ var AmptAwsClient = class extends AwsClient {
18522
+ fetch(input, init) {
18523
+ return (0, import_dread.default)(() => {
18524
+ try {
18525
+ return super.fetch(input, init);
18526
+ } catch (err) {
18527
+ systemError(err, "aws4fetch error");
18528
+ throw new RetryableError("aws4fetch error", { cause: err });
18529
+ }
18530
+ });
18531
+ }
18532
+ };
18301
18533
  async function getClient() {
18302
18534
  if (!_client) {
18303
18535
  const credentials = await loadCredentials();
18304
18536
  if (!globalThis.crypto) {
18305
18537
  Object.assign(globalThis, { crypto: import_node_crypto.webcrypto });
18306
18538
  }
18307
- _client = new AwsClient({
18539
+ _client = new AmptAwsClient({
18308
18540
  accessKeyId: credentials.accessKeyId,
18309
18541
  secretAccessKey: credentials.secretAccessKey,
18310
18542
  sessionToken: credentials.sessionToken,
@@ -42058,16 +42290,30 @@ async function models() {
42058
42290
  "anthropic.claude-v1",
42059
42291
  "anthropic.claude-instant-v1",
42060
42292
  "anthropic.claude-v2",
42061
- "stability.stable-diffusion-xl-v0"
42293
+ "stability.stable-diffusion-xl-v0",
42294
+ "amazon.titan-embed-text-v1"
42062
42295
  ];
42063
42296
  }
42064
42297
  var ModelType = /* @__PURE__ */ ((ModelType2) => {
42298
+ ModelType2["Embeddings"] = "embeddings";
42065
42299
  ModelType2["Language"] = "language";
42066
42300
  ModelType2["Image"] = "image";
42067
42301
  return ModelType2;
42068
42302
  })(ModelType || {});
42069
42303
  var AVERAGE_BYTES_PER_TOKEN = 6;
42070
42304
  var modelInfoMap = {
42305
+ "amazon.titan-embed-text-v1": {
42306
+ name: "Amazon Titan Embeddings",
42307
+ type: "embeddings" /* Embeddings */,
42308
+ streaming: false,
42309
+ provider: "Amazon",
42310
+ description: "The new Titan Embeddings G1 \u2013 Text v1.2 can intake up to 8k tokens and outputs a vector of 1536 dimensions. The model also works in 25+ different languages. The model is optimized for text retrieval tasks but can also perform additional tasks such as semantic similarity and clustering. Titan Embeddings G1 \u2013 Text v1.2 also supports long documents, however, for retrieval tasks it is recommended to segment documents into logical segments (such as paragraphs or sections). In line with our recommendation, our MTEB results are based on truncating all documents to 512 tokens. ",
42311
+ version: "v1.2",
42312
+ inferenceUsage: (body) => {
42313
+ const json = JSON.parse(Buffer.from(body).toString());
42314
+ return (json?.inputTextTokenCount ?? 0) * 10;
42315
+ }
42316
+ },
42071
42317
  "anthropic.claude-instant-v1": {
42072
42318
  name: "Claude Instant",
42073
42319
  type: "language" /* Language */,
@@ -42126,6 +42372,9 @@ function trackLanguageInference(inputSize, outputSize, modelInfo) {
42126
42372
  function trackImageInference(width, height, steps, modelInfo) {
42127
42373
  telemetry_default.count("inferenceUsage", modelInfo.inferenceUsage(width, height, steps), "ai");
42128
42374
  }
42375
+ function trackEmbeddingsInference(result, modelInfo) {
42376
+ telemetry_default.count("inferenceUsage", modelInfo.inferenceUsage(result), "ai");
42377
+ }
42129
42378
  async function _invoke(options, lock) {
42130
42379
  const contentType = options.contentType ?? "application/json";
42131
42380
  const accept = options.accept ?? "application/json";
@@ -42170,6 +42419,8 @@ async function _invoke(options, lock) {
42170
42419
  trackLanguageInference(0, result.body.length, modelInfo);
42171
42420
  } else if (modelInfo.type === "image") {
42172
42421
  trackImageInference(options.body.width, options.body.height, options.body.steps, modelInfo);
42422
+ } else if (modelInfo.type === "embeddings") {
42423
+ trackEmbeddingsInference(result.body, modelInfo);
42173
42424
  }
42174
42425
  responseBody = new ReadableStream({
42175
42426
  async pull(controller) {
@@ -42226,7 +42477,7 @@ async function chat(messages, options = {}) {
42226
42477
  transform(chunk2, controller) {
42227
42478
  const event = JSON.parse(decoder.decode(chunk2));
42228
42479
  if (event.completion) {
42229
- controller.enqueue(event.completion);
42480
+ controller.enqueue(Buffer.from(event.completion, "utf8"));
42230
42481
  }
42231
42482
  }
42232
42483
  });
@@ -42246,6 +42497,24 @@ chat.models = async () => {
42246
42497
  return ["anthropic.claude-instant-v1", "anthropic.claude-v1", "anthropic.claude-v2"];
42247
42498
  };
42248
42499
 
42500
+ // src/embed.ts
42501
+ async function embed(input, options = {}) {
42502
+ const response = await invoke2({
42503
+ modelId: options.modelId ?? "amazon.titan-embed-text-v1",
42504
+ body: {
42505
+ inputText: input
42506
+ }
42507
+ });
42508
+ const result = await response.json();
42509
+ return {
42510
+ embedding: result.embedding,
42511
+ inputTokenCount: result.inputTextTokenCount
42512
+ };
42513
+ }
42514
+ embed.models = async () => {
42515
+ return ["amazon.titan-embed-text-v1"];
42516
+ };
42517
+
42249
42518
  // src/render.ts
42250
42519
  async function render(prompt, options = {}) {
42251
42520
  const modelId = options.modelId ?? "stability.stable-diffusion-xl-v0";
@@ -42283,6 +42552,7 @@ render.models = async () => {
42283
42552
  ModelType,
42284
42553
  buildPrompt,
42285
42554
  chat,
42555
+ embed,
42286
42556
  getModelInfo,
42287
42557
  invoke,
42288
42558
  models,
package/dist/index.d.ts CHANGED
@@ -1,12 +1,14 @@
1
- type ModelId = 'anthropic.claude-v2' | 'anthropic.claude-instant-v1' | 'anthropic.claude-v1' | 'stability.stable-diffusion-xl-v0';
1
+ type ModelId = 'anthropic.claude-v2' | 'anthropic.claude-instant-v1' | 'anthropic.claude-v1' | 'stability.stable-diffusion-xl-v0' | 'amazon.titan-embed-text-v1';
2
2
  declare function models(): Promise<ModelId[]>;
3
3
  declare enum ModelType {
4
+ Embeddings = "embeddings",
4
5
  Language = "language",
5
6
  Image = "image"
6
7
  }
8
+ type EmbeddingsInferenceCostFunction = (body: Uint8Array) => number;
7
9
  type LanguageInferenceCostFunction = (inputSize: number, outputSize: number) => number;
8
10
  type ImageInferenceCostFunction = (width: number, height: number, steps: number) => number;
9
- type InferenceCostFunction = LanguageInferenceCostFunction | ImageInferenceCostFunction;
11
+ type InferenceCostFunction = EmbeddingsInferenceCostFunction | LanguageInferenceCostFunction | ImageInferenceCostFunction;
10
12
  interface ModelInfo {
11
13
  name: string;
12
14
  type: ModelType;
@@ -24,7 +26,11 @@ interface ImageModelInfo extends ModelInfo {
24
26
  type: ModelType.Image;
25
27
  inferenceUsage: ImageInferenceCostFunction;
26
28
  }
27
- declare function getModelInfo(id: ModelId): Promise<LanguageModelInfo | ImageModelInfo>;
29
+ interface EmbeddingsModelInfo extends ModelInfo {
30
+ type: ModelType.Embeddings;
31
+ inferenceUsage: EmbeddingsInferenceCostFunction;
32
+ }
33
+ declare function getModelInfo(id: ModelId): Promise<LanguageModelInfo | ImageModelInfo | EmbeddingsModelInfo>;
28
34
 
29
35
  interface InvokeOptions {
30
36
  modelId: ModelId;
@@ -68,6 +74,18 @@ declare namespace chat {
68
74
  var models: () => Promise<ModelId[]>;
69
75
  }
70
76
 
77
+ interface Embedding {
78
+ embedding: number[];
79
+ inputTokenCount: number;
80
+ }
81
+ interface EmbedOptions {
82
+ modelId?: ModelId;
83
+ }
84
+ declare function embed(input: string, options?: EmbedOptions): Promise<Embedding>;
85
+ declare namespace embed {
86
+ var models: () => Promise<ModelId[]>;
87
+ }
88
+
71
89
  interface RenderOptions {
72
90
  width?: number;
73
91
  height?: number;
@@ -81,4 +99,4 @@ declare namespace render {
81
99
  var models: () => Promise<string[]>;
82
100
  }
83
101
 
84
- export { ChatMessage, ChatOptions, ImageModelInfo, InvokeOptions, LanguageModelInfo, MessageRole, ModelId, ModelInfo, ModelType, RenderOptions, buildPrompt, chat, getModelInfo, invoke, models, render };
102
+ export { ChatMessage, ChatOptions, EmbedOptions, Embedding, EmbeddingsModelInfo, ImageModelInfo, InvokeOptions, LanguageModelInfo, MessageRole, ModelId, ModelInfo, ModelType, RenderOptions, buildPrompt, chat, embed, getModelInfo, invoke, models, render };
package/dist/index.js CHANGED
@@ -65,6 +65,205 @@ import {
65
65
  v4_default
66
66
  } from "./chunk-JPKYSWKV.js";
67
67
 
68
+ // ../../node_modules/dread/configure.js
69
+ var require_configure = __commonJS({
70
+ "../../node_modules/dread/configure.js"(exports, module2) {
71
+ "use strict";
72
+ var assert = __require("assert");
73
+ module2.exports = function configure(arg, current) {
74
+ if (arg.retries) {
75
+ if (arg.attempts) {
76
+ throw new Error("Specify attempts or retries, but not both");
77
+ }
78
+ arg.attempts = arg.retries + 1;
79
+ delete arg.retries;
80
+ }
81
+ const {
82
+ attempts = current.attempts,
83
+ backoff = current.backoff,
84
+ condition = current.condition,
85
+ timeout = current.timeout
86
+ } = arg;
87
+ assert(Number.isInteger(attempts) && attempts > 0, "attempts must be an integer > 0");
88
+ assert(typeof backoff === "function", "backoff must be a function");
89
+ assert(typeof condition === "function", "condition must be a function");
90
+ assert(timeout === void 0 || Number.isInteger(timeout), "timeout, if specified, must be a number");
91
+ arg.attempts = attempts;
92
+ arg.backoff = backoff;
93
+ arg.condition = condition;
94
+ arg.timeout = timeout;
95
+ return arg;
96
+ };
97
+ }
98
+ });
99
+
100
+ // ../../node_modules/dread/execute.js
101
+ var require_execute = __commonJS({
102
+ "../../node_modules/dread/execute.js"(exports, module2) {
103
+ "use strict";
104
+ var RETRYABLE = Symbol();
105
+ module2.exports = async function execute(task, { attempts, backoff, condition, timeout }) {
106
+ let number = 1, result, control, operationHandle, attemptHandle, delayHandle;
107
+ function abort(reason, retryable = true) {
108
+ if (result) {
109
+ return;
110
+ }
111
+ const error = typeof reason === "string" ? new Error(reason) : reason;
112
+ error[RETRYABLE] = retryable;
113
+ control(error);
114
+ }
115
+ const attempt = {
116
+ get attempt() {
117
+ return number;
118
+ },
119
+ get number() {
120
+ return number;
121
+ },
122
+ cancel(reason = "Attempt cancelled") {
123
+ abort(reason);
124
+ },
125
+ timeout(duration) {
126
+ clearTimeout(attemptHandle);
127
+ attemptHandle = setTimeout(function attemptTimeout() {
128
+ abort(`Attempt timed out after ${duration} ms`);
129
+ }, duration);
130
+ }
131
+ };
132
+ if (timeout) {
133
+ operationHandle = setTimeout(function operationTimeout() {
134
+ abort(`Operation timed out after ${timeout} ms`, false);
135
+ }, timeout);
136
+ }
137
+ for (; ; number += 1) {
138
+ try {
139
+ result = await Promise.race([
140
+ new Promise((_, reject) => {
141
+ control = reject;
142
+ }),
143
+ task(attempt)
144
+ ]);
145
+ return result;
146
+ } catch (error) {
147
+ const retryable = error[RETRYABLE];
148
+ delete error[RETRYABLE];
149
+ if (number < attempts) {
150
+ const shouldRetry = retryable === void 0 ? await condition(error) : retryable;
151
+ if (shouldRetry) {
152
+ const delay = await backoff(number, error);
153
+ await new Promise((resolve) => {
154
+ delayHandle = setTimeout(resolve, delay);
155
+ });
156
+ continue;
157
+ }
158
+ }
159
+ throw error;
160
+ } finally {
161
+ clearTimeout(delayHandle);
162
+ clearTimeout(attemptHandle);
163
+ clearTimeout(operationHandle);
164
+ }
165
+ }
166
+ };
167
+ }
168
+ });
169
+
170
+ // ../../node_modules/dread/backoff.js
171
+ var require_backoff = __commonJS({
172
+ "../../node_modules/dread/backoff.js"(exports, module2) {
173
+ "use strict";
174
+ var assert = __require("assert");
175
+ var JitterType = Object.freeze({
176
+ NONE: "NONE",
177
+ // use full backoff
178
+ FULL: "FULL",
179
+ // random value between 0 and backoff
180
+ HALF: "HALF"
181
+ // random value between backoff/2 and backoff
182
+ });
183
+ function getJitter({ jitter = JitterType.FULL }) {
184
+ if (typeof jitter === "boolean") {
185
+ return jitter ? JitterType.FULL : JitterType.NONE;
186
+ }
187
+ return jitter.toUpperCase();
188
+ }
189
+ function backoff(number, base, factor, cap) {
190
+ return Math.min(base * Math.pow(factor, number), cap);
191
+ }
192
+ function exp(options = {}) {
193
+ const { base = 100, factor = 2, limit = 1e4 } = options;
194
+ assert(Number.isInteger(base), "base must be an integer");
195
+ assert(Number.isInteger(factor), "factor must be an integer");
196
+ assert(Number.isInteger(limit), "limit must be an integer");
197
+ const cap = limit || Number.MAX_SAFE_INTEGER;
198
+ const jitter = getJitter(options);
199
+ assert(typeof jitter === "string", "jitter must be string");
200
+ assert(jitter in JitterType, `invalid jitter value, use JitterType ${Object.keys(JitterType)}`);
201
+ switch (jitter) {
202
+ case JitterType.FULL:
203
+ return (number) => Math.round(Math.random() * backoff(number, base, factor, cap));
204
+ case JitterType.HALF:
205
+ return (number) => {
206
+ const halfBackoff = backoff(number, base, factor, cap) / 2;
207
+ return Math.round(halfBackoff + Math.random() * halfBackoff);
208
+ };
209
+ case JitterType.NONE:
210
+ default:
211
+ return (number) => Math.round(backoff(number, base, factor, cap));
212
+ }
213
+ }
214
+ module2.exports = { exp, JitterType };
215
+ }
216
+ });
217
+
218
+ // ../../node_modules/dread/condition.js
219
+ var require_condition = __commonJS({
220
+ "../../node_modules/dread/condition.js"(exports, module2) {
221
+ "use strict";
222
+ function prop(n10) {
223
+ return (err) => !!err[n10];
224
+ }
225
+ function is(t8) {
226
+ return (err) => err instanceof t8;
227
+ }
228
+ function code(v7) {
229
+ return (err) => err.code === v7;
230
+ }
231
+ function always() {
232
+ return () => true;
233
+ }
234
+ module2.exports = { prop, is, code, always };
235
+ }
236
+ });
237
+
238
+ // ../../node_modules/dread/dread.js
239
+ var require_dread = __commonJS({
240
+ "../../node_modules/dread/dread.js"(exports, module2) {
241
+ "use strict";
242
+ var configure = require_configure();
243
+ var execute = require_execute();
244
+ var { exp, JitterType } = require_backoff();
245
+ var { prop, is, code, always } = require_condition();
246
+ var defaults = {
247
+ attempts: 10,
248
+ condition: prop("retryable"),
249
+ backoff: exp(),
250
+ timeout: void 0
251
+ };
252
+ module2.exports = function dread2() {
253
+ let task, config = defaults;
254
+ for (const arg of arguments) {
255
+ if (typeof arg === "function") {
256
+ task = arg;
257
+ } else {
258
+ config = configure(arg, config);
259
+ }
260
+ }
261
+ return typeof task === "function" ? execute(task, config) : dread2.bind(null, config);
262
+ };
263
+ Object.assign(module2.exports, { prop, is, code, exp, always, JitterType });
264
+ }
265
+ });
266
+
68
267
  // ../../node_modules/obliterator/iterator.js
69
268
  var require_iterator = __commonJS({
70
269
  "../../node_modules/obliterator/iterator.js"(exports, module2) {
@@ -5365,6 +5564,7 @@ var QuotaReader = class {
5365
5564
  };
5366
5565
 
5367
5566
  // ../../lib/aws/client.ts
5567
+ var import_dread = __toESM(require_dread(), 1);
5368
5568
  import { webcrypto } from "node:crypto";
5369
5569
 
5370
5570
  // ../../node_modules/aws4fetch/dist/aws4fetch.esm.mjs
@@ -5640,6 +5840,21 @@ function guessServiceRegion(url, headers) {
5640
5840
  return [HOST_SERVICES[service] || service, region2];
5641
5841
  }
5642
5842
 
5843
+ // ../../lib/runtime-logging/index.ts
5844
+ function systemError(errOrMsg, _msg) {
5845
+ const err = typeof errOrMsg === "string" ? void 0 : errOrMsg;
5846
+ const msg = typeof errOrMsg === "string" ? errOrMsg : _msg;
5847
+ process.stdout.write(
5848
+ JSON.stringify({
5849
+ _slsLog: true,
5850
+ time: Date.now(),
5851
+ level: 50,
5852
+ msg,
5853
+ ...err && { err: { message: err.message, stack: err.stack, code: err.code, name: err.name } }
5854
+ }) + "\n"
5855
+ );
5856
+ }
5857
+
5643
5858
  // ../../lib/aws/credentials.ts
5644
5859
  import { setTimeout as setTimeout2 } from "node:timers/promises";
5645
5860
  var defaultProvider2;
@@ -5671,13 +5886,29 @@ async function loadCredentials() {
5671
5886
 
5672
5887
  // ../../lib/aws/client.ts
5673
5888
  var _client;
5889
+ var RetryableError = class extends Error {
5890
+ retryable = true;
5891
+ name = "RetryableError";
5892
+ };
5893
+ var AmptAwsClient = class extends AwsClient {
5894
+ fetch(input, init) {
5895
+ return (0, import_dread.default)(() => {
5896
+ try {
5897
+ return super.fetch(input, init);
5898
+ } catch (err) {
5899
+ systemError(err, "aws4fetch error");
5900
+ throw new RetryableError("aws4fetch error", { cause: err });
5901
+ }
5902
+ });
5903
+ }
5904
+ };
5674
5905
  async function getClient() {
5675
5906
  if (!_client) {
5676
5907
  const credentials = await loadCredentials();
5677
5908
  if (!globalThis.crypto) {
5678
5909
  Object.assign(globalThis, { crypto: webcrypto });
5679
5910
  }
5680
- _client = new AwsClient({
5911
+ _client = new AmptAwsClient({
5681
5912
  accessKeyId: credentials.accessKeyId,
5682
5913
  secretAccessKey: credentials.secretAccessKey,
5683
5914
  sessionToken: credentials.sessionToken,
@@ -29320,16 +29551,30 @@ async function models() {
29320
29551
  "anthropic.claude-v1",
29321
29552
  "anthropic.claude-instant-v1",
29322
29553
  "anthropic.claude-v2",
29323
- "stability.stable-diffusion-xl-v0"
29554
+ "stability.stable-diffusion-xl-v0",
29555
+ "amazon.titan-embed-text-v1"
29324
29556
  ];
29325
29557
  }
29326
29558
  var ModelType = /* @__PURE__ */ ((ModelType2) => {
29559
+ ModelType2["Embeddings"] = "embeddings";
29327
29560
  ModelType2["Language"] = "language";
29328
29561
  ModelType2["Image"] = "image";
29329
29562
  return ModelType2;
29330
29563
  })(ModelType || {});
29331
29564
  var AVERAGE_BYTES_PER_TOKEN = 6;
29332
29565
  var modelInfoMap = {
29566
+ "amazon.titan-embed-text-v1": {
29567
+ name: "Amazon Titan Embeddings",
29568
+ type: "embeddings" /* Embeddings */,
29569
+ streaming: false,
29570
+ provider: "Amazon",
29571
+ description: "The new Titan Embeddings G1 \u2013 Text v1.2 can intake up to 8k tokens and outputs a vector of 1536 dimensions. The model also works in 25+ different languages. The model is optimized for text retrieval tasks but can also perform additional tasks such as semantic similarity and clustering. Titan Embeddings G1 \u2013 Text v1.2 also supports long documents, however, for retrieval tasks it is recommended to segment documents into logical segments (such as paragraphs or sections). In line with our recommendation, our MTEB results are based on truncating all documents to 512 tokens. ",
29572
+ version: "v1.2",
29573
+ inferenceUsage: (body) => {
29574
+ const json = JSON.parse(Buffer.from(body).toString());
29575
+ return (json?.inputTextTokenCount ?? 0) * 10;
29576
+ }
29577
+ },
29333
29578
  "anthropic.claude-instant-v1": {
29334
29579
  name: "Claude Instant",
29335
29580
  type: "language" /* Language */,
@@ -29388,6 +29633,9 @@ function trackLanguageInference(inputSize, outputSize, modelInfo) {
29388
29633
  function trackImageInference(width, height, steps, modelInfo) {
29389
29634
  telemetry_default.count("inferenceUsage", modelInfo.inferenceUsage(width, height, steps), "ai");
29390
29635
  }
29636
+ function trackEmbeddingsInference(result, modelInfo) {
29637
+ telemetry_default.count("inferenceUsage", modelInfo.inferenceUsage(result), "ai");
29638
+ }
29391
29639
  async function _invoke(options, lock) {
29392
29640
  const contentType = options.contentType ?? "application/json";
29393
29641
  const accept = options.accept ?? "application/json";
@@ -29432,6 +29680,8 @@ async function _invoke(options, lock) {
29432
29680
  trackLanguageInference(0, result.body.length, modelInfo);
29433
29681
  } else if (modelInfo.type === "image") {
29434
29682
  trackImageInference(options.body.width, options.body.height, options.body.steps, modelInfo);
29683
+ } else if (modelInfo.type === "embeddings") {
29684
+ trackEmbeddingsInference(result.body, modelInfo);
29435
29685
  }
29436
29686
  responseBody = new ReadableStream({
29437
29687
  async pull(controller) {
@@ -29488,7 +29738,7 @@ async function chat(messages, options = {}) {
29488
29738
  transform(chunk2, controller) {
29489
29739
  const event = JSON.parse(decoder.decode(chunk2));
29490
29740
  if (event.completion) {
29491
- controller.enqueue(event.completion);
29741
+ controller.enqueue(Buffer.from(event.completion, "utf8"));
29492
29742
  }
29493
29743
  }
29494
29744
  });
@@ -29508,6 +29758,24 @@ chat.models = async () => {
29508
29758
  return ["anthropic.claude-instant-v1", "anthropic.claude-v1", "anthropic.claude-v2"];
29509
29759
  };
29510
29760
 
29761
+ // src/embed.ts
29762
+ async function embed(input, options = {}) {
29763
+ const response = await invoke2({
29764
+ modelId: options.modelId ?? "amazon.titan-embed-text-v1",
29765
+ body: {
29766
+ inputText: input
29767
+ }
29768
+ });
29769
+ const result = await response.json();
29770
+ return {
29771
+ embedding: result.embedding,
29772
+ inputTokenCount: result.inputTextTokenCount
29773
+ };
29774
+ }
29775
+ embed.models = async () => {
29776
+ return ["amazon.titan-embed-text-v1"];
29777
+ };
29778
+
29511
29779
  // src/render.ts
29512
29780
  async function render(prompt, options = {}) {
29513
29781
  const modelId = options.modelId ?? "stability.stable-diffusion-xl-v0";
@@ -29544,6 +29812,7 @@ export {
29544
29812
  ModelType,
29545
29813
  buildPrompt,
29546
29814
  chat,
29815
+ embed,
29547
29816
  getModelInfo,
29548
29817
  invoke2 as invoke,
29549
29818
  models,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ampt/ai",
3
- "version": "2.0.0",
3
+ "version": "2.0.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",