DEV Community

kojix2
kojix2

Posted on

Calling OpenAI API from Crystal Language

If you want to use OpenAI API from Crystal Language, you can use the following code. (Note that you need a paid API KEY to call OpenAI API.) Make sure to set the environment variable so that ENV["OPENAI_ACCESS_TOKEN"] works.

require "option_parser"
require "http/client"
require "json"

data = {
  "model"       => "text-davinci-003",
  "prompt"      => "Hi!",
  "max_tokens"  => 10,
  "temperature" => 0,
}

OptionParser.parse do |parser|
  parser.on("-m INT", "--max-tokens INT") { |v| data["max_tokens"] = v.to_i }
end

data["prompt"] = ARGV.join(" ")

url = "https://api.openai.com/v1/completions"
api_key = ENV["OPENAI_ACCESS_TOKEN"]
headers = HTTP::Headers{
  "Authorization" => "Bearer #{api_key}",
  "Content-Type"  => "application/json",
}
response = HTTP::Client.post(url, body: data.to_json, headers: headers)

if response.status.success?
  response_data = JSON.parse(response.body)
  puts response_data["choices"][0]["text"]
else
  puts "Error: #{response.status_code} #{response.status}"
end
Enter fullscreen mode Exit fullscreen mode

How to use?

crystal run file_name.cr -- Are you fine?
crystal run file_name.cr -- -m 20 Are you fine?
Enter fullscreen mode Exit fullscreen mode

Or, after build,

executable_file Are you fine?
executable_file -m 20 Are you fine?
Enter fullscreen mode Exit fullscreen mode

Have a nice day!

Top comments (1)

Collapse
 
dallas_robertdallasrobe profile image
Dallas Robert Dallas Robert

WTB OPNEIA CREDIT