1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

スプシの式をGPTで生成する関数を作った

Last updated at Posted at 2023-04-23

概要

Googleスプレッドシート(以下スプシ)を使っている際に行いたい処理に使う関数名を思いつかないことがあります。
それを毎回ググって見つけるのが面倒なのでスプシ内で簡単に解決するツールを作りました。

動作の様子

スプシの式をGPT関数で生成するデモ.gif

操作説明

  1. スプシのセルに=GPT("<やりたいこと>")を入力する
  2. 手順1のセルに出てきた数式を任意のセルに貼り付ける

作り方

必要なもの

  • スプシ
  • OpenAI APIのキー
    • こちらから取得できます
    • 初めての方なら1ヶ月は無料です
    • 無料期間が終わっても常識的な範囲で使えば1ヶ月当たり10円もかからないと思います
      • 実行一回当たり大体0.01円です

手順

  1. スプシを開く
  2. 上部のメニューバーの拡張機能 > Apps Scriptをクリックする
    image.png
  3. 左の歯車マークのタブの下部で以下の通りスクリプトプロパティを設定する
    image.png
  4. 以下のコードをエディタに貼り付ける
/**
 * @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;
  }
}

以上!

まとめ

複雑なことをしようとするとそのままでは使えない式を出力することが多いです。しかし、ちょっと修正すれば動くようになります。業務に便利だと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?