Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/config/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const settings: Array<ISetting> = [
id: SettingEnum.AI_PROVIDER_OPTOIN_ID,
type: SettingType.SELECT,
packageValue: SettingEnum.SELF_HOSTED_MODEL,
required: true,
required: false,
public: false,
i18nLabel: 'Choose_AI_Provider_Label',
i18nPlaceholder: 'Choose_AI_Provider_Placeholder',
Expand All @@ -42,7 +42,7 @@ export const settings: Array<ISetting> = [
id: SettingEnum.SELF_HOSTED_MODEL_ADDRESS_ID,
type: SettingType.STRING,
packageValue: '',
required: true,
required: false,
public: false,
i18nLabel: 'Self_Hosted_AI_Model_URL_Label',
i18nPlaceholder: 'Self_Hosted_AI_Model_URL_Placeholder',
Expand All @@ -51,7 +51,7 @@ export const settings: Array<ISetting> = [
id: SettingEnum.OPEN_AI_API_KEY_ID,
type: SettingType.PASSWORD,
packageValue: '',
required: true,
required: false,
public: false,
i18nLabel: 'Open_AI_API_Key_Label',
i18nPlaceholder: 'Open_AI_API_Key_Placeholder',
Expand All @@ -60,7 +60,7 @@ export const settings: Array<ISetting> = [
id: SettingEnum.OPEN_AI_API_MODEL_ID,
type: SettingType.STRING,
packageValue: '',
required: true,
required: false,
public: false,
i18nLabel: 'Open_AI_Model',
i18nPlaceholder: 'Open_AI_Model_Placeholder',
Expand All @@ -69,7 +69,7 @@ export const settings: Array<ISetting> = [
id: SettingEnum.GEMINI_AI_API_KEY_ID,
type: SettingType.PASSWORD,
packageValue: '',
required: true,
required: false,
public: false,
i18nLabel: 'Gemini_API_Key_Label',
i18nPlaceholder: 'Gemini_API_Key_Placeholder',
Expand Down
56 changes: 22 additions & 34 deletions src/handlers/AIHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
IHttp,
IHttpResponse,
} from '@rocket.chat/apps-engine/definition/accessors';
import { IUser } from '@rocket.chat/apps-engine/definition/users';
import { QuickRepliesApp } from '../../QuickRepliesApp';
import { SettingEnum } from '../config/settings';
import {
Expand All @@ -16,9 +17,26 @@ class AIHandler {
private app: QuickRepliesApp,
private http: IHttp,
private userPreference: IPreference,
private user: IUser,
) {}
private language = this.userPreference.language;

private getConfigError(provider: string): string {
if (
this.userPreference.AIusagePreference ===
AIusagePreferenceEnum.Personal
) {
return t('AI_Not_Configured_Personal', this.language, {
provider,
});
}
return this.user.roles.includes('admin')
? t('AI_Not_Configured_Admin_Self', this.language, { provider })
: t('AI_Not_Configured_Workspace_User', this.language, {
provider,
});
}

public async handleResponse(
message: string,
prompt: string,
Expand Down Expand Up @@ -52,11 +70,7 @@ class AIHandler {
return this.handleGemini(content);

default:
const errorMsg =
this.userPreference.AIusagePreference ===
AIusagePreferenceEnum.Personal
? t('AI_Not_Configured_Personal', this.language)
: t('AI_Not_Configured_Admin', this.language);
const errorMsg = this.getConfigError('AI provider');

this.app.getLogger().log(errorMsg);
return errorMsg;
Expand All @@ -78,20 +92,7 @@ class AIHandler {

if (!url) {
this.app.getLogger().log('Self Hosted Model address not set.');
if (
this.userPreference.AIusagePreference ===
AIusagePreferenceEnum.Personal
) {
return t(
'AI_Self_Hosted_Model_Not_Configured',
this.language,
);
} else {
return t(
'AI_Workspace_Model_Not_Configured',
this.language,
);
}
return this.getConfigError('Self Hosted Model URL');
}

const requestBody = {
Expand Down Expand Up @@ -150,13 +151,7 @@ class AIHandler {

if (!openaikey || !openaimodel) {
this.app.getLogger().log('OpenAI settings not set properly.');
const errorMsg =
this.userPreference.AIusagePreference ===
AIusagePreferenceEnum.Personal
? t('AI_OpenAI_Model_Not_Configured', this.language)
: t('AI_Not_Configured_Admin', this.language);

return errorMsg;
return this.getConfigError('OpenAI API key or model');
}

const response: IHttpResponse = await this.http.post(
Expand Down Expand Up @@ -225,14 +220,7 @@ class AIHandler {

if (!geminiAPIkey) {
this.app.getLogger().log('Gemini API key not set Properly');

const errorMsg =
this.userPreference.AIusagePreference ===
AIusagePreferenceEnum.Personal
? t('AI_Gemini_Model_Not_Configured', this.language)
: t('AI_Not_Configured_Admin', this.language);

return errorMsg;
return this.getConfigError('Gemini API key');
}

const response: IHttpResponse = await this.http.post(
Expand Down
1 change: 1 addition & 0 deletions src/handlers/ExecuteBlockActionHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ export class ExecuteBlockActionHandler {
this.app,
this.http,
Preference,
user,
).handleResponse(message, prompt);

await aiStorage.updateResponse(response);
Expand Down
60 changes: 35 additions & 25 deletions src/handlers/Handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { IReply } from '../definition/reply/IReply';
import {
sendDefaultNotification,
sendHelperNotification,
sendNotification,
} from '../helper/notification';
import { UserPreferenceModal } from '../modal/UserPreferenceModal';
import { Language, t } from '../lib/Translation/translation';
Expand Down Expand Up @@ -172,7 +173,7 @@ export class Handler implements IHandler {
);
const value = this.params?.slice(1).join(' ') || '';
const existingPreference = await userPreference.getUserPreference();
const AiHandler = new AIHandler(this.app, this.http, existingPreference);
const AiHandler = new AIHandler(this.app, this.http, existingPreference, this.sender);
if (!value) {
await sendMessage(this.modify, this.sender, this.room, t('Error_Grammar_Correct', this.language));
return;
Expand All @@ -198,37 +199,46 @@ export class Handler implements IHandler {
'';
const textMessage = Message.trim();

if (textMessage) {
const aistorage = new AIstorage(
this.persis,
this.read.getPersistenceReader(),
this.sender.id,
);
await aistorage.updateMessage(textMessage);
const modal = await ReplyAIModal(
this.app,
this.sender,
if (!textMessage) {
await sendNotification(
this.read,
this.persis,
this.modify,
this.sender,
this.room,
this.language,
textMessage,
{ message: t('AI_No_Message_Found', this.language) },
);
return;
}

if (modal instanceof Error) {
this.app.getLogger().error(modal.message);
return;
}

const triggerId = this.triggerId;
const aistorage = new AIstorage(
this.persis,
this.read.getPersistenceReader(),
this.sender.id,
);
await aistorage.updateMessage(textMessage);
const modal = await ReplyAIModal(
this.app,
this.sender,
this.read,
this.persis,
this.modify,
this.room,
this.language,
textMessage,
);

if (triggerId) {
await this.modify
.getUiController()
.openSurfaceView(modal, { triggerId }, this.sender);
}
if (modal instanceof Error) {
this.app.getLogger().error(modal.message);
return;
}

const triggerId = this.triggerId;

if (triggerId) {
await this.modify
.getUiController()
.openSurfaceView(modal, { triggerId }, this.sender);
}
return;
}
}
10 changes: 4 additions & 6 deletions src/lib/Translation/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,11 @@ export const de = {
Send_This_Text: "Diese Antwort senden",
AI_Prompt_Options_Label: "AI-Eingabeaufforderungsoptionen",
AI_Prompt_Options_Placeholder: "Wählen Sie AI-Konfigurationsoptionen",
AI_Not_Configured_Personal: "AI ist nicht konfiguriert. Bitte überprüfen Sie Ihre Konfiguration, um diese Funktion zu nutzen.",
AI_Not_Configured_Admin: "AI ist nicht konfiguriert. Bitte kontaktieren Sie Ihren Administrator, um diese Funktion zu nutzen.",
AI_Self_Hosted_Model_Not_Configured: "Ihr selbst gehostetes Modell ist nicht richtig eingerichtet. Bitte überprüfen Sie Ihre Konfiguration",
AI_OpenAI_Model_Not_Configured: "Ihr OpenAI-Modell ist nicht richtig eingerichtet. Bitte überprüfen Sie Ihre Konfiguration",
AI_Gemini_Model_Not_Configured: "Ihr Gemini-Modell ist nicht richtig eingerichtet. Bitte überprüfen Sie Ihre Konfiguration",
AI_Workspace_Model_Not_Configured: "Ihre Workspace-AI ist nicht richtig eingerichtet. Bitte kontaktieren Sie Ihren Administrator",
AI_Not_Configured_Personal: "Ihr __provider__ ist nicht konfiguriert. Bitte richten Sie es mit `/quick config` ein.",
AI_Not_Configured_Admin_Self: "Der __provider__ ist nicht konfiguriert. Bitte fügen Sie ihn in den App-Einstellungen hinzu.",
AI_Not_Configured_Workspace_User: "Der __provider__ ist nicht konfiguriert. Bitte kontaktieren Sie Ihren Administrator.",
AI_Something_Went_Wrong: "Etwas ist schiefgelaufen. Bitte versuchen Sie es später noch einmal.",
AI_No_Message_Found: "Keine Nachricht in diesem Raum gefunden, um eine Antwort zu generieren. Bitte senden Sie zuerst eine Nachricht.",
Refresh_Button_Text: "Aktualisieren",
AI_Suggestions_Header: "Vorgeschlagene Antworten",
Auto_Suggest_Enabled: "Aktiviert",
Expand Down
10 changes: 4 additions & 6 deletions src/lib/Translation/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,11 @@ export const en = {
Send_This_Text: "Send this reply",
AI_Prompt_Options_Label : "AI Prompt Options",
AI_Prompt_Options_Placeholder : "Select AI Configuration Options",
AI_Not_Configured_Personal: "AI is not configured. Please Check your configuration to use this feature.",
AI_Not_Configured_Admin: "AI is not configured. Please contact your administrator to use this feature.",
AI_Self_Hosted_Model_Not_Configured: "Your Self Hosted Model is not set up properly. Please check your configuration",
AI_OpenAI_Model_Not_Configured: "Your OpenAI Model is not set up properly. Please check your configuration",
AI_Gemini_Model_Not_Configured: "Your Gemini Model is not set up properly. Please check your configuration",
AI_Workspace_Model_Not_Configured: "Your Workspace AI is not set up properly. Please contact your administrator",
AI_Not_Configured_Personal: "Your __provider__ is not configured. Please set it up using `/quick config`.",
AI_Not_Configured_Admin_Self: "The __provider__ is not configured. Please add it in the app settings.",
AI_Not_Configured_Workspace_User: "The __provider__ is not configured. Please contact your administrator.",
AI_Something_Went_Wrong: "Something went wrong. Please try again later.",
AI_No_Message_Found: "No message found in this room to generate a reply for. Please send a message first.",
Refresh_Button_Text: "Refresh",
AI_Suggestions_Header: "Suggested Replies",
Auto_Suggest_Enabled: "Enabled",
Expand Down
10 changes: 4 additions & 6 deletions src/lib/Translation/locales/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,11 @@ export const pl = {
Send_This_Text: "Wyślij tę odpowiedź",
AI_Prompt_Options_Label: "Opcje podpowiedzi AI",
AI_Prompt_Options_Placeholder: "Wybierz Opcje konfiguracji AI",
AI_Not_Configured_Personal: "AI nie jest skonfigurowane. Proszę sprawdzić swoją konfigurację, aby skorzystać z tej funkcji.",
AI_Not_Configured_Admin: "AI nie jest skonfigurowane. Proszę skontaktować się z administratorem, aby skorzystać z tej funkcji.",
AI_Self_Hosted_Model_Not_Configured: "Twój model hostowany lokalnie nie jest poprawnie skonfigurowany. Proszę sprawdzić swoją konfigurację",
AI_OpenAI_Model_Not_Configured: "Twój model OpenAI nie jest poprawnie skonfigurowany. Proszę sprawdzić swoją konfigurację",
AI_Gemini_Model_Not_Configured: "Twój model Gemini nie jest poprawnie skonfigurowany. Proszę sprawdzić swoją konfigurację",
AI_Workspace_Model_Not_Configured: "Twoja AI w Workspace nie jest poprawnie skonfigurowana. Proszę skontaktować się z administratorem",
AI_Not_Configured_Personal: "Twój __provider__ nie jest skonfigurowany. Proszę skonfigurować go używając `/quick config`.",
AI_Not_Configured_Admin_Self: "__provider__ nie jest skonfigurowany. Proszę dodać go w ustawieniach aplikacji.",
AI_Not_Configured_Workspace_User: "__provider__ nie jest skonfigurowany. Proszę skontaktować się z administratorem.",
AI_Something_Went_Wrong: "Coś poszło nie tak. Proszę spróbować ponownie później.",
AI_No_Message_Found: "Nie znaleziono wiadomości w tym pokoju do wygenerowania odpowiedzi. Proszę najpierw wysłać wiadomość.",
Refresh_Button_Text: "Odśwież",
AI_Suggestions_Header: "Sugerowane Odpowiedzi",
Auto_Suggest_Enabled: "Włączone",
Expand Down
10 changes: 4 additions & 6 deletions src/lib/Translation/locales/pt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,11 @@ export const pt = {
Send_This_Text: "Enviar esta resposta",
AI_Prompt_Options_Label: "Opções de prompt de IA",
AI_Prompt_Options_Placeholder: "Selecione opções de configuração de IA",
AI_Not_Configured_Personal: "IA não está configurada. Por favor, verifique sua configuração para usar este recurso.",
AI_Not_Configured_Admin: "IA não está configurada. Por favor, entre em contato com o administrador para usar este recurso.",
AI_Self_Hosted_Model_Not_Configured: "Seu Modelo Auto-Hospedado não está configurado corretamente. Por favor, verifique sua configuração",
AI_OpenAI_Model_Not_Configured: "Seu Modelo OpenAI não está configurado corretamente. Por favor, verifique sua configuração",
AI_Gemini_Model_Not_Configured: "Seu Modelo Gemini não está configurado corretamente. Por favor, verifique sua configuração",
AI_Workspace_Model_Not_Configured: "Sua IA do Workspace não está configurada corretamente. Por favor, entre em contato com o administrador",
AI_Not_Configured_Personal: "Seu __provider__ não está configurado. Por favor, configure-o usando `/quick config`.",
AI_Not_Configured_Admin_Self: "O __provider__ não está configurado. Por favor, adicione-o nas configurações do app.",
AI_Not_Configured_Workspace_User: "O __provider__ não está configurado. Por favor, entre em contato com o administrador.",
AI_Something_Went_Wrong: "Algo deu errado. Por favor, tente novamente mais tarde.",
AI_No_Message_Found: "Nenhuma mensagem encontrada nesta sala para gerar uma resposta. Por favor, envie uma mensagem primeiro.",
Refresh_Button_Text: "Atualizar",
AI_Suggestions_Header: "Respostas Sugeridas",
Auto_Suggest_Enabled: "Ativado",
Expand Down
10 changes: 4 additions & 6 deletions src/lib/Translation/locales/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,11 @@ export const ru = {
Send_This_Text: "Отправить этот ответ",
AI_Prompt_Options_Label: "Параметры подсказок ИИ",
AI_Prompt_Options_Placeholder: "Выберите параметры конфигурации AI",
AI_Not_Configured_Personal: "ИИ не настроен. Пожалуйста, проверьте свою конфигурацию, чтобы использовать эту функцию.",
AI_Not_Configured_Admin: "ИИ не настроен. Пожалуйста, свяжитесь с администратором, чтобы использовать эту функцию.",
AI_Self_Hosted_Model_Not_Configured: "Ваша собственная модель не настроена должным образом. Пожалуйста, проверьте свою конфигурацию",
AI_OpenAI_Model_Not_Configured: "Ваша модель OpenAI не настроена должным образом. Пожалуйста, проверьте свою конфигурацию",
AI_Gemini_Model_Not_Configured: "Ваша модель Gemini не настроена должным образом. Пожалуйста, проверьте свою конфигурацию",
AI_Workspace_Model_Not_Configured: "Ваша AI в Workspace не настроена должным образом. Пожалуйста, свяжитесь с администратором",
AI_Not_Configured_Personal: "Ваш __provider__ не настроен. Пожалуйста, настройте его с помощью `/quick config`.",
AI_Not_Configured_Admin_Self: "__provider__ не настроен. Пожалуйста, добавьте его в настройках приложения.",
AI_Not_Configured_Workspace_User: "__provider__ не настроен. Пожалуйста, свяжитесь с администратором.",
AI_Something_Went_Wrong: "Что-то пошло не так. Пожалуйста, попробуйте позже.",
AI_No_Message_Found: "Сообщение не найдено в этой комнате для генерации ответа. Пожалуйста, сначала отправьте сообщение.",
Refresh_Button_Text: "Обновить",
AI_Suggestions_Header: "Предложенные Ответы",
Auto_Suggest_Enabled: "Включено",
Expand Down
11 changes: 4 additions & 7 deletions src/lib/Translation/translation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,10 @@ export enum Language {
}

export const ErrorKeys = [
'AI_Not_Configured_Personal',
'AI_Not_Configured_Admin',
'AI_Self_Hosted_Model_Not_Configured',
'AI_OpenAI_Model_Not_Configured',
'AI_Gemini_Model_Not_Configured',
'AI_Workspace_Model_Not_Configured',
'AI_Something_Went_Wrong'
'AI_Not_Configured_Personal',
'AI_Not_Configured_Admin_Self',
'AI_Not_Configured_Workspace_User',
'AI_Something_Went_Wrong',
] as TranslationKey[];

export const t = (key: TranslationKey, language: Language, params?: object) => {
Expand Down