Merge pull request #98 from micz/openai_api

OpenAI API Integration
This commit is contained in:
Mic 2024-07-30 21:55:36 +02:00 committed by GitHub
commit 63d8b9ced4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 1579 additions and 83 deletions

View file

@ -3,6 +3,11 @@
<h2>Version 2.0.0 - 30/07/2024</h2>
<ul>
<li>Added OpenAI ChatGPT API connection [<a href="https://github.com/micz/ThunderAI/issues/40">#40</a>].</li>
<li>Information text in the options page improved.</li>
</ul>
<h2>Version 1.2.1 - 20/07/2024</h2>
<ul>
<li>Fixed changes in the ChatGPT web interface when importing in plain text [<a href="https://github.com/micz/ThunderAI/issues/87">#87</a>].</li>

View file

@ -28,5 +28,7 @@ ThunderAI's changes are logged [here](CHANGELOG.md).
<br>Thanks to:
<ul><li><a href="https://github.com/KudoAI/chatgpt.js">chatgpt.js</a> for providing methods to interact with the ChatGTP frontend.</li>
<li><a href="https://github.com/ali-raheem/Aify">Aify</a> for inspiration.</li>
<li><a href="https://github.com/boxabirds">Julian Harris</a> for his project <a href="https://github.com/boxabirds/chatgpt-frontend-nobuild">chatgpt-frontend-nobuild</a>, that has been used as a starting point for the API Web Interface.
.</li>
</ul>
<i>The specific references are described in the corresponding source files.</i>

View file

@ -320,11 +320,11 @@
"description": ""
},
"prefsInfoDesc_1": {
"message": "Es ist nicht mehr möglich, den Verlauf der ChatGPT-Chats zu deaktivieren. Daher gibt es keine Möglichkeit, zu verhindern, dass Anfragen, die über dieses Addon gestellt werden, in Ihrem ChatGPT-Chatverlauf erscheinen.",
"message": "Wenn eine weiße Seite erscheint, wenn das ChatGPT-Fenster geöffnet wird, bedeutet dies, dass es ein Problem beim Laden der ChatGPT-Seite gibt, das nicht mit der Verwendung dieses Add-Ons zusammenhängt.",
"description": ""
},
"prefsInfoDesc_2": {
"message": "Wenn eine weiße Seite erscheint, wenn das ChatGPT-Fenster geöffnet wird, bedeutet dies, dass es ein Problem beim Laden der ChatGPT-Seite gibt, das nicht mit der Verwendung dieses Add-Ons zusammenhängt.",
"message": "Um die ChatGPT-API zu verwenden, benötigen Sie einen OpenAI ChatGPT-API-Schlüssel und müssen ein Modell auswählen. Falls Sie dies nicht tun, wird ThunderAI auf die Verwendung der ChatGPT-Webschnittstelle zurückgreifen.",
"description": ""
},
"prefsInfoDesc_3": {
@ -386,5 +386,57 @@
"customprompts_form_label_define_response_lang": {
"message": "Definieren Sie die Antwortsprache im Prompt.",
"description": ""
},
"prefs_Connection_type": {
"message": "Verbindungstyp",
"description": ""
},
"prefs_Connection_type_ChatGTP_Web": {
"message": "ChatGTP Weboberfläche",
"description": ""
},
"prefs_Connection_type_ChatGTP_API": {
"message": "ChatGTP OpenAI API",
"description": ""
},
"prefs_ChatGPT_API_Key": {
"message": "ChatGPT API-Schlüssel",
"description": ""
},
"ChatGPT_Models": {
"message": "ChatGPT-Modelle",
"description": ""
},
"ChatGPT_Models_Fetch": {
"message": "Liste der ChatGPT-Modelle aktualisieren",
"description": ""
},
"ChatGPT_Models_Error_fetching": {
"message": "Fehler beim Abrufen der ChatGPT-Modelle",
"description": ""
},
"ChatGPT_Models_Loading": {
"message": "Laden...",
"description": ""
},
"error": {
"message": "ThunderAI-Fehler!",
"description": ""
},
"chatgpt_empty_apikey": {
"message": "Sie haben keinen API-Schlüssel für das ChatGPT-API hinzugefügt. Bitte fügen Sie einen auf der Optionsseite ein.",
"description": ""
},
"chatgpt_empty_model": {
"message": "Sie haben kein Modell für das ChatGPT-API ausgewählt. Bitte wählen Sie eines auf der Optionsseite aus.",
"description": ""
},
"chagtp_api_send_button": {
"message": "Modell wird verwendet",
"description": ""
},
"chagtp_api_connecting": {
"message": "Versucht, eine Verbindung zu OpenAI ChatGPT mit dem angegebenen API-Schlüssel herzustellen...",
"description": ""
}
}

View file

@ -320,11 +320,11 @@
"description": ""
},
"prefsInfoDesc_1": {
"message": "It is no longer possible to disable the history of ChatGPT chats. Therefore, there is no way to prevent requests made through this addon from appearing in your ChatGPT chat history.",
"message": "If a blank or white page appears when opening the ChatGPT web interface window, it means there is a problem loading the ChatGPT page, not related to the use of this add-on.",
"description": ""
},
"prefsInfoDesc_2": {
"message": "If a white page appears when opening the ChatGPT window, it means there is a problem loading the ChatGPT page, not related to the use of this add-on.",
"message": "To use the ChatGPT API, you need an OpenAI ChatGPT API Key and must choose a model. If you fail to do so, ThunderAI will fall back to using the ChatGPT web interface.",
"description": ""
},
"prefsInfoDesc_3": {
@ -386,5 +386,57 @@
"customprompts_form_label_define_response_lang": {
"message": "Define the reponse languange in the prompt",
"description": ""
},
"prefs_Connection_type": {
"message": "Connection Type",
"description": ""
},
"prefs_Connection_type_ChatGTP_Web": {
"message": "ChatGTP Web Interface",
"description": ""
},
"prefs_Connection_type_ChatGTP_API": {
"message": "ChatGTP OpenAI API",
"description": ""
},
"prefs_ChatGPT_API_Key": {
"message": "ChatGPT API Key",
"description": ""
},
"ChatGPT_Models": {
"message": "ChatGPT Models",
"description": ""
},
"ChatGPT_Models_Fetch": {
"message": "Update ChatGPT Models list",
"description": ""
},
"ChatGPT_Models_Error_fetching": {
"message": "Error trying to fetch ChatGPT models",
"description": ""
},
"ChatGPT_Models_Loading": {
"message": "Loading...",
"description": ""
},
"error": {
"message": "ThunderAI Error!",
"description": ""
},
"chatgpt_empty_apikey": {
"message": "You've not added an API Key for the ChatGPT API. Please insert one in the options page.",
"description": ""
},
"chatgpt_empty_model": {
"message": "You've not choosen a model for the ChatGPT API. Please choose one in the options page.",
"description": ""
},
"chagtp_api_send_button": {
"message": "Using model",
"description": ""
},
"chagtp_api_connecting": {
"message": "Will attempt to connect to OpenAI ChatGPT using the API key provided...",
"description": ""
}
}

