Merge pull request #495 from micz/api_improvements

Various API and code improvements
This commit is contained in:
Mic 2025-09-09 21:54:49 +02:00 committed by GitHub
commit fc2d7aa830
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
21 changed files with 166 additions and 46 deletions

View file

@ -9,7 +9,8 @@
<li>Added the <i>{%mail_attachments_info%}</i> placeholder to retrieve the name, type and file size of the mail attachments [<a href="https://github.com/micz/ThunderAI/issues/446">#446</a>].</li>
<li><i>[ChatGPT Web]</i> Added a message to explain to click on "Force completion" if the ChatGPT job is not done after 7 seconds [<a href="https://github.com/micz/ThunderAI/issues/419">#419</a>].</li>
<li><i>[All APIs]</i> The prompt id and name are now shown in the information header in the AI API chat [<a href="https://github.com/micz/ThunderAI/issues/436">#436</a>].</li>
<li>Minor code improvements and bugs fixed.</li>
<li><i>[Google Gemini API]</i>Support for the thinkingBudget parameter has been added [<a href="https://github.com/micz/ThunderAI/issues/494">#494</a>].</li>
<li>Various code improvements and minor bugs fixed.</li>
<li>...</li>
</ul>
<h2>Version 3.6.1 - 23/08/2025</h2>

View file

@ -108,7 +108,10 @@ switch (llm) {
model_string: prefs_api.chatgpt_model,
additional_messages: additional_text_elements
}), "info");
browser.runtime.sendMessage({command: "openai_api_ready_" + call_id, window_id: (await browser.windows.getCurrent()).id});
browser.runtime.sendMessage({
command: "openai_api_ready_" + call_id,
window_id: (await browser.windows.getCurrent()).id
});
break;
}
case "google_gemini_api": {
@ -116,6 +119,7 @@ switch (llm) {
google_gemini_api_key: prefs_default.google_gemini_api_key,
google_gemini_model: prefs_default.google_gemini_model,
google_gemini_system_instruction: prefs_default.google_gemini_system_instruction,
google_gemini_thinking_budget: prefs_default.google_gemini_thinking_budget,
do_debug: prefs_default.do_debug,
});
let i18nStrings = {};
@ -127,12 +131,14 @@ switch (llm) {
if(prefs_api.google_gemini_system_instruction && prefs_api.google_gemini_system_instruction.length > 0) {
additional_text_elements.push({label: browser.i18n.getMessage("GoogleGemini_SystemInstruction"), value: prefs_api.google_gemini_system_instruction});
}
additional_text_elements.push({label: 'Thinking Budget', value: prefs_api.google_gemini_thinking_budget});
additional_text_elements.push({label: "Prompt", value: '[' + prompt_id + '] ' + decodeURIComponent(prompt_name)});
worker.postMessage({
type: 'init',
google_gemini_api_key: prefs_api.google_gemini_api_key,
google_gemini_model: prefs_api.google_gemini_model,
google_gemini_system_instruction: prefs_api.google_gemini_system_instruction,
google_gemini_thinking_budget: prefs_api.google_gemini_thinking_budget,
do_debug: prefs_api.do_debug,
i18nStrings: i18nStrings,
});
@ -141,7 +147,10 @@ switch (llm) {
model_string: prefs_api.google_gemini_model,
additional_messages: additional_text_elements
}), "info");
browser.runtime.sendMessage({command: "google_gemini_api_ready_" + call_id, window_id: (await browser.windows.getCurrent()).id});
browser.runtime.sendMessage({
command: "google_gemini_api_ready_" + call_id,
window_id: (await browser.windows.getCurrent()).id
});
break;
}
case "ollama_api": {
@ -164,9 +173,12 @@ switch (llm) {
ollama_num_ctx: prefs_api.ollama_num_ctx,
ollama_think: prefs_api.ollama_think,
do_debug: prefs_api.do_debug,
i18nStrings: i18nStrings,
i18nStrings: i18nStrings
});
browser.runtime.sendMessage({
command: "ollama_api_ready_" + call_id,
window_id: (await browser.windows.getCurrent()).id
});
browser.runtime.sendMessage({command: "ollama_api_ready_" + call_id, window_id: (await browser.windows.getCurrent()).id});
let additional_text_elements = [];
additional_text_elements.push({label: "Prompt", value: '[' + prompt_id + '] ' + decodeURIComponent(prompt_name)});
messagesArea.appendUserMessage(getAPIsInitMessageString({
@ -208,7 +220,10 @@ switch (llm) {
host_string: prefs_api.openai_comp_host,
additional_messages: additional_text_elements
}), "info");
browser.runtime.sendMessage({command: "openai_comp_api_ready_" + call_id, window_id: (await browser.windows.getCurrent()).id});
browser.runtime.sendMessage({
command: "openai_comp_api_ready_" + call_id,
window_id: (await browser.windows.getCurrent()).id
});
break;
}
case "anthropic_api": {
@ -241,7 +256,10 @@ switch (llm) {
version_string: prefs_api.anthropic_version,
additional_messages: additional_text_elements
}), "info");
browser.runtime.sendMessage({command: "anthropic_api_ready_" + call_id, window_id: (await browser.windows.getCurrent()).id});
browser.runtime.sendMessage({
command: "anthropic_api_ready_" + call_id,
window_id: (await browser.windows.getCurrent()).id
});
break;
}
}
@ -313,4 +331,4 @@ browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
function sendPrompt(message){
messageInput._setMessageInputValue(convertNewlinesToBr(message.prompt));
messageInput._handleNewChatMessage();
}
}

