附註:
- 此教學課程需要存取 Oracle Cloud。若要註冊免費帳戶,請參閱開始使用 Oracle Cloud Infrastructure Free Tier 。
- 它使用 Oracle Cloud Infrastructure 憑證、租用戶及區間的範例值。完成實驗室時,請將這些值取代為您雲端環境特有的值。
在鐵路 Web 應用程式上使用 Ruby 以程式設計方式存取 OCI Generative 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。
目標
-
根據 GitLab 代理程式將連線至 OCI 租用戶的使用者設定 OCI API 金鑰。
-
建立並設定運算執行處理,以便將它用於 RoR 開發。
-
設定 RoR 應用程式、撰寫適當的程式碼以呼叫及顯示 OCI Generative AI 服務。
必要條件
-
存取 Oracle Cloud Infrastructure Identity and Access Management (OCI IAM) 中允許的 OCI 和原則。使用者應可存取想要使用 Terraform 代碼建立或更新的對應資源。
-
Ruby 和 RoR 的知識及其以 Model View Controller (MVC) Web 應用程式開發為基礎的工作方法。
-
對軟體開發之敏捷方法的基本理解。
作業 1:設定 Oracle Cloud Infrastructure API 金鑰
-
使用服務帳戶或管理員使用者登入 OCI 租用戶,並前往使用者設定值。
或
從 OCI IAM 主控台前往使用者。確定使用者具備在 OCI 上建立及更新基礎架構的所有必要存取權。
-
移至使用者的資源區段,按一下 API 金鑰和新增 API 金鑰。選取即可下載新的公用金鑰和私密金鑰、上傳您的公開金鑰或貼上您的公開金鑰。
-
將金鑰儲存在方便的位置,並依照下列頁面所示儲存配置檔案。使用 Ruby SDK 連線至您的租用戶時,將需要使用此組態檔和私密金鑰。
注意:
-
OCI 目前支援
US-CHICAGO-1
區域中的生成式 AI 服務。因此,請務必在您的租用戶中啟用並訂閱此區域。 -
若要從 OCI Compute 執行處理呼叫 OCI 服務,OCI 能夠以更安全的方式使用執行處理主體。避免使用使用者 API 金鑰作為最佳做法。如需詳細資訊,請參閱從執行處理呼叫服務。
-
作業 2:建立並設定用於 RoR 開發的 OCI Compute 執行處理
-
請前往在 OCI 上啟動 Windows 執行處理,在 OCI 上建立 Windows 運算執行處理。
-
建立 Windows 執行處理之後,請使用您的初始密碼登入,如下螢幕擷取畫面所示。
-
登入 Windows 運算執行處理之後,請安裝並設定 Ruby、Rails 上的 Ruby,然後使用 rails 命令建立新的應用程式。
rails new GenAIApp
移至您的應用程式目錄並執行下列命令,以啟動並執行鐵路應用程式伺服器。您應該能夠在
http://127.0.0.1:3000
上存取預設的鐵路應用程式。cd GenAIApp rails server -b 0.0.0.0
-
移至您的使用者本位目錄 (
c:/users/opc
),然後建立 Ruby SDK 的config
檔案。設定您下載至 Task 1.3 的組態檔,同時下載私密金鑰檔案。如需詳細資訊,請參閱 Oracle Cloud Infrastructure Ruby SDK 。注意:
-
您必須在第一次登入 OCI 運算執行處理時重設 Windows 密碼。請記住新密碼,因為下次登入時需要此密碼。
-
若要從網路外部存取您的 Rails 應用程式,您必須開啟連接埠
3000
,並且從建立的運算執行處理關閉 Windows 防火牆。
-
工作 3:設定 RoR 應用程式、撰寫適當的程式碼以呼叫及顯示 OCI Generative AI 服務
-
在您能夠執行您的 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]
-
執行
bundle install
命令以安裝所有套裝程式。bundle install
您的搭售品安裝應如下圖所示顯示輸出。
-
搭售品安裝完成後,請將路由新增至
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
-
我們必須開發應用程式
controller
檔案的程式碼,如下所示。這是使用 App 呼叫 OCI Generative 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
-
更新我們的檢視檔案內容。這將用來顯示 UI,並在應用程式上呼叫取得和張貼 API 呼叫。使用者將使用此 UI 頁面與您的 App 互動。
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。
注意:
-
您必須注意所有寶石及其版本,因為您可能需要根據組態更新
Gemfile
中的版本。 -
謹慎使用網路,讓 Ruby 能夠從您的執行處理連線至必要的 gem 提供者,以下載所需的寶石。
-
相關連結
認可
- 作者 - Lovelesh Saxena (主要軟體工程架構師)
其他學習資源
瀏覽 docs.oracle.com/learn 的其他實驗室,或前往 Oracle Learning YouTube 頻道存取更多免費學習內容。此外,請造訪 education.oracle.com/learning-explorer 以成為 Oracle Learning Explorer。
如需產品文件,請造訪 Oracle Help Center 。
Access OCI Generative AI Service Programmatically using Ruby on Rails Web Application
F96230-01
April 2024