@wabot-dev/framework 0.1.0-beta.33 → 0.1.0-beta.35

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.
@@ -0,0 +1,125 @@
1
+ import { Logger } from '../../../core/logger/Logger.js';
2
+ import { GoogleGenAI } from '@google/genai';
3
+
4
+ const SUPPORTED_MODELS = [
5
+ 'gemini-2.0-flash-exp',
6
+ 'gemini-1.5-flash',
7
+ 'gemini-1.5-pro',
8
+ 'gemini-pro',
9
+ ];
10
+ const DEFAULT_MODEL = 'gemini-1.5-flash';
11
+ class GeminiChatAdapter {
12
+ genai;
13
+ model;
14
+ logger = new Logger('wabot:gemini-chat-adapter');
15
+ constructor() {
16
+ const apiKey = process.env.GEMINI_API_KEY;
17
+ if (!apiKey) {
18
+ throw new Error('GEMINI_API_KEY env variable is required');
19
+ }
20
+ this.model = process.env.GEMINI_MODEL || DEFAULT_MODEL;
21
+ this.validateModel(this.model);
22
+ this.genai = new GoogleGenAI({ apiKey });
23
+ }
24
+ validateModel(model) {
25
+ if (!SUPPORTED_MODELS.includes(model)) {
26
+ throw new Error(`Unsupported Gemini model: ${model}. Supported models: ${SUPPORTED_MODELS.join(', ')}`);
27
+ }
28
+ }
29
+ async nextItem(req) {
30
+ const contents = this.buildContents(req.prevItems, req.systemPrompt);
31
+ const tools = req.tools.length > 0 ? req.tools.map(this.mapTool) : undefined;
32
+ const request = { model: this.model, contents, tools };
33
+ this.logger.debug(`Call Gemini API with Request: ${JSON.stringify(request)}`);
34
+ const response = await this.genai.models.generateContent(request);
35
+ return this.mapResponse(response);
36
+ }
37
+ buildContents(chatItems, systemPrompt) {
38
+ const contents = [];
39
+ if (systemPrompt) {
40
+ contents.push({ role: 'user', parts: [{ text: systemPrompt }] }, { role: 'model', parts: [{ text: 'I understand. I will follow these instructions.' }] });
41
+ }
42
+ chatItems.forEach(chatItem => {
43
+ switch (chatItem.type) {
44
+ case 'humanMessage':
45
+ this.validateMessageContent(chatItem.humanMessage.text, 'User');
46
+ contents.push({ role: 'user', parts: [{ text: chatItem.humanMessage.text }] });
47
+ break;
48
+ case 'botMessage':
49
+ this.validateMessageContent(chatItem.botMessage.text, 'Assistant');
50
+ contents.push({ role: 'model', parts: [{ text: chatItem.botMessage.text }] });
51
+ break;
52
+ case 'functionCall':
53
+ contents.push(...this.mapFunctionCall(chatItem.functionCall));
54
+ break;
55
+ }
56
+ });
57
+ return contents;
58
+ }
59
+ validateMessageContent(text, messageType) {
60
+ if (!text) {
61
+ throw new Error(`${messageType} message content is empty`);
62
+ }
63
+ }
64
+ mapFunctionCall(item) {
65
+ const args = JSON.parse(item.arguments || '{}');
66
+ return [
67
+ {
68
+ role: 'model',
69
+ parts: [{ functionCall: { name: item.name, args } }],
70
+ },
71
+ {
72
+ role: 'user',
73
+ parts: [{ functionResponse: { name: item.name, response: { result: item.result || 'No result' } } }],
74
+ },
75
+ ];
76
+ }
77
+ mapTool = (tool) => ({
78
+ functionDeclarations: [{
79
+ name: tool.name,
80
+ description: tool.description,
81
+ parameters: {
82
+ type: 'object',
83
+ properties: tool.parameters.reduce((acc, param) => ({ ...acc, [param.name]: { type: param.type, description: param.description } }), {}),
84
+ required: tool.parameters.map(param => param.name),
85
+ },
86
+ }],
87
+ });
88
+ mapResponse(response) {
89
+ this.validateResponse(response);
90
+ const part = response.response.candidates[0].content.parts[0];
91
+ const chatItem = part.text
92
+ ? { type: 'botMessage', botMessage: { text: part.text } }
93
+ : part.functionCall
94
+ ? {
95
+ type: 'functionCall',
96
+ functionCall: {
97
+ id: `gemini_${Date.now()}`,
98
+ name: part.functionCall.name,
99
+ arguments: JSON.stringify(part.functionCall.args || {}),
100
+ },
101
+ }
102
+ : (() => { throw new Error('Not supported Gemini Response'); })();
103
+ const usage = {
104
+ inputTokens: response.response.usageMetadata?.promptTokenCount || 0,
105
+ outputTokens: response.response.usageMetadata?.candidatesTokenCount || 0,
106
+ };
107
+ if (!response.response.usageMetadata) {
108
+ throw new Error('Unable to found usage info');
109
+ }
110
+ return { chatItem, usage };
111
+ }
112
+ validateResponse(response) {
113
+ if (!response.response) {
114
+ throw new Error('Invalid Gemini response structure');
115
+ }
116
+ if (!response.response.candidates?.[0]) {
117
+ throw new Error('No candidates in Gemini response');
118
+ }
119
+ if (!response.response.candidates[0].content?.parts?.[0]) {
120
+ throw new Error('No parts in Gemini response');
121
+ }
122
+ }
123
+ }
124
+
125
+ export { GeminiChatAdapter };
@@ -4,6 +4,16 @@ function validateArray(value, options) {
4
4
  error: { description: 'Should be an array', items: [] },
5
5
  };
