How to use openAI API

samuellubliner

Samuel Lubliner

Posted on August 7, 2023

How to use openAI API

require "http"
require "json"

request_headers_hash = {
  "Authorization" => "Bearer #{ENV.fetch("OPENAI_API_KEY")}",
  "content-type" => "application/json"
}

request_body_hash = {
  "model" => "gpt-3.5-turbo",
  "messages" => [
    {
      "role" => "system",
      "content" => "You are Ruby programing expert"
    },
    {
      "role" => "user",
      "content" => "What are the steps for creating a dynamic web application"
    }
  ]
}

request_body_json = JSON.generate(request_body_hash)

raw_response = HTTP.headers(request_headers_hash).post(
  "https://api.openai.com/v1/chat/completions",
  :body => request_body_json
).to_s

parsed_response = JSON.parse(raw_response)

pp parsed_response

Enter fullscreen mode Exit fullscreen mode
đź’– đź’Ş đź™… đźš©
samuellubliner
Samuel Lubliner

Posted on August 7, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related