Class: BuilderApm::Doctor::OpenAIChatGPT
- Inherits:
-
Object
- Object
- BuilderApm::Doctor::OpenAIChatGPT
- Defined in:
- lib/builder_apm/doctor/openai_chat_gpt.rb
Constant Summary collapse
- MAX_RETRIES =
3
- TIMEOUT_IN_SECONDS =
equivalent to 5 minutes
300
Instance Method Summary collapse
- #chat(messages) ⇒ Object
-
#initialize(api_key, model = "gpt-3.5-turbo") ⇒ OpenAIChatGPT
constructor
A new instance of OpenAIChatGPT.
- #role(ai_role = nil) ⇒ Object
- #temperature(temp = nil) ⇒ Object
Constructor Details
#initialize(api_key, model = "gpt-3.5-turbo") ⇒ OpenAIChatGPT
Returns a new instance of OpenAIChatGPT.
12 13 14 15 16 17 18 |
# File 'lib/builder_apm/doctor/openai_chat_gpt.rb', line 12 def initialize(api_key, model = "gpt-3.5-turbo") @api_key = api_key @uri = URI.parse("https://api.openai.com/v1/chat/completions") @role = "You are to be my assistant" @model = model @temperature = 0.2 end |
Instance Method Details
#chat(messages) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/builder_apm/doctor/openai_chat_gpt.rb', line 32 def chat() request = Net::HTTP::Post.new(@uri) request.content_type = "application/json" request["Authorization"] = "Bearer #{@api_key}" request.body = JSON.dump({ "model" => @model, "temperature" => temperature, "messages" => () }) = { use_ssl: @uri.scheme == "https", } begin retries ||= 0 response = Net::HTTP.start(@uri.hostname, @uri.port, ) do |http| http.read_timeout = TIMEOUT_IN_SECONDS http.request(request) end rescue Net::ReadTimeout => e if retries < MAX_RETRIES retries += 1 retry else raise e end end data = JSON.parse(response.body)["choices"] raise data.dig("error", "message") if data.is_a?(Hash) && data.dig("error", "message") data.dig(0, "message", "content") end |
#role(ai_role = nil) ⇒ Object
20 21 22 23 24 |
# File 'lib/builder_apm/doctor/openai_chat_gpt.rb', line 20 def role(ai_role = nil) @role = ai_role unless ai_role.nil? @role end |
#temperature(temp = nil) ⇒ Object
26 27 28 29 30 |
# File 'lib/builder_apm/doctor/openai_chat_gpt.rb', line 26 def temperature(temp = nil) @temperature = temp unless temp.nil? @temperature end |