Class: Openai::Chat
- Inherits:
-
Object
- Object
- Openai::Chat
- Defined in:
- lib/openai/chat.rb
Constant Summary collapse
- BASE_URL =
'https://api.openai.com'.freeze
Instance Attribute Summary collapse
-
#conn ⇒ Object
readonly
Returns the value of attribute conn.
-
#model ⇒ Object
readonly
Returns the value of attribute model.
-
#stream ⇒ Object
readonly
Returns the value of attribute stream.
-
#temperature ⇒ Object
readonly
Returns the value of attribute temperature.
Instance Method Summary collapse
- #call(messages) ⇒ Object
-
#initialize(options = {}) ⇒ Chat
constructor
A new instance of Chat.
Constructor Details
#initialize(options = {}) ⇒ Chat
Returns a new instance of Chat.
9 10 11 12 13 14 15 |
# File 'lib/openai/chat.rb', line 9 def initialize( = {}) @conn = Faraday.new( url: BASE_URL, headers: { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{[:api_key]}" } ) @model, @temperature, @stream = .values_at(:model, :temperature, :stream) end |
Instance Attribute Details
#conn ⇒ Object (readonly)
Returns the value of attribute conn.
7 8 9 |
# File 'lib/openai/chat.rb', line 7 def conn @conn end |
#model ⇒ Object (readonly)
Returns the value of attribute model.
7 8 9 |
# File 'lib/openai/chat.rb', line 7 def model @model end |
#stream ⇒ Object (readonly)
Returns the value of attribute stream.
7 8 9 |
# File 'lib/openai/chat.rb', line 7 def stream @stream end |
#temperature ⇒ Object (readonly)
Returns the value of attribute temperature.
7 8 9 |
# File 'lib/openai/chat.rb', line 7 def temperature @temperature end |
Instance Method Details
#call(messages) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/openai/chat.rb', line 17 def call() res = conn.post('/v1/chat/completions') do |req| req.body = { model: model, temperature: temperature, messages: , stream: stream }.to_json if stream req..on_data = Proc.new do |chunk, overall_received_bytes, env| chunk_text = get_chunk_text(chunk) yield chunk_text unless chunk_text.nil? end end end JSON.parse(res.body).dig("choices", 0, "message", "content") unless stream end |