AppSScript Code
var apiKey = 'XRqs0ATTneIjz477JWtMBSgPtylMZdto';
var url = 'https://api.mistral.ai/v1/chat/completions';
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Mistral AI')
.addItem('Generate Answers', 'generateAnswers')
.addToUi();
createHeader();
}
function createHeader() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var headers = ["Type Mistral prompt", "Mistral Response"];
var headerRange = sheet.getRange('A1:B1');
headerRange.setValues([headers]);
// Apply bold font and set font size
headerRange.setFontWeight("bold");
headerRange.setFontSize(14); // Change the font size as needed
}
function generateAnswers() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const activeCell = sheet.getActiveCell();
const row = activeCell.getRow();
const column = activeCell.getColumn();
if (column === 1) {
const question = activeCell.getValue();
const existingResponse = activeCell.offset(0, 1).getValue(); // Offset to the adjacent cell
if (!existingResponse) {
const prompt = `Generate a response for the following question: "${question}"`;
const response = getMistralAIResponse(prompt);
if (response) {
const generatedResponse = response.trim();
activeCell.offset(0, 1).setValue(generatedResponse); // Set response in the adjacent cell
} else {
Logger.log('Failed to get a response for question: ' + question);
}
} else {
Logger.log('Response already exists for question: ' + question);
}
} else {
Logger.log('Active cell should be in column A (containing questions)');
}
}
function getMistralAIResponse(prompt) {
// const apiKey = 'XRqs0ATTneIjz477JWtMBSgPtylMZdto';
// const url = 'https://api.mistral.ai/v1/chat/completions';
const payload = {
"model": "mistral-small-latest",
"messages": [{
"role": "user",
"content": prompt
}],
"temperature": 0.7,
"top_p": 1,
"max_tokens": 512,
"stream": false,
"safe_prompt": false,
"random_seed": 1337
};
const options = {
method: 'post',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + apiKey
},
payload: JSON.stringify(payload)
};
try {
const response = UrlFetchApp.fetch(url, options);
const responseCode = response.getResponseCode();
if (responseCode === 200) {
const responseData = JSON.parse(response.getContentText());
return responseData.choices[0].message.content.trim();
} else {
Logger.log('Error: ' + response.getContentText());
return null;
}
} catch (e) {
Logger.log('Error: ' + e);
return null;
}
}