@drax/ai-back 3.41.0 → 3.43.0

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 (117) hide show
  1. package/dist/agents/DraxAgent.js +3 -1
  2. package/dist/config/ElevenLabsTTSConfig.js +10 -0
  3. package/dist/controllers/AICrudController.js +1 -1
  4. package/dist/controllers/AIGenericController.js +23 -1
  5. package/dist/controllers/DraxAgentController.js +22 -0
  6. package/dist/controllers/TTSGenericController.js +61 -0
  7. package/dist/factory/ElevenLabsTTSProviderFactory.js +13 -0
  8. package/dist/factory/TTSProviderFactory.js +27 -0
  9. package/dist/factory/ai/AiProviderFactory.js +30 -0
  10. package/dist/factory/ai/DeepSeekAiProviderFactory.js +14 -0
  11. package/dist/factory/ai/GoogleAiProviderFactory.js +14 -0
  12. package/dist/factory/ai/OllamaAiProviderFactory.js +14 -0
  13. package/dist/factory/ai/OpenAiProviderFactory.js +14 -0
  14. package/dist/factory/tts/ElevenLabsTTSProviderFactory.js +13 -0
  15. package/dist/factory/tts/TTSProviderFactory.js +27 -0
  16. package/dist/index.js +23 -13
  17. package/dist/interfaces/ITTSProvider.js +1 -0
  18. package/dist/permissions/TTSPermissions.js +6 -0
  19. package/dist/providers/ElevenLabsTTSProvider.js +108 -0
  20. package/dist/providers/ai/DeepSeekAiProvider.js +34 -0
  21. package/dist/providers/ai/GoogleAiProvider.js +370 -0
  22. package/dist/providers/ai/OllamaAiProvider.js +345 -0
  23. package/dist/providers/ai/OpenAiProvider.js +305 -0
  24. package/dist/providers/tts/ElevenLabsTTSProvider.js +108 -0
  25. package/dist/routes/TTSRoutes.js +8 -0
  26. package/dist/schemas/TTSRequestSchema.js +24 -0
  27. package/dist/services/PromptAudioService.js +68 -0
  28. package/dist/services/TTSGenericService.js +21 -0
  29. package/package.json +3 -3
  30. package/src/agents/DraxAgent.ts +3 -1
  31. package/src/config/ElevenLabsTTSConfig.ts +13 -0
  32. package/src/controllers/AICrudController.ts +1 -1
  33. package/src/controllers/AIGenericController.ts +25 -1
  34. package/src/controllers/DraxAgentController.ts +24 -0
  35. package/src/controllers/TTSGenericController.ts +70 -0
  36. package/src/factory/{AiProviderFactory.ts → ai/AiProviderFactory.ts} +3 -3
  37. package/src/factory/ai/DeepSeekAiProviderFactory.ts +27 -0
  38. package/src/factory/{GoogleAiProviderFactory.ts → ai/GoogleAiProviderFactory.ts} +4 -4
  39. package/src/factory/{OllamaAiProviderFactory.ts → ai/OllamaAiProviderFactory.ts} +4 -4
  40. package/src/factory/{OpenAiProviderFactory.ts → ai/OpenAiProviderFactory.ts} +4 -4
  41. package/src/factory/tts/ElevenLabsTTSProviderFactory.ts +26 -0
  42. package/src/factory/tts/TTSProviderFactory.ts +42 -0
  43. package/src/index.ts +60 -11
  44. package/src/interfaces/IAIProvider.ts +38 -1
  45. package/src/interfaces/IDraxAgent.ts +4 -0
  46. package/src/interfaces/ITTSProvider.ts +47 -0
  47. package/src/permissions/AIPermissions.ts +0 -1
  48. package/src/permissions/TTSPermissions.ts +8 -0
  49. package/src/providers/{DeepSeekProvider.ts → ai/DeepSeekAiProvider.ts} +5 -5
  50. package/src/providers/{GoogleAiProvider.ts → ai/GoogleAiProvider.ts} +6 -3
  51. package/src/providers/{OllamaAiProvider.ts → ai/OllamaAiProvider.ts} +6 -3
  52. package/src/providers/{OpenAiProvider.ts → ai/OpenAiProvider.ts} +6 -3
  53. package/src/providers/tts/ElevenLabsTTSProvider.ts +132 -0
  54. package/src/routes/TTSRoutes.ts +13 -0
  55. package/src/schemas/TTSRequestSchema.ts +38 -0
  56. package/src/services/PromptAudioService.ts +87 -0
  57. package/src/services/TTSGenericService.ts +41 -0
  58. package/test/DeepSeekProvider.test.ts +4 -4
  59. package/test/DraxAgent.test.ts +64 -0
  60. package/test/PromptAudioService.test.ts +115 -0
  61. package/tsconfig.tsbuildinfo +1 -1
  62. package/types/agents/DraxAgent.d.ts.map +1 -1
  63. package/types/config/ElevenLabsTTSConfig.d.ts +10 -0
  64. package/types/config/ElevenLabsTTSConfig.d.ts.map +1 -0
  65. package/types/controllers/AIGenericController.d.ts.map +1 -1
  66. package/types/controllers/DraxAgentController.d.ts.map +1 -1
  67. package/types/controllers/TTSGenericController.d.ts +11 -0
  68. package/types/controllers/TTSGenericController.d.ts.map +1 -0
  69. package/types/factory/ElevenLabsTTSProviderFactory.d.ts +8 -0
  70. package/types/factory/ElevenLabsTTSProviderFactory.d.ts.map +1 -0
  71. package/types/factory/TTSProviderFactory.d.ts +15 -0
  72. package/types/factory/TTSProviderFactory.d.ts.map +1 -0
  73. package/types/factory/ai/AiProviderFactory.d.ts +8 -0
  74. package/types/factory/ai/AiProviderFactory.d.ts.map +1 -0
  75. package/types/factory/ai/DeepSeekAiProviderFactory.d.ts +8 -0
  76. package/types/factory/ai/DeepSeekAiProviderFactory.d.ts.map +1 -0
  77. package/types/factory/ai/GoogleAiProviderFactory.d.ts +8 -0
  78. package/types/factory/ai/GoogleAiProviderFactory.d.ts.map +1 -0
  79. package/types/factory/ai/OllamaAiProviderFactory.d.ts +8 -0
  80. package/types/factory/ai/OllamaAiProviderFactory.d.ts.map +1 -0
  81. package/types/factory/ai/OpenAiProviderFactory.d.ts +8 -0
  82. package/types/factory/ai/OpenAiProviderFactory.d.ts.map +1 -0
  83. package/types/factory/tts/ElevenLabsTTSProviderFactory.d.ts +8 -0
  84. package/types/factory/tts/ElevenLabsTTSProviderFactory.d.ts.map +1 -0
  85. package/types/factory/tts/TTSProviderFactory.d.ts +15 -0
  86. package/types/factory/tts/TTSProviderFactory.d.ts.map +1 -0
  87. package/types/index.d.ts +26 -12
  88. package/types/index.d.ts.map +1 -1
  89. package/types/interfaces/IAIProvider.d.ts +32 -1
  90. package/types/interfaces/IAIProvider.d.ts.map +1 -1
  91. package/types/interfaces/IDraxAgent.d.ts +3 -1
  92. package/types/interfaces/IDraxAgent.d.ts.map +1 -1
  93. package/types/interfaces/ITTSProvider.d.ts +39 -0
  94. package/types/interfaces/ITTSProvider.d.ts.map +1 -0
  95. package/types/permissions/TTSPermissions.d.ts +6 -0
  96. package/types/permissions/TTSPermissions.d.ts.map +1 -0
  97. package/types/providers/ElevenLabsTTSProvider.d.ts +38 -0
  98. package/types/providers/ElevenLabsTTSProvider.d.ts.map +1 -0
  99. package/types/providers/ai/DeepSeekAiProvider.d.ts +24 -0
  100. package/types/providers/ai/DeepSeekAiProvider.d.ts.map +1 -0
  101. package/types/providers/ai/GoogleAiProvider.d.ts +63 -0
  102. package/types/providers/ai/GoogleAiProvider.d.ts.map +1 -0
  103. package/types/providers/ai/OllamaAiProvider.d.ts +78 -0
  104. package/types/providers/ai/OllamaAiProvider.d.ts.map +1 -0
  105. package/types/providers/ai/OpenAiProvider.d.ts +97 -0
  106. package/types/providers/ai/OpenAiProvider.d.ts.map +1 -0
  107. package/types/providers/tts/ElevenLabsTTSProvider.d.ts +38 -0
  108. package/types/providers/tts/ElevenLabsTTSProvider.d.ts.map +1 -0
  109. package/types/routes/TTSRoutes.d.ts +4 -0
  110. package/types/routes/TTSRoutes.d.ts.map +1 -0
  111. package/types/schemas/TTSRequestSchema.d.ts +37 -0
  112. package/types/schemas/TTSRequestSchema.d.ts.map +1 -0
  113. package/types/services/PromptAudioService.d.ts +9 -0
  114. package/types/services/PromptAudioService.d.ts.map +1 -0
  115. package/types/services/TTSGenericService.d.ts +17 -0
  116. package/types/services/TTSGenericService.d.ts.map +1 -0
  117. package/src/factory/DeepSeekProviderFactory.ts +0 -27
