-
Notifications
You must be signed in to change notification settings - Fork 4
/
Code.gs
90 lines (82 loc) · 2.6 KB
/
Code.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Global variables
const SETTINGS_PROPERTY_STORE = 'openai-api-key';
/**
* Adds a custom menu to the active spreadsheet.
*/
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('LLM')
.addItem('Settings', 'showSettingsDialog')
.addToUi();
}
/**
* Shows a dialog box for setting the OpenAI API key.
*/
function showSettingsDialog() {
const html = HtmlService.createHtmlOutputFromFile('settings')
.setWidth(400)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(html, 'LLM Settings');
}
/**
* Saves the user's OpenAI API key to the script properties.
* @param {string} apiKey The OpenAI API key to save.
* @returns {boolean} true if the API key was saved successfully, false otherwise.
*/
function saveApiKey(apiKey) {
try {
PropertiesService.getScriptProperties().setProperty(SETTINGS_PROPERTY_STORE, apiKey);
return true;
} catch (error) {
console.error('Failed to save API key:', error);
return false;
}
}
/**
* Retrieves the saved OpenAI API key from the script properties.
* @returns {string} The saved OpenAI API key, or an empty string if none is set.
*/
function getApiKey() {
const apiKey = PropertiesService.getScriptProperties().getProperty(SETTINGS_PROPERTY_STORE);
return apiKey && apiKey !== '' ? apiKey : '';
}
/**
* Custom function to send a request to the OpenAI API.
* @param {string} inputText The text to send to the API.
* @param {string} prompt The prompt to use.
* @param {string=} model The model to use (default: 'gpt-4o-mini').
* @param {string=} temperature The temperature to use, lower is more precise, higher is more creative (default: '0.1').
* @returns {string} The response from the OpenAI API.
* @customfunction
*/
function LLM(inputText, prompt, model = 'gpt-4o-mini', temperature = 0) {
const apiKey = getApiKey();
if (!apiKey) {
throw new Error('OpenAI API key not set. Please visit the "LLM > Settings" menu to set your API key.');
}
const systemContent = "You are a helpful assistant.";
const options = {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
method: "POST",
payload: JSON.stringify({
"model": model,
"messages": [
{
"role": "system",
"content": systemContent
},
{
"role": "user",
"content": `${prompt}\n\n${inputText}`
}
],
"temperature": temperature
})
};
const response = UrlFetchApp.fetch("https://api.openai.com/v1/chat/completions", options);
const json = JSON.parse(response.getContentText());
return json.choices[0].message.content;
}