Skip to content

Commit

Permalink
Refactor - Rubocop FIX
Browse files Browse the repository at this point in the history
  • Loading branch information
nagstler committed Oct 30, 2024
1 parent 0424370 commit b0c796c
Show file tree
Hide file tree
Showing 14 changed files with 140 additions and 124 deletions.
12 changes: 5 additions & 7 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@ gem "minitest", "~> 5.0"

gem "rubocop", "~> 1.21"

gem 'rest-client'
gem "rest-client"

# Gemfile
group :test do
gem 'webmock'
gem 'simplecov'
gem 'simplecov_json_formatter'
end


gem "simplecov"
gem "simplecov_json_formatter"
gem "webmock"
end
4 changes: 1 addition & 3 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
require "bundler/gem_tasks"
require "rake/testtask"


Rake::TestTask.new(:test) do |t|
t.libs << "test"
t.pattern = 'test/**/*_test.rb'
t.pattern = "test/**/*_test.rb"
t.libs << "lib"
t.test_files = FileList["test/**/test_*.rb"]
end
Expand All @@ -16,4 +15,3 @@ require "rubocop/rake_task"
RuboCop::RakeTask.new

task default: %i[test rubocop]

4 changes: 2 additions & 2 deletions chatgpt-ruby.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ Gem::Specification.new do |spec|

spec.add_dependency "rest-client", "~> 2.1"

spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "minitest", "~> 5.0"
spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "simplecov", "~> 0.21"
spec.add_development_dependency "simplecov_json_formatter", "~> 0.1"
spec.add_development_dependency "webmock", "~> 3.18"
end
end
2 changes: 1 addition & 1 deletion lib/chatgpt.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ def reset_configuration!
@configuration = Configuration.new
end
end
end
end
52 changes: 27 additions & 25 deletions lib/chatgpt/client.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
# frozen_string_literal: true

# lib/chatgpt/client.rb
require 'rest-client'
require 'json'
require "rest-client"
require "json"

module ChatGPT
class Client
def initialize(api_key = nil)
@api_key = api_key || ChatGPT.configuration.api_key
@endpoint = 'https://api.openai.com/v1'
@endpoint = "https://api.openai.com/v1"
@config = ChatGPT.configuration
end

def completions(prompt, params = {})
engine = params[:engine] || @config.default_engine
url = "#{@endpoint}/engines/#{engine}/completions"

data = @config.default_parameters.merge(
prompt: prompt,
max_tokens: params[:max_tokens],
Expand All @@ -27,9 +29,9 @@ def completions(prompt, params = {})

def chat(messages, params = {})
url = "#{@endpoint}/chat/completions"

data = @config.default_parameters.merge(
model: params[:model] || 'gpt-3.5-turbo',
model: params[:model] || "gpt-3.5-turbo",
messages: messages,
temperature: params[:temperature],
top_p: params[:top_p],
Expand All @@ -42,10 +44,10 @@ def chat(messages, params = {})

def chat_stream(messages, params = {}, &block)
raise ArgumentError, "Block is required for streaming" unless block_given?

url = "#{@endpoint}/chat/completions"
data = @config.default_parameters.merge(
model: params[:model] || 'gpt-3.5-turbo',
model: params[:model] || "gpt-3.5-turbo",
messages: messages,
stream: true
).compact
Expand All @@ -61,8 +63,8 @@ def request_api(url, data)
url: url,
payload: data.to_json,
headers: {
'Authorization' => "Bearer #{@api_key}",
'Content-Type' => 'application/json'
"Authorization" => "Bearer #{@api_key}",
"Content-Type" => "application/json"
},
timeout: @config.request_timeout
)
Expand All @@ -73,9 +75,9 @@ def request_api(url, data)

def handle_error(error)
error_response = JSON.parse(error.response.body)
error_message = error_response['error']['message']
error_message = error_response["error"]["message"]
status_code = error.response.code

case status_code
when 401
raise ChatGPT::AuthenticationError.new(error_message, status_code)
Expand All @@ -94,24 +96,24 @@ def request_streaming(url, data)
url: url,
payload: data.to_json,
headers: {
'Authorization' => "Bearer #{@api_key}",
'Content-Type' => 'application/json'
"Authorization" => "Bearer #{@api_key}",
"Content-Type" => "application/json"
},
timeout: @config.request_timeout,
stream_to_buffer: true
) do |chunk, _x, _z|
if chunk.include?("data: ")
chunk.split("\n").each do |line|
if line.start_with?("data: ")
data = line.sub(/^data: /, '')
next if data.strip == "[DONE]"
begin
parsed = JSON.parse(data)
yield parsed if block_given?
rescue JSON::ParserError
next
end
next unless line.start_with?("data: ")