View file

@ -20,6 +20,7 @@
* The original code has been released under the Apache License, Version 2.0.
*/
import { prefs_default } from '../options/mzta-options-default.js';
const messagesAreaTemplate = document.createElement('template');
const messagesAreaStyle = document.createElement('style');
@ -383,7 +384,7 @@ class MessagesArea extends HTMLElement {
splitButton.appendChild(actionButton);
const fullTextHTMLAtAssignment = this.fullTextHTML.trim().replace(/^"|"$/g, '').replace(/^<p>&quot;/, '<p>').replace(/&quot;<\/p>$/, '</p>'); // strip quotation marks
//console.log(">>>>>>>>>>>> fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment);
let reply_type_pref = await browser.storage.sync.get({reply_type: 'reply_all'});
let reply_type_pref = await browser.storage.sync.get({ reply_type: prefs_default.reply_type });
if((promptData.action == "1") && (promptData.mailMessageId != -1)) {
const actionButton_line2 = document.createElement('span');
actionButton_line2.classList.add('action_btn_info');
@ -613,4 +614,4 @@ function removeAloneBRs(htmlString) {
});
return doc.body.innerHTML;
}
}

View file

@ -27,7 +27,13 @@ export class Anthropic {
max_tokens = 4096;
stream = false;
constructor(apiKey, version, model, max_tokens = 4096, stream = false) {
constructor({
apiKey = '',
version = '',
model = '',
max_tokens = 4096,
stream = false,
} = {}) {
this.apiKey = apiKey;
this.version = version;
this.model = model;
@ -104,4 +110,4 @@ export class Anthropic {
}
}
}
}

View file

@ -24,12 +24,26 @@ export class GoogleGemini {
model = '';
system_instruction = '';
stream = false;
thinking_budget = ''; // Model default
constructor(apiKey, model, system_instruction, stream) {
constructor({
apiKey = '',
model = '',
system_instruction = '',
stream = false,
thinking_budget = '',
} = {}) {
this.apiKey = apiKey;
this.model = model;
this.system_instruction = system_instruction;
this.stream = stream;
this.thinking_budget = String(thinking_budget ?? '').trim();
/* Info from: https://ai.google.dev/gemini-api/docs/thinking?#set-budget
# Turn on thinking with a specific token limit: "thinking_budget": 1024
# Thinking off: "thinking_budget": 0
# Turn on dynamic thinking: "thinking_budget": -1
# Keep model default thinking: "thinking_budget": ""
*/
}
@ -83,7 +97,15 @@ export class GoogleGemini {
parts:{
text: this.system_instruction
}
}
};
}
if(this.thinking_budget !== '') {
google_gemini_body.generationConfig = {
thinkingConfig: {
thinking_budget: this.thinking_budget,
}
};
}
// console.log("[ThunderAI] Google Gemini API request: " + JSON.stringify(google_gemini_body));