View file

@ -320,11 +320,11 @@
"description": ""
},
"prefsInfoDesc_1": {
"message": "Il n'est plus possible de désactiver l'historique des chats ChatGPT. Par conséquent, il n'y a aucun moyen d'empêcher les demandes effectuées via cet addon d'apparaître dans l'historique de vos chats ChatGPT.",
"message": "Si une page blanche apparaît lors de l'ouverture de la fenêtre ChatGPT, cela signifie qu'il y a un problème de chargement de la page ChatGPT, non lié à l'utilisation de cet addon.",
"description": ""
},
"prefsInfoDesc_2": {
"message": "Si une page blanche apparaît lors de l'ouverture de la fenêtre ChatGPT, cela signifie qu'il y a un problème de chargement de la page ChatGPT, non lié à l'utilisation de cet addon.",
"message": "Pour utiliser l'API ChatGPT, vous avez besoin d'une clé API OpenAI ChatGPT et devez choisir un modèle. Si vous ne le faites pas, ThunderAI utilisera l'interface web de ChatGPT par défaut.",
"description": ""
},
"prefsInfoDesc_3": {
@ -386,5 +386,57 @@
"customprompts_form_label_define_response_lang": {
"message": "Définir la langue de réponse dans le prompt.",
"description": ""
},
"prefs_Connection_type": {
"message": "Type de connexion",
"description": ""
},
"prefs_Connection_type_ChatGTP_Web": {
"message": "Interface Web ChatGTP",
"description": ""
},
"prefs_Connection_type_ChatGTP_API": {
"message": "API OpenAI ChatGTP",
"description": ""
},
"prefs_ChatGPT_API_Key": {
"message": "Clé API ChatGPT",
"description": ""
},
"ChatGPT_Models": {
"message": "Modèles ChatGPT",
"description": ""
},
"ChatGPT_Models_Fetch": {
"message": "Mettre à jour la liste des modèles ChatGPT",
"description": ""
},
"ChatGPT_Models_Error_fetching": {
"message": "Erreur lors de la récupération des modèles ChatGPT",
"description": ""
},
"ChatGPT_Models_Loading": {
"message": "Chargement...",
"description": ""
},
"error": {
"message": "Erreur ThunderAI !",
"description": ""
},
"chatgpt_empty_apikey": {
"message": "Vous n'avez pas ajouté de clé API pour l'API ChatGPT. Veuillez en insérer une sur la page des options.",
"description": ""
},
"chatgpt_empty_model": {
"message": "Vous n'avez pas choisi de modèle pour l'API ChatGPT. Veuillez en choisir un sur la page des options.",
"description": ""
},
"chagtp_api_send_button": {
"message": "Utilisation du modèle",
"description": ""
},
"chagtp_api_connecting": {
"message": "Tentative de connexion à OpenAI ChatGPT en utilisant la clé API fournie...",
"description": ""
}
}

View file

@ -320,11 +320,11 @@
"description": ""
},
"prefsInfoDesc_1": {
"message": "Non è più possibile disabilitare la cronologia delle chat di ChatGPT. Pertanto, non c'è modo di impedire che le richieste effettuate tramite questo componente aggiuntivo appaiano nella cronologia delle chat di ChatGPT.",
"message": "Se all'apertura della finestra dell'interfaccia web di ChatGPT, viene mostrata una pagina bianca o vuota, significa che c'è un problema di caricamento della pagina di ChatGPT, non relativo all'utilizzo di questo componente aggiuntivo.",
"description": ""
},
"prefsInfoDesc_2": {
"message": "Se all'apertura della finestra di ChatGPT, viene mostrata una pagina bianca, significa che c'è un problema di caricamento della pagina di ChatGPT, non relativo all'utilizzo di questo componente aggiuntivo.",
"message": "Per utilizzare l'API di ChatGPT, è necessaria una OpenAI ChatGPT API Key e devi scegliere un modello. Se non lo fai, ThunderAI utilizzerà l'interfaccia web di ChatGPT.",
"description": ""
},
"prefsInfoDesc_3": {
@ -386,5 +386,57 @@
"customprompts_form_label_define_response_lang": {
"message": "Definisci la lingua di risposta nel prompt.",
"description": ""
},
"prefs_Connection_type": {
"message": "Tipo di connessione",
"description": ""
},
"prefs_Connection_type_ChatGTP_Web": {
"message": "Interfaccia Web ChatGTP",
"description": ""
},
"prefs_Connection_type_ChatGTP_API": {
"message": "API OpenAI per ChatGTP",
"description": ""
},
"prefs_ChatGPT_API_Key": {
"message": "Chiave API ChatGPT",
"description": ""
},
"ChatGPT_Models": {
"message": "Modelli ChatGPT",
"description": ""
},
"ChatGPT_Models_Fetch": {
"message": "Aggiorna l'elenco dei modelli ChatGPT",
"description": ""
},
"ChatGPT_Models_Error_fetching": {
"message": "Errore durante il recupero dei modelli di ChatGPT",
"description": ""
},
"ChatGPT_Models_Loading": {
"message": "Caricamento in corso...",
"description": ""
},
"error": {
"message": "Errore ThunderAI!",
"description": ""
},
"chatgpt_empty_apikey": {
"message": "Non hai aggiunto una chiave API per l'API di ChatGPT. Per favore, inseriscine una nella pagina delle opzioni.",
"description": ""
},
"chatgpt_empty_model": {
"message": "Non hai scelto un modello per l'API di ChatGPT. Per favore, scegline uno nella pagina delle opzioni.",
"description": ""
},
"chagtp_api_send_button": {
"message": "Modello utilizzato",
"description": ""
},
"chagtp_api_connecting": {
"message": "Tentativo di connessione a OpenAI ChatGPT utilizzando la chiave API fornita...",
"description": ""
}
}

201
api_webchat/LICENSE Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

102
api_webchat/controller.js Normal file
View file

