주:

Ruby on Rails 웹 애플리케이션을 사용하여 프로그래밍 방식으로 OCI 생성형 AI 서비스에 액세스

소개

Oracle Cloud Infrastructure Generative AI(OCI Generative AI)는 기술과 상호 작용하는 방식을 혁신할 수 있는 혁신적인 새로운 인공 지능 도구입니다. 방대한 양의 텍스트 데이터를 학습하고 그 이전에 나온 단어를 기반으로 순서대로 다음 단어를 예측하는 방법을 배우는 대규모 언어 모델입니다. 이를 통해 OCI Generative AI는 텍스트 프롬프트에 대한 인간과 유사한 응답을 생성하여 자연스러운 언어를 만드는 데 매우 강력한 도구입니다.

OCI Generative AI의 가장 인상적인 기능 중 하나는 복잡한 주제를 이해하고 심층적인 설명과 응답을 제공하는 기능입니다. 오늘날 모든 조직은 애플리케이션에서 생성형 AI의 기능을 활용하고 고객을 위한 혁신적인 오퍼링을 만들고자 합니다.

이 자습서에서는 OCI가 전 세계 조직이 OCI를 통해 생성형 AI의 기능을 활용하는 데 어떻게 도움이 되는지 논의하고 이해합니다. 이 자습서에서는 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에서 기본 레일 앱에 액세스할 수 있어야 합니다.

    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 암호를 재설정해야 합니다. 새 암호를 기억하십시오. 이 암호는 다음에 로그인할 때 필요합니다.

    • 네트워크 외부에서 레일스 앱에 액세스하려면 3000 포트를 열고 생성된 컴퓨트 인스턴스에서 Windows 방화벽을 꺼야 합니다.

작업 3: RoR 애플리케이션 설정, 적절한 코드를 작성하여 OCI 생성 AI 서비스 호출 및 표시

  1. 레일스 앱을 실행하고 로컬 및 필요한 네트워크에서 액세스할 수 있게 되면, 첫 번째 단계는 어플리케이션에 필요한 보석을 설정하는 것입니다. 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를 표시하고 애플리케이션에 대한 GetPost 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 Generative AI를 호출할 수도 있어야 합니다.

    OCI GenAI RoR 앱 UI

    참고:

    • 구성에 따라 Gemfile에서 버전을 업데이트해야 하는 경우가 있을 수 있으므로 모든 보석 및 해당 버전을 처리해야 합니다.

    • 네트워킹을 관리하여 Ruby가 필요한 보석을 다운로드하기 위해 인스턴스에서 필요한 보석 제공자에 연결할 수 있도록 합니다.

확인

추가 학습 자원

docs.oracle.com/learn에서 다른 실습을 살펴보거나 Oracle Learning YouTube 채널에서 더 많은 무료 학습 콘텐츠에 액세스하십시오. 또한 education.oracle.com/learning-explorer를 방문하여 Oracle Learning Explorer가 되십시오.

제품 설명서는 Oracle Help Center를 참조하십시오.