ノート:

Ruby on Rails Webアプリケーションを使用したプログラムによるOCI生成AIサービスへのアクセス

イントロダクション

Oracle Cloud Infrastructure Generative AI(OCI Generative AI)は、革新的な新しい人工知能ツールであり、テクノロジーとのやり取り方法を変革する可能性があります。大規模な言語モデルであり、大量のテキストデータに基づいてトレーニングされ、その前に来た単語に基づいてシーケンス内の次の単語を予測することを学びます。これにより、OCI Generative AIは、テキスト・プロンプトに対する人間のような応答を生成できるため、自然音響言語を作成するための非常に強力なツールとなります。

OCI Generative AIの最も印象的な機能の1つは、複雑なトピックを理解し、詳細な説明と回答を提供できることです。最近では、すべての組織がジェネレーティブAIの力をアプリケーション内で活用し、顧客向けの革新的な製品を作りたいと考えています。

このチュートリアルでは、OCIが世界中の組織がOCIでジェネレーティブAIの力を活用するためにどのようにOCIが役立つかについて説明し、理解します。このチュートリアルでは、開発フレームワークとしてRuby on Rails (RoR)を使用し、Rubyプログラミング言語に基づいてOCI Generative AI APIを呼び出します。

目的

前提条件

タスク1: Oracle Cloud Infrastructure APIキーの設定

  1. サービス・アカウントまたは管理ユーザーを使用してOCIテナンシにログインし、ユーザー設定に移動します。

    ユーザー設定を開く

    または

    OCI IAMコンソールからユーザーに移動します。OCIでインフラストラクチャを作成および更新するために必要なすべてのアクセス権がユーザーに付与されていることを確認します。

  2. ユーザーの「リソース」セクションに移動し、「APIキー」および「APIキーの追加」をクリックします。新しい公開キーと秘密キーをダウンロードするか、公開キーをアップロードするか、公開キーを貼り付けます。

    APIキーの追加

  3. 鍵を便利な場所に保存し、次のページに示すように構成ファイルを保存します。Ruby SDKを使用してテナンシに接続する場合は、この構成ファイルと秘密キーが必要になります。

    構成ファイルの保存

    ノート:

    • OCIは、現在、US-CHICAGO-1リージョンでジェネレーティブAIサービスをサポートしています。そのため、必ずテナンシでこのリージョンを有効にしてサブスクライブしてください。

    • OCIコンピュート・インスタンスからOCIサービスを呼び出すために、OCIはインスタンス・プリンシパルを使用してより安全な方法を提供します。ユーザーAPIキーをベスト・プラクティスとして使用しないでください。詳細は、インスタンスからのサービスのコールを参照してください。

タスク2: RoR開発に使用するOCIコンピュート・インスタンスの作成と構成

  1. 「OCIでのWindowsインスタンスの起動」に移動して、OCIにWindowsコンピュート・インスタンスを作成します。

  2. Windowsインスタンスが作成されたら、次のスクリーンショットに示すように、初期パスワードを使用してログインします。

    Windowsコンピュート・インスタンス

  3. Windowsコンピュート・インスタンスにログインした後、Ruby、Ruby on Railsをインストールおよび構成し、railsコマンドを使用して新しいアプリケーションを作成します。

    rails new GenAIApp
    

    アプリケーション・ディレクトリに移動し、次のコマンドを実行して、レール・アプリケーション・サーバーを起動して実行します。http://127.0.0.1:3000のデフォルトのRailsアプリケーションにアクセスできるはずです。

    cd GenAIApp
    rails server -b 0.0.0.0
    
  4. ユーザーのホーム・ディレクトリ(c:/users/opc)に移動し、Ruby SDK用のconfigファイルを作成します。タスク1.3でダウンロードしたとおりに構成ファイルを構成し、ダウンロードした秘密キー・ファイルも配置します。詳細は、Oracle Cloud Infrastructure Ruby SDKを参照してください。

    ノート:

    • OCIコンピュート・インスタンスにログインするには、まずWindowsパスワードをリセットする必要があります。次回からログインするには新しいパスワードを覚えておいてください。

    • ネットワークの外からRailsアプリケーションにアクセスするには、ポート3000を開き、作成されたコンピュート・インスタンスからWindowsファイアウォールをオフにする必要があります。

