notdiamond 0.3.11 → 0.3.12

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 ADDED
@@ -0,0 +1,699 @@
1
+ 'use strict';
2
+
3
+ const dotenv = require('dotenv');
4
+ const openai = require('@langchain/openai');
5
+ const messages = require('@langchain/core/messages');
6
+ const anthropic = require('@langchain/anthropic');
7
+ const googleGenai = require('@langchain/google-genai');
8
+ const mistralai = require('@langchain/mistralai');
9
+ const chat_models = require('@langchain/core/language_models/chat_models');
10
+ const axios = require('axios');
11
+ const cohere = require('@langchain/cohere');
12
+ const togetherai = require('@langchain/community/chat_models/togetherai');
13
+
14
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
15
+
16
+ function _interopNamespaceCompat(e) {
17
+ if (e && typeof e === 'object' && 'default' in e) return e;
18
+ const n = Object.create(null);
19
+ if (e) {
20
+ for (const k in e) {
21
+ n[k] = e[k];
22
+ }
23
+ }
24
+ n.default = e;
25
+ return n;
26
+ }
27
+
28
+ const dotenv__namespace = /*#__PURE__*/_interopNamespaceCompat(dotenv);
29
+ const axios__default = /*#__PURE__*/_interopDefaultCompat(axios);
30
+
31
+ const name = "notdiamond";
32
+ const type = "module";
33
+ const version = "1.0.0";
34
+ const author = "not-diamond";
35
+ const license = "MIT";
36
+ const description = "TS/JS client for the NotDiamond API";
37
+ const main = "./dist/index.cjs";
38
+ const exports$1 = {
39
+ ".": {
40
+ "import": "./dist/index.mjs",
41
+ require: "./dist/index.cjs"
42
+ }
43
+ };
44
+ const types = "./dist/index.d.ts";
45
+ const repository = {
46
+ type: "git",
47
+ url: "https://github.com/Not-Diamond/notdiamond-node.git"
48
+ };
49
+ const bugs = {
50
+ url: "https://github.com/Not-Diamond/notdiamond-node/issues"
51
+ };
52
+ const homepage = "https://github.com/Not-Diamond/notdiamond-node#readme";
53
+ const files = [
54
+ "dist"
55
+ ];
56
+ const keywords = [
57
+ "ai",
58
+ "not-diamond",
59
+ "typescript",
60
+ "openai",
61
+ "chatgpt",
62
+ "anthropic",
63
+ "claude",
64
+ "gemini",
65
+ "model router"
66
+ ];
67
+ const scripts = {
68
+ prepare: "husky install",
69
+ "start:cjs": "node ./dist/index.cjs",
70
+ "start:esm": "node ./dist/index.mjs",
71
+ dev: "nodemon",
72
+ develop: "node --no-warnings=ExperimentalWarning --loader ts-node/esm ./src/index.ts",
73
+ test: "jest --passWithNoTests",
74
+ "test:watch": "jest --watch --passWithNoTests",
75
+ "test:coverage": "jest --coverage --passWithNoTests",
76
+ clean: "rimraf build && rimraf dist",
77
+ build: "swc ./src -d build",
78
+ "build:watch": "swc ./src -d build -w",
79
+ lint: "eslint ./src --ext .ts",
80
+ "lint:fix": "eslint ./src --ext .ts --fix",
81
+ prettier: "prettier '**/*.{ts,json,md}'",
82
+ "prettier:write": "prettier --write '**/*.{ts,json,md}'",
83
+ "type-check": "tsc --noEmit",
84
+ "lint-staged": "lint-staged",
85
+ release: "semantic-release",
86
+ bundle: "unbuild"
87
+ };
88
+ const dependencies = {
89
+ "@langchain/anthropic": "^0.3.1",
90
+ "@langchain/cohere": "^0.3.0",
91
+ "@langchain/community": "^0.3.3",
92
+ "@langchain/core": "^0.3.3",
93
+ "@langchain/google-genai": "^0.1.0",
94
+ "@langchain/mistralai": "^0.1.1",
95
+ "@langchain/openai": "^0.3.0",
96
+ "ansi-styles": "^6.2.1",
97
+ axios: "^1.7.7",
98
+ camelcase: "^8.0.0",
99
+ decamelize: "^6.0.0",
100
+ dotenv: "^16.4.5",
101
+ eventemitter3: "^5.0.1",
102
+ langchain: "^0.3.2",
103
+ langsmith: "^0.1.60",
104
+ "p-finally": "^2.0.1",
105
+ "p-queue": "^8.0.1",
106
+ "p-retry": "^6.2.0",
107
+ "p-timeout": "^6.1.2",
108
+ retry: "^0.13.1",
109
+ semver: "^7.6.3",
110
+ uuid: "^10.0.0",
111
+ zod: "^3.23.8",
112
+ "zod-to-json-schema": "^3.23.3"
113
+ };
114
+ const devDependencies = {
115
+ "@semantic-release/changelog": "^6.0.3",
116
+ "@semantic-release/commit-analyzer": "^12.0.0",
117
+ "@semantic-release/git": "^10.0.1",
118
+ "@semantic-release/github": "^10.0.0",
119
+ "@semantic-release/npm": "^12.0.0",
120
+ "@semantic-release/release-notes-generator": "^13.0.0",
121
+ "@swc/cli": "0.3.12",
122
+ "@swc/core": "1.5.7",
123
+ "@swc/jest": "0.2.36",
124
+ "@types/jest": "29.5.12",
125
+ "@types/node": "20.12.12",
126
+ "@typescript-eslint/eslint-plugin": "7.9.0",
127
+ "@typescript-eslint/parser": "7.9.0",
128
+ eslint: "8.57.0",
129
+ "eslint-config-prettier": "9.1.0",
130
+ "eslint-plugin-jest": "27.9.0",
131
+ "eslint-plugin-prettier": "5.1.3",
132
+ husky: "^9.0.0",
133
+ jest: "29.7.0",
134
+ "lint-staged": "^15.0.0",
135
+ nodemon: "3.1.0",
136
+ prettier: "3.2.5",
137
+ "regenerator-runtime": "^0.14.0",
138
+ rimraf: "5.0.7",
139
+ "semantic-release": "^23.0.0",
140
+ "ts-node": "^10.9.1",
141
+ typescript: "5.4.5",
142
+ unbuild: "^2.0.0"
143
+ };
144
+ const resolutions = {
145
+ "wrap-ansi": "7.0.0"
146
+ };
147
+ const engines = {
148
+ node: ">=20",
149
+ npm: ">=8"
150
+ };
151
+ const packageJson = {
152
+ name: name,
153
+ type: type,
154
+ version: version,
155
+ author: author,
156
+ license: license,
157
+ description: description,
158
+ main: main,
159
+ exports: exports$1,
160
+ types: types,
161
+ repository: repository,
162
+ bugs: bugs,
163
+ homepage: homepage,
164
+ files: files,
165
+ keywords: keywords,
166
+ scripts: scripts,
167
+ dependencies: dependencies,
168
+ devDependencies: devDependencies,
169
+ resolutions: resolutions,
170
+ engines: engines
171
+ };
172
+
173
+ var __defProp$1 = Object.defineProperty;
174
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
175
+ var __publicField$1 = (obj, key, value) => {
176
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
177
+ return value;
178
+ };
179
+ class ChatPerplexity extends chat_models.BaseChatModel {
180
+ constructor({ apiKey, model }) {
181
+ super({});
182
+ __publicField$1(this, "apiKey");
183
+ __publicField$1(this, "model");
184
+ this.apiKey = apiKey;
185
+ this.model = model;
186
+ }
187
+ _generate(messages, options, runManager) {
188
+ throw new Error(
189
+ "Method not implemented." + JSON.stringify(messages) + JSON.stringify(options) + JSON.stringify(runManager)
190
+ );
191
+ }
192
+ _llmType() {
193
+ return "perplexity";
194
+ }
195
+ /**
196
+ * Invokes the Perplexity model.
197
+ * @param messages The messages to send to the model.
198
+ * @returns The results of the model.
199
+ */
200
+ async invoke(messages$1) {
201
+ try {
202
+ const { data } = await axios__default.post(
203
+ "https://api.perplexity.ai/chat/completions",
204
+ {
205
+ model: this.model,
206
+ messages: messages$1.map((m) => ({
207
+ role: m._getType() === "human" ? "user" : m._getType(),
208
+ content: m.content
209
+ }))
210
+ },
211
+ {
212
+ headers: {
213
+ Authorization: `Bearer ${this.apiKey}`
214
+ }
215
+ }
216
+ );
217
+ return new messages.AIMessage(data.choices[0].message.content);
218
+ } catch (error) {
219
+ if (axios__default.isAxiosError(error) && error.response) {
220
+ throw new Error(`Perplexity API error: ${error.response.statusText}`);
221
+ }
222
+ throw error;
223
+ }
224
+ }
225
+ }
226
+
227
+ const SupportedProvider = {
228
+ OPENAI: "openai",
229
+ ANTHROPIC: "anthropic",
230
+ GOOGLE: "google",
231
+ MISTRAL: "mistral",
232
+ PERPLEXITY: "perplexity",
233
+ COHERE: "cohere",
234
+ TOGETHER: "together"
235
+ };
236
+ const SupportedModel = {
237
+ GPT_3_5_TURBO: "gpt-3.5-turbo",
238
+ GPT_3_5_TURBO_0125: "gpt-3.5-turbo-0125",
239
+ GPT_4: "gpt-4",
240
+ GPT_4_0613: "gpt-4-0613",
241
+ GPT_4_1106_PREVIEW: "gpt-4-1106-preview",
242
+ GPT_4_TURBO: "gpt-4-turbo",
243
+ GPT_4_TURBO_PREVIEW: "gpt-4-turbo-preview",
244
+ GPT_4_TURBO_2024_04_09: "gpt-4-turbo-2024-04-09",
245
+ GPT_4O_2024_05_13: "gpt-4o-2024-05-13",
246
+ GPT_4O_2024_08_06: "gpt-4o-2024-08-06",
247
+ GPT_4O: "gpt-4o",
248
+ GPT_4O_MINI_2024_07_18: "gpt-4o-mini-2024-07-18",
249
+ GPT_4O_MINI: "gpt-4o-mini",
250
+ GPT_4_0125_PREVIEW: "gpt-4-0125-preview",
251
+ O1_PREVIEW: "o1-preview",
252
+ O1_PREVIEW_2024_09_12: "o1-preview-2024-09-12",
253
+ O1_MINI: "o1-mini",
254
+ O1_MINI_2024_09_12: "o1-mini-2024-09-12",
255
+ CLAUDE_2_1: "claude-2.1",
256
+ CLAUDE_3_OPUS_20240229: "claude-3-opus-20240229",
257
+ CLAUDE_3_SONNET_20240229: "claude-3-sonnet-20240229",
258
+ CLAUDE_3_5_SONNET_20240620: "claude-3-5-sonnet-20240620",
259
+ CLAUDE_3_HAIKU_20240307: "claude-3-haiku-20240307",
260
+ GEMINI_PRO: "gemini-pro",
261
+ GEMINI_1_PRO_LATEST: "gemini-1.0-pro-latest",
262
+ GEMINI_15_PRO_LATEST: "gemini-1.5-pro-latest",
263
+ GEMINI_15_PRO_EXP_0801: "gemini-1.5-pro-exp-0801",
264
+ GEMINI_15_FLASH_LATEST: "gemini-1.5-flash-latest",
265
+ COMMAND_R: "command-r",
266
+ COMMAND_R_PLUS: "command-r-plus",
267
+ MISTRAL_LARGE_LATEST: "mistral-large-latest",
268
+ MISTRAL_LARGE_2407: "mistral-large-2407",
269
+ MISTRAL_LARGE_2402: "mistral-large-2402",
270
+ MISTRAL_MEDIUM_LATEST: "mistral-medium-latest",
271
+ MISTRAL_SMALL_LATEST: "mistral-small-latest",
272
+ CODESTRAL_LATEST: "codestral-latest",
273
+ OPEN_MISTRAL_7B: "open-mistral-7b",
274
+ OPEN_MIXTRAL_8X7B: "open-mixtral-8x7b",
275
+ OPEN_MIXTRAL_8X22B: "open-mixtral-8x22b",
276
+ MISTRAL_7B_INSTRUCT_V0_2: "Mistral-7B-Instruct-v0.2",
277
+ MIXTRAL_8X7B_INSTRUCT_V0_1: "Mixtral-8x7B-Instruct-v0.1",
278
+ MIXTRAL_8X22B_INSTRUCT_V0_1: "Mixtral-8x22B-Instruct-v0.1",
279
+ LLAMA_3_70B_CHAT_HF: "Llama-3-70b-chat-hf",
280
+ LLAMA_3_8B_CHAT_HF: "Llama-3-8b-chat-hf",
281
+ QWEN2_72B_INSTRUCT: "Qwen2-72B-Instruct",
282
+ LLAMA_3_1_8B_INSTRUCT_TURBO: "Meta-Llama-3.1-8B-Instruct-Turbo",
283
+ LLAMA_3_1_70B_INSTRUCT_TURBO: "Meta-Llama-3.1-70B-Instruct-Turbo",
284
+ LLAMA_3_1_405B_INSTRUCT_TURBO: "Meta-Llama-3.1-405B-Instruct-Turbo",
285
+ LLAMA_3_1_SONAR_LARGE_128K_ONLINE: "llama-3.1-sonar-large-128k-online",
286
+ OPEN_MISTRAL_NEMO: "open-mistral-nemo"
287
+ };
288
+ ({
289
+ [SupportedProvider.OPENAI]: [
290
+ SupportedModel.GPT_3_5_TURBO,
291
+ SupportedModel.GPT_3_5_TURBO_0125,
292
+ SupportedModel.GPT_4,
293
+ SupportedModel.GPT_4_0613,
294
+ SupportedModel.GPT_4_1106_PREVIEW,
295
+ SupportedModel.GPT_4_TURBO,
296
+ SupportedModel.GPT_4_TURBO_PREVIEW,
297
+ SupportedModel.GPT_4_TURBO_2024_04_09,
298
+ SupportedModel.GPT_4O_2024_05_13,
299
+ SupportedModel.GPT_4O_2024_08_06,
300
+ SupportedModel.GPT_4O,
301
+ SupportedModel.GPT_4O_MINI_2024_07_18,
302
+ SupportedModel.GPT_4O_MINI,
303
+ SupportedModel.GPT_4_0125_PREVIEW,
304
+ SupportedModel.O1_PREVIEW,
305
+ SupportedModel.O1_PREVIEW_2024_09_12,
306
+ SupportedModel.O1_MINI,
307
+ SupportedModel.O1_MINI_2024_09_12
308
+ ],
309
+ [SupportedProvider.ANTHROPIC]: [
310
+ SupportedModel.CLAUDE_2_1,
311
+ SupportedModel.CLAUDE_3_OPUS_20240229,
312
+ SupportedModel.CLAUDE_3_SONNET_20240229,
313
+ SupportedModel.CLAUDE_3_5_SONNET_20240620,
314
+ SupportedModel.CLAUDE_3_HAIKU_20240307
315
+ ],
316
+ [SupportedProvider.GOOGLE]: [
317
+ SupportedModel.GEMINI_PRO,
318
+ SupportedModel.GEMINI_1_PRO_LATEST,
319
+ SupportedModel.GEMINI_15_PRO_LATEST,
320
+ SupportedModel.GEMINI_15_PRO_EXP_0801,
321
+ SupportedModel.GEMINI_15_FLASH_LATEST
322
+ ],
323
+ [SupportedProvider.MISTRAL]: [
324
+ SupportedModel.MISTRAL_LARGE_LATEST,
325
+ SupportedModel.MISTRAL_LARGE_2407,
326
+ SupportedModel.MISTRAL_LARGE_2402,
327
+ SupportedModel.MISTRAL_MEDIUM_LATEST,
328
+ SupportedModel.MISTRAL_SMALL_LATEST,
329
+ SupportedModel.CODESTRAL_LATEST,
330
+ SupportedModel.OPEN_MISTRAL_7B,
331
+ SupportedModel.OPEN_MIXTRAL_8X7B,
332
+ SupportedModel.OPEN_MIXTRAL_8X22B,
333
+ SupportedModel.OPEN_MISTRAL_NEMO
334
+ ],
335
+ [SupportedProvider.PERPLEXITY]: [
336
+ SupportedModel.LLAMA_3_1_SONAR_LARGE_128K_ONLINE
337
+ ],
338
+ [SupportedProvider.COHERE]: [
339
+ SupportedModel.COMMAND_R,
340
+ SupportedModel.COMMAND_R_PLUS
341
+ ],
342
+ [SupportedProvider.TOGETHER]: [
343
+ SupportedModel.MISTRAL_7B_INSTRUCT_V0_2,
344
+ SupportedModel.MIXTRAL_8X7B_INSTRUCT_V0_1,
345
+ SupportedModel.MIXTRAL_8X22B_INSTRUCT_V0_1,
346
+ SupportedModel.LLAMA_3_70B_CHAT_HF,
347
+ SupportedModel.LLAMA_3_8B_CHAT_HF,
348
+ SupportedModel.QWEN2_72B_INSTRUCT,
349
+ SupportedModel.LLAMA_3_1_8B_INSTRUCT_TURBO,
350
+ SupportedModel.LLAMA_3_1_70B_INSTRUCT_TURBO,
351
+ SupportedModel.LLAMA_3_1_405B_INSTRUCT_TURBO
352
+ ]
353
+ });
354
+
355
+ function getLangChainModel(provider, llmKeys, responseModel) {
356
+ const { OPENAI, ANTHROPIC, GOOGLE, MISTRAL, PERPLEXITY, COHERE, TOGETHER } = SupportedProvider;
357
+ switch (provider.provider) {
358
+ case OPENAI:
359
+ if (responseModel) {
360
+ return new openai.ChatOpenAI({
361
+ modelName: provider.model,
362
+ apiKey: llmKeys.openai || process.env.OPENAI_API_KEY
363
+ }).withStructuredOutput(responseModel);
364
+ }
365
+ return new openai.ChatOpenAI({
366
+ modelName: provider.model,
367
+ apiKey: llmKeys.openai || process.env.OPENAI_API_KEY
368
+ });
369
+ case ANTHROPIC:
370
+ if (responseModel) {
371
+ return new anthropic.ChatAnthropic({
372
+ modelName: provider.model,
373
+ anthropicApiKey: llmKeys.anthropic || process.env.ANTHROPIC_API_KEY
374
+ }).withStructuredOutput(responseModel);
375
+ }
376
+ return new anthropic.ChatAnthropic({
377
+ modelName: provider.model,
378
+ anthropicApiKey: llmKeys.anthropic || process.env.ANTHROPIC_API_KEY
379
+ });
380
+ case GOOGLE:
381
+ if (responseModel) {
382
+ return new googleGenai.ChatGoogleGenerativeAI({
383
+ modelName: provider.model,
384
+ apiKey: llmKeys.google || process.env.GOOGLE_API_KEY
385
+ }).withStructuredOutput(responseModel);
386
+ }
387
+ return new googleGenai.ChatGoogleGenerativeAI({
388
+ modelName: provider.model,
389
+ apiKey: llmKeys.google || process.env.GOOGLE_API_KEY
390
+ });
391
+ case MISTRAL:
392
+ if (responseModel) {
393
+ return new mistralai.ChatMistralAI({
394
+ modelName: provider.model,
395
+ apiKey: llmKeys.mistral || process.env.MISTRAL_API_KEY
396
+ }).withStructuredOutput(responseModel);
397
+ }
398
+ return new mistralai.ChatMistralAI({
399
+ modelName: provider.model,
400
+ apiKey: llmKeys.mistral || process.env.MISTRAL_API_KEY
401
+ });
402
+ case PERPLEXITY:
403
+ if (responseModel) {
404
+ return new ChatPerplexity({
405
+ apiKey: llmKeys.perplexity || process.env.PPLX_API_KEY || "",
406
+ model: provider.model
407
+ }).withStructuredOutput(responseModel);
408
+ }
409
+ return new ChatPerplexity({
410
+ apiKey: llmKeys.perplexity || process.env.PPLX_API_KEY || "",
411
+ model: provider.model
412
+ });
413
+ case COHERE:
414
+ if (responseModel) {
415
+ return new cohere.ChatCohere({
416
+ apiKey: process.env.COHERE_API_KEY || llmKeys.cohere,
417
+ model: provider.model
418
+ }).withStructuredOutput(responseModel);
419
+ }
420
+ return new cohere.ChatCohere({
421
+ apiKey: process.env.COHERE_API_KEY || llmKeys.cohere,
422
+ model: provider.model
423
+ });
424
+ case TOGETHER:
425
+ if (responseModel) {
426
+ return new togetherai.ChatTogetherAI({
427
+ apiKey: process.env.TOGETHER_API_KEY || llmKeys.together,
428
+ model: provider.model
429
+ }).withStructuredOutput(responseModel);
430
+ }
431
+ return new togetherai.ChatTogetherAI({
432
+ apiKey: process.env.TOGETHER_API_KEY || llmKeys.together,
433
+ model: provider.model
434
+ });
435
+ default:
436
+ throw new Error(`Unsupported provider: ${provider.provider}`);
437
+ }
438
+ }
439
+ async function callLLM(provider, options, llmKeys) {
440
+ const model = getLangChainModel(provider, llmKeys, options.responseModel);
441
+ const langChainMessages = extendProviderSystemPrompt(
442
+ options.messages.map(convertToLangChainMessage),
443
+ options,
444
+ provider
445
+ );
446
+ const response = await model.invoke(langChainMessages);
447
+ return extractContent(response);
448
+ }
449
+ function extendProviderSystemPrompt(messages$1, options, provider) {
450
+ const matchingProvider = options.llmProviders.find(
451
+ (p) => p.provider === provider.provider && p.model === provider.model
452
+ );
453
+ if (matchingProvider && matchingProvider.systemPrompt) {
454
+ messages$1.unshift(new messages.SystemMessage(matchingProvider.systemPrompt));
455
+ }
456
+ return messages$1;
457
+ }
458
+ function convertToLangChainMessage(msg) {
459
+ switch (msg.role) {
460
+ case "user":
461
+ return new messages.HumanMessage(msg.content);
462
+ case "assistant":
463
+ return new messages.AIMessage(msg.content);
464
+ case "system":
465
+ return new messages.SystemMessage(msg.content);
466
+ default:
467
+ return new messages.HumanMessage(msg.content);
468
+ }
469
+ }
470
+ async function* callLLMStream(provider, options, llmKeys) {
471
+ const model = getLangChainModel(provider, llmKeys, options.responseModel);
472
+ const langChainMessages = extendProviderSystemPrompt(
473
+ options.messages.map(convertToLangChainMessage),
474
+ options,
475
+ provider
476
+ );
477
+ const stream = await model.stream(langChainMessages);
478
+ for await (const chunk of stream) {
479
+ yield extractContent(chunk);
480
+ }
481
+ }
482
+ function extractContent(response) {
483
+ if ("content" in response) {
484
+ return typeof response.content === "string" ? response.content : JSON.stringify(response.content);
485
+ }
486
+ return typeof response === "string" ? response : JSON.stringify(response);
487
+ }
488
+
489
+ var __defProp = Object.defineProperty;
490
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
491
+ var __publicField = (obj, key, value) => {
492
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
493
+ return value;
494
+ };
495
+ const SDK_VERSION = packageJson.version;
496
+ dotenv__namespace.config();
497
+ const DEFAULT_TIMEOUT = 5;
498
+ const BASE_URL = "https://api.notdiamond.ai";
499
+ class NotDiamond {
500
+ constructor(options = {}) {
501
+ __publicField(this, "apiKey");
502
+ __publicField(this, "apiUrl");
503
+ __publicField(this, "modelSelectUrl");
504
+ __publicField(this, "feedbackUrl");
505
+ __publicField(this, "createUrl");
506
+ __publicField(this, "llmKeys");
507
+ this.apiKey = options.apiKey || process.env.NOTDIAMOND_API_KEY || "";
508
+ this.apiUrl = options.apiUrl || process.env.NOTDIAMOND_API_URL || BASE_URL;
509
+ this.llmKeys = options.llmKeys || {};
510
+ this.modelSelectUrl = `${this.apiUrl}/v2/modelRouter/modelSelect`;
511
+ this.feedbackUrl = `${this.apiUrl}/v2/report/metrics/feedback`;
512
+ this.createUrl = `${this.apiUrl}/v2/preferences/userPreferenceCreate`;
513
+ }
514
+ getAuthHeader() {
515
+ return `Bearer ${this.apiKey}`;
516
+ }
517
+ async postRequest(url, body) {
518
+ try {
519
+ const response = await axios__default.post(url, body, {
520
+ headers: {
521
+ Authorization: this.getAuthHeader(),
522
+ Accept: "application/json",
523
+ "Content-Type": "application/json",
524
+ "User-Agent": `TS-SDK/${SDK_VERSION}`
525
+ }
526
+ });
527
+ return response.data;
528
+ } catch (error) {
529
+ if (axios__default.isAxiosError(error) && error.response) {
530
+ return { detail: "An error occurred." };
531
+ }
532
+ console.error("error", error);
533
+ return { detail: "An unexpected error occurred." };
534
+ }
535
+ }
536
+ /**
537
+ * Selects the best model for the given messages.
538
+ * @param options The options for the model.
539
+ * @returns The results of the model.
540
+ */
541
+ async modelSelect(options) {
542
+ const requestBody = {
543
+ messages: options.messages,
544
+ llm_providers: options.llmProviders.map((provider) => ({
545
+ provider: provider.provider,
546
+ model: provider.model,
547
+ ...provider.contextLength !== void 0 && {
548
+ context_length: provider.contextLength
549
+ },
550
+ ...provider.customInputPrice !== void 0 && {
551
+ input_price: provider.customInputPrice
552
+ },
553
+ ...provider.inputPrice !== void 0 && {
554
+ input_price: provider.inputPrice
555
+ },
556
+ ...provider.customOutputPrice !== void 0 && {
557
+ output_price: provider.customOutputPrice
558
+ },
559
+ ...provider.outputPrice !== void 0 && {
560
+ output_price: provider.outputPrice
561
+ },
562
+ ...provider.customLatency !== void 0 && {
563
+ latency: provider.customLatency
564
+ },
565
+ ...provider.latency !== void 0 && { latency: provider.latency },
566
+ ...provider.isCustom !== void 0 && {
567
+ is_custom: provider.isCustom
568
+ }
569
+ })),
570
+ ...options.tradeoff && {
571
+ tradeoff: options.tradeoff
572
+ },
573
+ ...options.maxModelDepth && {
574
+ max_model_depth: options.maxModelDepth
575
+ },
576
+ ...options.tools && { tools: options.tools },
577
+ ...options.hashContent !== void 0 && {
578
+ hash_content: options.hashContent
579
+ },
580
+ ...options.preferenceId && { preference_id: options.preferenceId },
581
+ ...options.timeout ? { timeout: options.timeout } : {
582
+ timeout: DEFAULT_TIMEOUT
583
+ },
584
+ ...options.default && { default: options.default },
585
+ ...options.previousSession && {
586
+ previous_session: options.previousSession
587
+ },
588
+ ...options.responseModel && {
589
+ response_model: options.responseModel
590
+ }
591
+ };
592
+ return this.postRequest(
593
+ this.modelSelectUrl,
594
+ requestBody
595
+ );
596
+ }
597
+ /**
598
+ * Sends feedback to the NotDiamond API.
599
+ * @param options The options for the feedback.
600
+ * @returns The results of the feedback.
601
+ */
602
+ async feedback(options) {
603
+ return this.postRequest(this.feedbackUrl, {
604
+ session_id: options.sessionId,
605
+ feedback: options.feedback,
606
+ provider: options.provider
607
+ });
608
+ }
609
+ /**
610
+ * Creates a preference id.
611
+ * @returns The preference id.
612
+ */
613
+ async createPreferenceId() {
614
+ const response = await this.postRequest(
615
+ this.createUrl,
616
+ {}
617
+ );
618
+ if ("preference_id" in response) {
619
+ return response.preference_id;
620
+ }
621
+ throw new Error("Invalid response: preference_id not found");
622
+ }
623
+ /**
624
+ *
625
+ * @param options The options for the model.
626
+ * @returns A promise that resolves to the results of the model.
627
+ */
628
+ async acreate(options) {
629
+ const selectedModel = await this.modelSelect(options);
630
+ const { providers } = selectedModel;
631
+ const content = await callLLM(providers[0], options, this.llmKeys);
632
+ return { content, providers };
633
+ }
634
+ /**
635
+ *
636
+ * @param options The options for the model.
637
+ * @param callback Optional callback function to handle the result.
638
+ * @returns A promise that resolves to the results of the model or a callback function
639
+ */
640
+ create(options, callback) {
641
+ const promise = this.acreate(options);
642
+ if (callback) {
643
+ promise.then((result) => callback(null, result)).catch((error) => callback(error));
644
+ } else {
645
+ return promise;
646
+ }
647
+ }
648
+ /**
649
+ * Streams the results of the model asynchronously.
650
+ * @param options The options for the model.
651
+ * @returns A promise that resolves to an object containing the provider and an AsyncIterable of strings.
652
+ */
653
+ async astream(options) {
654
+ const selectedModel = await this.modelSelect(options);
655
+ const { providers } = selectedModel;
656
+ const stream = await Promise.resolve(
657
+ callLLMStream(
658
+ providers?.[0] || {
659
+ provider: "openai",
660
+ model: "gpt-3.5-turbo"
661
+ },
662
+ options,
663
+ this.llmKeys
664
+ )
665
+ );
666
+ return {
667
+ provider: providers?.[0] || {
668
+ provider: "openai",
669
+ model: "gpt-3.5-turbo"
670
+ },
671
+ stream
672
+ };
673
+ }
674
+ /**
675
+ * Streams the results of the model.
676
+ * @param options The options for the model.
677
+ * @param callback Optional callback function to handle each chunk of the stream.
678
+ * @returns A promise that resolves to an object containing the provider and an AsyncIterable of strings or a callback function
679
+ */
680
+ stream(options, callback) {
681
+ if (!options.llmProviders || options.llmProviders.length === 0) {
682
+ throw new Error("No LLM providers specified");
683
+ }
684
+ const promise = this.astream(options);
685
+ if (callback) {
686
+ promise.then(async ({ provider, stream }) => {
687
+ for await (const chunk of stream) {
688
+ callback(null, { provider, chunk });
689
+ }
690
+ }).catch((error) => callback(error));
691
+ } else {
692
+ return promise;
693
+ }
694
+ }
695
+ }
696
+
697
+ exports.NotDiamond = NotDiamond;
698
+ exports.SupportedModel = SupportedModel;
699
+ exports.SupportedProvider = SupportedProvider;