DEV Community

kojix2
kojix2

Posted on

Calling the ChatGPT API interactively from Crystal language

terminal

require "http/client"
require "json"
require "colorize"

struct PostData
  include JSON::Serializable
  property model : String
  property messages : Array(Hash(String, String))
  property temperature : Float64
  property top_p : Float64
  property n : Int32

  def initialize
    @model = "gpt-3.5-turbo"
    @messages = [] of Hash(String, String)
    @n = 1
    @temperature = 1.0
    @top_p = 1.0
  end
end

data = PostData.new

url = "https://api.openai.com/v1/chat/completions"
api_key = ENV["OPENAI_API_KEY"]
headers = HTTP::Headers{
  "Authorization" => "Bearer #{api_key}",
  "Content-Type"  => "application/json",
}

def get_input(prompt)
  print prompt
  STDIN.gets.to_s.chomp
end

def send_chat_request(url, data, headers)
  STDERR.puts data.pretty_inspect.colorize(:dark_gray) # comment out here!
  HTTP::Client.post(url, body: data.to_json, headers: headers)
end

loop do
  msg = get_input("> ")
  break if msg.empty?
  data.messages << {"role" => "user", "content" => msg}

  response = send_chat_request(url, data, headers)
  response_data = JSON.parse(response.body)

  if response.status.success?
    result = response_data["choices"][0]["message"]["content"]
    data.messages << {"role" => "assistant", "content" => result.to_s}
    puts result.colorize(:green)
  else
    STDERR.puts "Error: #{response.status_code} #{response.status}".colorize(:yellow).mode(:bold)
    STDERR.puts response.body.colorize(:yellow)
    exit 1
  end
end
Enter fullscreen mode Exit fullscreen mode

According to ChatGPT, the description of this code is as follows


The code is a program written in the Crystal language that uses the OpenAI ChatGPT API to conduct a chat conversation.

The first few lines import the required libraries - HTTP client, JSON parser, and colorize (for terminal color highlighting). The next part defines a struct named PostData that represents the data to be sent in the API request. It has several properties, including the model name, messages array, and temperature and top_p values, which are used to configure the behavior of the ChatGPT model.

The get_input function is defined to prompt the user for input, and the send_chat_request function is used to send the request to the API endpoint, using the data provided as the request body.

The main part of the program is a loop that iteratively prompts the user for input, sends the input to the API endpoint using the send_chat_request function, and then processes the response. If the response is successful, it extracts the result from the response data and displays it to the user in green color. If there is an error in the response, it displays an error message in yellow color and exits the program.

Overall, the program provides a simple command-line interface for conducting a chat conversation using the OpenAI ChatGPT API.


Wonderful. I can't explain what I wrote in my code very well, but ChatGPT does it very well.

Have a nice day!

Top comments (0)