Created
June 24, 2024 23:32
-
-
Save BrianSigafoos/8516072fe645e43c4966e22d690e89fc to your computer and use it in GitHub Desktop.
openai
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# Simple self-contained Ruby file to call OpenAI API endpoints | |
require "httparty" | |
require "json" | |
module OpenAI | |
class Client | |
CHAT_API_ENDPOINT = "https://api.openai.com/v1/chat/completions" | |
CHAT_MODEL = "gpt-4o" | |
def initialize(secret_key, organization_id) | |
@secret_key = secret_key | |
@organization_id = organization_id | |
end | |
def chat(messages:, temperature: 1) | |
opts = {messages: messages, temperature: temperature} | |
resp = chat_json_post(**opts) | |
format_and_log_response(resp, opts) | |
end | |
private | |
attr_reader :secret_key, :organization_id | |
def chat_json_post(messages:, temperature:) | |
HTTParty.post( | |
CHAT_API_ENDPOINT, | |
headers: headers, | |
body: { | |
model: CHAT_MODEL, | |
messages: messages, | |
temperature: temperature | |
}.compact.to_json | |
) | |
end | |
def headers | |
{ | |
"Content-Type" => "application/json", | |
"Authorization" => "Bearer #{@secret_key}", | |
"OpenAI-Organization" => @organization_id | |
}.compact | |
end | |
def format_and_log_response(resp, opts) | |
if resp.key?("error") | |
error_message = resp["error"]["message"] | |
puts "Error: #{error_message}" | |
return {error: error_message} | |
end | |
reply = resp.dig("choices", 0, "message", "content")&.strip | |
metadata = {usage: resp.dig("usage")&.transform_keys(&:to_sym)} | |
log_chat(data: opts.merge(reply: reply, metadata: metadata)) | |
{reply: reply, metadata: metadata} | |
end | |
def log_chat(data:) | |
log_data = { | |
prompt: data[:messages], | |
temperature: data[:temperature], | |
reply: data[:reply], | |
metadata: data[:metadata] | |
} | |
puts "Chat log: #{log_data.to_json}" | |
end | |
end | |
end | |
class CLI | |
def initialize | |
@secret_key = ENV["OPENAI_API_KEY"] | |
@organization_id = ENV["OPENAI_ORG_ID"] | |
@client = OpenAI::Client.new(@secret_key, @organization_id) | |
end | |
def run | |
puts "Please enter your question:" | |
question = gets.chomp | |
messages = [{role: "user", content: question}] | |
response = @client.chat(messages: messages) | |
if response[:error] | |
puts "API Error: #{response[:error]}" | |
elsif response[:reply] | |
puts "Response: #{response[:reply]}" | |
else | |
puts "No response from the API." | |
end | |
end | |
end | |
CLI.new.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment