LoginSignup
2
1

More than 1 year has passed since last update.

10分でできるGasからChatGPTを呼び出す方法

Last updated at Posted at 2023-03-04

APIのKeyを生成する

・OpenAIのサイトでAPIキーを作成
OpneAiのサイト

・ アカウント作成後、PersonalのView API KEysをクリック
image.png

・Create New secret Keyをクリック
すぐに秘密鍵が作成されるので、表示された秘密鍵をコピー
image.png

Google Apps Script

・googleスプレットシートを作成し、拡張機能のApps Scriptをクリック
image.png

・設定ボタンのスクリプトプロパティに先ほどの秘密鍵を登録
image.png

・スクリプトを作成
max_tokensは文字数ですので、必要に応じて変更してください


function ApiChatGPT() {
  const apiKey = ScriptProperties.getProperty('ChatGPTAPIKey');
  const apiUrl = 'https://api.openai.com/v1/chat/completions';
  const messages = [{'role': 'user', 'content': 'ChatGPTをどう使ったらよいですか?'}];
  const maxTokens = 500;
 
  const headers = {
    'Authorization':'Bearer '+ apiKey,
    'Content-type': 'application/json',
    'X-Slack-No-Retry': 1
  };
  const options = {
    'muteHttpExceptions' : true,
    'headers': headers, 
    'method': 'POST',
    'payload': JSON.stringify({
      'model': 'gpt-3.5-turbo',
      'max_tokens' : maxTokens,
      'temperature' : 0.9,
      'messages': messages})
  };
  const response = JSON.parse(UrlFetchApp.fetch(apiUrl, options).getContentText());
  console.log(response.choices[0].message.content);
}

・実行ボタンをクリック
image.png

・初めて実行する場合は承認する必要があります
image.png

無料枠について

・下記にアクセスしてあとどれくらい使用できるか確認できます
https://platform.openai.com/account/usage

他の情報だと18ドル分使えるとのことでしたが、2023/3/4時点だと無料枠は5ドルでした
無料枠が終わった後は下記の金額になります
※暫く運用してどれくらいで無料枠を使いきるか検証したいと思います

1000トークンあたり、約0.2円 ($0.002)

2
1
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
2
1