2
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 3 years have passed since last update.

【Rails&OpenAI API】「オススメの~」を教えてくれるChatGPT風アプリを作ってみた。

2
Last updated at Posted at 2023-04-06

はじめに

流行りのChatGPTを使って何かそれっぽいアプリを作ってみたいと思ったので、APIであるOpenAI APIを使って作ってみたという感じです。

いつもの通り脳筋ですので、もっとこうした方が良い等あれば遠慮なくご意見ください!
railsは6.1.7
rubyは3.0.~台を利用しています

手順

1.APIの登録
2.controllerやviewの記述

1-1.APIの発行

正直が私がAPIの登録方法を説明するよりも詳しい方がたくさんいらっしゃるので、詳しく説明してくださっている記事を紹介します↓↓

紹介させていただいた記事はAPIの取得の手順のみです。
利用料金のシステム等、少しややこしい&記事執筆時と料金体系が変化している可能性があるので、この記事だけでなくご自身で詳しく調べた上でAPIキーを取得してください。

1-2.railsにAPIの登録

APIを使えるようにするためにgem "ruby-openai"
APIの外部流出を防ぐためにgem "dotenv-rails"を使用します。

gemfile
gem "dotenv-rails"
gem "ruby-openai"

bundle installをお忘れなく

appディレクトリ直下に.envファイルを作成し、以下の記述をしてください

.env
OPENAI_API_KEY=ご自身のAPIキー

.gitignoreには以下を追記

.gitignore
.env

2.controllerやviewの記述

chatsコントローラーのindex.html.erbにてやり取りする想定です。

rails g controller chatsで作成しておいてください

routes.rb
Rails.application.routes.draw do
 resources :chats
 root 'chats#index'
end
chats_controller.rb

class ChatsController < ApplicationController
  def index
    if params[:question].present?
        client = OpenAI::Client.new(access_token: ENV["OPENAI_API_KEY"])
        response = client.chat(
          parameters: {
              model: "gpt-3.5-turbo",
              messages: [{ role: "user", content: params[:question] }],
          })
    
        @answer = response.dig("choices", 0, "message", "content")
    end
  end
end
views/chats/index.html.erb
<div class="question">
  <%= form_with(url: chats_path, method: :get) do |f| %>
    <%= f.text_field :question, size: 50 %>
    <%= f.submit "質問する" %>
  <% end %>
</div>

<div class="answer">
  <%= @answer %>
</div>

記述に関しては以上です。

3.「オススメの~」というような質問に答えて欲しい時

コントローラー内に記述した
messages: [{ role: "user", content: params[:question] }]contentの中身がミソです。

params[:question]はフォームに記入された内容が入るので、キーワードに合ったオススメの映画をAIに答えて欲しいのであれば

messages: [{ role: "user", content: "次のキーワードに該当する映画を5つ紹介してください。#{params[:question]}" }]

というようにすれば返信してくれるという訳です!

ChatGPT同様に英語で質問した方が返答の精度はもちろん高くなるので、色々試してみてください!

Lets'!プロンプトエンジニアリング!

お世話になった記事

ありがとうございました。

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