@ -0,0 +1,102 @@
/*
* ThunderAI [https://micz.it/thunderbird-addon-thunderai/]
* Copyright (C) 2024 Mic (m@micz.it)
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* This file contains a modified version of the code from the project at https://github.com/boxabirds/chatgpt-frontend-nobuild
* The original code has been released under the Apache License, Version 2.0.
*/
// The controller wires up all the components and workers together,
// managing the dependencies. A kind of "DI" class.
const worker = new Worker('model-worker.js', { type: 'module' });
const messagesArea = document.querySelector('messages-area');
messagesArea.init(worker);
// Initialize the messageInput component and pass the worker to it
const messageInput = document.querySelector('message-input');
messageInput.init(worker);
messageInput.setMessagesArea(messagesArea);
// Data received from the user
let promptData = null;
// ============================== TESTING
// let browser = {
// i18n: {
// getMessage: async function(key) {
// return key;
// }
// },
// storage: {
// sync: {
// get: async function(key) {
// return 'apitest';
// }
// }
// }
// }
// ============================== TESTING - END
const params = new URLSearchParams(window.location.search);
let prefs_api = await browser.storage.sync.get({chatgpt_api_key: '', chatgpt_model: ''});
// const openaiApiKey = params.get('openapi-key');
//console.log(">>>>>>>>>>> chatgpt_api_key: " + prefs_api_key.chatgpt_api_key);
worker.postMessage({ type: 'init', chatgpt_api_key: prefs_api.chatgpt_api_key, chatgpt_model: prefs_api.chatgpt_model});
messagesArea.appendUserMessage(browser.i18n.getMessage("chagtp_api_connecting"), "info");
// Event listeners for worker messages
// TODO I'm sure there's a better way to do this
worker.onmessage = function(event) {
const { type, payload } = event.data;
switch (type) {
case 'messageSent':
messageInput.handleMessageSent();
break;
case 'newToken':
messagesArea.handleNewToken(payload.token);
break;
case 'tokensDone':
messagesArea.handleTokensDone(promptData);
messageInput.enableInput();
break;
case 'error':
messagesArea.appendBotMessage(payload,'error');
break;
default:
console.error('[ThunderAI] Unknown event type from API worker:', type);
}
};
// handling commands from the backgound page
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
//console.log(">>>>>>>>>>>>> controller.js onMessage: " + JSON.stringify(message));
if (message.command === "chatgpt_send") {
//send the received prompt to the chatgpt api
if(message.do_custom_text=="1") {
let userInput = prompt(browser.i18n.getMessage("chatgpt_win_custom_text"));
if(userInput !== null) {
message.prompt += " " + userInput;
}
}
promptData = message;
messageInput._setMessageInputValue(message.prompt);
messageInput._handleNewChatMessage();
}
});

20
api_webchat/index.html Normal file
View file

@ -0,0 +1,20 @@
<head>
<!-- Other meta tags and stylesheets -->
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<!-- Use the custom tags directly -->
<div id="appContainer">
<messages-area></messages-area>
<message-input></message-input>
</div>
<div id="content">
</div>
<!-- Include the JavaScript files at bottom to avoid blocking UI -->
<script src="messageInput.js" type="module" defer></script>
<script src="markdown-it.min.js"></script>
<script src="messagesArea.js" type="module" defer></script>
<script src="controller.js" type="module" defer></script>
</body>

2
api_webchat/markdown-it.min.js vendored Normal file

File diff suppressed because one or more lines are too long

161
api_webchat/messageInput.js Normal file
View file

@ -0,0 +1,161 @@
/*
* ThunderAI [https://micz.it/thunderbird-addon-thunderai/]
* Copyright (C) 2024 Mic (m@micz.it)
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* This file contains a modified version of the code from the project at https://github.com/boxabirds/chatgpt-frontend-nobuild
* The original code has been released under the Apache License, Version 2.0.
*/
const messageInputTemplate = document.createElement('template');
const messagesInputStyle = document.createElement('style');
messagesInputStyle .textContent = `
:host {
display: flex;
justify-content: space-between;
align-items: center;
height: 24px;
margin: var(--margin);
margin-bottom: 20px;
}
#messageInputField {
flex-grow: 1;
padding: 10px;
font-size: 1rem;
border: 1px solid lightgrey;
border-radius: 10px;
margin-right: var(--padding);
outline: none;
}
#messageInputField:focus {
border-color: darkgrey;
}
#sendButton {
width: 44px;
height: 36px;
cursor: pointer;
border-radius: 10px;
}
@media (prefers-color-scheme: dark) {
#messageInputField {
background-color: #303030;
color: #ffffff;
}
}
`;
messageInputTemplate.content.appendChild(messagesInputStyle);
const inputField = document.createElement('input');
inputField.type = 'text';
inputField.id = 'messageInputField';
inputField.placeholder = '';
inputField.autocomplete = 'off';
messageInputTemplate.content.appendChild(inputField);
const sendButton = document.createElement('button');
sendButton.id = 'sendButton';
const sendIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
sendIcon.setAttribute('width', '24');
sendIcon.setAttribute('height', '24');
sendIcon.setAttribute('viewBox', '0 0 24 24');
sendIcon.setAttribute('fill', 'none');
sendIcon.classList.add('text-white', 'dark:text-black');
const sendPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
sendPath.setAttribute('d', 'M7 11L12 6L17 11M12 18V7');
sendPath.setAttribute('stroke', 'currentColor');
sendPath.setAttribute('stroke-width', '2');
sendPath.setAttribute('stroke-linecap', 'round');
sendPath.setAttribute('stroke-linejoin', 'round');
sendIcon.appendChild(sendPath);
sendButton.appendChild(sendIcon);
messageInputTemplate.content.appendChild(sendButton);
class MessageInput extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(messageInputTemplate.content.cloneNode(true));
this._messageInputField = shadowRoot.querySelector('#messageInputField');
this._sendButton = shadowRoot.querySelector('#sendButton');
this._messageInputField.addEventListener('keydown', this._handleKeyDown.bind(this));
this._sendButton.addEventListener('click', this._handleClick.bind(this));
}
connectedCallback() {
// Set focus to the input field when the element is added to the DOM
this._messageInputField.focus();
}
async init(worker) {
this.worker = worker;
let prefs_api = await browser.storage.sync.get({chatgpt_model: ''});
this._sendButton.title = await browser.i18n.getMessage("chagtp_api_send_button") + ": " + prefs_api.chatgpt_model;
}
setMessagesArea(messagesAreaComponent) {
this.messagesAreaComponent = messagesAreaComponent;
}
handleMessageSent() {
console.log("[ThunderAI] handleMessageSent");
this._messageInputField.value = '';
}
enableInput() {
console.log("[ThunderAI] enableInput");
this._messageInputField.value = '';
this._sendButton.removeAttribute('disabled');
this._messageInputField.removeAttribute('disabled');
}
_handleKeyDown(event) {
if (event.key === 'Enter') {
this._handleNewChatMessage();
}
}
_handleClick() {
this._handleNewChatMessage();
}
_handleNewChatMessage() {
//do nothing if input is empty
if ((!this._messageInputField.value)||(this._messageInputField.value.trim().length === 0)) {
return;
}
// prevent user from interacting while we're waiting
this._sendButton.setAttribute('disabled', 'disabled');
this._messageInputField.setAttribute('disabled', 'disabled');
let messageContent = this._messageInputField.value;
this._messageInputField.value = '';
if (this.messagesAreaComponent) {
this.messagesAreaComponent.appendUserMessage(messageContent);
}
this.worker.postMessage({ type: 'chatMessage', message: messageContent });
}
_setMessageInputValue(msg) {
this._messageInputField.value = msg;
}
}
customElements.define('message-input', MessageInput);

