louisbrulenaudet commited on
Commit
3801376
1 Parent(s): 503edad

Update code.gs

Browse files

- Input Validation: Added a check to ensure the API key is not empty.
- Error Handling: Enhanced error handling for API requests.
- SystemPrompt (optional string): The system prompt to customize the assistant's behavior when calling HF function.
- Documentation.

Files changed (1) hide show
  1. code.gs +59 -20
code.gs CHANGED
@@ -1,6 +1,12 @@
 
 
 
 
1
  const API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3";
2
 
3
- // Function to display a menu in Google Sheets
 
 
4
  function onOpen() {
5
  const ui = SpreadsheetApp.getUi();
6
  ui.createMenu('Hugging Sheets')
@@ -8,19 +14,33 @@ function onOpen() {
8
  .addToUi();
9
  }
10
 
11
- // Function to prompt the user for their Hugging Face API key
 
 
12
  function showApiKeyPrompt() {
13
  const ui = SpreadsheetApp.getUi();
14
  const response = ui.prompt('Enter your Hugging Face API Key:');
15
  if (response.getSelectedButton() == ui.Button.OK) {
16
- const apiKey = response.getResponseText();
17
- PropertiesService.getScriptProperties().setProperty('HF_API_KEY', apiKey);
18
- ui.alert('API Key saved successfully!');
 
 
 
 
19
  }
20
  }
21
 
22
- // Function to call the Hugging Face API
23
- function queryHuggingFace(prompt, model) {
 
 
 
 
 
 
 
 
24
  const apiKey = PropertiesService.getScriptProperties().getProperty('HF_API_KEY');
25
  if (!apiKey) {
26
  throw new Error('Please enter your Hugging Face API key using the menu.');
@@ -33,7 +53,7 @@ function queryHuggingFace(prompt, model) {
33
  };
34
 
35
 
36
- const formattedPrompt = `<s> [INST] You are a helpful and honest assistant. Please, respond concisely and truthfully. [/INST] ${prompt} </s>`;
37
  const payload = {
38
  "inputs": formattedPrompt
39
  };
@@ -45,26 +65,45 @@ function queryHuggingFace(prompt, model) {
45
  "payload": JSON.stringify(payload)
46
  };
47
 
48
- const response = UrlFetchApp.fetch(url, options);
49
- const json = JSON.parse(response.getContentText());
50
-
51
- return json;
 
 
 
52
  }
53
 
54
- // Function to create the custom formula "=HF(prompt, model)"
55
- function HF(prompt, model) {
 
 
 
 
 
 
 
 
56
  try {
57
- const response = queryHuggingFace(prompt, model);
58
- const fullResponse = response[0].generated_text; // Adjust based on the actual response structure
59
- // Extract the part of the response after the prompt
60
- const generatedOutput = fullResponse.split(`</s>`).pop().trim();
61
- return generatedOutput;
 
 
 
 
62
  } catch (error) {
63
  return `Error: ${error.message}`;
64
  }
65
  }
66
 
67
- // Add the formula to Google Sheets
 
 
 
 
68
  function onInstall(e) {
69
  onOpen(e);
70
  const formula = SpreadsheetApp.newUserDefinedFunctionBuilder()
 
1
+ // Default system prompt used if none is provided
2
+ const DEFAULT_SYSTEM_PROMPT = 'You are a helpful and honest assistant. Please, respond concisely and truthfully.';
3
+
4
+ // Base URL for Hugging Face API
5
  const API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3";
6
 
7
+ /**
8
+ * Adds a custom menu to Google Sheets to allow users to input their Hugging Face API key.
9
+ */
10
  function onOpen() {
11
  const ui = SpreadsheetApp.getUi();
12
  ui.createMenu('Hugging Sheets')
 
14
  .addToUi();
15
  }
16
 
17
+ /**
18
+ * Prompts the user to enter their Hugging Face API key and saves it in the script properties.
19
+ */
20
  function showApiKeyPrompt() {
21
  const ui = SpreadsheetApp.getUi();
22
  const response = ui.prompt('Enter your Hugging Face API Key:');
23
  if (response.getSelectedButton() == ui.Button.OK) {
24
+ const apiKey = response.getResponseText().trim();
25
+ if (apiKey) {
26
+ PropertiesService.getScriptProperties().setProperty('HF_API_KEY', apiKey);
27
+ ui.alert('API Key saved successfully!');
28
+ } else {
29
+ ui.alert('API Key cannot be empty.');
30
+ }
31
  }
32
  }
33
 
34
+ /**
35
+ * Sends a request to the Hugging Face API with the specified prompt and model.
36
+ *
37
+ * @param {string} prompt - The input prompt to be sent to the model.
38
+ * @param {string} model - The model ID to query (e.g., 'mistralai/Mistral-7B-Instruct-v0.3').
39
+ * @param {string} [systemPrompt=DEFAULT_SYSTEM_PROMPT] - The system prompt to customize the assistant's behavior.
40
+ * @returns {object} JSON response from the Hugging Face API.
41
+ * @throws {Error} If the API key is not set or if the API request fails.
42
+ */
43
+ function queryHuggingFace(prompt, model, systemPrompt = DEFAULT_SYSTEM_PROMPT) {
44
  const apiKey = PropertiesService.getScriptProperties().getProperty('HF_API_KEY');
45
  if (!apiKey) {
46
  throw new Error('Please enter your Hugging Face API key using the menu.');
 
53
  };
54
 
55
 
56
+ const formattedPrompt = <s> [INST] ${systemPrompt} [/INST] ${prompt} </s>`;
57
  const payload = {
58
  "inputs": formattedPrompt
59
  };
 
65
  "payload": JSON.stringify(payload)
66
  };
67
 
68
+ try {
69
+ const response = UrlFetchApp.fetch(url, options);
70
+ const json = JSON.parse(response.getContentText());
71
+ return json;
72
+ } catch (error) {
73
+ throw new Error(`Failed to fetch data from Hugging Face API: ${error.message}`);
74
+ }
75
  }
76
 
77
+ /**
78
+ * Custom Google Sheets formula to query the Hugging Face API and return the generated text.
79
+ * Function to create the custom formula =HF(prompt, model, [systemPrompt])
80
+ *
81
+ * @param {string} prompt - The input prompt to be sent to the model.
82
+ * @param {string} model - The model ID to query (e.g., 'mistralai/Mistral-7B-Instruct-v0.3').
83
+ * @param {string} [systemPrompt] - The system prompt to customize the assistant's behavior. Defaults to DEFAULT_SYSTEM_PROMPT.
84
+ * @returns {string} The generated output text from the Hugging Face API, or an error message if the request fails.
85
+ */
86
+ function HF(prompt, model, systemPrompt) {
87
  try {
88
+ const response = queryHuggingFace(prompt, model, systemPrompt);
89
+ if (response && response.length > 0 && response[0].generated_text) {
90
+ const fullResponse = response[0].generated_text;
91
+ // Extract the part of the response after the prompt
92
+ const generatedOutput = fullResponse.split(`</s>`).pop().trim();
93
+ return generatedOutput;
94
+ } else {
95
+ return 'Error: Invalid response structure from Hugging Face API.';
96
+ }
97
  } catch (error) {
98
  return `Error: ${error.message}`;
99
  }
100
  }
101
 
102
+ /**
103
+ * Add the formula to Google Sheets.
104
+ *
105
+ * @param {object} e - The event object.
106
+ */
107
  function onInstall(e) {
108
  onOpen(e);
109
  const formula = SpreadsheetApp.newUserDefinedFunctionBuilder()