@alquimia-ai/tools 1.0.2 → 1.0.5

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 (57) hide show
  1. package/dist/actions/index.d.mts +38 -3
  2. package/dist/actions/index.d.ts +38 -3
  3. package/dist/actions/index.js +152 -20
  4. package/dist/actions/index.js.map +1 -1
  5. package/dist/actions/index.mjs +153 -12
  6. package/dist/actions/index.mjs.map +1 -1
  7. package/dist/hooks/index.d.mts +2 -3
  8. package/dist/hooks/index.d.ts +2 -3
  9. package/dist/hooks/index.js +29 -60
  10. package/dist/hooks/index.js.map +1 -1
  11. package/dist/hooks/index.mjs +16 -42
  12. package/dist/hooks/index.mjs.map +1 -1
  13. package/dist/providers/index.d.mts +74 -0
  14. package/dist/providers/index.d.ts +74 -0
  15. package/dist/providers/index.js +2183 -0
  16. package/dist/providers/index.js.map +1 -0
  17. package/dist/providers/index.mjs +2173 -0
  18. package/dist/providers/index.mjs.map +1 -0
  19. package/dist/providers-D6FJ6tlA.d.mts +33 -0
  20. package/dist/providers-D6FJ6tlA.d.ts +33 -0
  21. package/dist/sdk/index.d.mts +41 -68
  22. package/dist/sdk/index.d.ts +41 -68
  23. package/dist/sdk/index.js +1 -374
  24. package/dist/sdk/index.js.map +1 -1
  25. package/dist/sdk/index.mjs +1 -356
  26. package/dist/sdk/index.mjs.map +1 -1
  27. package/dist/services/index.js +0 -7
  28. package/dist/services/index.mjs +1 -0
  29. package/dist/types/index.js +0 -4
  30. package/dist/utils/index.js +0 -14
  31. package/package.json +16 -27
  32. package/dist/actions/alquimia.action.d.mts +0 -3
  33. package/dist/actions/alquimia.action.d.ts +0 -3
  34. package/dist/actions/alquimia.action.js +0 -62
  35. package/dist/actions/alquimia.action.js.map +0 -1
  36. package/dist/actions/alquimia.action.mjs +0 -38
  37. package/dist/actions/alquimia.action.mjs.map +0 -1
  38. package/dist/actions/baseApi.action.d.mts +0 -20
  39. package/dist/actions/baseApi.action.d.ts +0 -20
  40. package/dist/actions/baseApi.action.js +0 -202
  41. package/dist/actions/baseApi.action.js.map +0 -1
  42. package/dist/actions/baseApi.action.mjs +0 -173
  43. package/dist/actions/baseApi.action.mjs.map +0 -1
  44. package/dist/alquimia-sdk-DK0XLjol.d.mts +0 -77
  45. package/dist/alquimia-sdk-DK0XLjol.d.ts +0 -77
  46. package/dist/context/index.d.mts +0 -22
  47. package/dist/context/index.d.ts +0 -22
  48. package/dist/context/index.js +0 -124
  49. package/dist/context/index.js.map +0 -1
  50. package/dist/context/index.mjs +0 -96
  51. package/dist/context/index.mjs.map +0 -1
  52. package/dist/index.d.mts +0 -33
  53. package/dist/index.d.ts +0 -33
  54. package/dist/index.js +0 -1277
  55. package/dist/index.js.map +0 -1
  56. package/dist/index.mjs +0 -1202
  57. package/dist/index.mjs.map +0 -1