data = line.sub(/^data: /, "")
next if data.strip == "[DONE]"

begin
parsed = JSON.parse(data)
yield parsed if block_given?
rescue JSON::ParserError
next
end
end
end
Expand All @@ -120,4 +122,4 @@ def request_streaming(url, data)
handle_error(e)
end
end
end
end
8 changes: 5 additions & 3 deletions lib/chatgpt/configuration.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
# frozen_string_literal: true

# lib/chatgpt/configuration.rb
module ChatGPT
class Configuration
attr_accessor :api_key, :api_version, :default_engine,
:request_timeout, :max_retries, :default_parameters

def initialize
@api_version = 'v1'
@default_engine = 'text-davinci-002'
@api_version = "v1"
@default_engine = "text-davinci-002"
@request_timeout = 30
@max_retries = 3
@default_parameters = {
Expand All @@ -17,4 +19,4 @@ def initialize
}
end
end
end
end
34 changes: 18 additions & 16 deletions lib/chatgpt/errors.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
# frozen_string_literal: true

# lib/chatgpt/errors.rb
module ChatGPT
class Error < StandardError; end

class APIError < Error
attr_reader :status_code, :error_type

def initialize(message = nil, status_code = nil, error_type = nil)
@status_code = status_code
@error_type = error_type
super(message)
end
class Error < StandardError; end

class APIError < Error
attr_reader :status_code, :error_type

def initialize(message = nil, status_code = nil, error_type = nil)
@status_code = status_code
@error_type = error_type
super(message)
end

class AuthenticationError < APIError; end
class RateLimitError < APIError; end
class InvalidRequestError < APIError; end
class TokenLimitError < APIError; end
end
end

class AuthenticationError < APIError; end
class RateLimitError < APIError; end
class InvalidRequestError < APIError; end
class TokenLimitError < APIError; end
end
4 changes: 3 additions & 1 deletion lib/chatgpt/version.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# frozen_string_literal: true

# lib/chatgpt/version.rb
module Chatgpt
module Ruby
VERSION = "2.0.0"
end
end
end
18 changes: 10 additions & 8 deletions test/chatgpt/chat_test.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
# frozen_string_literal: true

# test/chatgpt/chat_test.rb
require 'test_helper'
require "test_helper"

class TestChatGPTChatIntegration < Minitest::Test
include TestHelpers

def setup
@api_key = 'test-key'
@api_key = "test-key"
@client = ChatGPT::Client.new(@api_key)
end

def test_basic_chat
stub_chat_request
messages = [{ role: "user", content: "Hello!" }]
response = @client.chat(messages)

assert_equal 1, response["choices"].length
assert response["choices"][0]["message"]["content"]
assert_equal "assistant", response["choices"][0]["message"]["role"]
Expand All @@ -25,7 +27,7 @@ def test_chat_with_system_message
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello!" }
]

response = @client.chat(messages)
assert response["choices"][0]["message"]["content"]
end
Expand All @@ -34,20 +36,20 @@ def test_chat_with_custom_parameters
stub_chat_request(temperature: 0.7)
messages = [{ role: "user", content: "Hello!" }]
response = @client.chat(messages, temperature: 0.7)

assert response["choices"][0]["message"]["content"]
end

def test_chat_streaming
stub_chat_stream_request
messages = [{ role: "user", content: "Hello!" }]
chunks = []

@client.chat_stream(messages) do |chunk|
chunks << chunk
end

assert chunks.length > 0
assert chunks.length.positive?
assert chunks.all? { |c| c["choices"][0]["delta"] }
end

Expand All @@ -67,4 +69,4 @@ def test_chat_with_rate_limit
end
assert_equal 429, error.status_code
end
end
end
10 changes: 6 additions & 4 deletions test/chatgpt/completions_test.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# frozen_string_literal: true

# test/chatgpt/completions_test.rb
require 'test_helper'
require "test_helper"

class TestChatGPTCompletionsIntegration < Minitest::Test
include TestHelpers

def setup
@api_key = 'test-key'
@api_key = "test-key"
@client = ChatGPT::Client.new(@api_key)
end

Expand All @@ -25,7 +27,7 @@ def test_completions_with_custom_params
top_p: 0.9,
n: 2
}

response = @client.completions("Hello, my name is", custom_params)
assert_equal 2, response["choices"].length
end
Expand Down Expand Up @@ -71,4 +73,4 @@ def test_completions_returns_error_with_rate_limit
assert_equal "Rate limit exceeded", error.message
assert_equal 429, error.status_code
end
end
end
Loading

0 comments on commit b0c796c

Please sign in to comment.