概要
Googleスプレッドシート(以下スプシ)を使っている際に行いたい処理に使う関数名を思いつかないことがあります。
それを毎回ググって見つけるのが面倒なのでスプシ内で簡単に解決するツールを作りました。
動作の様子
操作説明
- スプシのセルに
=GPT("<やりたいこと>")
を入力する - 手順1のセルに出てきた数式を任意のセルに貼り付ける
作り方
必要なもの
- スプシ
- OpenAI APIのキー
- こちらから取得できます
- 初めての方なら1ヶ月は無料です
- 無料期間が終わっても常識的な範囲で使えば1ヶ月当たり10円もかからないと思います
- 実行一回当たり大体0.01円です
手順
/**
* @param {string} input どんなことをする式を生成したいか
* @return {string} 式
* @customfunction
*/
function GPT(input) {
const msgs = [
{ role: "system", content: "次の要求を満たすGoogle SpreadSheetの式を出力して。出力には自然言語を含めず式のみにして"},
{ role: "user", content: input},
];
return FetchGptCompletion(msgs);
}
/**
* @typedef {Object} Message
* @property {string} role systemかuserかassistant
* @property {string} content
*
* @param {Message[]} msgs
* @return {string}
*/
function FetchGptCompletion(msgs) {
const ENDPOINT = 'https://api.openai.com/v1/chat/completions';
const apiKey = PropertiesService.getScriptProperties().getProperty('OPENAI_KEY');
// リクエストのボディを作成
const requestBody = {
// モデルを指定
model: 'gpt-3.5-turbo',
// クエリとなる文字列を指定
messages: msgs,
// 回答文の最大トークン数。日本語なら文字数と大体同じ
// GPT-3.5なら1000辺り$0.002なので大きめでもOK
// 式を出力してもらうため少なめ
max_tokens: 100,
// 回答の多様性
// 式を出力してもらうため低め
temperature: 0.2,
};
try {
// リクエストを送信
const res = UrlFetchApp.fetch(ENDPOINT, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + apiKey,
// 答えはjsonでほしい
Accept: 'application/json',
},
// これが無いとpayloadがOpenAIのサーバーに読まれない
contentType: "application/json",
// これが無いとpayloadがOpenAIのサーバーに読まれない
payload: JSON.stringify(requestBody),
});
const resCode = res.getResponseCode();
if(resCode !== 200) {
if(resCode === 429) return "利用上限に達しました。このAPIの管理者が上限を変更しない限り来月まで使用できません"
else return `レスポンスコード: ${resCode}`;
}
var resPayloadObj = JSON.parse(res.getContentText())
if(resPayloadObj.choices.length === 0) return "予期しない原因でAIからの応答が空でした";
const rawAnswerText = resPayloadObj.choices[0].message.content;
// 先頭に改行文字が2つあるのは邪魔なので消す
const trimedAnswerText = rawAnswerText.replace(/^\n+/, "");
return trimedAnswerText
} catch(e) {
const errorMsg = `APIリクエストに失敗しました。\n${e.stack}`
console.error(errorMsg);
return errorMsg;
}
}
以上!
まとめ
複雑なことをしようとするとそのままでは使えない式を出力することが多いです。しかし、ちょっと修正すれば動くようになります。業務に便利だと思います。