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?

Rails + HTTPartyでOpenAI APIを使ってみた

Posted at

はじめに

最近、ChatGPTをはじめとする生成AIが話題ですが、OpenAIが提供するAPIを使えば、自分のアプリにも自然言語生成を簡単に組み込むことができます。

この記事では、RailsアプリからHTTPartyを使ってOpenAIのChat API(GPT-4)を呼び出す方法を紹介します。

対象読者

  • OpenAI APIをRailsで使いたい人
  • ChatGPTの力をアプリに組み込みたい人

Step1: OpenAI APIキーの取得と管理

まずは、OpenAIの公式サイトからAPIキーを取得します。

取得したAPIキーは、セキュリティ上 .env などで安全に管理しましょう。または、creadentilas.yml.encに保存しましょう。

# .env
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Step2: HTTPartyのインストール

OpenAI APIをHTTP経由で叩くために httparty を使います。

# Gemfile
gem 'httparty'
$ bundle install

Step3: OpenAIクライアントクラスの作成

Railsのサービスクラスとして、OpenAIと会話するためのクラスを作成します。

# app/services/openai_service.rb

require 'httparty'

class OpenaiService
  include HTTParty
  base_uri 'https://api.openai.com/v1'

  def initialize
    @headers = {
      "Authorization" => "Bearer #{ENV['OPENAI_API_KEY']}",
      "Content-Type" => "application/json"
    }
  end

  def chat(prompt)
    body = {
      model: "gpt-4",
      messages: [
        { role: "user", content: prompt }
      ],
      temperature: 0.7
    }

    response = self.class.post(
      "/chat/completions",
      headers: @headers,
      body: body.to_json
    )

    if response.success?
      response.parsed_response["choices"][0]["message"]["content"]
    else
      "エラー: #{response.code} - #{response.body}"
    end
  end
end

Step4: 実際に使ってみる

ターミナルまたはコントローラから呼び出して確認してみます。

service = OpenaiService.new
puts service.chat("GPT-4について簡単に説明してください。")

まとめ

今回は、RailsアプリからHTTPartyを使ってOpenAIのChat API(GPT-4)を呼び出す方法を紹介しました。

  • OpenAIのAPIキーは .envcredentials.yml.enc で安全に管理
  • HTTPartyを使えば、シンプルなHTTP通信でChatGPTのような応答が実現可能
  • temperature パラメータで応答の創造性をコントロールできる
  • role: system を使えば、GPTの性格や専門性を自在に設定できる

OpenAI APIを使うことで、自分のアプリに自然な対話・分析・文章生成機能を簡単に組み込めます。

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?