@@ -0,0 +1,345 @@
1
+ import { toJSONSchema } from "zod";
2
+ import PromptAudioService from "../../services/PromptAudioService.js";
3
+ class OllamaAiProvider {
4
+ constructor(baseUrl, model, visionModel, embeddingModel, aiLogService) {
5
+ if (!baseUrl) {
6
+ throw new Error("Ollama AI baseUrl required");
7
+ }
8
+ if (!model) {
9
+ throw new Error("Ollama AI model required");
10
+ }
11
+ this._baseUrl = baseUrl.replace(/\/+$/, "");
12
+ this._model = model;
13
+ this._visionModel = visionModel;
14
+ this._embeddingModel = embeddingModel;
15
+ this._aiLogService = aiLogService;
16
+ }
17
+ get model() {
18
+ if (!this._model) {
19
+ throw new Error("Ollama AI model not found");
20
+ }
21
+ return this._model;
22
+ }
23
+ get visionModel() {
24
+ return this._visionModel;
25
+ }
26
+ get embeddingModel() {
27
+ return this._embeddingModel ?? this.model;
28
+ }
29
+ async post(path, body) {
30
+ const response = await fetch(`${this._baseUrl}${path}`, {
31
+ method: "POST",
32
+ headers: {
33
+ "Content-Type": "application/json",
34
+ },
35
+ body: JSON.stringify(body),
36
+ });
37
+ if (!response.ok) {
38
+ const errorText = await response.text();
39
+ throw new Error(`Ollama AI request failed (${response.status}): ${errorText}`);
40
+ }
41
+ return await response.json();
42
+ }
43
+ async buildUserMessage(input) {
44
+ if (input.userContent && input.userContent.length > 0) {
45
+ return await this.mapContentPartsToMessage(input.userContent);
46
+ }
47
+ if (input.userImages && input.userImages.length > 0) {
48
+ return {
49
+ role: "user",
50
+ content: input.userInput ?? "",
51
+ images: await Promise.all(input.userImages.map(image => this.imageUrlToBase64(image.url))),
52
+ };
53
+ }
54
+ return {
55
+ role: "user",
56
+ content: input.userInput ?? "",
57
+ };
58
+ }
59
+ async mapContentPartsToMessage(content, role = "user") {
60
+ const text = [];
61
+ const images = [];
62
+ for (const part of content) {
63
+ if (part.type === "text") {
64
+ text.push(part.text);
65
+ continue;
66
+ }
67
+ images.push(await this.imageUrlToBase64(part.imageUrl));
68
+ }
69
+ return {
70
+ role,
71
+ content: text.join("\n"),
72
+ ...(images.length > 0 ? { images } : {}),
73
+ };
74
+ }
75
+ async imageUrlToBase64(url) {
76
+ const dataUrlMatch = url.match(/^data:[^;,]+;base64,(.+)$/);
77
+ if (dataUrlMatch) {
78
+ return dataUrlMatch[1];
79
+ }
80
+ const response = await fetch(url);
81
+ if (!response.ok) {
82
+ throw new Error(`Ollama AI image request failed (${response.status}): ${url}`);
83
+ }
84
+ const buffer = Buffer.from(await response.arrayBuffer());
85
+ return buffer.toString("base64");
86
+ }
87
+ async mapHistory(history = []) {
88
+ const messages = [];
89
+ for (const message of history) {
90
+ if (typeof message.content === "string") {
91
+ messages.push({
92
+ role: message.role,
93
+ content: message.content,
94
+ });
95
+ continue;
96
+ }
97
+ messages.push(await this.mapContentPartsToMessage(message.content, message.role));
98
+ }
99
+ return messages;
100
+ }
101
+ hasImageInput(input) {
102
+ if (input.userImages && input.userImages.length > 0) {
103
+ return true;
104
+ }
105
+ if (input.userContent?.some(part => part.type === 'image')) {
106
+ return true;
107
+ }
108
+ return input.history?.some(message => Array.isArray(message.content) && message.content.some(part => part.type === 'image')) ?? false;
109
+ }
110
+ serializePromptInput(input, systemPrompt) {
111
+ return JSON.stringify({
112
+ systemPrompt,
113
+ history: input.history,
114
+ userInput: input.userInput,
115
+ userContent: input.userContent,
116
+ memory: input.memory,
117
+ knowledgeBase: input.knowledgeBase,
118
+ tools: input.tools?.map(tool => ({
119
+ name: tool.name,
120
+ description: tool.description,
121
+ parameters: tool.parameters,
122
+ })),
123
+ });
124
+ }
125
+ serializePromptOutput(output) {
126
+ if (typeof output === "string") {
127
+ return output;
128
+ }
129
+ if (output === null || output === undefined) {
130
+ return undefined;
131
+ }
132
+ return JSON.stringify(output);
133
+ }
134
+ buildLogPayload(input, params) {
135
+ return {
136
+ provider: "ollamaai",
137
+ model: params.model,
138
+ operationTitle: input.operationTitle,
139
+ operationGroup: input.operationGroup,
140
+ ip: input.ip,
141
+ userAgent: input.userAgent,
142
+ input: this.serializePromptInput(input, params.systemPrompt),
143
+ inputImages: input.userImages?.map(image => ({
144
+ url: image.url,
145
+ })) ?? input.userContent
146
+ ?.filter(part => part.type === "image")
147
+ .map(part => ({
148
+ url: part.imageUrl,
149
+ })),
150
+ inputFiles: input.inputFiles,
151
+ inputTokens: params.inputTokens,
152
+ outputTokens: params.outputTokens,
153
+ tokens: params.tokens,
154
+ startedAt: params.startedAt,
155
+ endedAt: params.endedAt,
156
+ responseTime: params.endedAt ? `${params.endedAt.getTime() - params.startedAt.getTime()}ms` : undefined,
157
+ output: this.serializePromptOutput(params.output),
158
+ success: params.success,
159
+ errorMessage: params.errorMessage,
160
+ tenant: input.tenant,
161
+ user: input.user,
162
+ };
163
+ }
164
+ async registerPromptLog(input, params) {
165
+ if (!this._aiLogService) {
166
+ return;
167
+ }
168
+ try {
169
+ await this._aiLogService.create(this.buildLogPayload(input, params));
170
+ }
171
+ catch (e) {
172
+ console.error("Error registerPromptLog", {
173
+ name: e?.name,
174
+ message: e?.message,
175
+ stack: e?.stack,
176
+ });
177
+ }
178
+ }
179
+ async generateEmbedding({ text, model }) {
180
+ const response = await this.post("/api/embed", {
181
+ model: model ?? this.embeddingModel,
182
+ input: text,
183
+ });
184
+ return response.embeddings?.[0] ?? response.embedding ?? [];
185
+ }
186
+ mapTools(tools = []) {
187
+ return tools.map(tool => ({
188
+ type: "function",
189
+ function: {
190
+ name: tool.name,
191
+ description: tool.description,
192
+ parameters: tool.parameters ?? {
193
+ type: "object",
194
+ properties: {},
195
+ additionalProperties: false,
196
+ },
197
+ },
198
+ }));
199
+ }
200
+ normalizeResponseFormat(input) {
201
+ if (input.zodSchema) {
202
+ return toJSONSchema(input.zodSchema, {
203
+ target: "draft-7",
204
+ });
205
+ }
206
+ if (!input.jsonSchema) {
207
+ return undefined;
208
+ }
209
+ const jsonSchema = input.jsonSchema;
210
+ if (jsonSchema.type === "json_schema" && jsonSchema.json_schema?.schema) {
211
+ return jsonSchema.json_schema.schema;
212
+ }
213
+ return jsonSchema;
214
+ }
215
+ parseToolArguments(args) {
216
+ if (!args) {
217
+ return {};
218
+ }
219
+ if (typeof args === "object") {
220
+ return args;
221
+ }
222
+ try {
223
+ return JSON.parse(args);
224
+ }
225
+ catch (e) {
226
+ throw new Error(`Invalid tool arguments: ${args}`);
227
+ }
228
+ }
229
+ serializeToolOutput(output) {
230
+ if (typeof output === "string") {
231
+ return output;
232
+ }
233
+ if (output === undefined) {
234
+ return "";
235
+ }
236
+ return JSON.stringify(output);
237
+ }
238
+ async buildToolMessages(toolCalls = [], tools = []) {
239
+ const toolMessages = [];
240
+ for (const toolCall of toolCalls) {
241
+ const toolName = toolCall.function?.name;
242
+ const tool = tools.find(t => t.name === toolName);
243
+ if (!tool) {
244
+ throw new Error(`Tool not found: ${toolName}`);
245
+ }
246
+ const args = this.parseToolArguments(toolCall.function?.arguments);
247
+ const output = await tool.execute(args);
248
+ toolMessages.push({
249
+ role: "tool",
250
+ name: toolName,
251
+ content: this.serializeToolOutput(output),
252
+ });
253
+ }
254
+ return toolMessages;
255
+ }
256
+ async prompt(input) {
257
+ if (!input.systemPrompt) {
258
+ throw new Error("systemPrompt required");
259
+ }
260
+ let systemPrompt = input.systemPrompt;
261
+ if (input.memory && input.memory.length > 0) {
262
+ systemPrompt += `\n\n ${input.memoryHeader ?? '[MEMORIA]'}\n ${input.memory.map(m => `${m.key}: ${m.value}`).join('\n')}`;
263
+ }
264
+ if (input.knowledgeBase && input.knowledgeBase.length > 0) {
265
+ systemPrompt += `\n\n${input.knowledgeBaseHeader ?? '[BASE DE CONOCIMIENTO]'}\n ${input.knowledgeBase.join('\n')}`;
266
+ }
267
+ const model = input.model ?? (this.hasImageInput(input) ? this.visionModel ?? this.model : this.model);
268
+ const startedAt = new Date();
269
+ const startTime = performance.now();
270
+ let tokens = 0;
271
+ let inputTokens = 0;
272
+ let outputTokens = 0;
273
+ try {
274
+ const messages = [
275
+ { role: 'system', content: systemPrompt },
276
+ ...await this.mapHistory(input.history),
277
+ await this.buildUserMessage(input),
278
+ ];
279
+ const tools = input.tools ?? [];
280
+ const maxIterations = input.toolMaxIterations ?? 5;
281
+ const responseFormat = this.normalizeResponseFormat(input);
282
+ let output;
283
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
284
+ const response = await this.post("/api/chat", {
285
+ model,
286
+ messages,
287
+ stream: false,
288
+ ...(responseFormat ? { format: responseFormat } : {}),
289
+ ...(tools.length > 0 ? { tools: this.mapTools(tools) } : {}),
290
+ });
291
+ inputTokens += response.prompt_eval_count ?? 0;
292
+ outputTokens += response.eval_count ?? 0;
293
+ tokens += (response.prompt_eval_count ?? 0) + (response.eval_count ?? 0);
294
+ const message = response.message ?? {};
295
+ const toolCalls = message.tool_calls ?? [];
296
+ if (toolCalls.length === 0) {
297
+ output = message.content ?? response.response ?? "";
298
+ break;
299
+ }
300
+ messages.push(message);
301
+ messages.push(...await this.buildToolMessages(toolCalls, tools));
302
+ }
303
+ if (output === undefined) {
304
+ throw new Error(`Tool max iterations reached: ${maxIterations}`);
305
+ }
306
+ const endTime = performance.now();
307
+ const time = endTime - startTime;
308
+ const endedAt = new Date();
309
+ const audio = await PromptAudioService.build(input, output);
310
+ await this.registerPromptLog(input, {
311
+ model,
312
+ systemPrompt,
313
+ startedAt,
314
+ endedAt,
315
+ inputTokens,
316
+ outputTokens,
317
+ tokens,
318
+ output,
319
+ success: true,
320
+ });
321
+ return {
322
+ output,
323
+ tokens,
324
+ inputTokens,
325
+ outputTokens,
326
+ time,
327
+ ...(audio ? { audio } : {}),
328
+ };
329
+ }
330
+ catch (e) {
331
+ const endedAt = new Date();
332
+ await this.registerPromptLog(input, {
333
+ model,
334
+ systemPrompt,
335
+ startedAt,
336
+ endedAt,
337
+ success: false,
338
+ errorMessage: e?.message,
339
+ });
340
+ throw e;
341
+ }
342
+ }
343
+ }
344
+ export default OllamaAiProvider;
345
+ export { OllamaAiProvider };
@@ -0,0 +1,305 @@
1
+ import OpenAI from "openai";
2
+ import { zodResponseFormat } from "openai/helpers/zod";
3
+ import PromptAudioService from "../../services/PromptAudioService.js";
4
+ class OpenAiProvider {
5
+ constructor(apiKey, model, visionModel, aiLogService) {
6
+ if (!apiKey) {
7
+ throw new Error("OpenAI apiKey required");
8
+ }
9
+ if (!model) {
10
+ throw new Error("OpenAI model required");
11
+ }
12
+ this._apiKey = apiKey;
13
+ this._model = model;
14
+ this._visionModel = visionModel;
15
+ this._aiLogService = aiLogService;
16
+ }
17
+ get model() {
18
+ if (!this._model) {
19
+ throw new Error("OpenAI model not found");
20
+ }
21
+ return this._model;
22
+ }
23
+ get client() {
24
+ if (!this._client) {
25
+ this._client = new OpenAI({
26
+ apiKey: this._apiKey,
27
+ });
28
+ }
29
+ return this._client;
30
+ }
31
+ get visionModel() {
32
+ return this._visionModel;
33
+ }
34
+ buildUserContent(input) {
35
+ if (input.userContent && input.userContent.length > 0) {
36
+ return this.mapContentParts(input.userContent);
37
+ }
38
+ if (input.userImages && input.userImages.length > 0) {
39
+ const content = [];
40
+ if (input.userInput) {
41
+ content.push({ type: 'text', text: input.userInput });
42
+ }
43
+ content.push(...input.userImages.map(image => ({
44
+ type: 'image_url',
45
+ image_url: {
46
+ url: image.url,
47
+ ...(image.detail ? { detail: image.detail } : {}),
48
+ }
49
+ })));
50
+ return content;
51
+ }
52
+ return input.userInput ?? "";
53
+ }
54
+ mapContentParts(content) {
55
+ return content.map(part => {
56
+ if (part.type === 'text') {
57
+ return {
58
+ type: 'text',
59
+ text: part.text
60
+ };
61
+ }
62
+ return {
63
+ type: 'image_url',
64
+ image_url: {
65
+ url: part.imageUrl,
66
+ ...(part.detail ? { detail: part.detail } : {}),
67
+ }
68
+ };
69
+ });
70
+ }
71
+ mapHistory(history = []) {
72
+ return history.map(message => ({
73
+ role: message.role,
74
+ content: typeof message.content === 'string'
75
+ ? message.content
76
+ : this.mapContentParts(message.content)
77
+ }));
78
+ }
79
+ hasImageInput(input) {
80
+ if (input.userImages && input.userImages.length > 0) {
81
+ return true;
82
+ }
83
+ if (input.userContent?.some(part => part.type === 'image')) {
84
+ return true;
85
+ }
86
+ return input.history?.some(message => Array.isArray(message.content) && message.content.some(part => part.type === 'image')) ?? false;
87
+ }
88
+ serializePromptInput(input, systemPrompt) {
89
+ return JSON.stringify({
90
+ systemPrompt,
91
+ history: input.history,
92
+ userInput: input.userInput,
93
+ userContent: input.userContent,
94
+ memory: input.memory,
95
+ knowledgeBase: input.knowledgeBase,
96
+ tools: input.tools?.map(tool => ({
97
+ name: tool.name,
98
+ description: tool.description,
99
+ parameters: tool.parameters,
100
+ })),
101
+ });
102
+ }
103
+ serializePromptOutput(output) {
104
+ if (typeof output === "string") {
105
+ return output;
106
+ }
107
+ if (output === null || output === undefined) {
108
+ return undefined;
109
+ }
110
+ return JSON.stringify(output);
111
+ }
112
+ buildLogPayload(input, params) {
113
+ return {
114
+ provider: "openai",
115
+ model: params.model,
116
+ operationTitle: input.operationTitle,
117
+ operationGroup: input.operationGroup,
118
+ ip: input.ip,
119
+ userAgent: input.userAgent,
120
+ input: this.serializePromptInput(input, params.systemPrompt),
121
+ inputImages: input.userImages?.map(image => ({
122
+ url: image.url,
123
+ })) ?? input.userContent
124
+ ?.filter(part => part.type === "image")
125
+ .map(part => ({
126
+ url: part.imageUrl,
127
+ })),
128
+ inputFiles: input.inputFiles,
129
+ inputTokens: params.inputTokens,
130
+ outputTokens: params.outputTokens,
131
+ tokens: params.tokens,
132
+ startedAt: params.startedAt,
133
+ endedAt: params.endedAt,
134
+ responseTime: params.endedAt ? `${params.endedAt.getTime() - params.startedAt.getTime()}ms` : undefined,
135
+ output: this.serializePromptOutput(params.output),
136
+ success: params.success,
137
+ errorMessage: params.errorMessage,
138
+ tenant: input.tenant,
139
+ user: input.user,
140
+ };
141
+ }
142
+ async registerPromptLog(input, params) {
143
+ if (!this._aiLogService) {
144
+ return;
145
+ }
146
+ try {
147
+ await this._aiLogService.create(this.buildLogPayload(input, params));
148
+ }
149
+ catch (e) {
150
+ console.error("Error registerPromptLog", {
151
+ name: e?.name,
152
+ message: e?.message,
153
+ stack: e?.stack,
154
+ });
155
+ }
156
+ }
157
+ async generateEmbedding({ text, model = "text-embedding-ada-002" }) {
158
+ const response = await this.client.embeddings.create({
159
+ model: model,
160
+ input: text,
161
+ });
162
+ return response.data[0].embedding;
163
+ }
164
+ mapTools(tools = []) {
165
+ return tools.map(tool => ({
166
+ type: "function",
167
+ function: {
168
+ name: tool.name,
169
+ description: tool.description,
170
+ parameters: tool.parameters ?? {
171
+ type: "object",
172
+ properties: {},
173
+ additionalProperties: false,
174
+ },
175
+ },
176
+ }));
177
+ }
178
+ parseToolArguments(args) {
179
+ if (!args) {
180
+ return {};
181
+ }
182
+ try {
183
+ return JSON.parse(args);
184
+ }
185
+ catch (e) {
186
+ throw new Error(`Invalid tool arguments: ${args}`);
187
+ }
188
+ }
189
+ serializeToolOutput(output) {
190
+ if (typeof output === "string") {
191
+ return output;
192
+ }
193
+ if (output === undefined) {
194
+ return "";
195
+ }
196
+ return JSON.stringify(output);
197
+ }
198
+ async buildToolMessages(toolCalls = [], tools = []) {
199
+ const toolMessages = [];
200
+ for (const toolCall of toolCalls) {
201
+ const toolName = toolCall.function?.name;
202
+ const tool = tools.find(t => t.name === toolName);
203
+ if (!tool) {
204
+ throw new Error(`Tool not found: ${toolName}`);
205
+ }
206
+ const args = this.parseToolArguments(toolCall.function?.arguments);
207
+ const output = await tool.execute(args);
208
+ toolMessages.push({
209
+ role: "tool",
210
+ tool_call_id: toolCall.id,
211
+ content: this.serializeToolOutput(output),
212
+ });
213
+ }
214
+ return toolMessages;
215
+ }
216
+ async prompt(input) {
217
+ if (!input.systemPrompt) {
218
+ throw new Error("systemPrompt required");
219
+ }
220
+ let systemPrompt = input.systemPrompt;
221
+ if (input.memory && input.memory.length > 0) {
222
+ systemPrompt += `\n\n ${input.memoryHeader ?? '[MEMORIA]'}\n ${input.memory.map(m => `${m.key}: ${m.value}`).join('\n')}`;
223
+ }
224
+ if (input.knowledgeBase && input.knowledgeBase.length > 0) {
225
+ systemPrompt += `\n\n${input.knowledgeBaseHeader ?? '[BASE DE CONOCIMIENTO]'}\n ${input.knowledgeBase.join('\n')}`;
226
+ }
227
+ const userInput = this.buildUserContent(input);
228
+ const model = input.model ?? (this.hasImageInput(input) ? this.visionModel ?? this.model : this.model);
229
+ const startedAt = new Date();
230
+ const startTime = performance.now();
231
+ let tokens = 0;
232
+ let inputTokens = 0;
233
+ let outputTokens = 0;
234
+ try {
235
+ const messages = [
236
+ { role: 'system', content: systemPrompt },
237
+ ...this.mapHistory(input.history),
238
+ { role: 'user', content: userInput },
239
+ ];
240
+ const tools = input.tools ?? [];
241
+ const maxIterations = input.toolMaxIterations ?? 5;
242
+ let output;
243
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
244
+ const chatCompletion = await this.client.chat.completions.create({
245
+ messages,
246
+ ...(input.zodSchema ? { response_format: zodResponseFormat(input.zodSchema, "event") } : {}),
247
+ ...(input.jsonSchema ? { response_format: input.jsonSchema } : {}),
248
+ ...(tools.length > 0 ? { tools: this.mapTools(tools) } : {}),
249
+ model: model,
250
+ });
251
+ tokens += chatCompletion.usage?.total_tokens ?? 0;
252
+ inputTokens += chatCompletion.usage?.prompt_tokens ?? 0;
253
+ outputTokens += chatCompletion.usage?.completion_tokens ?? 0;
254
+ const message = chatCompletion.choices[0].message;
255
+ const toolCalls = message.tool_calls ?? [];
256
+ if (toolCalls.length === 0) {
257
+ output = message.content;
258
+ break;
259
+ }
260
+ messages.push(message);
261
+ messages.push(...await this.buildToolMessages(toolCalls, tools));
262
+ }
263
+ if (output === undefined) {
264
+ throw new Error(`Tool max iterations reached: ${maxIterations}`);
265
+ }
266
+ const endTime = performance.now();
267
+ const time = endTime - startTime;
268
+ const endedAt = new Date();
269
+ const audio = await PromptAudioService.build(input, output);
270
+ await this.registerPromptLog(input, {
271
+ model,
272
+ systemPrompt,
273
+ startedAt,
274
+ endedAt,
275
+ inputTokens,
276
+ outputTokens,
277
+ tokens,
278
+ output,
279
+ success: true,
280
+ });
281
+ return {
282
+ output,
283
+ tokens,
284
+ inputTokens,
285
+ outputTokens,
286
+ time,
287
+ ...(audio ? { audio } : {}),
288
+ };
289
+ }
290
+ catch (e) {
291
+ const endedAt = new Date();
292
+ await this.registerPromptLog(input, {
293
+ model,
294
+ systemPrompt,
295
+ startedAt,
296
+ endedAt,
297
+ success: false,
298
+ errorMessage: e?.message,
299
+ });
300
+ throw e;
301
+ }
302
+ }
303
+ }
304
+ export default OpenAiProvider;
305
+ export { OpenAiProvider };