1
0

More than 1 year has passed since last update.

ChatGPT APIをお試しで使ってみる。

Posted at

背景

入力したキーワードからクイズを生成してくれるWebアプリを作りたく、ChatGPT APIを利用するにあたり、準備作業を記事にしてみました。

準備

以下のサイトを参考に実施しました。
https://aismiley.co.jp/ai_news/what-is-the-chatgpt-api/

まずはOpenAIのサイトにアクセスしてログインします。
アカウントがない場合は、アカウントを作成します。
https://openai.com/product

ログイン後、以下のサイトからAPI Keysを発行します。
https://platform.openai.com/account/api-keys

こんな感じの画面

「Create new secret key」を押下して、適当なAPIKey名を入力、
「Create secret key」をクリックしたら、一度だけキーが表示されるので控えておきます。

テスト実装

APIキーが取れたので、APIを叩いてみます。
過去に作成したアプリのバックエンド資材をコピーしてきてTMDBAPI部分をChatGPTに置き換えてみます。言語はPythonです。

まずは必要なライブラリを落としてきます。

pip install openai

インストールした結果、0.27.8バージョンが入ってきました。
(openai以外のライブラリは過去に作成したアプリ開発時に入れたものです。)

とりあえず最小構成で構築してみます。

test.py

import pandas as pd
from flask_cors import CORS
from flask import Flask, request, jsonify
from deep_translator import GoogleTranslator
import openai

app = Flask(__name__)
CORS(app)

@app.route("/")
def test():

  openai.api_key = "{OpenAIから取得したAPIKey}"

  prompt = "こんにちは、私の名前は"
  model = "text-davinci-002"
  response = openai.Completion.create(
    engine=model,
    prompt=prompt,
    max_tokens=5
  )

  return response.choices[0].text

if __name__ == "__main__":
  app.run(debug=True)

test.http

###
GET http://localhost:5000/

test.pyを実行します。

test.httpから叩いてみたらなんかエラーが出ました。

エラーレスポンスがHTMLになっていたので、見てみます。
プラン、料金云々言っています。

クレジットカードの設定、上限金額の設定を行う必要があるみたいですね。
https://qiita.com/kotattsu3/items/d6533adc785ee8509e2c

Qiitaの通り実施したらAPI叩けました。(アンジェラ Goldって何...?)

以下のサイトを真似てコードを修正したらそれっぽいものを返却してくれるようになりました。
https://dev.classmethod.jp/articles/openai-api-chat-python-first-step/

import pandas as pd
from flask_cors import CORS
from flask import Flask, request, jsonify
from deep_translator import GoogleTranslator
import openai

app = Flask(__name__)
CORS(app)

@app.route("/")
def test():
  openai.api_key = "{OpenAIから取得したAPIKey}"

  response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
          {"role": "user", "content": "大谷翔平について教えて"},
      ],
  )

  return response.choices[0]["message"]["content"].strip()

if __name__ == "__main__":
  app.run(debug=True)

得られた結果

おまけ

サイトによって少し書き方が違う?

const completion = await openAiApi.createChatCompletion({
    model: "gpt-3.5-turbo",
response = openai.Completion.create(
  engine="davinci",

createChatCompletionの方がChatAPIっぽい回答が得られるらしいです。

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