View file

@ -24,8 +24,14 @@ export class Ollama {
num_ctx = 0;
think = false;
constructor(host, model, stream = false, num_ctx = 0, think = false) {
this.host = host.trim().replace(/\/+$/, "");
constructor({
host = '',
model = '',
stream = false,
num_ctx = 0,
think = false,
} = {}) {
this.host = (host || '').trim().replace(/\/+$/, "");
this.model = model;
this.stream = stream;
this.num_ctx = num_ctx;
@ -123,4 +129,4 @@ export class Ollama {
// return output;
// }
// }
}
}

View file

@ -27,7 +27,13 @@ export class OpenAI {
stream = false;
store = false;
constructor(apiKey, model, developer_messages, stream, store) {
constructor({
apiKey = '',
model = '',
developer_messages = '',
stream = false,
store = false
} = {}) {
this.apiKey = apiKey;
this.model = model;
this.developer_messages = developer_messages;
@ -120,4 +126,4 @@ export class OpenAI {
return data.token_count;
}
}
}

View file

@ -27,8 +27,14 @@ export class OpenAIComp {
use_v1 = true;
stream = false;
constructor(host, model, apiKey = '', stream = false, use_v1 = true) {
this.host = host.trim().replace(/\/+$/, "");
constructor({
host = '',
model = '',
apiKey = '',
stream = false,
use_v1 = true,
} = {}) {
this.host = (host || '').trim().replace(/\/+$/, "");
this.model = model;
this.stream = stream;
this.apiKey = apiKey;
@ -107,4 +113,4 @@ export class OpenAIComp {
}
}
}
}

View file

@ -19,6 +19,7 @@
// Some original methods are derived from https://github.com/ali-raheem/Aify/blob/cfadf52f576b7be3720b5b73af7c8d3129c054da/plugin/html/actions.js
import { getPrompts } from './mzta-prompts.js';
import { prefs_default } from '../options/mzta-options-default.js';
import {
getLanguageDisplayName,
getMenuContextCompose,
@ -194,7 +195,14 @@ export class mzta_Menus {
case 'prompt_add_tags': { // Add tags to the email
let tags_current_email = [];
let tags_current_email_final = [];
let prefs_at = await browser.storage.sync.get({add_tags_maxnum: 3, connection_type: '', add_tags_force_lang: true, add_tags_auto_force_existing: false, default_chatgpt_lang: '', do_debug: false});
let prefs_at = await browser.storage.sync.get({
add_tags_maxnum: prefs_default.add_tags_maxnum,
connection_type: prefs_default.connection_type,
add_tags_force_lang: prefs_default.add_tags_force_lang,
add_tags_auto_force_existing: prefs_default.add_tags_auto_force_existing,
default_chatgpt_lang: prefs_default.default_chatgpt_lang,
do_debug: prefs_default.do_debug,
});
let def_conntype = getConnectionType(prefs_at.connection_type, curr_prompt);
if((def_conntype === '')||(def_conntype === null)||(def_conntype === undefined)||(def_conntype === 'chatgpt_web')){
console.error("[ThunderAI | AddTags] Invalid connection type: " + def_conntype);
@ -246,7 +254,11 @@ export class mzta_Menus {
}
case 'prompt_get_calendar_event': { // Get a calendar event info
let calendar_event_data = '';
let prefs_at = await browser.storage.sync.get({connection_type: '', calendar_enforce_timezone: false, calendar_timezone: '',});
let prefs_at = await browser.storage.sync.get({
connection_type: prefs_default.connection_type,
calendar_enforce_timezone: prefs_default.calendar_enforce_timezone,
calendar_timezone: prefs_default.calendar_timezone,
});
if((prefs_at.connection_type === '')||(prefs_at.connection_type === null)||(prefs_at.connection_type === undefined)||(prefs_at.connection_type === 'chatgpt_web')){
console.error("[ThunderAI | GetCalendarEvent] Invalid connection type: " + prefs_at.connection_type);
taWorkingStatus.stopWorking();
@ -528,4 +540,4 @@ export class mzta_Menus {
return false;
}
}
}

View file

@ -16,6 +16,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { prefs_default } from '../options/mzta-options-default.js';
/* ================= PLACEHOLDERS PROPERTIES ========================================
================ BASE PROPERTIES
@ -480,11 +482,11 @@ export const placeholdersUtils = {
finalSubs['tags_full_list'] = placeholdersUtils.failSafePlaceholders(tags_full_list[0]);
break;
case 'thunderai_def_sign':
let prefs_def_sign = await browser.storage.sync.get({default_sign_name: ''});
let prefs_def_sign = await browser.storage.sync.get({ default_sign_name: prefs_default.default_sign_name });
finalSubs['thunderai_def_sign'] = placeholdersUtils.failSafePlaceholders(prefs_def_sign.default_sign_name);
break;
case 'thunderai_def_lang':
let prefs_def_lang = await browser.storage.sync.get({default_chatgpt_lang: ''});
let prefs_def_lang = await browser.storage.sync.get({ default_chatgpt_lang: prefs_default.default_chatgpt_lang });
finalSubs['thunderai_def_lang'] = placeholdersUtils.failSafePlaceholders(prefs_def_lang.default_chatgpt_lang);
break;
case 'mail_attachments_info':
@ -516,4 +518,4 @@ export const placeholdersUtils = {
return element;
}
}
}

View file

@ -19,6 +19,7 @@
import { prefs_default } from "../options/mzta-options-default.js";
import { taLogger } from './mzta-logger.js';
import { prefs_default } from '../options/mzta-options-default.js';
export class mzta_specialCommand {
@ -72,7 +73,7 @@
let prefs_api = await browser.storage.sync.get({
chatgpt_api_key: prefs_default.chatgpt_api_key,
chatgpt_model: prefs_default.chatgpt_model,
chatgpt_developer_messages: prefs_default.chatgpt_developer_messages
chatgpt_developer_messages: prefs_default.chatgpt_developer_messages,
});
this.worker.postMessage({
type: 'init',
@ -88,13 +89,15 @@
let prefs_api = await browser.storage.sync.get({
google_gemini_api_key: prefs_default.google_gemini_api_key,
google_gemini_model: prefs_default.google_gemini_model,
google_gemini_system_instruction: prefs_default.google_gemini_system_instruction
google_gemini_system_instruction: prefs_default.google_gemini_system_instruction,
google_gemini_thinking_budget: prefs_default.google_gemini_thinking_budget,
});
this.worker.postMessage({
type: 'init',
google_gemini_api_key: prefs_api.google_gemini_api_key,
google_gemini_model: this.custom_model != '' ? this.custom_model : prefs_api.google_gemini_model,
google_gemini_system_instruction: prefs_api.google_gemini_system_instruction,
google_gemini_thinking_budget: prefs_api.google_gemini_thinking_budget,
do_debug: this.do_debug,
i18nStrings: ''
});
@ -121,6 +124,7 @@
openai_comp_api_key: prefs_default.openai_comp_api_key,
openai_comp_use_v1: prefs_default.openai_comp_use_v1,
openai_comp_chat_name: prefs_default.openai_comp_chat_name,
do_debug: prefs_default.do_debug,
});
this.worker.postMessage({
type: 'init',
@ -198,4 +202,4 @@
}
});
}
}
}

View file

@ -18,11 +18,12 @@
import { placeholdersUtils } from './mzta-placeholders.js';
import { extractJsonObject } from './mzta-utils.js';
import { prefs_default } from '../options/mzta-options-default.js';
export const taPromptUtils = {
async getDefaultSignature(){
let prefs = await browser.storage.sync.get({default_sign_name: ''});
let prefs = await browser.storage.sync.get({ default_sign_name: prefs_default.default_sign_name });
if(prefs.default_sign_name===''){
return '';
}else{
@ -68,7 +69,7 @@ export const taPromptUtils = {
selection_html: selection_html,
tags_full_list: tags_full_list
});
let prefs_ph = await browser.storage.sync.get({placeholders_use_default_value: false});
let prefs_ph = await browser.storage.sync.get({ placeholders_use_default_value: prefs_default.placeholders_use_default_value });
fullPrompt = (placeholdersUtils.replacePlaceholders({
text: curr_prompt.text,
replacements: finalSubs,
@ -104,7 +105,7 @@ export const taPromptUtils = {
async getDefaultLang(curr_prompt){
let chatgpt_lang = '';
if(String(curr_prompt.define_response_lang) == "1"){
let prefs = await browser.storage.sync.get({default_chatgpt_lang: ''});
let prefs = await browser.storage.sync.get({ default_chatgpt_lang: prefs_default.default_chatgpt_lang });
chatgpt_lang = prefs.default_chatgpt_lang;
if(chatgpt_lang === ''){
chatgpt_lang = browser.i18n.getMessage("reply_same_lang");
@ -152,4 +153,4 @@ export const taPromptUtils = {
}
return tags;
}
};
};

View file

@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { prefs_default } from '../options/mzta-options-default.js';
const sparks_min = '1.2.0'; // Minimum version of ThunderAI-Sparks required for the add-on to work
export const ChatGPTWeb_models = ['gpt-5','gpt-5-instant','gpt-5-t-mini','gpt-5-thinking']; // List of models available in ChatGPT Web
@ -388,7 +389,7 @@ export async function getTagsList(){
}
export async function createTag(tag) {
let prefs_tag = await browser.storage.sync.get({add_tags_first_uppercase: true});
let prefs_tag = await browser.storage.sync.get({ add_tags_first_uppercase: prefs_default.add_tags_first_uppercase });
if(prefs_tag.add_tags_first_uppercase) tag = tag.toLowerCase().charAt(0).toUpperCase() + tag.toLowerCase().slice(1);
try {
if(await isThunderbird128OrGreater()) {

View file

@ -39,7 +39,13 @@ self.onmessage = async function(event) {
// console.log(">>>>>>>>>>>>>> event.data: " + JSON.stringify(event.data));
anthropic_api_key = event.data.anthropic_api_key;
anthropic_model = event.data.anthropic_model;
anthropic = new Anthropic(anthropic_api_key, event.data.anthropic_version, anthropic_model, event.data.anthropic_max_tokens, true);
anthropic = new Anthropic({
apiKey: anthropic_api_key,
version: event.data.anthropic_version,
model: anthropic_model,
max_tokens: event.data.anthropic_max_tokens,
stream: true
});
do_debug = event.data.do_debug;
i18nStrings = event.data.i18nStrings;
taLog = new taLogger('model-worker-anthropic', do_debug);

View file

@ -38,7 +38,13 @@ self.onmessage = async function(event) {
if (event.data.type === 'init') {
google_gemini_api_key = event.data.google_gemini_api_key;
google_gemini_model = event.data.google_gemini_model;
google_gemini = new GoogleGemini(google_gemini_api_key, google_gemini_model, event.data.google_gemini_system_instruction, true);
google_gemini = new GoogleGemini({
apiKey: google_gemini_api_key,
model: google_gemini_model,
system_instruction: event.data.google_gemini_system_instruction,
thinking_budget: event.data.google_gemini_thinking_budget,
stream: true
});
do_debug = event.data.do_debug;
i18nStrings = event.data.i18nStrings;
taLog = new taLogger('model-worker-google_gemini', do_debug);

View file

@ -42,7 +42,12 @@ self.onmessage = async function(event) {
ollama_model = event.data.ollama_model;
ollama_num_ctx = event.data.ollama_num_ctx;
//console.log(">>>>>>>>>>> ollama_host: " + ollama_host);
ollama = new Ollama(ollama_host, ollama_model, true, ollama_num_ctx);
ollama = new Ollama({
host: ollama_host,
model: ollama_model,
stream: true,
num_ctx: ollama_num_ctx
});
do_debug = event.data.do_debug;
i18nStrings = event.data.i18nStrings;
taLog = new taLogger('model-worker-ollama', do_debug);
@ -138,4 +143,4 @@ self.onmessage = async function(event) {
stopStreaming = true;
break; //stop
}
};
};

View file

@ -38,7 +38,13 @@ self.onmessage = async function(event) {
if (event.data.type === 'init') {
chatgpt_api_key = event.data.chatgpt_api_key;
chatgpt_model = event.data.chatgpt_model;
openai = new OpenAI(chatgpt_api_key, chatgpt_model, event.data.chatgpt_developer_messages, true, event.data.chatgpt_api_store);
openai = new OpenAI({
apiKey: chatgpt_api_key,
model: chatgpt_model,
developer_messages: event.data.chatgpt_developer_messages,
stream: true,
store: event.data.chatgpt_api_store
});
do_debug = event.data.do_debug;
i18nStrings = event.data.i18nStrings;
taLog = new taLogger('model-worker-openai', do_debug);

View file

@ -42,7 +42,13 @@ self.onmessage = async function(event) {
openai_comp_model = event.data.openai_comp_model;
openai_comp_api_key = event.data.openai_comp_api_key;
openai_comp_use_v1 = event.data.openai_comp_use_v1;
openai_comp = new OpenAIComp(openai_comp_host, openai_comp_model, openai_comp_api_key, true, openai_comp_use_v1);
openai_comp = new OpenAIComp({
host: openai_comp_host,
model: openai_comp_model,
apiKey: openai_comp_api_key,
stream: true,
use_v1: openai_comp_use_v1
});
do_debug = event.data.do_debug;
i18nStrings = event.data.i18nStrings;
taLog = new taLogger('model-worker-openai_comp', do_debug);

View file

@ -444,7 +444,7 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_
if((originalText == null) || (originalText == "")) {
originalText = prompt_info.body_text;
}
let reply_type_pref = await browser.storage.sync.get({reply_type: 'reply_all'});
let reply_type_pref = await browser.storage.sync.get({ reply_type: prefs_default.reply_type });
//console.log(">>>>>>>>>> prompt_info: " + JSON.stringify(prompt_info));
let pre_script = `let mztaWinId = `+ createdTab.windowId +`;
let mztaStatusPageDesc="`+ browser.i18n.getMessage("prefs_status_page") +`";

View file

@ -12,7 +12,8 @@
<li>Added the <i>{%mail_attachments_info%}</i> placeholder to retrieve the name, type and file size of the mail attachments [<a href="https://github.com/micz/ThunderAI/issues/446">#446</a>].</li>
<li><i>[ChatGPT Web]</i> Added a message to explain to click on "Force completion" if the ChatGPT job is not done after 7 seconds [<a href="https://github.com/micz/ThunderAI/issues/419">#419</a>].</li>
<li><i>[All APIs]</i> The prompt id and name are now shown in the information header in the AI API chat [<a href="https://github.com/micz/ThunderAI/issues/436">#436</a>].</li>
<li>Minor code improvements and bugs fixed.</li>
<li><i>[Google Gemini API]</i>Support for the thinkingBudget parameter has been added [<a href="https://github.com/micz/ThunderAI/issues/494">#494</a>].</li>
<li>Various code improvements and minor bugs fixed.</li>
<li>...</li>
</ul>
<h2>Version 3.6.1 - 23/08/2025</h2>

View file

@ -17,11 +17,15 @@
*/
import { taLogger } from '../../js/mzta-logger.js';
import { prefs_default } from '../../options/mzta-options-default.js';
let taLog = null;
document.addEventListener('DOMContentLoaded', async () => {
let prefs = await browser.storage.sync.get({do_debug: false, connection_type: 'chatgpt_web'});
let prefs = await browser.storage.sync.get({
do_debug: prefs_default.do_debug,
connection_type: prefs_default.connection_type,
});
taLog = new taLogger("mzta-popup",prefs.do_debug);
i18n.updateDocument();
if(prefs.connection_type === 'chatgpt_web'){
@ -62,4 +66,4 @@ document.addEventListener('DOMContentLoaded', async () => {
});
}
}
}, { once: true });
}, { once: true });