DEV Community

Samuel Lubliner
Samuel Lubliner

Posted on

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

Top comments (0)