package/dist/index.mjs DELETED
@@ -1,1202 +0,0 @@
1
- // src/button.tsx
2
- import { jsx } from "react/jsx-runtime";
3
- var Button = ({ children, className, appName }) => {
4
- return /* @__PURE__ */ jsx(
5
- "button",
6
- {
7
- className,
8
- onClick: () => alert(`Hello from your ${appName} app!`),
9
- children
10
- }
11
- );
12
- };
13
-
14
- // src/card.tsx
15
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
16
- function Card({
17
- className,
18
- title,
19
- children,
20
- href
21
- }) {
22
- return /* @__PURE__ */ jsxs(
23
- "a",
24
- {
25
- className,
26
- href: `${href}?utm_source=create-turbo&utm_medium=basic&utm_campaign=create-turbo"`,
27
- rel: "noopener noreferrer",
28
- target: "_blank",
29
- children: [
30
- /* @__PURE__ */ jsxs("h2", { children: [
31
- title,
32
- " ",
33
- /* @__PURE__ */ jsx2("span", { children: "->" })
34
- ] }),
35
- /* @__PURE__ */ jsx2("p", { children })
36
- ]
37
- }
38
- );
39
- }
40
-
41
- // src/code.tsx
42
- import { jsx as jsx3 } from "react/jsx-runtime";
43
- function Code({
44
- children,
45
- className
46
- }) {
47
- return /* @__PURE__ */ jsx3("code", { className, children });
48
- }
49
-
50
- // src/sdk/alquimia-sdk.ts
51
- import axios from "axios";
52
- var AlquimiaSDK = class {
53
- constructor(config, enforceCharacterization = true) {
54
- this.conversationId = null;
55
- this.sessionId = null;
56
- this.streamId = null;
57
- this.tools = [];
58
- this.extraData = {};
59
- this.forceProfile = {};
60
- this.config = config;
61
- this.enforceCharacterization = enforceCharacterization;
62
- this.axiosInstance = axios.create();
63
- this.axiosInstance.interceptors.response.use(
64
- (response) => response,
65
- async (error) => {
66
- if (error.response?.status) {
67
- if (this.loggerProvider) {
68
- await this.loggerProvider.logError(
69
- "Server Error",
70
- error,
71
- {
72
- url: error.config.url,
73
- method: error.config.method,
74
- data: error.config.data,
75
- status: error.response.status,
76
- responseData: error.response.data
77
- }
78
- );
79
- }
80
- }
81
- return Promise.reject(error);
82
- }
83
- );
84
- this.textToSpeech = this.textToSpeech.bind(this);
85
- this.speechToText = this.speechToText.bind(this);
86
- }
87
- static configure(apiKey, inferUrl, streamUrl, assistantId) {
88
- return {
89
- apiKey,
90
- chatUrl: `${inferUrl}/chat/${assistantId}`,
91
- streamUrl: `${streamUrl}/${assistantId}`,
92
- assistantId
93
- };
94
- }
95
- widthConversationId(conversationId) {
96
- this.conversationId = conversationId;
97
- return this;
98
- }
99
- withWhisperProvider(provider) {
100
- this.whisperProvider = provider;
101
- return this;
102
- }
103
- withStableDiffusionProvider(provider) {
104
- this.stableDiffusionProvider = provider;
105
- return this;
106
- }
107
- withAnalyzeCharacterizationProvider(provider) {
108
- this.analyzeCharacterizationProvider = provider;
109
- return this;
110
- }
111
- withRatingsProvider(provider) {
112
- this.ratingsProvider = provider;
113
- return this;
114
- }
115
- withLoggerProvider(provider) {
116
- this.loggerProvider = provider;
117
- return this;
118
- }
119
- getEnforceCharacterization() {
120
- return this.enforceCharacterization ?? true;
121
- }
122
- withTools(tools) {
123
- this.tools = tools;
124
- return this;
125
- }
126
- withExtraData(extraData) {
127
- this.extraData = extraData;
128
- return this;
129
- }
130
- withForceProfile(forceProfile) {
131
- this.forceProfile = forceProfile;
132
- return this;
133
- }
134
- textToSpeech(text) {
135
- if (!this.whisperProvider) {
136
- throw new Error("Whisper provider not initialized");
137
- }
138
- return this.whisperProvider.textToSpeech(text);
139
- }
140
- speechToText(audio) {
141
- if (!this.whisperProvider) {
142
- throw new Error("Whisper provider not initialized");
143
- }
144
- return this.whisperProvider.speechToText(audio);
145
- }
146
- async sendMessage(query, traceParent) {
147
- if (!this.conversationId) {
148
- throw new Error("Conversation not initialized");
149
- }
150
- const initMessage = {
151
- query,
152
- session_id: this.conversationId,
153
- tools: this.tools,
154
- extra_data: this.extraData,
155
- force_profile: this.forceProfile
156
- };
157
- const result = (await this.axiosInstance.post(this.config.chatUrl, initMessage, {
158
- headers: {
159
- "Content-Type": "application/json",
160
- "x-trace-parent": traceParent || ""
161
- }
162
- })).data;
163
- this.streamId = result.data.stream_id;
164
- return this;
165
- }
166
- async generateImage(query) {
167
- if (!this.stableDiffusionProvider) {
168
- throw new Error("Stable Diffusion provider not initialized");
169
- }
170
- return this.stableDiffusionProvider.generateImage(query);
171
- }
172
- async analyzeCharacterization(text) {
173
- if (!this.analyzeCharacterizationProvider) {
174
- throw new Error("analyze characterization provider not initialized");
175
- }
176
- return this.analyzeCharacterizationProvider.analyzeCharacterization(text);
177
- }
178
- async rate(data) {
179
- if (!this.ratingsProvider) {
180
- throw new Error("ratings provider not initialized");
181
- }
182
- return this.ratingsProvider.rate(data);
183
- }
184
- async logInfo(message, data) {
185
- if (!this.loggerProvider) {
186
- throw new Error("logger provider not initialized");
187
- }
188
- return this.loggerProvider.logInfo(message, data);
189
- }
190
- async logError(message, error, data) {
191
- if (!this.loggerProvider) {
192
- throw new Error("logger provider not initialized");
193
- }
194
- return this.loggerProvider.logError(message, error, data);
195
- }
196
- getUrlStream() {
197
- return `${this.config.streamUrl}/${this.streamId}`;
198
- }
199
- };
200
- var alquimia_sdk_default = AlquimiaSDK;
201
-
202
- // src/sdk/providers/providers.ts
203
- var GenerativeProvider = class {
204
- constructor(config) {
205
- this.config = config;
206
- }
207
- };
208
- var WhisperProvider = class {
209
- constructor(config) {
210
- this.config = config;
211
- }
212
- };
213
- var StableDiffusionProvider = class {
214
- constructor(config) {
215
- this.config = config;
216
- }
217
- };
218
- var CharacterizationProvider = class {
219
- constructor(config) {
220
- this.config = config;
221
- }
222
- };
223
- var RatingsProvider = class {
224
- constructor(config) {
225
- this.config = config;
226
- }
227
- };
228
- var LoggerProvider = class {
229
- constructor(config) {
230
- this.config = config;
231
- }
232
- };
233
-
234
- // src/sdk/providers/alquimia.ts
235
- import axios2 from "axios";
236
- var AlquimiaWhisperProvider = class extends WhisperProvider {
237
- constructor(config) {
238
- super(config);
239
- }
240
- async textToSpeech(text) {
241
- const axiosClient = axios2.create({
242
- baseURL: this.config.baseURL
243
- });
244
- try {
245
- const response = await axiosClient.post(
246
- this.config.ttsRoute,
247
- {
248
- text
249
- },
250
- { responseType: "blob" }
251
- );
252
- return response.data;
253
- } catch (error) {
254
- console.error("Error converting text to speech:", error);
255
- throw error;
256
- }
257
- }
258
- async speechToText(audio) {
259
- const axiosClient = axios2.create({
260
- baseURL: this.config.baseURL
261
- });
262
- try {
263
- const response = await axiosClient.post(this.config.sttRoute, {
264
- audio
265
- });
266
- return response.data;
267
- } catch (error) {
268
- console.error("Error converting speech to text:", error);
269
- throw error;
270
- }
271
- }
272
- };
273
- var AlquimiaRatingsProvider = class extends RatingsProvider {
274
- constructor(config) {
275
- super(config);
276
- }
277
- async rate(data) {
278
- const path = `${this.config.baseUrl}${this.config.route}`;
279
- try {
280
- let response;
281
- const headers = {
282
- Authorization: `Bearer ${this.config.token}`,
283
- "Content-Type": "application/json",
284
- ...this.config.headers || {}
285
- };
286
- response = await axios2.post(`${path}`, data, { headers });
287
- return {
288
- success: true,
289
- data: response.data
290
- };
291
- } catch (error) {
292
- if (axios2.isAxiosError(error)) {
293
- return {
294
- success: false,
295
- error: {
296
- message: error.message,
297
- response: {
298
- status: error.response?.status,
299
- data: error.response?.data
300
- },
301
- details: error.response?.data
302
- }
303
- };
304
- }
305
- return {
306
- success: false,
307
- error: {
308
- message: error instanceof Error ? error.message : "Unknown error occurred",
309
- response: {
310
- status: 500
311
- }
312
- }
313
- };
314
- }
315
- }
316
- };
317
-
318
- // src/utils/utils.ts
319
- function generateTranslatePrompt(text) {
320
- const prompt = `
321
- Arrange the following text according to the given object structure and return it as plain json, values summarized to one word, no formatting:
322
- {
323
- restrictions: {
324
- value: [''],
325
- description: 'Restrictions to certain foods'
326
- },
327
- alergies: {
328
- value: [''],
329
- description: 'Alergies to certain foods'
330
- },
331
- wine_preference: {
332
- value: [''],
333
- description: 'Preferences for the wine'
334
- },
335
- meal_preference: {
336
- value: [''],
337
- description: 'Preferences for the meal'
338
- }
339
- }
340
-
341
- Text: "${text}"
342
-
343
- Output:
344
- `;
345
- return prompt;
346
- }
347
- function getCookies(name) {
348
- if (typeof document === "undefined") return void 0;
349
- const value = `; ${document.cookie}`;
350
- const parts = value.split(`; ${name}=`);
351
- if (parts.length === 2) return parts.pop()?.split(";").shift();
352
- }
353
- function generateHeaders(config) {
354
- const headers = {
355
- "Content-Type": "application/json"
356
- };
357
- if (config.token) {
358
- headers["Authorization"] = `Bearer ${config.token}`;
359
- }
360
- if (config.headers) {
361
- Object.entries(config.headers).forEach(([key, value]) => {
362
- headers[key] = value;
363
- });
364
- }
365
- return headers;
366
- }
367
- function isTextContent(buffer) {
368
- try {
369
- const text = new TextDecoder().decode(buffer);
370
- return /^[\w\#\-\*]/.test(text.trim());
371
- } catch {
372
- return false;
373
- }
374
- }
375
- function getQueryParam(param) {
376
- if (typeof window !== "undefined") {
377
- const urlParams = new URLSearchParams(window.location.search);
378
- return urlParams.get(param);
379
- }
380
- return null;
381
- }
382
- function defineAssistantId(defaultId) {
383
- if (typeof window !== "undefined" && window.location.pathname === "/") {
384
- const queryAssistantId = getQueryParam("talkwith");
385
- if (queryAssistantId) {
386
- localStorage.setItem("assistantId", queryAssistantId);
387
- return queryAssistantId;
388
- }
389
- const storedAssistantId = localStorage.getItem("assistantId");
390
- return storedAssistantId || defaultId;
391
- }
392
- return defaultId;
393
- }
394
- function formatTimeWithUnit(timeMs) {
395
- if (timeMs >= 1e3) {
396
- return `${(timeMs / 1e3).toFixed(1)}s`;
397
- }
398
- return `${Math.round(timeMs)}ms`;
399
- }
400
- function serializeAxiosError(error) {
401
- if (error instanceof Error) {
402
- const customError = error;
403
- return {
404
- message: customError?.message,
405
- name: customError?.name,
406
- stack: customError?.stack,
407
- code: customError?.code,
408
- status: customError?.status
409
- };
410
- }
411
- return {
412
- message: String(error),
413
- name: "Unknown Error"
414
- };
415
- }
416
- function parseConversationsMapCookie(cookieValue) {
417
- try {
418
- const decodedValue = decodeURIComponent(cookieValue);
419
- return JSON.parse(decodedValue);
420
- } catch (e) {
421
- console.error("Error parsing conversations cookie:", e);
422
- return {};
423
- }
424
- }
425
- function getTopicSessionId(topicId) {
426
- const conversationsStr = getCookies("alquimia-sessions") || "{}";
427
- if (!conversationsStr) {
428
- const sessionCookie = getCookies("alquimia-session");
429
- return sessionCookie || "";
430
- }
431
- const conversationsMap = parseConversationsMapCookie(conversationsStr);
432
- return conversationsMap[topicId] || "";
433
- }
434
- function createMessageId() {
435
- return Math.floor(Math.random() * 1e6).toString();
436
- }
437
-
438
- // src/sdk/providers/openai.ts
439
- import OpenAI from "openai";
440
- var OpenAIWhisperProvider = class extends WhisperProvider {
441
- async textToSpeech(text) {
442
- return new Blob();
443
- }
444
- async speechToText(audio) {
445
- return "";
446
- }
447
- };
448
- var OpenAIAnalyzeCharProvider = class extends CharacterizationProvider {
449
- constructor(config) {
450
- super(config);
451
- this.client = new OpenAI({
452
- apiKey: config.apiKey
453
- });
454
- }
455
- async analyzeCharacterization(text) {
456
- const prompt = generateTranslatePrompt(text);
457
- const response = await this.client.chat.completions.create({
458
- model: "gpt-4o-mini",
459
- messages: [
460
- { role: "system", content: "You are a helpful assistant." },
461
- { role: "user", content: prompt }
462
- ],
463
- max_tokens: 150,
464
- temperature: 0.7
465
- });
466
- const arrangedText = response.choices[0].message.content.trim();
467
- try {
468
- const arrangedObject = JSON.parse(arrangedText);
469
- return arrangedObject;
470
- } catch (error) {
471
- throw new Error("Failed to parse the response from OpenAI");
472
- }
473
- }
474
- };
475
- var OpenAIStableDiffusionProvider = class extends StableDiffusionProvider {
476
- constructor(config) {
477
- super(config);
478
- this.client = new OpenAI({
479
- apiKey: config.apiKey
480
- });
481
- }
482
- async generateImage(query) {
483
- const response = await this.client.images.generate({
484
- model: "dall-e-3",
485
- prompt: query,
486
- n: 1,
487
- size: "1024x1024"
488
- });
489
- return response.data[0].url;
490
- }
491
- };
492
-
493
- // src/sdk/providers/stability.ts
494
- import { Buffer } from "buffer";
495
- import axios3 from "axios";
496
- var StabilityProvider = class extends StableDiffusionProvider {
497
- constructor(config) {
498
- super(config);
499
- }
500
- async generateImage(query) {
501
- const payload = {
502
- prompt: "query",
503
- output_format: "webp"
504
- };
505
- const response = await axios3.postForm(
506
- `https://api.stability.ai/v2beta/stable-image/generate/ultra`,
507
- axios3.toFormData(payload, new FormData()),
508
- {
509
- validateStatus: void 0,
510
- responseType: "arraybuffer",
511
- headers: {
512
- Authorization: `Bearer ${this.config.apiKey}`,
513
- Accept: "image/*"
514
- }
515
- }
516
- );
517
- if (response.status === 200) {
518
- const base64Image = Buffer.from(response.data).toString("base64");
519
- return `data:image/webp;base64,${base64Image}`;
520
- } else {
521
- throw new Error(`${response.status}: ${response.data.toString()}`);
522
- }
523
- }
524
- };
525
-
526
- // src/sdk/providers/eleven-labs.ts
527
- import { ElevenLabsClient, ElevenLabs } from "elevenlabs";
528
- import axios4 from "axios";
529
- var requestSpecs = {
530
- optimize_streaming_latency: ElevenLabs.OptimizeStreamingLatency.Zero,
531
- output_format: ElevenLabs.OutputFormat.Mp344100128,
532
- model_id: "eleven_multilingual_v1",
533
- language: "es",
534
- voice_settings: {
535
- stability: 0.1,
536
- similarity_boost: 0.15,
537
- style: 0.2
538
- }
539
- };
540
- var ElevenLabsWhisperProvider = class extends WhisperProvider {
541
- constructor(config) {
542
- super(config);
543
- this.client = new ElevenLabsClient(config);
544
- }
545
- async speechToText(audio) {
546
- return "";
547
- }
548
- async textToSpeech(text) {
549
- const axiosClient = axios4.create({
550
- baseURL: this.config.baseURL,
551
- headers: {
552
- Accept: "audio/mpeg",
553
- "Content-Type": "application/json",
554
- "Xi-Api-Key": this.config.apiKey
555
- }
556
- });
557
- try {
558
- const response = await axiosClient.post(
559
- `/v1/text-to-speech/${this.config.voiceId}`,
560
- {
561
- text,
562
- ...requestSpecs
563
- },
564
- { responseType: "blob" }
565
- );
566
- return response.data;
567
- } catch (error) {
568
- console.error("Error converting text to speech:", error);
569
- throw error;
570
- }
571
- }
572
- };
573
-
574
- // src/sdk/providers/elastic-search.ts
575
- import pino from "pino";
576
- var ElasticLoggerProvider = class _ElasticLoggerProvider extends LoggerProvider {
577
- constructor(config) {
578
- super(config);
579
- this.logger = console;
580
- }
581
- static async create(config) {
582
- const provider = new _ElasticLoggerProvider(config);
583
- await provider.initialize(config);
584
- return provider;
585
- }
586
- async initialize(config) {
587
- if (typeof window === "undefined") {
588
- const [pinoElastic] = await Promise.all([
589
- import("pino-elasticsearch")
590
- ]);
591
- const streamToElastic = pinoElastic.default({
592
- index: config.index || "logs-index",
593
- node: config.endpoint,
594
- esVersion: config.esVersion || 7,
595
- flushBytes: config.flushBytes || 1e3,
596
- auth: {
597
- username: config.username || "",
598
- password: config.password || ""
599
- },
600
- tls: {
601
- rejectUnauthorized: false
602
- },
603
- op_type: "create"
604
- });
605
- streamToElastic.on("error", (err) => {
606
- console.error("Elasticsearch stream error:", err);
607
- });
608
- streamToElastic.on("insertError", (err) => {
609
- console.error("Elasticsearch insert error:", err);
610
- });
611
- streamToElastic.on("insert", () => {
612
- console.log("Successfully sent log to Elasticsearch");
613
- });
614
- this.logger = pino({
615
- level: "info",
616
- timestamp: () => `,"time":"${(/* @__PURE__ */ new Date()).toISOString()}"`
617
- }, streamToElastic);
618
- }
619
- }
620
- logInfo(message, data) {
621
- this.logger.info({ ...data }, message);
622
- }
623
- logError(message, error, data) {
624
- const errorDetails = {
625
- message: error.message,
626
- name: error.name,
627
- stack: error.stack
628
- };
629
- this.logger.error({ error, ...data, ...errorDetails }, message);
630
- }
631
- };
632
-
633
- // src/hooks/alquimia.hook.tsx
634
- import { useEffect as useEffect2, useState } from "react";
635
-
636
- // src/context/session-context.tsx
637
- import { createContext, useContext, useEffect, useReducer } from "react";
638
-
639
- // src/reducer/characterization-reducer.tsx
640
- var characterizationReducer = (state, action) => {
641
- switch (action.type) {
642
- case "SET_SESSION":
643
- return {
644
- ...state,
645
- sessionId: action.payload.sessionId,
646
- characterizationData: action.payload.characterizationData
647
- };
648
- case "CLEAR_SESSION":
649
- return {
650
- ...state,
651
- sessionId: null,
652
- characterizationData: null
653
- };
654
- default:
655
- return state;
656
- }
657
- };
658
-
659
- // src/context/session-context.tsx
660
- import { openDB } from "idb";
661
- import { jsx as jsx4 } from "react/jsx-runtime";
662
- var initialState = {
663
- sessionId: null,
664
- characterizationData: null
665
- };
666
- var AlquimiaContext = createContext(null);
667
- var useSessionContext = () => {
668
- const context = useContext(AlquimiaContext);
669
- if (!context) {
670
- console.warn("useSessionContext must be used within a session provider. Returning default value.");
671
- return {
672
- userSessionState: initialState,
673
- saveUserSession: null
674
- };
675
- }
676
- return context;
677
- };
678
- var SessionProvider = ({ children }) => {
679
- const [userSessionState, sessionDispatch] = useReducer(characterizationReducer, initialState);
680
- useEffect(() => {
681
- getSession();
682
- }, []);
683
- const getSession = async () => {
684
- const userCookie = await getCookies("alquimia-session") || "";
685
- const db = await openDB("alquimiaDB", 1, {
686
- upgrade(db2) {
687
- if (!db2.objectStoreNames.contains("session")) {
688
- db2.createObjectStore("session", { keyPath: "key" });
689
- }
690
- }
691
- });
692
- const sessionIdEntry = await db.get("session", "sessionId");
693
- const characterizationDataEntry = await db.get("session", "characterizationData");
694
- const sessionDataMatchesCookie = sessionIdEntry?.value === userCookie;
695
- if (sessionIdEntry && characterizationDataEntry && sessionDataMatchesCookie) {
696
- sessionDispatch({
697
- type: "SET_SESSION",
698
- payload: {
699
- sessionId: sessionIdEntry.value,
700
- characterizationData: characterizationDataEntry.value
701
- }
702
- });
703
- }
704
- };
705
- const saveUserSession = async (id, data) => {
706
- const db = await openDB("alquimiaDB", 1);
707
- await db.put("session", { key: "sessionId", value: id });
708
- await db.put("session", { key: "characterizationData", value: data });
709
- sessionDispatch({
710
- type: "SET_SESSION",
711
- payload: { sessionId: id, characterizationData: data }
712
- });
713
- };
714
- const getSessionData = () => {
715
- return userSessionState;
716
- };
717
- return /* @__PURE__ */ jsx4(AlquimiaContext.Provider, { value: { userSessionState, getSessionData, saveUserSession }, children });
718
- };
719
-
720
- // src/hooks/alquimia.hook.tsx
721
- function useAlquimia(sdk) {
722
- const [chunkReceived, setChunkReceived] = useState("");
723
- const [currentMessageIdChuncked, setCurrentMessageIdChuncked] = useState("");
724
- const [input, setInput] = useState("");
725
- const [isLoading, setIsLoading] = useState(false);
726
- const [isMessageStreaming, setIsMessageStreaming] = useState(false);
727
- const [streamingMessageId, setStreamingMessageId] = useState(null);
728
- const [isAudioRecording, setIsAudioRecording] = useState(false);
729
- const [messageMetaData, setMessageMetaData] = useState(null);
730
- const [messages, setMessages] = useState([]);
731
- const [sessionId, setSessionId] = useState(null);
732
- const [activeTool, setActiveTool] = useState(null);
733
- const [lastRequest, setLastRequest] = useState(null);
734
- const { userSessionState, saveUserSession } = useSessionContext();
735
- const shouldShowCharacterizationButton = sdk.getEnforceCharacterization() && !userSessionState?.characterizationData;
736
- useEffect2(() => {
737
- if (chunkReceived)
738
- processMessageChunk(currentMessageIdChuncked, chunkReceived);
739
- }, [chunkReceived]);
740
- useEffect2(() => {
741
- if (userSessionState?.characterizationData && sdk.getEnforceCharacterization()) {
742
- sdk.withExtraData(userSessionState?.characterizationData);
743
- }
744
- }, [userSessionState]);
745
- function cleanMessages() {
746
- setMessages([]);
747
- }
748
- async function processMessageChunk(messageId, chunk, error_code, error_detail, additionalInfo) {
749
- setMessages((currentMessages) => {
750
- const messageIndex = currentMessages.findIndex(
751
- (message) => message.id === messageId
752
- );
753
- if (messageIndex !== -1) {
754
- const updatedMessages = [...currentMessages];
755
- const updatedMessage = {
756
- ...updatedMessages[messageIndex],
757
- content: `${updatedMessages[messageIndex]?.content || ""}${chunk}`,
758
- id: updatedMessages[messageIndex]?.id || "",
759
- role: updatedMessages[messageIndex]?.role || "assistant",
760
- error_code,
761
- error_detail,
762
- additionalInfo,
763
- created_at: (/* @__PURE__ */ new Date()).getTime().toString()
764
- };
765
- updatedMessages[messageIndex] = updatedMessage;
766
- return updatedMessages;
767
- } else {
768
- return [
769
- ...currentMessages,
770
- {
771
- content: `${chunk}`,
772
- role: "assistant",
773
- id: messageId,
774
- error_code,
775
- error_detail,
776
- created_at: (/* @__PURE__ */ new Date()).getTime().toString()
777
- }
778
- ];
779
- }
780
- });
781
- }
782
- async function handleSubmit(event, traceParentId, sessionId2, additionalInfo) {
783
- setIsLoading(true);
784
- event.preventDefault();
785
- if (input) {
786
- addUserMessage(input);
787
- const messageId = createMessageId();
788
- setCurrentMessageIdChuncked(messageId);
789
- setStreamingMessageId(messageId);
790
- await sendMessage(input, (chunk) => {
791
- processMessageChunk(
792
- messageId,
793
- chunk?.data?.content || "",
794
- chunk?.error_code,
795
- chunk?.error_detail,
796
- additionalInfo
797
- );
798
- }, traceParentId, sessionId2);
799
- setInput("");
800
- }
801
- setIsLoading(false);
802
- }
803
- function handleInputChange(event) {
804
- setInput(event.target.value);
805
- }
806
- function handleReplaceInput(input2) {
807
- setInput(input2);
808
- }
809
- function populateMessages(messages2) {
810
- setMessages(messages2);
811
- }
812
- function handleLoadingCancel() {
813
- setIsLoading(false);
814
- setIsMessageStreaming(false);
815
- setInput("");
816
- }
817
- function addUserMessage(message) {
818
- setMessages((prevMessages) => [
819
- ...prevMessages,
820
- {
821
- content: message,
822
- role: "user",
823
- id: createMessageId(),
824
- created_at: (/* @__PURE__ */ new Date()).getTime().toString()
825
- }
826
- ]);
827
- }
828
- function getCookie(name) {
829
- const cookies2 = document.cookie.split(";");
830
- for (let cookie of cookies2) {
831
- const [cookieName, cookieValue] = cookie.trim().split("=");
832
- if (cookieName === name) {
833
- return decodeURIComponent(cookieValue);
834
- }
835
- }
836
- return null;
837
- }
838
- async function sendMessage(message, callBack, traceParentId, sessionId2) {
839
- const conversationId = sessionId2 || getCookie("alquimia-session");
840
- setIsMessageStreaming(true);
841
- setActiveTool(null);
842
- setLastRequest(message);
843
- const response = await sdk.widthConversationId(conversationId || "").sendMessage(message, traceParentId);
844
- const es = new EventSource(response.getUrlStream());
845
- es.onmessage = (event) => {
846
- const parsedData = JSON.parse(event.data);
847
- if (parsedData.tooler && parsedData.tooler.length > 0 && !activeTool) {
848
- setActiveTool({
849
- tooler: parsedData.tooler
850
- });
851
- }
852
- if (parsedData.error_code) {
853
- callBack({
854
- type: "error",
855
- error_code: parsedData.error_code,
856
- error_detail: parsedData.error_detail
857
- });
858
- }
859
- if (parsedData.is_complete) {
860
- setIsMessageStreaming(false);
861
- setStreamingMessageId(null);
862
- es.close();
863
- } else {
864
- callBack(parsedData.answer);
865
- }
866
- };
867
- }
868
- async function handleSaveCharacterization(translation) {
869
- const conversationId = getCookie("alquimia-session");
870
- if (!conversationId || !saveUserSession) return;
871
- saveUserSession(conversationId, translation);
872
- }
873
- return {
874
- activeTool,
875
- cleanMessages,
876
- createMessageId,
877
- handleInputChange,
878
- handleReplaceInput,
879
- handleSubmit,
880
- handleSaveCharacterization,
881
- handleLoadingCancel,
882
- input,
883
- isLoading,
884
- isMessageStreaming,
885
- streamingMessageId,
886
- isAudioRecording,
887
- shouldShowCharacterizationButton,
888
- lastRequest,
889
- messageMetaData,
890
- messages,
891
- populateMessages,
892
- processMessageChunk,
893
- sendMessage,
894
- sessionId,
895
- setActiveTool,
896
- setSessionId,
897
- setLastRequest,
898
- setIsAudioRecording
899
- };
900
- }
901
-
902
- // src/hooks/useRatings.ts
903
- import { useState as useState2, useReducer as useReducer2 } from "react";
904
- var initialState2 = {
905
- ratingStars: 0,
906
- ratingThumbs: "",
907
- ratingComment: ""
908
- };
909
- function ratingReducer(state, action) {
910
- switch (action.type) {
911
- case "SET_RATING_STARS":
912
- return { ...state, ratingStars: action.payload };
913
- case "SET_RATING_THUMBS":
914
- return { ...state, ratingThumbs: action.payload };
915
- case "SET_RATING_COMMENT":
916
- return { ...state, ratingComment: action.payload };
917
- default:
918
- return state;
919
- }
920
- }
921
- function useRatings({ assistantId, sendRating, topicId }) {
922
- const [isLoading, setIsLoading] = useState2(false);
923
- const [hasReviewed, setHasReviewed] = useState2(false);
924
- const [state, dispatch] = useReducer2(ratingReducer, initialState2);
925
- const setRatingStars = (rating) => {
926
- dispatch({ type: "SET_RATING_STARS", payload: rating });
927
- };
928
- const setRatingThumbs = (rating) => {
929
- dispatch({ type: "SET_RATING_THUMBS", payload: rating });
930
- };
931
- const setRatingComment = (comment) => {
932
- dispatch({ type: "SET_RATING_COMMENT", payload: comment });
933
- };
934
- const thumbsScore = (value) => {
935
- return value === "thumbsUp" ? 5 : value === "thumbsDown" ? 0 : 0;
936
- };
937
- const handleRate = async (key, value, onHandleRateSuccess) => {
938
- setIsLoading(true);
939
- const sessionId = getTopicSessionId(topicId);
940
- const ratingObj = {
941
- topicId: parseInt(topicId),
942
- sessionId: sessionId || "",
943
- assistantId,
944
- score: key === "score" ? value : thumbsScore(value),
945
- description: key === "description" ? value : state.ratingComment
946
- };
947
- try {
948
- const response = await sendRating(ratingObj);
949
- if (!response.success) {
950
- setIsLoading(false);
951
- onHandleRateSuccess(false, response.error.message);
952
- return;
953
- }
954
- if (key === "score") {
955
- setRatingStars(value);
956
- } else if (key === "description") {
957
- setRatingComment(value);
958
- }
959
- setHasReviewed(true);
960
- setIsLoading(false);
961
- onHandleRateSuccess(true);
962
- } catch (err) {
963
- setIsLoading(false);
964
- onHandleRateSuccess(false, String(err));
965
- }
966
- };
967
- return {
968
- handleRate,
969
- ratingStars: state.ratingStars,
970
- ratingThumbs: state.ratingThumbs,
971
- ratingComment: state.ratingComment,
972
- isLoading,
973
- hasReviewed
974
- };
975
- }
976
-
977
- // src/actions/alquimia.action.ts
978
- import { randomUUID } from "crypto";
979
- import { cookies } from "next/headers";
980
- async function initConversation(reset, topicId) {
981
- const cookieStore = await cookies();
982
- if (!topicId) {
983
- let conversationId = randomUUID().toString();
984
- const alquimia_session = cookieStore.get("alquimia-session");
985
- if (!alquimia_session || reset) {
986
- cookieStore.set("alquimia-session", conversationId);
987
- } else {
988
- conversationId = alquimia_session.value;
989
- }
990
- return conversationId;
991
- }
992
- let conversationsMap = {};
993
- const existingConversations = cookieStore.get("alquimia-sessions");
994
- if (existingConversations) {
995
- try {
996
- const decodedValue = decodeURIComponent(existingConversations.value);
997
- conversationsMap = JSON.parse(decodedValue);
998
- } catch (e) {
999
- console.error("Error parsing conversations cookie:", e);
1000
- conversationsMap = {};
1001
- }
1002
- }
1003
- if (!conversationsMap[topicId] || reset) {
1004
- conversationsMap[topicId] = randomUUID().toString();
1005
- }
1006
- cookieStore.set("alquimia-sessions", JSON.stringify(conversationsMap));
1007
- return conversationsMap[topicId];
1008
- }
1009
-
1010
- // src/actions/baseApi.action.ts
1011
- async function createResource(config, payload) {
1012
- try {
1013
- const headers = generateHeaders(config);
1014
- const response = await fetch(`${config.baseUrl}${config.route}`, {
1015
- method: "POST",
1016
- headers,
1017
- body: JSON.stringify(payload),
1018
- cache: "default"
1019
- });
1020
- if (!response.ok) {
1021
- const error = await response.json();
1022
- return {
1023
- success: false,
1024
- error: {
1025
- message: error.message || `Server returned ${response.status}`,
1026
- code: response.status.toString(),
1027
- details: {
1028
- status: response.status,
1029
- statusText: response.statusText
1030
- }
1031
- }
1032
- };
1033
- }
1034
- return {
1035
- success: true,
1036
- data: await response.json()
1037
- };
1038
- } catch (error) {
1039
- throw new Error("Failed to create resource");
1040
- }
1041
- }
1042
- async function readResource(config, id) {
1043
- try {
1044
- const headers = generateHeaders(config);
1045
- const url = id ? `${config.baseUrl}${config.route}/${id}` : `${config.baseUrl}${config.route}`;
1046
- const response = await fetch(url, {
1047
- method: "GET",
1048
- headers,
1049
- cache: "default"
1050
- });
1051
- if (!response.ok) {
1052
- const error = await response.json();
1053
- return {
1054
- success: false,
1055
- error: {
1056
- message: error.message || `Server returned ${response.status}`,
1057
- code: response.status.toString(),
1058
- details: {
1059
- status: response.status,
1060
- statusText: response.statusText
1061
- }
1062
- }
1063
- };
1064
- }
1065
- const contentType = response.headers.get("content-type");
1066
- if (contentType?.includes("application/json")) {
1067
- return {
1068
- success: true,
1069
- data: await response.json(),
1070
- contentType: contentType || void 0
1071
- };
1072
- }
1073
- const arrayBuffer = await response.arrayBuffer();
1074
- if (contentType?.includes("octet-stream") && isTextContent(arrayBuffer)) {
1075
- return {
1076
- success: true,
1077
- data: arrayBuffer,
1078
- contentType: "text/plain"
1079
- };
1080
- }
1081
- return {
1082
- success: true,
1083
- data: await response.json(),
1084
- contentType: contentType || void 0
1085
- };
1086
- } catch (error) {
1087
- throw new Error("Failed to read resource");
1088
- }
1089
- }
1090
- async function updateResource(config, id, data) {
1091
- try {
1092
- const headers = generateHeaders(config);
1093
- const response = await fetch(`${config.baseUrl}${config.route}/${id}`, {
1094
- method: "PUT",
1095
- headers,
1096
- body: JSON.stringify(data),
1097
- cache: "default"
1098
- });
1099
- if (!response.ok) {
1100
- const error = await response.json();
1101
- return {
1102
- success: false,
1103
- error: {
1104
- message: error.message || `Server returned ${response.status}`,
1105
- code: response.status.toString(),
1106
- details: {
1107
- status: response.status,
1108
- statusText: response.statusText
1109
- }
1110
- }
1111
- };
1112
- }
1113
- return {
1114
- success: true,
1115
- data: await response.json()
1116
- };
1117
- } catch (error) {
1118
- throw new Error("Failed to update resource");
1119
- }
1120
- }
1121
- async function deleteResource(config, id) {
1122
- try {
1123
- const headers = generateHeaders(config);
1124
- const response = await fetch(`${config.baseUrl}${config.route}/${id}`, {
1125
- method: "DELETE",
1126
- headers,
1127
- cache: "default"
1128
- });
1129
- if (!response.ok) {
1130
- const error = await response.json();
1131
- return {
1132
- success: false,
1133
- error: {
1134
- message: error.message || `Server returned ${response.status}`,
1135
- code: response.status.toString(),
1136
- details: {
1137
- status: response.status,
1138
- statusText: response.statusText
1139
- }
1140
- }
1141
- };
1142
- }
1143
- return {
1144
- success: true
1145
- };
1146
- } catch (error) {
1147
- throw new Error("Failed to delete resource");
1148
- }
1149
- }
1150
-
1151
- // src/types/type.ts
1152
- var ToolFactory = class {
1153
- constructor(toolSpec) {
1154
- this.toolSpec = null;
1155
- this.toolSpec = toolSpec;
1156
- }
1157
- static createTool(toolSpec) {
1158
- return toolSpec;
1159
- }
1160
- };
1161
- export {
1162
- AlquimiaRatingsProvider,
1163
- alquimia_sdk_default as AlquimiaSDK,
1164
- AlquimiaWhisperProvider,
1165
- Button,
1166
- Card,
1167
- CharacterizationProvider,
1168
- Code,
1169
- ElasticLoggerProvider,
1170
- ElevenLabsWhisperProvider,
1171
- GenerativeProvider,
1172
- LoggerProvider,
1173
- OpenAIAnalyzeCharProvider,
1174
- OpenAIStableDiffusionProvider,
1175
- OpenAIWhisperProvider,
1176
- RatingsProvider,
1177
- SessionProvider,
1178
- StabilityProvider,
1179
- StableDiffusionProvider,
1180
- ToolFactory,
1181
- WhisperProvider,
1182
- createMessageId,
1183
- createResource,
1184
- defineAssistantId,
1185
- deleteResource,
1186
- formatTimeWithUnit,
1187
- generateHeaders,
1188
- generateTranslatePrompt,
1189
- getCookies,
1190
- getQueryParam,
1191
- getTopicSessionId,
1192
- initConversation,
1193
- isTextContent,
1194
- parseConversationsMapCookie,
1195
- readResource,
1196
- serializeAxiosError,
1197
- updateResource,
1198
- useAlquimia,
1199
- useRatings,
1200
- useSessionContext
1201
- };
1202
- //# sourceMappingURL=index.mjs.map