| const DEFAULT_SYSTEM_PROMPT = 'You are a helpful and honest assistant. Please, respond concisely and truthfully.'; |
| const DEFAULT_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"; |
|
|
| |
| |
| |
| function onOpen() { |
| const ui = SpreadsheetApp.getUi(); |
| ui.createMenu('Hugging Sheets') |
| .addItem('Enter your HF API Key', 'showApiKeyPrompt') |
| .addToUi(); |
| } |
|
|
| |
| |
| |
| function showApiKeyPrompt() { |
| const ui = SpreadsheetApp.getUi(); |
| const response = ui.prompt('Enter your Hugging Face API Key:'); |
| if (response.getSelectedButton() == ui.Button.OK) { |
| const apiKey = response.getResponseText().trim(); |
| if (apiKey) { |
| PropertiesService.getScriptProperties().setProperty('HF_API_KEY', apiKey); |
| ui.alert('API Key saved successfully!'); |
| } else { |
| ui.alert('API Key cannot be empty.'); |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| function queryHuggingFace(prompt, model = DEFAULT_MODEL, systemPrompt = DEFAULT_SYSTEM_PROMPT) { |
| const apiKey = PropertiesService.getScriptProperties().getProperty('HF_API_KEY'); |
| if (!apiKey) { |
| throw new Error('Please enter your Hugging Face API key using the menu.'); |
| } |
|
|
| const formattedPrompt = `<s> [INST] ${systemPrompt} ${prompt} [/INST] </s>`; |
| const payload = { |
| "inputs": formattedPrompt |
| }; |
|
|
| const payloadString = JSON.stringify(payload); |
|
|
| const url = `https: |
| const options = { |
| 'method': 'post', |
| 'contentType': 'application/json', |
| 'headers': { |
| 'Authorization': `Bearer ${apiKey}` |
| }, |
| 'payload': payloadString |
| }; |
|
|
| try { |
| const response = UrlFetchApp.fetch(url, options); |
| const json = JSON.parse(response.getContentText()); |
| return json; |
| } catch (error) { |
| throw new Error(`Failed to fetch data from Hugging Face API: ${error.message}`); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| function HF(prompt, model = DEFAULT_MODEL, systemPrompt = DEFAULT_SYSTEM_PROMPT) { |
| try { |
| const response = queryHuggingFace(prompt, model, systemPrompt); |
| if (response && response.length > 0 && response[0].generated_text) { |
| const fullResponse = response[0].generated_text; |
| |
| const generatedOutput = fullResponse.split(`</s>`).pop().trim(); |
| return generatedOutput; |
| } else { |
| return 'Error: Invalid response structure from Hugging Face API.'; |
| } |
| } catch (error) { |
| return `Error: ${error.message}`; |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| function onInstall(e) { |
| onOpen(e); |
| const formula = SpreadsheetApp.newUserDefinedFunctionBuilder() |
| .setName('HF') |
| .setFunction('HF') |
| .build(); |
| SpreadsheetApp.installUserDefinedFunction(formula); |
| } |