@alquimia-ai/tools 1.0.13 → 1.0.16

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.
@@ -1,107 +0,0 @@
1
-
2
- import { useState, useReducer } from "react";
3
- import { RatingData } from "../types/type";
4
- import { getTopicSessionId } from "../utils/utils";
5
-
6
- interface RatingState {
7
- ratingStars: number;
8
- ratingThumbs: "thumbsUp" | "thumbsDown" | "";
9
- ratingComment: string;
10
- }
11
-
12
- type RatingAction =
13
- | { type: "SET_RATING_STARS"; payload: number }
14
- | { type: "SET_RATING_THUMBS"; payload: "thumbsUp" | "thumbsDown" | "" }
15
- | { type: "SET_RATING_COMMENT"; payload: string };
16
-
17
- const initialState: RatingState = {
18
- ratingStars: 0,
19
- ratingThumbs: "",
20
- ratingComment: "",
21
- };
22
-
23
- function ratingReducer(state: RatingState, action: RatingAction): RatingState {
24
- switch (action.type) {
25
- case "SET_RATING_STARS":
26
- return { ...state, ratingStars: action.payload };
27
- case "SET_RATING_THUMBS":
28
- return { ...state, ratingThumbs: action.payload };
29
- case "SET_RATING_COMMENT":
30
- return { ...state, ratingComment: action.payload };
31
- default:
32
- return state;
33
- }
34
- }
35
-
36
- interface UseRatingsParams {
37
- assistantId: string;
38
- topicId: string;
39
- sendRating: (ratingData: RatingData) => Promise<any>;
40
- onError?: (componentName: string, error: Error) => void;
41
- }
42
-
43
-
44
- export function useRatings({ assistantId, sendRating, topicId }: UseRatingsParams) {
45
- const [isLoading, setIsLoading] = useState<boolean>(false);
46
- const [hasReviewed, setHasReviewed] = useState<boolean>(false);
47
- const [state, dispatch] = useReducer(ratingReducer, initialState);
48
-
49
- const setRatingStars = (rating: number) => {
50
- dispatch({ type: "SET_RATING_STARS", payload: rating });
51
- };
52
-
53
- const setRatingThumbs = (rating: "thumbsUp" | "thumbsDown" | "") => {
54
- dispatch({ type: "SET_RATING_THUMBS", payload: rating });
55
- };
56
-
57
- const setRatingComment = (comment: string) => {
58
- dispatch({ type: "SET_RATING_COMMENT", payload: comment });
59
- };
60
-
61
- const thumbsScore = (value: string) => {
62
- return value === "thumbsUp" ? 5 : value === "thumbsDown" ? 0 : 0;
63
- }
64
-
65
- const handleRate = async (key: string, value: any | string, onHandleRateSuccess: (success: boolean, err?: string) => void) => {
66
- setIsLoading(true);
67
- const sessionId = getTopicSessionId(topicId);
68
-
69
- const ratingObj: RatingData = {
70
- topicId: parseInt(topicId),
71
- sessionId: sessionId || "",
72
- assistantId: assistantId,
73
- score: key === "score" ? value : thumbsScore(value),
74
- description: key === "description" ? value : state.ratingComment,
75
- };
76
-
77
- try {
78
- const response = await sendRating(ratingObj);
79
- if (!response.success) {
80
- setIsLoading(false);
81
- onHandleRateSuccess(false, response.error.message);
82
- return;
83
- }
84
-
85
- if (key === "score") {
86
- setRatingStars(value);
87
- } else if (key === "description") {
88
- setRatingComment(value);
89
- }
90
- setHasReviewed(true);
91
- setIsLoading(false);
92
- onHandleRateSuccess(true);
93
- } catch (err) {
94
- setIsLoading(false);
95
- onHandleRateSuccess(false, String(err));
96
- }
97
- };
98
-
99
- return {
100
- handleRate,
101
- ratingStars: state.ratingStars,
102
- ratingThumbs: state.ratingThumbs,
103
- ratingComment: state.ratingComment,
104
- isLoading,
105
- hasReviewed
106
- };
107
- }
@@ -1,97 +0,0 @@
1
- import { WhisperProvider, RatingsProvider } from "./providers";
2
- import { RatingData } from "../types/type";
3
- import axios from "axios";
4
-
5
- class AlquimiaWhisperProvider extends WhisperProvider {
6
- constructor(config: { baseURL: string; ttsRoute: string; sttRoute: string }) {
7
- super(config);
8
- }
9
-
10
- async textToSpeech(text: string): Promise<any> {
11
- const axiosClient = axios.create({
12
- baseURL: this.config.baseURL,
13
- });
14
-
15
- try {
16
- const response = await axiosClient.post(
17
- this.config.ttsRoute,
18
- {
19
- text: text,
20
- },
21
- { responseType: "blob" }
22
- );
23
-
24
- return response.data;
25
- } catch (error) {
26
- console.error("Error converting text to speech:", error);
27
- throw error;
28
- }
29
- }
30
-
31
- async speechToText(audio: string): Promise<string> {
32
- const axiosClient = axios.create({
33
- baseURL: this.config.baseURL,
34
- });
35
-
36
- try {
37
- const response = await axiosClient.post(this.config.sttRoute, {
38
- audio: audio,
39
- });
40
-
41
- return response.data;
42
- } catch (error) {
43
- console.error("Error converting speech to text:", error);
44
- throw error;
45
- }
46
- }
47
- }
48
-
49
- class AlquimiaRatingsProvider extends RatingsProvider {
50
- constructor(config: { baseUrl: string; route: string; token: string; headers?: Record<string, string> }) {
51
- super(config);
52
- }
53
-
54
- async rate(data: RatingData): Promise<Record<string, any>> {
55
- const path = `${this.config.baseUrl}${this.config.route}`;
56
- try {
57
- let response;
58
- const headers = {
59
- Authorization: `Bearer ${this.config.token}`,
60
- "Content-Type": "application/json",
61
- ...this.config.headers || {}
62
- };
63
-
64
- response = await axios.post(`${path}`, data, { headers });
65
- return {
66
- success: true,
67
- data: response.data
68
- }
69
- } catch (error) {
70
- if (axios.isAxiosError(error)) {
71
- return {
72
- success: false,
73
- error: {
74
- message: error.message,
75
- response: {
76
- status: error.response?.status,
77
- data: error.response?.data
78
- },
79
- details: error.response?.data
80
- }
81
- };
82
- }
83
-
84
- return {
85
- success: false,
86
- error: {
87
- message: error instanceof Error ? error.message : 'Unknown error occurred',
88
- response: {
89
- status: 500
90
- }
91
- }
92
- };
93
- }
94
- }
95
- }
96
-
97
- export { AlquimiaWhisperProvider, AlquimiaRatingsProvider };
@@ -1,82 +0,0 @@
1
- import { LoggerProvider } from "./providers";
2
- import pino from "pino";
3
-
4
- interface ElasticLoggerConfig {
5
- endpoint: string;
6
- username: string;
7
- password: string;
8
- index?: string;
9
- esVersion?: number;
10
- flushBytes?: number;
11
- }
12
-
13
- class ElasticLoggerProvider extends LoggerProvider {
14
- private logger: pino.Logger;
15
-
16
- private constructor(config: ElasticLoggerConfig) {
17
- super(config);
18
- this.logger = console as any;
19
- }
20
-
21
- public static async create(config: ElasticLoggerConfig): Promise<ElasticLoggerProvider> {
22
- const provider = new ElasticLoggerProvider(config);
23
- await provider.initialize(config);
24
- return provider;
25
- }
26
-
27
- private async initialize(config: ElasticLoggerConfig) {
28
- if (typeof window === 'undefined') {
29
- const [pinoElastic] = await Promise.all([
30
- import('pino-elasticsearch')
31
- ]);
32
-
33
- const streamToElastic = pinoElastic.default({
34
- index: config.index || "logs-index",
35
- node: config.endpoint,
36
- esVersion: config.esVersion || 7,
37
- flushBytes: config.flushBytes || 1000,
38
- auth: {
39
- username: config.username || "",
40
- password: config.password || "",
41
- },
42
- tls: {
43
- rejectUnauthorized: false,
44
- },
45
- op_type: 'create',
46
- });
47
-
48
- streamToElastic.on('error', (err) => {
49
- console.error('Elasticsearch stream error:', err);
50
- });
51
-
52
- streamToElastic.on('insertError', (err) => {
53
- console.error('Elasticsearch insert error:', err);
54
- });
55
-
56
- streamToElastic.on('insert', () => {
57
- console.log('Successfully sent log to Elasticsearch');
58
- });
59
-
60
-
61
- this.logger = pino({
62
- level: 'info',
63
- timestamp: () => `,"time":"${new Date().toISOString()}"`,
64
- }, streamToElastic);
65
- }
66
- }
67
-
68
- logInfo(message: string, data?: Record<string, any>): void {
69
- this.logger.info({ ...data }, message);
70
- }
71
-
72
- logError(message: string, error: Error, data?: Record<string, any>): void {
73
- const errorDetails = {
74
- message: error.message,
75
- name: error.name,
76
- stack: error.stack,
77
- };
78
- this.logger.error({ error, ...data, ...errorDetails }, message);
79
- }
80
- }
81
-
82
- export { ElasticLoggerProvider };
@@ -1,58 +0,0 @@
1
- import { WhisperProvider } from "./providers";
2
- import { ElevenLabsClient, ElevenLabs } from "elevenlabs";
3
- import axios from "axios";
4
-
5
- const requestSpecs = {
6
- optimize_streaming_latency: ElevenLabs.OptimizeStreamingLatency.Zero,
7
- output_format: ElevenLabs.OutputFormat.Mp344100128,
8
- model_id: "eleven_multilingual_v1",
9
- language: "es",
10
- voice_settings: {
11
- stability: 0.1,
12
- similarity_boost: 0.15,
13
- style: 0.2,
14
- },
15
- };
16
-
17
- class ElevenLabsWhisperProvider extends WhisperProvider {
18
- private client: ElevenLabsClient;
19
-
20
- constructor(config: { apiKey: string, voiceId: string, baseURL: string }) {
21
- super(config);
22
- this.client = new ElevenLabsClient(config);
23
- }
24
-
25
- async speechToText(audio: string): Promise<string> {
26
- return '';
27
- }
28
-
29
- async textToSpeech(text: string): Promise<any> {
30
-
31
- const axiosClient = axios.create({
32
- baseURL: this.config.baseURL,
33
- headers: {
34
- Accept: "audio/mpeg",
35
- "Content-Type": "application/json",
36
- "Xi-Api-Key": this.config.apiKey,
37
- },
38
- });
39
-
40
- try {
41
- const response = await axiosClient.post(
42
- `/v1/text-to-speech/${this.config.voiceId}`,
43
- {
44
- text: text,
45
- ...requestSpecs,
46
- },
47
- { responseType: 'blob' }
48
- );
49
-
50
- return response.data;
51
- } catch (error) {
52
- console.error('Error converting text to speech:', error);
53
- throw error;
54
- }
55
- }
56
- }
57
-
58
- export { ElevenLabsWhisperProvider };
@@ -1,7 +0,0 @@
1
- export * from "./providers";
2
- export * from "./alquimia";
3
- export * from "./providers";
4
- export * from "./openai";
5
- export * from "./stability";
6
- export * from "./eleven-labs";
7
- export * from "./elastic-search";
@@ -1,69 +0,0 @@
1
- import { generateTranslatePrompt } from "../utils/utils";
2
- import { StableDiffusionProvider, WhisperProvider, CharacterizationProvider } from "./providers";
3
- import OpenAI from "openai";
4
-
5
- class OpenAIWhisperProvider extends WhisperProvider {
6
- async textToSpeech(text: string): Promise<Blob> {
7
- return new Blob();
8
- }
9
-
10
- async speechToText(audio: string): Promise<string> {
11
- return '';
12
- }
13
- }
14
- class OpenAIAnalyzeCharProvider extends CharacterizationProvider {
15
- private client : any
16
-
17
- constructor(config:Record<string,any>){
18
- super(config)
19
- this.client = new OpenAI({
20
- apiKey: config.apiKey
21
- })
22
- }
23
-
24
- async analyzeCharacterization(text: string): Promise<Record<string, any>> {
25
- const prompt = generateTranslatePrompt(text);
26
-
27
- const response = await this.client.chat.completions.create({
28
- model: 'gpt-4o-mini',
29
- messages: [
30
- { role: 'system', content: 'You are a helpful assistant.' },
31
- { role: 'user', content: prompt },
32
- ],
33
- max_tokens: 150,
34
- temperature: 0.7,
35
- });
36
-
37
- const arrangedText = response.choices[0].message.content.trim();
38
-
39
- try {
40
- const arrangedObject = JSON.parse(arrangedText);
41
- return arrangedObject;
42
- } catch (error) {
43
- throw new Error('Failed to parse the response from OpenAI');
44
- }
45
- }
46
- }
47
-
48
- class OpenAIStableDiffusionProvider extends StableDiffusionProvider {
49
- private client : any
50
-
51
- constructor(config:Record<string,any>){
52
- super(config)
53
- this.client = new OpenAI({
54
- apiKey: config.apiKey
55
- })
56
- }
57
-
58
- async generateImage(query: string): Promise<string> {
59
- const response = await this.client.images.generate({
60
- model: "dall-e-3",
61
- prompt: query,
62
- n: 1,
63
- size: "1024x1024",
64
- });
65
- return response.data[0].url;
66
- }
67
- }
68
-
69
- export { OpenAIWhisperProvider, OpenAIStableDiffusionProvider, OpenAIAnalyzeCharProvider };
@@ -1,61 +0,0 @@
1
-
2
- export abstract class GenerativeProvider {
3
- private config: Record<string, any>;
4
-
5
- constructor(config: Record<string, any>) {
6
- this.config = config;
7
- }
8
- }
9
-
10
- export abstract class WhisperProvider {
11
- protected config: Record<string, any>;
12
-
13
- constructor(config: Record<string, any>) {
14
- this.config = config;
15
- }
16
-
17
- abstract textToSpeech(text: string): Promise<Blob>
18
-
19
- abstract speechToText(audio: string): Promise<string>
20
- }
21
-
22
- export abstract class StableDiffusionProvider {
23
- protected config: Record<string, any>;
24
-
25
- constructor(config: Record<string, any>) {
26
- this.config = config;
27
- }
28
-
29
- abstract generateImage(query: string): Promise<string>
30
- }
31
-
32
- export abstract class CharacterizationProvider {
33
- protected config: Record<string, any>;
34
-
35
- constructor(config: Record<string, any>) {
36
- this.config = config;
37
- }
38
-
39
- abstract analyzeCharacterization(text: string): Promise<Record<string, any>>
40
- }
41
-
42
- export abstract class RatingsProvider {
43
- protected config: Record<string, any>;
44
-
45
- constructor(config: Record<string, any>) {
46
- this.config = config;
47
- }
48
-
49
- abstract rate(data: Record<string, any>): Promise<Record<string, any>>;
50
- }
51
-
52
- export abstract class LoggerProvider {
53
- protected config: Record<string, any>;
54
-
55
- constructor(config: Record<string, any>) {
56
- this.config = config;
57
- }
58
-
59
- abstract logInfo(message: string, data?: Record<string, any>): void;
60
- abstract logError(message: string, error: Error, data?: Record<string, any>): void;
61
- }
@@ -1,38 +0,0 @@
1
- import { StableDiffusionProvider } from "./providers";
2
- import { Buffer } from "buffer/";
3
- import axios from "axios";
4
-
5
- class StabilityProvider extends StableDiffusionProvider {
6
- constructor(config: Record<string, any>) {
7
- super(config);
8
- }
9
-
10
- async generateImage(query: string): Promise<string> {
11
- const payload = {
12
- prompt: "query",
13
- output_format: "webp",
14
- };
15
-
16
- const response = await axios.postForm(
17
- `https://api.stability.ai/v2beta/stable-image/generate/ultra`,
18
- axios.toFormData(payload, new FormData()),
19
- {
20
- validateStatus: undefined,
21
- responseType: "arraybuffer",
22
- headers: {
23
- Authorization: `Bearer ${this.config.apiKey}`,
24
- Accept: "image/*",
25
- },
26
- }
27
- );
28
-
29
- if (response.status === 200) {
30
- const base64Image = Buffer.from(response.data).toString("base64");
31
- return `data:image/webp;base64,${base64Image}`;
32
- } else {
33
- throw new Error(`${response.status}: ${response.data.toString()}`);
34
- }
35
- }
36
- }
37
-
38
- export { StabilityProvider };
@@ -1,33 +0,0 @@
1
- export interface CharacterizationState {
2
- sessionId: string | null;
3
- characterizationData: any;
4
- }
5
-
6
- export type CharacterizationAction =
7
- | {
8
- type: "SET_SESSION";
9
- payload: { sessionId: string; characterizationData: any };
10
- }
11
- | { type: "CLEAR_SESSION" };
12
-
13
- export const characterizationReducer = (
14
- state: CharacterizationState,
15
- action: CharacterizationAction
16
- ): CharacterizationState => {
17
- switch (action.type) {
18
- case "SET_SESSION":
19
- return {
20
- ...state,
21
- sessionId: action.payload.sessionId,
22
- characterizationData: action.payload.characterizationData,
23
- };
24
- case "CLEAR_SESSION":
25
- return {
26
- ...state,
27
- sessionId: null,
28
- characterizationData: null,
29
- };
30
- default:
31
- return state;
32
- }
33
- };