298
api_webchat/messagesArea.js Normal file
View file

@ -0,0 +1,298 @@
/*
* ThunderAI [https://micz.it/thunderbird-addon-thunderai/]
* Copyright (C) 2024 Mic (m@micz.it)
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* This file contains a modified version of the code from the project at https://github.com/boxabirds/chatgpt-frontend-nobuild
* The original code has been released under the Apache License, Version 2.0.
*/
const messagesAreaTemplate = document.createElement('template');
const messagesAreaStyle = document.createElement('style');
messagesAreaStyle.textContent = `
:host {
display: flex;
flex-direction: column;
height: 100%;
overflow-y: auto;
}
#messages {
display: flex;
flex-direction: column;
justify-content: flex-end;
min-height: 100%;
margin-left: var(--margin);
margin-right: var(--margin);
}
.message {
margin: 0;
line-height: 1.3;
padding: 5px;
border-radius: 10px;
}
.message p{
margin: 0;
padding: 0;
}
.token {
display: inline;
opacity: 0;
animation: fadeIn 1000ms forwards;
}
.action-buttons {
line-height: 1.3;
text-align: center;
}
.action-buttons button {
display: inline;
margin: 0 10px;
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
}
@keyframes fadeIn {
to {
opacity: 1;
}
}
h2 {
font-weight: bold;
font-size: 1rem;
margin-top: 20px;
}
hr {
width: 100%;
}
.error{
background: lightcoral;
color: white;
margin-bottom: var(--margin);
}
.info{
background: lightblue;
color: navy;
margin-bottom: var(--margin);
}
`;
messagesAreaTemplate.content.appendChild(messagesAreaStyle);
const messagesDiv = document.createElement('div');
messagesDiv.id = 'messages';
messagesAreaTemplate.content.appendChild(messagesDiv);
class MessagesArea extends HTMLElement {
fullTextHTML = "";
constructor() {
super();
this.accumulatingMessageEl = null;
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(messagesAreaTemplate.content.cloneNode(true));
this.messages = shadowRoot.querySelector('#messages');
}
createNewAccumulatingMessage() {
const lastMessage = this.messages.lastElementChild;
const isLastMessageFromUser = lastMessage && lastMessage.classList.contains('user');
if (isLastMessageFromUser) {
const header = document.createElement('h2');
header.textContent = "ChatGTP";
this.messages.appendChild(header);
}
this.accumulatingMessageEl = document.createElement('div');
this.accumulatingMessageEl.classList.add('message', 'bot');
this.messages.appendChild(this.accumulatingMessageEl);
}
init(worker) {
this.worker = worker;
}
handleTokensDone(promptData = null) {
this.flushAccumulatingMessage();
this.addActionButtons(promptData);
this.addDivider();
}
appendUserMessage(messageText, type="user") {
this.fullTextHTML = "";
console.log("[ThunderAI] appendUserMessage: " + messageText);
const header = document.createElement('h2');
let source = "You";
switch (type) {
case "user":
source = "You";
break;
case "info":
source = "Information";
break;
}
header.textContent = source;
this.messages.appendChild(header);
const messageElement = document.createElement('div');
messageElement.classList.add('message', type);
messageElement.textContent = messageText;
this.messages.appendChild(messageElement);
this.scrollToBottom();
}
appendBotMessage(messageText, type="bot") {
console.log("[ThunderAI] appendBotMessage: " + messageText);
this.fullTextHTML = messageText;
const lastMessage = this.messages.lastElementChild;
const isLastMessageFromUser = lastMessage && lastMessage.classList.contains('user');
if (isLastMessageFromUser) {
const header = document.createElement('h2');
header.textContent = "Chat GPT" + (type=='error' ? " - Error" : "");
this.messages.appendChild(header);
}
const messageElement = document.createElement('div');
messageElement.classList.add('message', type);
messageElement.textContent = messageText;
this.messages.appendChild(messageElement);
this.scrollToBottom();
}
handleNewToken(token) {
if (!this.accumulatingMessageEl) {
this.createNewAccumulatingMessage();
}
const newTokenElement = document.createElement('span');
newTokenElement.classList.add('token');
newTokenElement.textContent = token;
this.accumulatingMessageEl.appendChild(newTokenElement);
this.scrollToBottom();
if (token === '\n') {
this.flushAccumulatingMessage();
}
}
scrollToBottom() {
this.messages.scrollTop = this.messages.scrollHeight;
}
addActionButtons(promptData = null) {
// ============================== TESTING
// promptData = {
// action: "1",
// tabId: 1,
// mailMessageId: 1
// }
// let browser = {
// i18n: {
// getMessage: async function(key) {
// return key;
// }
// },
// storage: {
// sync: {
// get: async function(key) {
// return 'apitest';
// }
// }
// }
// }
// ============================== TESTING - END
if(promptData == null) { return; }
const actionButtons = document.createElement('div');
actionButtons.classList.add('action-buttons');
const actionButton = document.createElement('button');
actionButton.textContent = 'Use this answer';
//actionButton.textContent = browser.i18n.getMessage("chatgpt_win_get_answer");
const fullTextHTMLAtAssignment = this.fullTextHTML;
actionButton.addEventListener('click', () => {
switch(promptData.action) {
case "1": // do reply
console.log("[ThundeAI] (do reply) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment);
browser.runtime.sendMessage({command: "chatgpt_replyMessage", text: fullTextHTMLAtAssignment, tabId: promptData.tabId, mailMessageId: promptData.mailMessageId});
browser.runtime.sendMessage({command: "chatgpt_close"});
break;
case "2": // replace text
console.log("[ThundeAI] (replace text) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment);
browser.runtime.sendMessage({command: "chatgpt_replaceSelectedText", text: fullTextHTMLAtAssignment, tabId: promptData.tabId, mailMessageId: promptData.mailMessageId});
//console.log(response);
browser.runtime.sendMessage({command: "chatgpt_close"});
break;
}
});
const closeButton = document.createElement('button');
closeButton.textContent = browser.i18n.getMessage("chatgpt_win_close");
closeButton.addEventListener('click', () => {
console.log("[ThundeAI] (close) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment);
browser.runtime.sendMessage({command: "chatgpt_close"}); // close window
});
if(promptData.action != 0) { actionButtons.appendChild(actionButton); }
actionButtons.appendChild(closeButton);
this.messages.appendChild(actionButtons);
this.scrollToBottom();
}
addDivider() {
const divider = document.createElement('hr');
this.messages.appendChild(divider);
this.scrollToBottom();
}
flushAccumulatingMessage() {
if (this.accumulatingMessageEl) {
// Collect all tokens in a full text
let fullText = '';
this.accumulatingMessageEl.querySelectorAll('.token').forEach(tokenEl => {
fullText += tokenEl.textContent;
});
// Convert Markdown to DOM nodes using the markdown-it library
const md = window.markdownit();
const html = md.render(fullText);
this.fullTextHTML += html;
// Create a new DOM parser
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Remove existing tokens
while (this.accumulatingMessageEl.firstChild) {
this.accumulatingMessageEl.removeChild(this.accumulatingMessageEl.firstChild);
}
// Append new nodes
Array.from(doc.body.childNodes).forEach(node => {
this.accumulatingMessageEl.appendChild(node);
});
this.accumulatingMessageEl = null;
}
}
}
customElements.define('messages-area', MessagesArea);

130
api_webchat/model-worker.js Normal file
View file

@ -0,0 +1,130 @@
/*
* ThunderAI [https://micz.it/thunderbird-addon-thunderai/]
* Copyright (C) 2024 Mic (m@micz.it)
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* This file contains a modified version of the code from the project at https://github.com/boxabirds/chatgpt-frontend-nobuild
* The original code has been released under the Apache License, Version 2.0.
*/
import { OpenAI } from '../js/api/openai.js';
//========================== for testing
// const MOCK_TOKENS = ['Good', ' morning', ' Mr', ' Plop', 'py', ',', 'and', ' I', ' said', '\n', '"', 'Good', ' morn', 'ing', ' Mrs',' Plop', 'py', ,'"', '\n', 'Oh', ' how', ' the', ' win', 'ter', ' even', 'ings', ' must', ' just', ' fly'];
//
// function mockDelay(ms) {
// return new Promise(resolve => setTimeout(resolve, ms));
// }
// async function processMockTokens() {
// for (const token of MOCK_TOKENS) {
// await mockDelay(Math.random() * 50 + 50); // Random delay between 100ms and 150ms
// postMessage({ type: 'newToken', payload: { token } });
// }
// postMessage({ type: 'tokensDone' });
// }
//========================== for testing - END
let chatgpt_api_key = null;
let chatgpt_model = '';
let openai = null;
let conversationHistory = [];
let assistantResponseAccumulator = '';
self.onmessage = async function(event) {
if (event.data.type === 'init') {
chatgpt_api_key = event.data.chatgpt_api_key;
chatgpt_model = event.data.chatgpt_model;
//console.log(">>>>>>>>>>> chatgpt_api_key: " + chatgpt_api_key);
openai = new OpenAI(chatgpt_api_key, chatgpt_model, true);
} else if (event.data.type === 'chatMessage') {
conversationHistory.push({ role: 'user', content: event.data.message });
// ============================== TESTING
// // Simulate sending the message to an HTTP endpoint
// await mockDelay(1000); // Wait for 1 second
// // Notify that the chat message was sent
// postMessage({ type: 'messageSent' });
// // Start processing tokens
// await processMockTokens();
// return;
// ============================== TESTING - END
// https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo
// 4096 output tokens
// 128,000 input tokens
// const response = await fetch(API_URL, {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// "Authorization": `Bearer ${openaiApiKey}`,
// },
// body: JSON.stringify({
// model: "gpt-4-1106-preview",
// messages: conversationHistory,
// stream: true,
// }),
// });
const response = await openai.fetchResponse(conversationHistory); //4096);
postMessage({ type: 'messageSent' });
if (!response.ok) {
const errorJSON = await response.json();
const errorDetail = JSON.stringify(errorJSON);
//console.log(">>>>>>>>>>>>> errorJSON.error.message: " + JSON.stringify(errorJSON.error.message));
postMessage({ type: 'error', payload: errorJSON.error.message });
throw new Error("[ThunderAI] OpenAI API request failed: " + response.status + " " + response.statusText + ", Detail: " + errorDetail);
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
while (true) {
const { done, value } = await reader.read();
if (done) {
conversationHistory.push({ role: 'assistant', content: assistantResponseAccumulator });
assistantResponseAccumulator = '';
postMessage({ type: 'tokensDone' });
break;
}
// lots of low-level OpenAI response parsing stuff
const chunk = decoder.decode(value);
const lines = chunk.split("\n");
const parsedLines = lines
.map((line) => line.replace(/^data: /, "").trim()) // Remove the "data: " prefix
.filter((line) => line !== "" && line !== "[DONE]") // Remove empty lines and "[DONE]"
.map((line) => JSON.parse(line)); // Parse the JSON string
for (const parsedLine of parsedLines) {
const { choices } = parsedLine;
const { delta } = choices[0];
const { content } = delta;
// Update the UI with the new content
if (content) {
assistantResponseAccumulator += content;
postMessage({ type: 'newToken', payload: { token: content } });
}
}
}
}
};

49
api_webchat/styles.css Normal file
View file

@ -0,0 +1,49 @@
/* Global styles */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center; /* Center horizontally */
height: 100vh; /* Full viewport height */
}
#appContainer {
display: flex;
flex-direction: column;
height: 100vh; /* Full height of the viewport */
max-width: 768px; /* Max width of 768px */
width: 100%; /* Use full width up to 768px */
margin: 0 auto; /* Center horizontally without affecting vertical alignment */
}
messages-area {
flex-grow: 1;
overflow: auto;
}
/* Colors */
:root {
--red: #ff0000;
--green: #00ff00;
--margin: 10px;
--padding: 10px;
}
/* Typography */
h1, h2, h3, h4, h5, h6 {
margin: 0 0 10px 0;
font-weight: normal;
}
p {
margin: 0 0 10px 0;
}
/* Dark mode styles */
@media (prefers-color-scheme: dark) {
body {
background-color: #000000;
color: #ffffff;
}
}

88
js/api/openai.js Normal file
View file

@ -0,0 +1,88 @@
/*
* ThunderAI [https://micz.it/thunderbird-addon-thunderai/]
* Copyright (C) 2024 Mic (m@micz.it)
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Some original methods derived from https://github.com/ali-raheem/Aify/blob/4ece286095ea7a6cf89d696902e6b81b5d1c3a4b/plugin/html/API.js
export class OpenAI {
apiKey = '';
model = '';
stream = false;
constructor(apiKey, model, stream) {
this.apiKey = apiKey;
this.model = model;
this.stream = stream;
}
fetchModels = async () => {
const response = await fetch("https://api.openai.com/v1/models", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer "+ this.apiKey
},
});
if (!response.ok) {
const errorDetail = await response.text();
let err_msg = "[ThunderAI] OpenAI API request failed: " + response.status + " " + response.statusText + ", Detail: " + errorDetail;
console.error(err_msg);
return false;
}
let output = await response.json();
return output.data.filter(item => item.id.startsWith('gpt-')).sort((a, b) => b.id.localeCompare(a.id));
}
fetchResponse = async (messages, maxTokens = 0) => {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer "+ this.apiKey
},
body: JSON.stringify({
model: this.model,
messages: messages,
stream: this.stream,
...(maxTokens > 0 ? { 'max_tokens': parseInt(maxTokens) } : {})
}),
});
return response;
}
async countTokensUsingAPI(model, text) {
const response = await fetch('https://api.openai.com/v1/engines/'+model+'/tokenizer', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.apiKey
},
body: JSON.stringify({ text })
});
const data = await response.json();
return data.token_count;
}
}

View file

@ -2,7 +2,7 @@
"manifest_version": 2,
"name": "ThunderAI",
"description": "__MSG_extensionDescription__",
"version": "1.2.1",
"version": "2.0.0",
"author": "Mic (m@micz.it)",
"homepage_url": "https://micz.it/thunderbird-addon-thunderai/",
"browser_specific_settings": {
@ -31,6 +31,7 @@
"activeTab",
"accountsRead",
"downloads",
"notifications",
"<all_urls>"
],
"background": {

View file

@ -146,55 +146,108 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_
browser.tabs.sendMessage(curr_tabId, { command: "promptTooLong" });
return;
}
let newWindow = await browser.windows.create({
url: "https://chatgpt.com",
type: "popup",
width: prefs.chatgpt_win_width,
height: prefs.chatgpt_win_height
});
console.log("[ThunderAI] Script started...");
createdWindowID = newWindow.id;
const createdTab = newWindow.tabs[0];
// check if the API is present, otherwise open the web interface
if (prefs.chatgpt_api_key == '') {
showNotification(browser.i18n.getMessage('error'),browser.i18n.getMessage('chatgpt_empty_apikey'));
prefs.connection_type = 'chatgpt_web';
}
if (prefs.chatgpt_model == '') {
showNotification(browser.i18n.getMessage('error'),browser.i18n.getMessage('chatgpt_empty_model'));
prefs.connection_type = 'chatgpt_web';
}
// Wait for tab loaded.
await new Promise(resolve => {
const tabIsLoaded = tab => {
return tab.status == "complete" && tab.url != "about:blank";
};
const listener = (tabId, changeInfo, updatedTab) => {
if (tabIsLoaded(updatedTab)) {
browser.tabs.onUpdated.removeListener(listener);
resolve();
}
}
// Early exit if loaded already
if (tabIsLoaded(createdTab)) {
resolve();
} else {
browser.tabs.onUpdated.addListener(listener);
}
});
let pre_script = `let mztaStatusPageDesc="`+ browser.i18n.getMessage("prefs_status_page") +`";
let mztaForceCompletionDesc="`+ browser.i18n.getMessage("chatgpt_force_completion") +`";
let mztaForceCompletionTitle="`+ browser.i18n.getMessage("chatgpt_force_completion_title") +`";
let mztaDoCustomText=`+ do_custom_text +`;
let mztaKeepFormatting=`+ prefs.chatgpt_keep_formatting +`;
let mztaPromptName="[`+ i18nConditionalGet(prompt_name) +`]";
`;
browser.tabs.executeScript(createdTab.id, { code: pre_script + mzta_script, matchAboutBlank: false })
.then(async () => {
console.log("[ThunderAI] Script injected successfully");
let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId);
let mailMessageId = -1;
if(mailMessage) mailMessageId = mailMessage.id;
browser.tabs.sendMessage(createdTab.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId});
})
.catch(err => {
console.error("[ThunderAI] Error injecting the script: ", err);
switch(prefs.connection_type){
case 'chatgpt_web':
// We are using the ChatGPT web interface
let newWindow = await browser.windows.create({
url: "https://chatgpt.com",
type: "popup",
width: prefs.chatgpt_win_width,
height: prefs.chatgpt_win_height
});
console.log("[ThunderAI] ChatGPT web interface script started...");
createdWindowID = newWindow.id;
let createdTab = newWindow.tabs[0];
// Wait for tab loaded.
await new Promise(resolve => {
const tabIsLoaded = tab => {
return tab.status == "complete" && tab.url != "about:blank";
};
const listener = (tabId, changeInfo, updatedTab) => {
if (tabIsLoaded(updatedTab)) {
browser.tabs.onUpdated.removeListener(listener);
resolve();
}
}
// Early exit if loaded already
if (tabIsLoaded(createdTab)) {
resolve();
} else {
browser.tabs.onUpdated.addListener(listener);
}
});
let pre_script = `let mztaStatusPageDesc="`+ browser.i18n.getMessage("prefs_status_page") +`";
let mztaForceCompletionDesc="`+ browser.i18n.getMessage("chatgpt_force_completion") +`";
let mztaForceCompletionTitle="`+ browser.i18n.getMessage("chatgpt_force_completion_title") +`";
let mztaDoCustomText=`+ do_custom_text +`;
let mztaKeepFormatting=`+ prefs.chatgpt_keep_formatting +`;
let mztaPromptName="[`+ i18nConditionalGet(prompt_name) +`]";
`;
browser.tabs.executeScript(createdTab.id, { code: pre_script + mzta_script, matchAboutBlank: false })
.then(async () => {
console.log("[ThunderAI] ChatGPT web interface script injected successfully");
let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId);
let mailMessageId = -1;
if(mailMessage) mailMessageId = mailMessage.id;
browser.tabs.sendMessage(createdTab.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId});
})
.catch(err => {
console.error("[ThunderAI] ChatGPT web interface error injecting the script: ", err);
});
break; // chatgpt_web
case 'chatgpt_api':
// We are using the ChatGPT API
let newWindow2 = await browser.windows.create({
url: browser.runtime.getURL('api_webchat/index.html'),
type: "popup",
width: prefs.chatgpt_win_width,
height: prefs.chatgpt_win_height
});
createdWindowID = newWindow2.id;
let createdTab2 = newWindow2.tabs[0];
// Wait for tab loaded. // TODO This is needed in 128+, but doesn't work in 115
// await new Promise(resolve => {
// const tabIsLoaded2 = tab => {
// return tab.status == "complete" && tab.url != "about:blank";
// };
// const listener2 = (tabId, changeInfo, updatedTab) => {
// if (tabIsLoaded2(updatedTab)) {
// browser.tabs.onUpdated.removeListener(listener2);
// resolve();
// }
// }
// // Early exit if loaded already
// if (tabIsLoaded2(createdTab2)) {
// resolve();
// } else {
// browser.tabs.onUpdated.addListener(listener2);
// }
// });
let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId);
let mailMessageId = -1;
if(mailMessage) mailMessageId = mailMessage.id;
browser.tabs.sendMessage(createdTab2.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId, do_custom_text: do_custom_text});
break; // chatgpt_api
}
}
function checkScreenDimensions(prefs){
@ -207,6 +260,15 @@ function checkScreenDimensions(prefs){
return prefs;
}
function showNotification(title, message) {
browser.notifications.create({
"type": "basic",
"title": title,
"iconUrl": browser.extension.getURL("images/icon.png"),
"message": message
});
}
// Menus handling
const menus = new mzta_Menus(openChatGPT);
menus.loadMenus();

View file

@ -22,4 +22,7 @@ export const prefs_default = {
chatpgt_use_gpt4: false,
chatgpt_keep_formatting: false,
default_chatgpt_lang: '',
connection_type: 'chatgpt_web', //Other values: 'chatgpt_api'
chatgpt_api_key: '',
chatgpt_model: '',
}

View file

@ -1,16 +1,3 @@
@media (prefers-color-scheme: dark) {
body {
background-color: rgb(35, 34, 43);
color: rgb(251, 251, 254);
}
a:link { color: #409EFF; }
a:visited { color: #409EFF; }
a:hover { color: #66B1FF; }
a:active { color: #66B1FF; }
}
div#miczDescription{
padding:0px 15px 0px 15px;
font-size: 13px;
@ -99,4 +86,49 @@ div#miczTranslate{
font-size: 14px;
font-weight: bold;
margin-bottom: 1em;
}
tr.conntype_chatgpt_api, tr.conntype_chatgpt_api2{
background-color: rgb(185, 220, 252);
}
tr.conntype_chatgpt_web, tr.conntype_chatgpt_web2{
background-color: rgb(255, 209, 183);
}
/* color to be used for a local LLM
.conntype_chatgpt_web,.conntype_local_llm{
background-color: rgb(205, 255, 205);
}
*/
#model_fetch_loading{
display: none;
font-style: italic;
}
@media (prefers-color-scheme: dark) {
body {
background-color: rgb(35, 34, 43);
color: rgb(251, 251, 254);
}
a:link { color: #409EFF; }
a:visited { color: #409EFF; }
a:hover { color: #66B1FF; }
a:active { color: #66B1FF; }
tr.conntype_chatgpt_api, tr.conntype_chatgpt_api2{
background-color: rgb(0, 0, 58);
}
tr.conntype_chatgpt_web,tr.conntype_chatgpt_web2{
background-color: rgb(39, 11, 0);
}
/* color to be used for a local LLM
.conntype_chatgpt_web,.conntype_local_llm{
background-color: rgb(0, 39, 0);
}
*/
}

View file

@ -6,7 +6,7 @@
</head>
<body>
<div id="miczRelNotes"><a href="mzta-release-notes.html">__MSG_prefs_OptionText_release_notes__</a></div>
<div id="miczStatusPage"><a href="https://micz.it/thunderbird-addon-thunderai/status/">__MSG_prefs_status_page__</a></div>
<div id="miczStatusPage" class="conntype_chatgpt_web"><a href="https://micz.it/thunderbird-addon-thunderai/status/">__MSG_prefs_status_page__</a></div>
<table id="miczPrefs">
<tr>
<td><span>__MSG_prefs_OptionText_chatgpt_win_text__</span></td>
@ -60,6 +60,22 @@
</td>
</tr>
<tr>
<td>
<label>
<span>__MSG_prefs_Connection_type__</span>
</label>
</td>
<td>
<label>
<select id="connection_type" name="connection_type" class="option-input">
<option value="chatgpt_web">__MSG_prefs_Connection_type_ChatGTP_Web__</option>
<option value="chatgpt_api">__MSG_prefs_Connection_type_ChatGTP_API__</option>
</select>
</label>
</td>
</tr>
<tr>
<tr class="conntype_chatgpt_web">
<td><label>
<span>__MSG_prefs_OptionText_chatpgt_keep_formatting__</span>
</label></td>
@ -70,7 +86,7 @@
</label>
</td>
</tr>
<tr>
<tr class="conntype_chatgpt_web">
<td><label>
<span>__MSG_prefs_OptionText_chatpgt_use_gpt4__</span>
</label></td>
@ -81,15 +97,40 @@
</label>
</td>
</tr>
<tr class="conntype_chatgpt_api">
<td><label>
<span>__MSG_prefs_ChatGPT_API_Key__</span>
</label></td>
<td>
<label>
<input type="text" id="chatgpt_api_key" name="chatgpt_api_key" class="option-input" style="width:28em" />
&nbsp;<span></span>
</label>
</td>
</tr>
<tr class="conntype_chatgpt_api">
<td>
<label>
<span>__MSG_ChatGPT_Models__</span>
</label>
</td>
<td>
<button id="btnUpdateChatGPTModels">__MSG_ChatGPT_Models_Fetch__</button> <span id="model_fetch_loading">__MSG_ChatGPT_Models_Loading__</span><br>
<label>
<select id="chatgpt_model" name="chatgpt_model" class="option-input">
</select>
</label>
</td>
</tr>
</table>
<div id="btn_custom_prompts">
<button id="btnManagePrompts">__MSG_prefs_OptionText_btnManagePrompts__</button>
</div>
<div id="miczDescription">
<h1>__MSG_prefsInfoTitle__</h1>
<p>__MSG_prefsInfoDesc_1__<br/>
__MSG_prefsInfoDesc_2__<br/>
__MSG_prefsInfoDesc_3__</p>
<p><span class="conntype_chatgpt_web">__MSG_prefsInfoDesc_1__<br/></span>
<span class="conntype_chatgpt_api">__MSG_prefsInfoDesc_2__<br/>
__MSG_prefsInfoDesc_3__</span></p>
</div>
<div id="miczTranslate">__MSG_TranslateText__ <a href="https://micz.it/thunderbird-addon-thunderai/translate/">__MSG_TranslateLink__</a></div>
<div id="miczDonation">__MSG_prefsDonation_1__<br/><a href="http://micz.it/thunderbird-addon-thunderai/donate/">__MSG_prefsDonation_2__</a></div>

View file

@ -18,7 +18,7 @@
import { prefs_default } from './mzta-options-default.js';
import { getLanguageDisplayName } from '../js/mzta-utils.js'
import { OpenAI } from '../js/api/openai.js';
function saveOptions(e) {
e.preventDefault();
@ -46,9 +46,10 @@ function saveOptions(e) {
browser.storage.sync.set(options);
}
function restoreOptions() {
async function restoreOptions() {
function setCurrentChoice(result) {
document.querySelectorAll(".option-input").forEach(element => {
//console.log("[ThunderAI] Options restoring " + element.id + " = " + result[element.id]);
switch (element.type) {
case 'checkbox':
element.checked = result[element.id] || false;
@ -68,6 +69,7 @@ function restoreOptions() {
if (element.tagName === 'SELECT') {
let default_select_value = '';
if(element.id == 'reply_type') default_select_value = 'reply_all';
if(element.id == 'connection_type') default_select_value = 'chatgpt_web';
element.value = result[element.id] || default_select_value;
if (element.value === '') {
element.selectedIndex = -1;
@ -79,20 +81,66 @@ function restoreOptions() {
});
}
function onError(error) {
console.log(`[ThunderAI] Error: ${error}`);
}
let getting = browser.storage.sync.get(null);
getting.then(setCurrentChoice, onError);
let getting = await browser.storage.sync.get(prefs_default);
setCurrentChoice(getting);
}
document.addEventListener('DOMContentLoaded', () => {
restoreOptions();
function showConnectionOptions() {
let chatgpt_web_display = 'table-row';
let chatgpt_api_display = 'none';
let conntype_select = document.getElementById("connection_type");
let parent = conntype_select.parentElement.parentElement.parentElement;
parent.classList.toggle("conntype_chatgpt_api", (conntype_select.value === "chatgpt_api"));
parent.classList.toggle("conntype_chatgpt_web", (conntype_select.value === "chatgpt_web"));
if (conntype_select.value === "chatgpt_web") {
chatgpt_web_display = 'table-row';
}else{
chatgpt_web_display = 'none';
}
if (conntype_select.value === "chatgpt_api") {
chatgpt_api_display = 'table-row';
}else{
chatgpt_api_display = 'none';
}
document.querySelectorAll(".conntype_chatgpt_web").forEach(element => {
element.style.display = chatgpt_web_display;
});
document.querySelectorAll(".conntype_chatgpt_api").forEach(element => {
element.style.display = chatgpt_api_display;
});
}
function warnAPIKeyEmpty() {
let apiKeyInput = document.getElementById('chatgpt_api_key');
let btnFetchModels = document.getElementById('btnUpdateChatGPTModels');
let modelChatGPT = document.getElementById('chatgpt_model');
if(apiKeyInput.value === ''){
apiKeyInput.style.border = '2px solid red';
btnFetchModels.disabled = true;
modelChatGPT.disabled = true;
modelChatGPT.selectedIndex = -1;
modelChatGPT.style.border = 'none';
}else{
apiKeyInput.style.border = 'none';
btnFetchModels.disabled = false;
modelChatGPT.disabled = false;
if((modelChatGPT.selectedIndex === -1)||(modelChatGPT.value === '')){
modelChatGPT.style.border = '2px solid red';
}else{
modelChatGPT.style.border = 'none';
}
}
}
document.addEventListener('DOMContentLoaded', async () => {
await restoreOptions();
i18n.updateDocument();
document.querySelectorAll(".option-input").forEach(element => {
element.addEventListener("change", saveOptions);
});
showConnectionOptions();
document.getElementById('btnManagePrompts').addEventListener('click', () => {
// check if the tab is already there
browser.tabs.query({url: browser.runtime.getURL('../customprompts/mzta-custom-prompts.html')}).then((tabs) => {
@ -105,4 +153,42 @@ document.addEventListener('DOMContentLoaded', () => {
}
})
});
let conntype_select = document.getElementById("connection_type");
conntype_select.addEventListener("change", showConnectionOptions);
conntype_select.addEventListener("change", warnAPIKeyEmpty);
document.getElementById("chatgpt_api_key").addEventListener("change", warnAPIKeyEmpty);
let prefs = await browser.storage.sync.get({chatgpt_api_key: '', chatgpt_model: ''});
let select_chatgpt_model = document.getElementById('chatgpt_model');
const option = document.createElement('option');
option.value = prefs.chatgpt_model;
option.text = prefs.chatgpt_model;
select_chatgpt_model.appendChild(option);
document.getElementById('btnUpdateChatGPTModels').addEventListener('click', async () => {
document.getElementById('model_fetch_loading').style.display = 'inline';
let openai = new OpenAI(document.getElementById("chatgpt_api_key").value, true);
openai.fetchModels().then((data) => {
if(!data){
document.getElementById('model_fetch_loading').style.display = 'none';
console.error("[ThunderAI] " + browser.i18n.getMessage("ChatGPT_Models_Error_fetching"));
alert(browser.i18n.getMessage("ChatGPT_Models_Error_fetching"));
return;
}
console.log(">>>>>>>>> ChatGPT models: " + JSON.stringify(data));
data.forEach(model => {
if (!Array.from(select_chatgpt_model.options).some(option => option.value === model.id)) {
const option = document.createElement('option');
option.value = model.id;
option.text = model.id;
select_chatgpt_model.appendChild(option);
}
});
document.getElementById('model_fetch_loading').style.display = 'none';
})
warnAPIKeyEmpty();
});
}, { once: true });

View file

@ -7,6 +7,11 @@
<body>
<div id="miczBackPrefs"><a href="mzta-options.html">__MSG_backToOptionsText__</a></div>
<div id="miczRelNotes"><h1>ThunderAI Release Notes</h1>
<h2>Version 2.0.0 - 30/07/2024</h2>
<ul>
<li>Added OpenAI ChatGPT API connection [<a href="https://github.com/micz/ThunderAI/issues/40">#40</a>].</li>
<li>Information text in the options page improved.</li>
</ul>
<h2>Version 1.2.1 - 20/07/2024</h2>
<ul>
<li>Fixed changes in the ChatGPT web interface when importing in plain text [<a href="https://github.com/micz/ThunderAI/issues/87">#87</a>].</li>