irb-ai 0.1.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: f469ef7c3508a83ad5ce0aa12007feec5a906337a5ec40fce273d989508a6dc3
4
+ data.tar.gz: 2225d8e843ec53fdbcdc44d915de4002867d7e274e4f8a8940afa2671c121c3b
5
+ SHA512:
6
+ metadata.gz: 98c81665723d05f587379071fb0151831ea1c7519f8390bf74ee049e430453c3ca78ea146e68660ae183b09fb7c1ffdeb77080b8e7ab0d7718f06be967f9e77a
7
+ data.tar.gz: 210b7b3a03131947ae1d555e31721b2911800845437bfae699e9224562c8e97b3132806470d7c7fe8ddaea9a1f960ed9be2c14ae10e0f0736c512ad95f815a02
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-05-29
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at stan.lo@shopify.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in irb-ai.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "test-unit", "~> 3.0"
11
+ gem "syntax_tree"
data/Gemfile.lock ADDED
@@ -0,0 +1,72 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ irb-ai (0.1.0)
5
+ irb (~> 1.6)
6
+ ruby-openai (~> 4.1)
7
+ tracer (~> 0.2.2)
8
+ tty-markdown (~> 0.7.2)
9
+
10
+ GEM
11
+ remote: https://rubygems.org/
12
+ specs:
13
+ faraday (2.7.5)
14
+ faraday-net_http (>= 2.0, < 3.1)
15
+ ruby2_keywords (>= 0.0.4)
16
+ faraday-multipart (1.0.4)
17
+ multipart-post (~> 2)
18
+ faraday-net_http (3.0.2)
19
+ io-console (0.6.0)
20
+ irb (1.6.4)
21
+ reline (>= 0.3.0)
22
+ kramdown (2.4.0)
23
+ rexml
24
+ multipart-post (2.3.0)
25
+ pastel (0.8.0)
26
+ tty-color (~> 0.5)
27
+ power_assert (2.0.3)
28
+ prettier_print (1.2.1)
29
+ rake (13.0.6)
30
+ reline (0.3.4)
31
+ io-console (~> 0.5)
32
+ rexml (3.2.5)
33
+ rouge (4.1.1)
34
+ ruby-openai (4.1.0)
35
+ faraday (>= 1)
36
+ faraday-multipart (>= 1)
37
+ ruby2_keywords (0.0.5)
38
+ strings (0.2.1)
39
+ strings-ansi (~> 0.2)
40
+ unicode-display_width (>= 1.5, < 3.0)
41
+ unicode_utils (~> 1.4)
42
+ strings-ansi (0.2.0)
43
+ syntax_tree (6.1.1)
44
+ prettier_print (>= 1.2.0)
45
+ test-unit (3.5.9)
46
+ power_assert
47
+ tracer (0.2.2)
48
+ tty-color (0.6.0)
49
+ tty-markdown (0.7.2)
50
+ kramdown (>= 1.16.2, < 3.0)
51
+ pastel (~> 0.8)
52
+ rouge (>= 3.14, < 5.0)
53
+ strings (~> 0.2.0)
54
+ tty-color (~> 0.5)
55
+ tty-screen (~> 0.8)
56
+ tty-screen (0.8.1)
57
+ unicode-display_width (2.4.2)
58
+ unicode_utils (1.4.0)
59
+
60
+ PLATFORMS
61
+ arm64-darwin-22
62
+ ruby
63
+ x86_64-linux
64
+
65
+ DEPENDENCIES
66
+ irb-ai!
67
+ rake (~> 13.0)
68
+ syntax_tree
69
+ test-unit (~> 3.0)
70
+
71
+ BUNDLED WITH
72
+ 2.4.10
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Stan Lo
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,112 @@
1
+ # IRB-AI
2
+
3
+ `IRB-AI` is an experimental project that explores various ways to enhance users' IRB experience through AI (currently using `ChatGPT`).
4
+
5
+ ## Installation
6
+
7
+ Add this gem to your `Gemfile`:
8
+
9
+ ```rb
10
+ gem "irb-ai", group: [:development, :test]
11
+ ```
12
+
13
+ ## Setup
14
+
15
+ Ensure you have your [OpenAI API](https://openai.com/blog/openai-api) stored in `ENV["OPENAI_API_KEY"]`.
16
+
17
+ ## Usage
18
+
19
+ At the moment, this gem only provides the `explain` command:
20
+
21
+ - `explain <expression> as <context expression>` explains the execution of `<expression>` by observing `<context expression>`
22
+ - For instance, `explain Post.find_the_closest as Post` will trace `Post`'s method calls to collect runtime information.
23
+ - `explain <expression>` is equivalent to `explain <expression> as self`
24
+
25
+ Including `<context expression>` is advised because this project relies on [`ruby/tracer`](https://github.com/ruby/tracer)'s
26
+ [`ObjectTracer`](https://github.com/ruby/tracer#objecttracer), which only collects traces around the target object.
27
+
28
+ The more detailed [`CallTracer`](https://github.com/ruby/tracer#calltracer) is not used because the current ChatGPT models
29
+ have a relatively low token limit (`gpt-3.5-turbo` allows only `4000` tokens). Thus, using it can easily exceed that limit and
30
+ result in the request being rejected.
31
+
32
+ ### Configurations
33
+
34
+ You can specify the model through `IRB::AI.model = "<my model>"`. The default is `gpt-3.5-turbo`.
35
+
36
+ ## Example
37
+
38
+ Given this script:
39
+
40
+ ```rb
41
+ require "bundler/inline"
42
+
43
+ gemfile do
44
+ gem "irb-ai"
45
+ gem "activesupport"
46
+ end
47
+
48
+ require "irb/ai"
49
+ require "active_support"
50
+ require "active_support/core_ext/object/blank"
51
+
52
+ old_secret = SecureRandom.base64(24)
53
+ old_encryptor = ActiveSupport::MessageEncryptor.new old_secret
54
+ new_secret = SecureRandom.base64(24)
55
+ new_encryptor = ActiveSupport::MessageEncryptor.new new_secret
56
+ new_encryptor.rotate old_secret
57
+
58
+ msg_from_old_encryptor = old_encryptor.encrypt_and_sign("test")
59
+ # target: new_encryptor.decrypt_and_verify(msg_from_old_encryptor)
60
+
61
+ binding.irb
62
+ ```
63
+
64
+ If you run `explain new_encryptor.decrypt_and_verify(msg_from_old_encryptor) as new_encryptor` from the breakpoint, you'll get something similar to this:
65
+
66
+ ```md
67
+ This is an analysis of the program's behaviour when running the expression `new_encryptor.decrypt_and_verify(msg_from_old_encryptor)`
68
+
69
+ ### Code Summary
70
+
71
+ From the given information, there is no program source code provided.
72
+
73
+ ### Execution Summary
74
+
75
+ The `decrypt_and_verify` method was called on an instance of `ActiveSupport::MessageEncryptor` with a message received from an old encryptor. The method returned the decrypted message "test".
76
+
77
+ ### Execution Details
78
+
79
+ 1. The `decrypt_and_verify` method was called on an instance of `ActiveSupport::MessageEncryptor` with a message received from an old encryptor.
80
+ 2. The `decrypt_and_verify` method called the `verifier` method on the same instance of `ActiveSupport::MessageEncryptor`.
81
+ 3. An `ActiveSupport::MessageVerifier::InvalidSignature` exception was raised at line 178 in `message_verifier.rb`, indicating that the message could not be authenticated with the given signature (which was generated by the old encryptor).
82
+ 4. The exception was caught by `run_rotations` in `rotator.rb`.
83
+ 5. `run_rotations` calls `decrypt_and_verify` again, this time with a different key used by the new encryptor.
84
+ 6. `decrypt_and_verify` called `verifier` again, but this time with the new key used by the new encryptor.
85
+ 7. The `verifier` method verified the signature of the message using the new key, and found it to be valid.
86
+ 8. The `decrypt_and_verify` method decrypted the message using the new key, which was used to encrypt the message before it was signed.
87
+ 9. The decrypted message "test" was returned from the `decrypt_and_verify` method.
88
+
89
+ Thus the program successfully decrypted and authenticated the message received from the old encryptor.
90
+ ```
91
+
92
+ ## Development
93
+
94
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test-unit` to run the tests.
95
+ You can also run `bin/console` for an interactive prompt that will allow you to experiment.
96
+
97
+ To install this gem onto your local machine, run `bundle exec rake install`.
98
+ To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`,
99
+ which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
100
+
101
+ ## Contributing
102
+
103
+ Bug reports and pull requests are welcome on GitHub at https://github.com/st0012/irb-ai.
104
+ This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/st0012/irb-ai/blob/main/CODE_OF_CONDUCT.md).
105
+
106
+ ## License
107
+
108
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
109
+
110
+ ## Code of Conduct
111
+
112
+ Everyone interacting in the IRB::AI project's codebases, issue trackers, chat rooms, and mailing lists is expected to follow the [code of conduct](https://github.com/st0012/irb-ai/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/*_test.rb"]
10
+ end
11
+
12
+ task default: :test
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IRB
4
+ module AI
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
data/lib/irb/ai.rb ADDED
@@ -0,0 +1,347 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ai/version"
4
+ require "tracer"
5
+ require "irb"
6
+ require "openai"
7
+ require "tty-markdown"
8
+
9
+ module IRB
10
+ module AI
11
+ NULL_VALUE = "NULL RETURN VALUE"
12
+
13
+ class << self
14
+ def debug_mode?
15
+ ENV["IRB_AI_DEBUG"] && !ENV["IRB_AI_DEBUG"].empty?
16
+ end
17
+
18
+ def ai_client
19
+ @ai_client ||= OpenAI::Client.new(access_token: ENV["OPENAI_API_KEY"])
20
+ end
21
+
22
+ def model=(model)
23
+ @model
24
+ end
25
+
26
+ def model
27
+ @model ||= "gpt-3.5-turbo"
28
+ end
29
+
30
+ def register_irb_commands
31
+ ec = IRB::ExtendCommandBundle.instance_variable_get(:@EXTEND_COMMANDS)
32
+
33
+ [
34
+ [
35
+ :explain,
36
+ :Explain,
37
+ nil,
38
+ [:explain, IRB::ExtendCommandBundle::OVERRIDE_ALL]
39
+ ]
40
+ ].each do |ecconfig|
41
+ ec.push(ecconfig)
42
+ IRB::ExtendCommandBundle.def_extend_command(*ecconfig)
43
+ end
44
+ end
45
+
46
+ def execute_expression(expression:, context_binding:, context_obj:)
47
+ output = StringIO.new
48
+ exception = nil
49
+ return_value = IRB::AI::NULL_VALUE
50
+ ObjectTracer
51
+ .new(
52
+ context_obj,
53
+ output: output,
54
+ colorize: false,
55
+ header: "object-trace"
56
+ )
57
+ .start do
58
+ ExceptionTracer
59
+ .new(output: output, colorize: false, header: "exception-trace")
60
+ .start do
61
+ begin
62
+ return_value = eval(expression, context_binding)
63
+ rescue Exception => e
64
+ exception = e
65
+ end
66
+ end
67
+ end
68
+
69
+ traces = output.string.split("\n")
70
+
71
+ [return_value, exception, traces]
72
+ end
73
+
74
+ def send_messages(
75
+ expression:,
76
+ context_binding:,
77
+ context_obj:,
78
+ traces:,
79
+ exception:,
80
+ return_value:
81
+ )
82
+ messages = [
83
+ {
84
+ role: "system",
85
+ content:
86
+ "I will help you understand your Ruby application's behaviour."
87
+ },
88
+ {
89
+ role: "user",
90
+ content:
91
+ generate_message(
92
+ expression: expression,
93
+ traces: traces,
94
+ exception: exception,
95
+ context_binding: context_binding,
96
+ context_obj: context_obj,
97
+ return_value: return_value
98
+ )
99
+ }
100
+ ]
101
+
102
+ puts "Getting response from OpenAI..."
103
+
104
+ response =
105
+ AI.ai_client.chat(parameters: { model: AI.model, messages: messages })
106
+
107
+ if AI.debug_mode?
108
+ puts "==================== Raw Response ===================="
109
+ pp response
110
+ puts "======================================================"
111
+ end
112
+
113
+ response
114
+ end
115
+
116
+ def generate_message(
117
+ expression:,
118
+ context_binding:,
119
+ context_obj:,
120
+ traces:,
121
+ exception:,
122
+ return_value:
123
+ )
124
+ information =
125
+ information_section(
126
+ expression: expression,
127
+ traces: traces,
128
+ exception: exception,
129
+ context_binding: context_binding,
130
+ context_obj: context_obj,
131
+ return_value: return_value
132
+ )
133
+
134
+ request = request_section(expression: expression, exception: exception)
135
+ msg = <<~MSG
136
+ ### Information
137
+
138
+ #{information}
139
+
140
+ ### Request
141
+
142
+ #{request}
143
+ MSG
144
+
145
+ if AI.debug_mode?
146
+ puts "==================== Message ===================="
147
+ puts msg
148
+ puts "================================================="
149
+ end
150
+
151
+ msg
152
+ end
153
+
154
+ def information_section(
155
+ expression:,
156
+ context_binding:,
157
+ context_obj:,
158
+ traces:,
159
+ exception:,
160
+ return_value:
161
+ )
162
+ msg = <<~MSG
163
+ - The expression `#{expression}` returned `#{return_value}` (ignore if its value equals to `#{IRB::AI::NULL_VALUE}`)
164
+ - Here are the runtime traces when running the expression is evaluated (ignore if blank):
165
+
166
+ #{traces.join("\n")}
167
+
168
+ - The execution happened in the context of the object #{context_obj}
169
+ - If a trace has `object-trace` header, that means the trace is about the execution of this object
170
+ - If you see no `object-trace`, that means the object is not involved in the execution. if that's the case,
171
+ you can ignore the context object and the code around the binding when generating the response
172
+ MSG
173
+
174
+ if exception
175
+ msg += <<~MSG
176
+ - The execution caused the following exception: #{exception} (ignore if blank)
177
+ - Exception backtrace is: #{exception.backtrace}
178
+ - If you see multiple `exception-trace`, that means multiple exceptions were raised during the execution
179
+ - But only the last trace is directly associated with the exception you see above
180
+ - Use other exception traces to understand the execution flow in general and don't assume they have direct link to the exception above
181
+ MSG
182
+ else
183
+ msg += <<~MSG
184
+ - The execution DID NOT cause an exception
185
+ - Please ignore all `exception-trace`
186
+ MSG
187
+ end
188
+
189
+ msg
190
+ end
191
+
192
+ def request_section(expression:, exception:)
193
+ msg = <<~MSG
194
+ Please respond in the following format, with markdown syntax, and use code highlight when appropriate:
195
+
196
+ ```
197
+ This is an analysis of the program's behaviour when running the expression `#{expression}`
198
+
199
+ ### Code Summary (skip if no program source code is given)
200
+
201
+ <summary of the program's intended behaviour from the given code (ignore the breakpoint)>
202
+
203
+ ### Execution Summary
204
+
205
+ <summary of the program's actual behaviour from the given traces>
206
+ <unless the program failed due to an exception, DO NOT assume the program failed because of the `exception-trace`s>
207
+
208
+
209
+ ### Execution Details
210
+
211
+ <detailed step-by-step explanation of the program's actual behaviour based on the source code and given trace>
212
+ <strictly follow the below format>
213
+
214
+ <example>
215
+ 1. The program started at line 1
216
+ 2. The program called method `foo` at line 2
217
+ 3. The program called method `bar` at line 3
218
+ 4. The trace shows that the program raised an exception at line 4
219
+ </example>
220
+ MSG
221
+
222
+ msg +=
223
+ if exception
224
+ <<~MSG
225
+ ### Debugging Suggestion for #{exception}
226
+
227
+ <potential causes of the error based on the program's execution details as explained in the previous section>
228
+ <if you think the information is not sufficient, please explicit mention that and explain what information is missing>
229
+ MSG
230
+ else
231
+ <<~MSG
232
+ <DO NOT assume the program failed due to an exception>
233
+ MSG
234
+ end
235
+
236
+ msg
237
+ end
238
+
239
+ def code_around_binding(b)
240
+ original_colorize = IRB.conf[:USE_COLORIZE]
241
+ IRB.conf[:USE_COLORIZE] = false
242
+ file, line = b.source_location
243
+
244
+ File.read(file).lines[(line - 20)..(line + 4)].join
245
+ ensure
246
+ IRB.conf[:USE_COLORIZE] = original_colorize
247
+ end
248
+ end
249
+ end
250
+
251
+ module ExtendCommand
252
+ class Explain < IRB::ExtendCommand::Nop
253
+ IRB_PATH = Gem.loaded_specs["irb"].full_gem_path
254
+
255
+ category "AI"
256
+ description "WIP"
257
+
258
+ def self.transform_args(args)
259
+ # Return a string literal as is for backward compatibility
260
+ if args.empty? || string_literal?(args)
261
+ args
262
+ else # Otherwise, consider the input as a String for convenience
263
+ args.strip.dump
264
+ end
265
+ end
266
+
267
+ def execute(*args)
268
+ input = args.first&.chomp
269
+
270
+ expression, context_obj_expression = input.split(/\sas\s/, 2)
271
+
272
+ unless expression
273
+ puts "Please provide the expression to explain. Usage: `explain <expression> [as <context object>]]`"
274
+ return
275
+ end
276
+
277
+ context_binding = irb_context.workspace.binding
278
+
279
+ context_obj =
280
+ if context_obj_expression
281
+ eval(context_obj_expression, context_binding)
282
+ else
283
+ irb_context.workspace.main
284
+ end
285
+
286
+ return_value, exception, traces =
287
+ IRB::AI.execute_expression(
288
+ expression: expression,
289
+ context_binding: context_binding,
290
+ context_obj: context_obj
291
+ )
292
+
293
+ response =
294
+ IRB::AI.send_messages(
295
+ expression: expression,
296
+ context_binding: context_binding,
297
+ context_obj: context_obj,
298
+ traces: traces,
299
+ exception: exception,
300
+ return_value: return_value
301
+ )
302
+
303
+ while error = response.dig("error", "message")
304
+ if error.match?(/reduce the length/)
305
+ if traces.length >= 1
306
+ puts "The generated request is too long. Trying again with reduced runtimne traces..."
307
+ traces = traces.last(traces.length / 2)
308
+ response =
309
+ IRB::AI.send_messages(
310
+ expression: expression,
311
+ context_binding: context_binding,
312
+ context_obj: context_obj,
313
+ traces: traces,
314
+ exception: exception,
315
+ return_value: return_value
316
+ )
317
+ else
318
+ puts "The generated request is too long even without runtime traces. Please try again with a shorter expression."
319
+ return
320
+ end
321
+ else
322
+ puts "OpenAI returned an error: #{error["message"]}"
323
+ return
324
+ end
325
+ end
326
+
327
+ finish_reason = response.dig("choices", 0, "finish_reason")
328
+
329
+ case finish_reason
330
+ when "stop"
331
+ when "length"
332
+ else
333
+ puts "OpenAI did not finish processing the request (reason: #{finish_reason}). Please try again."
334
+ return
335
+ end
336
+
337
+ content = response.dig("choices", 0, "message", "content")
338
+ puts content
339
+
340
+ parsed = TTY::Markdown.parse(content)
341
+ puts parsed
342
+ end
343
+ end
344
+ end
345
+ end
346
+
347
+ IRB::AI.register_irb_commands
metadata ADDED
@@ -0,0 +1,112 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: irb-ai
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Stan Lo
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-05-30 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: irb
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.6'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.6'
27
+ - !ruby/object:Gem::Dependency
28
+ name: tracer
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.2.2
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.2.2
41
+ - !ruby/object:Gem::Dependency
42
+ name: ruby-openai
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '4.1'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '4.1'
55
+ - !ruby/object:Gem::Dependency
56
+ name: tty-markdown
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 0.7.2
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 0.7.2
69
+ description: IRB-AI is an experimental project that explores various ways to enhance
70
+ users' IRB experience through AI.
71
+ email:
72
+ - stan001212@gmail.com
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - CHANGELOG.md
78
+ - CODE_OF_CONDUCT.md
79
+ - Gemfile
80
+ - Gemfile.lock
81
+ - LICENSE.txt
82
+ - README.md
83
+ - Rakefile
84
+ - lib/irb/ai.rb
85
+ - lib/irb/ai/version.rb
86
+ homepage: https://github.com/st0012/irb-ai
87
+ licenses:
88
+ - MIT
89
+ metadata:
90
+ homepage_uri: https://github.com/st0012/irb-ai
91
+ source_code_uri: https://github.com/st0012/irb-ai
92
+ changelog_uri: https://github.com/st0012/irb-ai/releases
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: 2.6.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.4.10
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: IRB commands powered by AI.
112
+ test_files: []