6
6
  }
7
+ if (options?.minLength != null && value.length < options.minLength) {
8
+ return {
9
+ error: { description: 'exceeds the established min length limit', items: [] },
10
+ };
11
+ }
12
+ if (options?.maxLength != null && value.length > options.maxLength) {
13
+ return {
14
+ error: { description: 'exceeds the established max length limit', items: [] },
15
+ };
16
+ }
7
17
  const { itemsValidator } = options ?? {};
8
18
  const valueOut = [];
9
19
  const errorItems = [];
@@ -7,7 +7,9 @@ function validateModel(value, info) {
7
7
  for (const propertyName in info.properties) {
8
8
  const propertyInfo = info.properties[propertyName];
9
9
  const propertyValidators = propertyInfo.validators ?? [];
10
- resultValue[propertyName] = value[propertyName] ?? resultValue[propertyName];
10
+ resultValue[propertyName] = propertyInfo.isOptional
11
+ ? (value[propertyName] ?? resultValue[propertyName])
12
+ : value[propertyName];
11
13
  if (resultValue[propertyName] == null && propertyInfo.isOptional) {
12
14
  resultValue[propertyName] = undefined;
13
15
  continue;
@@ -195,6 +195,8 @@ type IModelValidatorsInfo<V> = {
195
195
  };
196
196
 
197
197
  interface IValidateArrayOptions {
198
+ minLength?: number;
199
+ maxLength?: number;
198
200
  }
199
201
  interface IValidateArrayOptionsWithItemsValidators extends IValidateArrayOptions {
200
202
  itemsValidator?: {
@@ -829,6 +831,21 @@ declare class DeepSeekChatAdapter implements IChatAdapter {
829
831
  private mapResponse;
830
832
  }
831
833
 
834
+ declare class GeminiChatAdapter implements IChatAdapter {
835
+ private genai;
836
+ private model;
837
+ private logger;
838
+ constructor();
839
+ private validateModel;
840
+ nextItem(req: IChatAdapterNextItemReq): Promise<IChatAdapterNextItemRes>;
841
+ private buildContents;
842
+ private validateMessageContent;
843
+ private mapFunctionCall;
844
+ private mapTool;
845
+ private mapResponse;
846
+ private validateResponse;
847
+ }
848
+
832
849
  declare class OpenaiChatAdapter implements IChatAdapter {
833
850
  private openai;
834
851
  private logger;
@@ -1288,4 +1305,4 @@ interface IValidateMaxOptions {
1288
1305
  }
1289
1306
  declare function validateMax(value: any, options: IValidateMaxOptions): IValidationResult<any>;
1290
1307
 
1291
- export { Async, Auth, Chat, ChatAdapter, ChatBot, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, ClaudeChatAdapter, CmdChannel, Command, CommandMetadataStore, Container, ControllerMetadataStore, CustomError, DeepSeekChatAdapter, Entity, Env, EnvWhatsAppRepository, ExpressProvider, HtmlModule, HttpServerProvider, type IArrayValidationError, type IArrayValidationResult, type IBotMessageItem, type IChannelMessage, type IChannelMetadata, type IChatAdapter, type IChatAdapterNextItemReq, type IChatAdapterNextItemRes, type IChatBot, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatItem, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type ICommandConfig, type ICommandHandler, type ICommandHandlerConfig, type IConstructor, type ICrudRepository, type ICustomErrorData, type IEndPointMetadata, type IEntityData, type IEnvType, type IFunctionCall, type IFunctionCallItem, type IGetConfig, type IGetWhatsAppTemplateRequest, type IHtmlModuleOptions, type IHumanMessageItem, type IJobData, type IJobEvent, type IJobEventListener, type IJobRepository, type IJwtRefreshTokenData, type ILanguageModelUsage, type IListenWhatsAppMessageRequest, type IMessageContext, type IMessageMetadata, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IMindsetTool, type IMindsetToolParameter, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPostConfig, type IPrimitive, type IPropertyValidatorInfo, type IReceivedMessage, type IRestControllerConfig, type IRestControllerMetadata, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type IStorableData, type ITelegramChannelConfig, type IValidateArrayOptions, type IValidateArrayOptionsWithItemsValidators, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppContact, type IWhatsAppData, type IWhatsAppMessage, type IWhatsAppMessageListener, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsAppTemplate, type IWhatsAppTemplateComponent, type IWhatsAppTemplateMessage, type IWhatsAppTemplateParameter, type IWhatsAppTemplateResponse, type IWhatsAppWebhookPayload, type IWhatsappChannelConfig, type IchatControllerConfig, Job, JobRepository, JobRunner, JobsEventsHub, Jwt, JwtAccessAndRefreshTokenDto, JwtConfig, JwtGuardMiddleware, JwtRefreshToken, JwtRefreshTokenRepository, JwtSigner, JwtTokenDto, Lifecycle, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, Mapper, Mindset, MindsetMetadataStore, MindsetOperator, OpenaiChatAdapter, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, Persistent, PgChatMemory, PgChatRepository, PgCrudRepository, PgJobRepository, PgRepositoryBase, PgWhatsAppRepository, RamChatMemory, RamChatRepository, Random, RestControllerMetadataStore, SocketChannel, SocketChannelConfig, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, ValidationMetadataStore, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByDevConnection, WhatsAppReceiverByWebHook, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByDevConnection, WhatsappChannelConfig, chatBot, chatController, chatItemTypeOptions, cmd, command, commandHandler, container, get, inject, injectable, isArray, isBoolean, isDate, isModel, isNotEmpty, isNumber, isOptional, isPresent, isString, jwtGuard, max, middleware, min, mindset, mindsetFunction, mindsetModule, modelInfo, param, post, restController, runAsyncCommandHandlers, runChatControllers, runRestControllers, scoped, singleton, socket, telegram, validate, validateArray, validateIsBoolean, validateIsDate, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsapp };
1308
+ export { Async, Auth, Chat, ChatAdapter, ChatBot, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, ClaudeChatAdapter, CmdChannel, Command, CommandMetadataStore, Container, ControllerMetadataStore, CustomError, DeepSeekChatAdapter, Entity, Env, EnvWhatsAppRepository, ExpressProvider, GeminiChatAdapter, HtmlModule, HttpServerProvider, type IArrayValidationError, type IArrayValidationResult, type IBotMessageItem, type IChannelMessage, type IChannelMetadata, type IChatAdapter, type IChatAdapterNextItemReq, type IChatAdapterNextItemRes, type IChatBot, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatItem, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type ICommandConfig, type ICommandHandler, type ICommandHandlerConfig, type IConstructor, type ICrudRepository, type ICustomErrorData, type IEndPointMetadata, type IEntityData, type IEnvType, type IFunctionCall, type IFunctionCallItem, type IGetConfig, type IGetWhatsAppTemplateRequest, type IHtmlModuleOptions, type IHumanMessageItem, type IJobData, type IJobEvent, type IJobEventListener, type IJobRepository, type IJwtRefreshTokenData, type ILanguageModelUsage, type IListenWhatsAppMessageRequest, type IMessageContext, type IMessageMetadata, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IMindsetTool, type IMindsetToolParameter, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPostConfig, type IPrimitive, type IPropertyValidatorInfo, type IReceivedMessage, type IRestControllerConfig, type IRestControllerMetadata, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type IStorableData, type ITelegramChannelConfig, type IValidateArrayOptions, type IValidateArrayOptionsWithItemsValidators, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppContact, type IWhatsAppData, type IWhatsAppMessage, type IWhatsAppMessageListener, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsAppTemplate, type IWhatsAppTemplateComponent, type IWhatsAppTemplateMessage, type IWhatsAppTemplateParameter, type IWhatsAppTemplateResponse, type IWhatsAppWebhookPayload, type IWhatsappChannelConfig, type IchatControllerConfig, Job, JobRepository, JobRunner, JobsEventsHub, Jwt, JwtAccessAndRefreshTokenDto, JwtConfig, JwtGuardMiddleware, JwtRefreshToken, JwtRefreshTokenRepository, JwtSigner, JwtTokenDto, Lifecycle, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, Mapper, Mindset, MindsetMetadataStore, MindsetOperator, OpenaiChatAdapter, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, Persistent, PgChatMemory, PgChatRepository, PgCrudRepository, PgJobRepository, PgRepositoryBase, PgWhatsAppRepository, RamChatMemory, RamChatRepository, Random, RestControllerMetadataStore, SocketChannel, SocketChannelConfig, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, ValidationMetadataStore, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByDevConnection, WhatsAppReceiverByWebHook, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByDevConnection, WhatsappChannelConfig, chatBot, chatController, chatItemTypeOptions, cmd, command, commandHandler, container, get, inject, injectable, isArray, isBoolean, isDate, isModel, isNotEmpty, isNumber, isOptional, isPresent, isString, jwtGuard, max, middleware, min, mindset, mindsetFunction, mindsetModule, modelInfo, param, post, restController, runAsyncCommandHandlers, runChatControllers, runRestControllers, scoped, singleton, socket, telegram, validate, validateArray, validateIsBoolean, validateIsDate, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsapp };
package/dist/src/index.js CHANGED
@@ -61,6 +61,7 @@ export { SocketServerProvider } from './feature/socket/SocketServerProvider.js';
61
61
  export { PgJobRepository } from './addon/async/pg/PgJobRepository.js';
62
62
  export { ClaudeChatAdapter } from './addon/chat-bot/claude/ClaudeChatAdapter.js';
63
63
  export { DeepSeekChatAdapter } from './addon/chat-bot/deepseek/DeepSeekChatAdapter.js';
64
+ export { GeminiChatAdapter } from './addon/chat-bot/gemini/GeminiChatAdapter.js';
64
65
  export { OpenaiChatAdapter } from './addon/chat-bot/openia/OpenaiChatAdapter.js';
65
66
  export { PgChatRepository } from './addon/chat-bot/pg/PgChatRepository.js';
66
67
  export { PgChatMemory } from './addon/chat-bot/pg/PgChatMemory.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wabot-dev/framework",
3
- "version": "0.1.0-beta.33",
3
+ "version": "0.1.0-beta.35",
4
4
  "description": "Framework for IA Chat Bots",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",
@@ -36,6 +36,7 @@
36
36
  },
37
37
  "peerDependencies": {
38
38
  "@anthropic-ai/sdk": "^0.60.0",
39
+ "@google/genai": "^1.16.0",
39
40
  "@types/debug": "^4.1.12",
40
41
  "@types/express": "^5.0.1",
41
42
  "@types/jsonwebtoken": "^9.0.10",