タスク3: RoRアプリケーションの設定、OCI生成AIサービスの呼出しと表示に適したコードの記述

  1. Railsアプリを実行し、ローカルおよび必要なネットワークからアクセスできるようになったら、まずアプリケーションに必要な宝石を設定します。次のコード・スニペットに示すように、Gemfileを開き、その内容を更新します。

    Gemfile:

    source 'https://rubygems.org'
    git_source(:github) { |repo| "https://github.com/#{repo}.git" }
    
    ruby '3.2.3'
    
    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main'
    gem 'rails', '~> 6.1.4', '>= 6.1.4.1'
    
    # Gem for OCI SDK
    gem 'oci'
    
    # Use sqlite3 as the database for Active Record
    gem 'sqlite3', '~> 1.4'
    # Use Puma as the app server
    gem 'puma', '~> 5.0'
    # Use SCSS for stylesheets
    gem 'sass-rails', '>= 6'
    # Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
    gem 'webpacker', '~> 5.0'
    # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
    gem 'turbolinks', '~> 5'
    # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
    gem 'jbuilder', '~> 2.7'
    # Use Redis adapter to run Action Cable in production
    # gem 'redis', '~> 4.0'
    # Use Active Model has_secure_password
    # gem 'bcrypt', '~> 3.1.7'
    
    gem 'tzinfo-data'
    
    # Use Active Storage variant
    # gem 'image_processing', '~> 1.2'
    
    # Reduces boot times through caching; required in config/boot.rb
    gem 'bootsnap', '>= 1.4.4', require: false
    
    group :development, :test do
      # Call 'byebug' anywhere in the code to stop execution and get a debugger console
      gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
    end
    
    group :development do
      # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
      gem 'web-console', '>= 4.1.0'
      # Display performance information such as SQL time and flame graphs for each request in your browser.
      # Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md
      gem 'rack-mini-profiler', '~> 2.0'
    end
    
    group :test do
      # Adds support for Capybara system testing and selenium driver
      gem 'capybara', '>= 3.26'
      gem 'selenium-webdriver'
      # Easy installation and use of web drivers to run system tests with browsers
      gem 'webdrivers'
    end
    
    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
    gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
    
  2. bundle installコマンドを実行して、すべてのパッケージをインストールします。

    bundle install
    

    バンドルのインストールでは、次の図に示すように出力が表示されます。

    バンドルのインストール

  3. バンドルのインストールが完了したら、routes.rbファイルにルートを追加します。これにより、アプリケーションに公開されているAPIが提供され、コール時にアクションを実行する必要があります。

    config/routes.rb:

    Rails.application.routes.draw do
      root "genai_app#checkin"
      get "/checkin", to: "genai_app#checkin"
      post "/checkin", to: "genai_app#checkinpost"
    end
    
  4. 次に示すように、アプリケーションcontrollerファイルのコードを開発する必要があります。これは、アプリケーションを使用してOCI生成AI APIをコールしたときに実行されるメイン・コードです。

    app/controller/genai_app_controller.rb:

    require 'oci'
    
    class GenAIAppController < ApplicationController
    
      def checkin
        lines = File.readlines("C:/Users/opc/GenAIApp/app/controllers/chatlog.txt")
        @chatLines = lines
      end
    
      def checkinpost
        File.open("C:/Users/opc/GenAIApp/app/controllers/chatlog.txt", "a") { |f| f.write "\nusr::#{params[:message]}" }
        if params[:message].include? "AskAI:"
          fullMessage = params[:message].split("AskAI:")[1].strip()
          region = 'us-chicago-1'
          gen_ai_inference_client = OCI::GenerativeAiInference::GenerativeAiInferenceClient.new(region: region)
          compartment_id = 'ocid1.compartment.oc1..aaaaaaaasdk6oyucuqzcaixwxtnxzlt6xxxxxxxxxxuzrm6vmdqgh6wipa' # compartmentId that has policies grant permissions for using Generative AI Service
          model_id = 'cohere.command'
          prompt = params[:message].split("AskAI:")[1].strip()
          max_tokens = 500
          temperature = 0.75
          frequency_penalty = 1.0
          top_p = 0.7
    
          details = OCI::GenerativeAiInference::Models::GenerateTextDetails.new('compartment_id': compartment_id,
                                                                                'serving_mode': OCI::GenerativeAiInference::Models::OnDemandServingMode.new(
                                                                                  'model_id': model_id
                                                                                ),
                                                                                'inference_request': OCI::GenerativeAiInference::Models::
                                                                                    CohereLlmInferenceRequest.new(
                                                                                      'prompt': prompt,
                                                                                      'is_stream': false,
                                                                                      'max_tokens': max_tokens,
                                                                                      'temperature': temperature,
                                                                                      'top_p': top_p,
                                                                                      'frequency_penalty': frequency_penalty
                                                                                    ))
    
          response = gen_ai_inference_client.generate_text(details)
          text_response = response.data.to_s[170...-150]
          File.open("C:/Users/opc/GenAIApp/app/controllers/chatlog.txt", "a") { |f| f.write "\nnex::#{text_response}" }
          print(text_response)
        end
    
      redirect_to("/checkin")
      end
    
    end
    
  5. ビュー・ファイルのコンテンツを更新します。これは、UIを表示し、アプリケーションでGetおよびPost APIコールをコールするために使用されます。このUIページは、ユーザーがアプリと対話するために使用されます。

    app/view/checkin.html.erb:

    <style>
    
      .greenB {
        background-color: white;
        color: black;
        font-size: 16px;
        border-bottom: 5px solid darkgreen;
        text-decoration: none;
        font-family:verdana;
        font-weight:bold;
        width: 100%;
        height: 50px;
        display: inline-block;
        display:flex;/*CSS3*/
        align-items:center;/*Vertical align*/
        justify-content:center;/*horizontal align*/
      }
    
      .blueB {
        background-color: white;
        color: black;
        font-size: 16px;
        border-bottom: 5px solid #2E86C1;
        text-decoration: none;
        font-family:verdana;
        font-weight:bold;
        width: 100%;
        height: 50px;
        display: inline-block;
        display:flex;/*CSS3*/
        align-items:center;/*Vertical align*/
        justify-content:center;/*horizontal align*/
      }
    
      .greenB:hover {background-color: darkgreen; color: white}
      .blueB:hover {background-color: #2E86C1; color: white}
    </style>
    
    </br>
    <table width=100%>
      <tr>
        <td width=2%>
        </td>
        <td width=98%>
          <div style="color:black;font-family:verdana;font-size:25px;">
            <b>Hey, welcome to Nex!</b>
          </div>
          </br>
          <div style="color:black;font-family:verdana;font-size:17px;">
            <b>New Checking/Chat</b>
          </div>
          </br>
          <div style="color:darkgreen;font-family:verdana;font-size:14px;padding-bottom:20px;">
            <b> Start a new chat with Nex </b>
          </div>
          </br>
          <div style="font-family:verdana;font-size:15px;display:block;height:450px;overflow:auto;">
            <% for line in @chatLines do %>
              <% if line.include? "nex::" %>
                <table width=90%>
                  <tr>
                    <td width=70% style="color:white;background-color:#2E86C1;padding:10px;">
                      <%= line.split("nex::")[1] %>
                    </td>
                    <td width=30%>
                    </td>
                  </tr><tr height=2px></tr>
                </table>
              <% end %>
              <% if line.include? "usr::" %>
                <table width=97%>
                  <tr>
                    <td width=30%>
                    </td>
                    <td width=70% style="color:white;background-color:darkgreen;padding:10px;">
                      <%= line.split("usr::")[1] %>
                    </td>
                  </tr><tr height=2px></tr>
                </table>
              <% end %>
            <% end %>
    
            <table width=90%>
              <tr>
                <td width=70%>
                  <%= submit_tag 'Track it!', name: nil, class: "greenB", :style => "width: 200px;" %>
                </td>
                <td width=30%>
                </td>
              </tr><tr height=5px></tr>
            </table>
          </div>
    
          <%= form_tag({:controller=>"genai_app", :action=>"checkinpost"}, method: :post) do %>
            <table width=100%>
                <tr>
                  <td width=80%>
                    <%= text_field_tag :message, "", :placeholder => "Enter your message", :style => "width: 100%; font-size:17px; padding:15px;" %>
                  </td>
                  <td width=3%>
                  </td>
                  <td width=15%>
                    <%= submit_tag 'Send Message', name: nil, class: "blueB" %>
                  </td>
                  <td width=3%>
                  </td>
                </tr>
            </table>
          <% end %>
        </td>
      </tr>
    </table>
    

    これらすべての変更を行った後、更新されたアプリケーションを表示でき、プロンプトに質問してOCI生成AIを起動できる必要があります。

    OCI GenAI RoRアプリケーションUI

    ノート:

    • 構成に応じてGemfileのバージョンを更新する必要がある場合があるため、すべての宝石とそのバージョンを処理する必要があります。

    • Rubyがインスタンスから必要なgemプロバイダに接続して必要なgemをダウンロードできるように、ネットワーキングを処理します。

承認

その他の学習リソース

docs.oracle.com/learnの他のラボをご覧いただくか、Oracle Learning YouTubeチャネルで無料のラーニング・コンテンツにアクセスしてください。また、education.oracle.com/learning-explorerにアクセスして、Oracle Learning Explorerになります。

製品ドキュメントは、Oracle Help Centerを参照してください。