richat 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 58bf302c022f3345bdc1b3fcf5dc315f9bd12f58d9f680370b2cb5f630942505
4
+ data.tar.gz: 04ab5c941a0b242170a7f881ff7fcdeb93cb5dc16a154db27cafa8a45407233c
5
+ SHA512:
6
+ metadata.gz: f2741a9bc6378d3c9eb17aa2e654c0932a5eaa689bc13dc880a3cfe39123d10eb9a71ffba9482588b488c571bf3a5688b653ad1c0cee708e36066c09f1b15be3
7
+ data.tar.gz: 8a99c9a0ee58787c0e24db37ed489b894cfd62a8f3be0278484aa04bf348e5153af163a9a5ec61138ef96469b5370a2e38b495d826ed3aa1ef00d81c26ca5b1e
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.7
7
+ before_install: gem install bundler -v 1.17.3
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at fzdp01@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+ gem "faraday"
5
+ # Specify your gem's dependencies in richat.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,41 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ richat (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ diff-lcs (1.4.4)
10
+ faraday (2.7.4)
11
+ faraday-net_http (>= 2.0, < 3.1)
12
+ ruby2_keywords (>= 0.0.4)
13
+ faraday-net_http (3.0.2)
14
+ rake (10.5.0)
15
+ rspec (3.10.0)
16
+ rspec-core (~> 3.10.0)
17
+ rspec-expectations (~> 3.10.0)
18
+ rspec-mocks (~> 3.10.0)
19
+ rspec-core (3.10.1)
20
+ rspec-support (~> 3.10.0)
21
+ rspec-expectations (3.10.1)
22
+ diff-lcs (>= 1.2.0, < 2.0)
23
+ rspec-support (~> 3.10.0)
24
+ rspec-mocks (3.10.2)
25
+ diff-lcs (>= 1.2.0, < 2.0)
26
+ rspec-support (~> 3.10.0)
27
+ rspec-support (3.10.2)
28
+ ruby2_keywords (0.0.5)
29
+
30
+ PLATFORMS
31
+ ruby
32
+
33
+ DEPENDENCIES
34
+ bundler (~> 1.17)
35
+ faraday
36
+ rake (~> 10.0)
37
+ richat!
38
+ rspec (~> 3.0)
39
+
40
+ BUNDLED WITH
41
+ 1.17.3
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 fzdp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # Richat
2
+
3
+ ## A powerful command-line ChatGPT tool.
4
+
5
+ Richat is a command-line ChatGPT tool implemented in Ruby that supports highly customizable configuration. It can save chat logs, performs fuzzy searches on historical inputs, allows for prompt customization and switching at any time.
6
+
7
+ https://user-images.githubusercontent.com/6159178/228784846-a31772c0-53a5-4aff-92ae-2e33d9c6fad5.mov
8
+
9
+ ## Installation
10
+
11
+ ```
12
+ gem install richat
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ There are two ways to configure OpenAI API key
18
+
19
+ 1. set `OPENAI_API_KEY` env variable
20
+ 2. edit `~/.richat/config.json` file and set API key, for example
21
+
22
+ ```
23
+ {
24
+ "chatgpt": {
25
+ "api_key": "YOUR OPENAI API KEY"
26
+ }
27
+ }
28
+ ```
29
+
30
+ Then run `richat` command to talk with ChatGPT.
31
+
32
+ <img width="800" alt="image" src="https://user-images.githubusercontent.com/6159178/228755576-5d76a777-f07e-43f6-8141-4f9e19f15372.png">
33
+
34
+ ### Configuration
35
+
36
+ Use `/config` command to show current configuration.
37
+
38
+ ```
39
+ >> /config
40
+ Configuration file path is /Users/fzdp/.richat/config.json
41
+ {
42
+ "chatgpt": {
43
+ "api_key": "YOUR_OPENAI_API_KEY",
44
+ "model": "gpt-3.5-turbo",
45
+ "temperature": 0.7
46
+ },
47
+ "log": {
48
+ "enable": true,
49
+ "log_dir": "~/.richat/logs",
50
+ "user_role": "USR",
51
+ "ai_role": "GPT",
52
+ "system_role": "SYS"
53
+ },
54
+ "shell": {
55
+ "save_history": true,
56
+ "enable_chat_context": true,
57
+ "show_welcome_info": true,
58
+ "history_file": "~/.richat/shell_history.txt"
59
+ },
60
+ "prompt": {
61
+ "prompt_dir": "~/.richat/prompts",
62
+ "default": ""
63
+ }
64
+ }
65
+ ```
66
+
67
+ Edit `~/.richat/config.json` if you need customize configuration.
68
+
69
+ ### Chat log
70
+
71
+ By default, Richat will log your chat history and log names are in date format.
72
+
73
+ Set `log.enable` to false if you don't need log feature.
74
+
75
+ <img width="409" alt="" src="https://user-images.githubusercontent.com/6159178/228758657-1dbbe25b-e768-403d-8b42-3b270f53fe2a.png">
76
+
77
+ ### Prompt
78
+
79
+ You can place prompt files in `~/.richat/prompts` or other directory defined in configure file.
80
+
81
+ For example, if you place `emoji`, `linux`, `wikipedia` in the directory, then in Richat shell `/prompt` command will show these prompt files.
82
+
83
+ <img width="960" alt="" src="https://user-images.githubusercontent.com/6159178/228761906-4ab74529-3ccb-41b7-badc-98cc0fd9bd72.png">
84
+
85
+ #### Change prompt
86
+
87
+ You can use `/prompt` command to switch prompt, the argument is prompt file name or prompt file index.
88
+
89
+ <img width="960" alt="" src="https://user-images.githubusercontent.com/6159178/228764026-79bbbfef-cd5d-4641-9edf-91f7d71063a5.png">
90
+
91
+ #### Set default prompt
92
+
93
+ For example if you want to use linux as default prompt, just edit config file
94
+
95
+ ```json
96
+ {
97
+ "prompt": {
98
+ "default": "linux"
99
+ }
100
+ }
101
+ ```
102
+
103
+ Then Richat shell will use linux prompt when it's run
104
+
105
+ <img width="960" alt="" src="https://user-images.githubusercontent.com/6159178/228766064-12230d33-158a-413e-8473-6a7dc60f28bd.png">
106
+
107
+ ### Input history
108
+
109
+ By default your input history will be saved in `~/.richat/shell_history_file`.
110
+
111
+ In Richat shell mode, there are three ways to enhance chat experience.
112
+
113
+ 1. press TAB to auto complete input
114
+ 2. press Arrow keys to traverse history
115
+ 3. press `Control + R` to fuzzy search input
116
+
117
+ ### Stream mode
118
+
119
+ ChatGPT stream mode is auto enabled in Richat shell mode
120
+
121
+ https://user-images.githubusercontent.com/6159178/228770757-c3e1c286-7077-4a00-b376-a491ca280126.mov
122
+
123
+ ### Cli
124
+
125
+ You can run `richat` with additional chat content directly
126
+
127
+ ```
128
+ ~ richat hello world
129
+ Hello! How can I assist you today?
130
+ ```
131
+
132
+ ### Chat context
133
+
134
+ Chat context is enabled by default, because ChatGPT have no memory of past requests, all relevant information must be supplied via the conversation.
135
+
136
+ You can turn it off in config file.
137
+
138
+ ## Contributing
139
+
140
+ Bug reports and pull requests are welcome on GitHub at https://github.com/fzdp/richat.
141
+
142
+ ## License
143
+
144
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
145
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "richat"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/exe/richat ADDED
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'richat'
5
+
6
+ log_dir = File.expand_path(Richat::Config.get("log", "log_dir"))
7
+ FileUtils.mkdir_p(log_dir) unless File.directory?(log_dir)
8
+
9
+ prompt_dir = File.expand_path(Richat::Config.get("prompt", "prompt_dir"))
10
+ FileUtils.mkdir_p(prompt_dir) unless File.directory?(prompt_dir)
11
+
12
+ chat_config = {
13
+ api_key: Richat::Config.get("chatgpt", "api_key"),
14
+ model: Richat::Config.get("chatgpt", "model"),
15
+ temperature: Richat::Config.get("chatgpt", "temperature"),
16
+ stream: true
17
+ }
18
+
19
+ if Richat::Config.get("log", "enable")
20
+ logger = Richat::Logger.new(log_file: "#{log_dir}/#{Time.now.strftime('%Y%m%d')}.md")
21
+ else
22
+ logger = Richat::Logger.empty_logger
23
+ end
24
+
25
+ if ARGV.size.zero?
26
+ client = Openai::Chat.new(chat_config)
27
+ Richat::Shell.new(chat_client: client, logger: logger).call
28
+ else
29
+ client = Openai::Chat.new(chat_config.merge(stream: false))
30
+ Richat::Cli.new(chat_client: client, logger: logger, user_content: ARGV.join(" ")).call
31
+ end
@@ -0,0 +1,15 @@
1
+ class Hash
2
+ def deep_merge(other_hash)
3
+ result = self.dup
4
+
5
+ other_hash.each do |key, value|
6
+ if value.is_a?(Hash) && self[key].is_a?(Hash)
7
+ result[key] = result[key].deep_merge(value)
8
+ else
9
+ result[key] = value
10
+ end
11
+ end
12
+
13
+ result
14
+ end
15
+ end
@@ -0,0 +1,48 @@
1
+ require 'faraday'
2
+
3
+ module Openai
4
+ class Chat
5
+ BASE_URL = 'https://api.openai.com'.freeze
6
+
7
+ attr_reader :conn, :model, :temperature, :stream
8
+
9
+ def initialize(options = {})
10
+ @conn = Faraday.new(
11
+ url: BASE_URL,
12
+ headers: { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{options[:api_key]}" }
13
+ )
14
+ @model, @temperature, @stream = options.values_at(:model, :temperature, :stream)
15
+ end
16
+
17
+ def call(messages)
18
+ res = conn.post('/v1/chat/completions') do |req|
19
+ req.body = {
20
+ model: model,
21
+ temperature: temperature,
22
+ messages: messages,
23
+ stream: stream
24
+ }.to_json
25
+
26
+ if stream
27
+ req.options.on_data = Proc.new do |chunk, overall_received_bytes, env|
28
+ chunk_text = get_chunk_text(chunk)
29
+ yield chunk_text unless chunk_text.nil?
30
+ end
31
+ end
32
+ end
33
+
34
+ JSON.parse(res.body).dig("choices", 0, "message", "content") unless stream
35
+ end
36
+
37
+ private
38
+
39
+ def get_chunk_text(chunk)
40
+ chunk_text = ''
41
+ chunk.split("\n\n").map { |data_str| data_str.sub(/^(data: )/, '') }.each do |data_str|
42
+ return nil if data_str == '[DONE]'
43
+ chunk_text += JSON.parse(data_str).dig('choices', 0, 'delta', 'content') || ''
44
+ end
45
+ chunk_text
46
+ end
47
+ end
48
+ end
data/lib/richat/cli.rb ADDED
@@ -0,0 +1,21 @@
1
+ module Richat
2
+ class Cli
3
+ attr_reader :chat_client, :logger, :user_content
4
+
5
+ def initialize(options = {})
6
+ @chat_client = options[:chat_client]
7
+ @logger = options[:logger]
8
+ @user_content = options[:user_content]
9
+ end
10
+
11
+ def call
12
+ logger.call(role: Config.get("log", "user_role"), content: user_content)
13
+ response = chat_client.call([{ role: 'user', content: user_content }])
14
+
15
+ if !response.nil? && !response.empty?
16
+ logger.call(role: Config.get("log", "ai_role"), content: response)
17
+ puts response
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,131 @@
1
+ module Richat
2
+ class Command
3
+ EXIT_CODE = 0
4
+ NEXT_CODE = 1
5
+ PROMPT_CHANGED_CODE = 2
6
+
7
+ class << self
8
+ attr_reader :prompt, :prompt_id
9
+
10
+ def call(user_input)
11
+ user_input = user_input.strip
12
+ return unless user_input.start_with?("/")
13
+ if user_input == "/help"
14
+ handle_help
15
+ elsif user_input == "/config"
16
+ handle_config
17
+ elsif user_input == "/exit"
18
+ handle_exit
19
+ elsif user_input =~ /^\/prompt\s*/
20
+ if user_input == "/prompt"
21
+ handle_prompt
22
+ else
23
+ handle_choose_prompt(user_input.split(" ").last)
24
+ end
25
+ end
26
+ end
27
+
28
+ def handle_exit
29
+ puts "Bye"
30
+ EXIT_CODE
31
+ end
32
+
33
+ def handle_config
34
+ puts "\e[32mConfiguration file path is #{File.expand_path("~/.richat/config.json")}\e[0m"
35
+ puts JSON.pretty_generate(Config.config)
36
+ NEXT_CODE
37
+ end
38
+
39
+ def handle_help
40
+ puts "\e[32m/exit\e[0m exit Richat"
41
+ puts "\e[32m/config\e[0m show configuration"
42
+ puts "\e[32m/prompt\e[0m show prompt list"
43
+ puts "\e[32m/help\e[0m show help info"
44
+ NEXT_CODE
45
+ end
46
+
47
+ def prompt_id_list
48
+ Dir.entries(File.expand_path(Config.get("prompt", "prompt_dir"))).delete_if {|s| [".",".."].include?(s)}
49
+ end
50
+
51
+ def handle_prompt
52
+ id_list = prompt_id_list
53
+ if id_list.empty?
54
+ print_exception "#{File.expand_path(Config.get("prompt", "prompt_dir"))} has no prompt files."
55
+ return NEXT_CODE
56
+ end
57
+
58
+ if prompt.nil? || prompt.empty?
59
+ puts "\e[32mCurrent prompt not set.\e[0m"
60
+ puts "Use command \e[32m/prompt prompt_index\e[0m or \e[32m/prompt prompt_id\e[0m to set prompt."
61
+ end
62
+
63
+ id_list.each_with_index do |pt, idx|
64
+ if pt == prompt_id
65
+ puts "#{idx}. \e[32m#{pt}\e[0m"
66
+ else
67
+ puts "#{idx}. #{pt}"
68
+ end
69
+ end
70
+ NEXT_CODE
71
+ end
72
+
73
+ def handle_choose_prompt(arg)
74
+ id_list = prompt_id_list
75
+ if id_list.empty?
76
+ print_exception("Prompt files not found.")
77
+ return NEXT_CODE
78
+ end
79
+
80
+ if id_list.include?(arg)
81
+ current_prompt_id = arg
82
+ elsif arg =~ /\d/
83
+ pt_id = id_list[arg.to_i]
84
+ if pt_id.nil?
85
+ print_exception("Prompt not found.")
86
+ return NEXT_CODE
87
+ end
88
+ current_prompt_id = pt_id
89
+ else
90
+ print_exception("Prompt not found.")
91
+ return NEXT_CODE
92
+ end
93
+
94
+ if current_prompt_id == @prompt_id
95
+ print_exception("Prompt not changed.")
96
+ return NEXT_CODE
97
+ end
98
+
99
+ prompt_content = File.read(File.join(File.expand_path(Config.get("prompt", "prompt_dir")), current_prompt_id))
100
+ if prompt_content.empty?
101
+ print_exception("Prompt is empty.")
102
+ return NEXT_CODE
103
+ end
104
+
105
+ puts "Changed prompt to #{current_prompt_id}."
106
+ @prompt_id = current_prompt_id
107
+ @prompt = prompt_content
108
+ PROMPT_CHANGED_CODE
109
+ end
110
+
111
+ def print_exception(message)
112
+ puts "\e[31m#{message}\e[0m"
113
+ end
114
+
115
+ def print_welcome
116
+ puts "Richat is a command-line ChatGPT tool implemented in Ruby that supports highly customizable configuration, press \e[32m/help\e[0m to display help info. If you have any suggestions or questions, please feel free to provide feedback on https://github.com/fzdp/richat."
117
+ end
118
+
119
+ def load_default_prompt
120
+ @prompt ||= begin
121
+ @prompt_id = Config.get("prompt", "default")
122
+ if @prompt_id.nil? || @prompt_id.empty?
123
+ @prompt_id = nil
124
+ return
125
+ end
126
+ File.read(File.join(File.expand_path(Config.get("prompt", "prompt_dir")), @prompt_id))
127
+ end
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,47 @@
1
+ module Richat
2
+ class Config
3
+ DEFAULT_CONFIG = {
4
+ "chatgpt" => {
5
+ "api_key" => ENV["OPENAI_API_KEY"],
6
+ "model" => "gpt-3.5-turbo",
7
+ "temperature" => 0.7
8
+ },
9
+ "log" => {
10
+ "enable" => true,
11
+ "log_dir" => "~/.richat/logs",
12
+ "user_role" => "USR",
13
+ "ai_role" => "GPT",
14
+ "system_role" => "SYS"
15
+ },
16
+ "shell" => {
17
+ "save_shell_history" => true,
18
+ "enable_chat_context" => true,
19
+ "show_welcome_info" => true,
20
+ "shell_history_file" => "~/.richat/history.txt"
21
+ },
22
+ "prompt" => {
23
+ "prompt_dir" => "~/.richat/prompts",
24
+ "default" => ""
25
+ }
26
+ }.freeze
27
+
28
+ class << self
29
+ attr_reader :config
30
+
31
+ def get(*keys)
32
+ (@config ||= merge_config).dig(*keys)
33
+ end
34
+ end
35
+
36
+ private
37
+
38
+ def self.merge_config
39
+ user_config = if File.exist?((config_file = File.expand_path("~/.richat/config.json")))
40
+ JSON.parse(File.read(config_file))
41
+ else
42
+ {}
43
+ end
44
+ DEFAULT_CONFIG.deep_merge(user_config)
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,29 @@
1
+ require 'logger'
2
+
3
+ module Richat
4
+ class Logger
5
+ attr_reader :logger
6
+
7
+ def initialize(options = {})
8
+ original_log_header = ::Logger::LogDevice.instance_method(:add_log_header)
9
+ ::Logger::LogDevice.define_method(:add_log_header) {}
10
+
11
+ @logger = ::Logger.new(options[:log_file])
12
+ ::Logger::LogDevice.define_method(original_log_header.name, original_log_header)
13
+
14
+ @logger.formatter = proc do |severity, datetime, role, msg|
15
+ "[#{role}] #{datetime.strftime('%Y-%m-%d %H:%M:%S')}\n\n#{msg}\n\n"
16
+ end
17
+ end
18
+
19
+ def call(log_data)
20
+ logger.info(log_data[:role]) { log_data[:content] }
21
+ end
22
+
23
+ class << self
24
+ def empty_logger
25
+ ->() {}
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,88 @@
1
+ require 'readline'
2
+
3
+ module Richat
4
+ class Shell
5
+ attr_reader :chat_client, :logger, :user_role, :ai_role, :system_role, :history_path
6
+
7
+ def initialize(options = {})
8
+ @chat_client = options[:chat_client]
9
+ @logger = options[:logger]
10
+ @user_role = Config.get("log", "user_role")
11
+ @ai_role = Config.get("log", "ai_role")
12
+ @system_role = Config.get("log", "system_role")
13
+ @history_path = File.expand_path(Config.get("shell", "shell_history_file"))
14
+ File.open(@history_path, 'w') {} unless File.exists?(@history_path)
15
+ end
16
+
17
+ def call
18
+ enable_context_message = Config.get("shell", "enable_chat_context")
19
+ enable_full_completion = Config.get("shell", "save_shell_history")
20
+
21
+ if enable_full_completion
22
+ Readline::HISTORY.push(*File.readlines(history_path).last(1000).map(&:chomp))
23
+ end
24
+
25
+ Readline.completion_proc = proc { |s| Readline::HISTORY&.grep(/^#{Regexp.escape(s)}/) }
26
+ Readline.completion_append_character = ""
27
+
28
+ default_prompt = Command.load_default_prompt
29
+ if default_prompt.nil? || default_prompt.empty?
30
+ context_messages = []
31
+ else
32
+ context_messages = [{ role: 'system', content: default_prompt }]
33
+ end
34
+
35
+ Command.print_welcome if Config.get("shell", "show_welcome_info")
36
+
37
+ begin
38
+ while (user_content = Readline.readline("\e[32m#{Command.prompt_id&.+" "}\e[0m\e[33m>> \e[0m", true))
39
+ if user_content.empty?
40
+ Readline::HISTORY&.pop
41
+ next
42
+ end
43
+
44
+ File.open(history_path, 'a') { |f| f.puts(user_content) } if enable_full_completion
45
+
46
+ if (code = Command.call(user_content))
47
+ if code == Command::NEXT_CODE
48
+ next
49
+ elsif code == Command::EXIT_CODE
50
+ break
51
+ elsif code == Command::PROMPT_CHANGED_CODE
52
+ context_messages = [{ role: 'system', content: Command.prompt }]
53
+ next
54
+ end
55
+ end
56
+
57
+ logger.call(role: user_role, content: user_content)
58
+ response = ''
59
+
60
+ context_messages << { role: 'user', content: user_content }
61
+
62
+ chat_client.call(context_messages) do |chunk|
63
+ response += chunk
64
+ print chunk
65
+ end
66
+
67
+ if response.empty?
68
+ Command.print_exception("Empty response from ChatGPT.")
69
+ break
70
+ end
71
+
72
+ logger.call(role: ai_role, content: response)
73
+
74
+ if enable_context_message
75
+ context_messages << { role: 'assistant', content: response }
76
+ else
77
+ context_messages.pop
78
+ end
79
+
80
+ puts
81
+ end
82
+ rescue SignalException, Exception => e
83
+ puts e.message
84
+ Command.handle_exit
85
+ end
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,3 @@
1
+ module Richat
2
+ VERSION = "0.2.0"
3
+ end
data/lib/richat.rb ADDED
@@ -0,0 +1,13 @@
1
+ require "richat/version"
2
+
3
+ require_relative 'extension/hash'
4
+ require_relative 'richat/config'
5
+ require_relative 'richat/command'
6
+ require_relative 'openai/chat'
7
+ require_relative 'richat/logger'
8
+ require_relative 'richat/shell'
9
+ require_relative 'richat/cli'
10
+
11
+ module Richat
12
+ class Error < StandardError; end
13
+ end
data/richat.gemspec ADDED
@@ -0,0 +1,38 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "richat/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "richat"
8
+ spec.version = Richat::VERSION
9
+ spec.authors = ["fzdp"]
10
+ spec.email = ["fzdp01@gmail.com"]
11
+
12
+ spec.summary = %q{Richat is a command-line ChatGPT tool}
13
+ spec.description = %q{Richat is a command-line ChatGPT tool implemented in Ruby that supports highly customizable configuration. It can save chat logs, performs fuzzy searches on historical inputs, allows for prompt customization and switching at any time}
14
+ spec.homepage = "https://github.com/fzdp/richat"
15
+ spec.license = "MIT"
16
+
17
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
18
+ if spec.respond_to?(:metadata)
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/fzdp/richat"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against " \
23
+ "public gem pushes."
24
+ end
25
+
26
+ # Specify which files should be added to the gem when it is released.
27
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
28
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
29
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ spec.add_development_dependency "bundler", "~> 1.17"
36
+ spec.add_development_dependency "rake", "~> 10.0"
37
+ spec.add_development_dependency "rspec", "~> 3.0"
38
+ end
metadata ADDED
@@ -0,0 +1,112 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: richat
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - fzdp
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-03-30 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.17'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.17'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ description: Richat is a command-line ChatGPT tool implemented in Ruby that supports
56
+ highly customizable configuration. It can save chat logs, performs fuzzy searches
57
+ on historical inputs, allows for prompt customization and switching at any time
58
+ email:
59
+ - fzdp01@gmail.com
60
+ executables:
61
+ - richat
62
+ extensions: []
63
+ extra_rdoc_files: []
64
+ files:
65
+ - ".gitignore"
66
+ - ".rspec"
67
+ - ".travis.yml"
68
+ - CODE_OF_CONDUCT.md
69
+ - Gemfile
70
+ - Gemfile.lock
71
+ - LICENSE.txt
72
+ - README.md
73
+ - Rakefile
74
+ - bin/console
75
+ - bin/setup
76
+ - exe/richat
77
+ - lib/extension/hash.rb
78
+ - lib/openai/chat.rb
79
+ - lib/richat.rb
80
+ - lib/richat/cli.rb
81
+ - lib/richat/command.rb
82
+ - lib/richat/config.rb
83
+ - lib/richat/logger.rb
84
+ - lib/richat/shell.rb
85
+ - lib/richat/version.rb
86
+ - richat.gemspec
87
+ homepage: https://github.com/fzdp/richat
88
+ licenses:
89
+ - MIT
90
+ metadata:
91
+ homepage_uri: https://github.com/fzdp/richat
92
+ source_code_uri: https://github.com/fzdp/richat
93
+ post_install_message:
94
+ rdoc_options: []
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: '0'
102
+ required_rubygems_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ requirements: []
108
+ rubygems_version: 3.0.9
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: Richat is a command-line ChatGPT tool
112
+ test_files: []