charai 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a2bb9857e550fece14adf8d4b0ff13d3f1bd5006be2cad4a047e03a23e6192ef
4
+ data.tar.gz: bed2120f92dc260ea88d6f38bcef45f533705f2b027239e4e21068d17ed1e59d
5
+ SHA512:
6
+ metadata.gz: 295c7c1f728df8c6daa02814c0a00a21c02c9b4182e361688a38a4e011b90368b98f78efcce5eb0baf996862ee4081c2c1a5b6d2b7359e948dad0d71ba1fadc0
7
+ data.tar.gz: 85660fa979d2f8476022a625eed86c2b870f1d6983c194a0f846bafbfa3a9c27fefd558bbde1bcf522f4bc1cf183782bd09e4ba67797198691e9cbdac4c13bea
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.2
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gemspec
6
+
7
+ gem 'allure-rspec'
8
+ gem "pry-byebug"
9
+ gem "puma"
10
+ gem "rake"
11
+ gem "rspec"
12
+ gem "rubocop"
13
+ gem "sinatra", require: false
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 YusukeIwaki
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,169 @@
1
+ # Charai
2
+
3
+ Chat + Ruby + AI = Charai
4
+
5
+ ## Setup
6
+
7
+ Add `gem 'charai'` into your project's Gemfile, and then `bundle install`
8
+
9
+ Also, this gem requires **Firefox Developer Edition** to be installed on the location below:
10
+
11
+ - /Applications/Firefox Developer Edition.app (macOS)
12
+ - /usr/bin/firefox-devedition (Linux)
13
+
14
+ ## Configuration
15
+
16
+ Configure your Capybara driver like below.
17
+
18
+ ```
19
+ Capybara.register_driver :charai do |app|
20
+ Charai::Driver.new(app, openai_configuration: config)
21
+ end
22
+
23
+ Capybara.register_driver :charai_headless do |app|
24
+ Charai::Driver.new(app, openai_configuration: config, headless: true)
25
+ end
26
+ ```
27
+
28
+ Please note that this driver required OpenAI service.
29
+
30
+ ### OpenAI
31
+
32
+ ```
33
+ config = Charai::OpenaiConfiguration.new(
34
+ model: 'gpt-4o',
35
+ api_key: 'sk-xxxxxxxxxxx'
36
+ )
37
+ ```
38
+
39
+ ### Azure OpenAI (Recommended)
40
+
41
+ ```
42
+ config = Charai::AzureOpenaiConfiguration.new(
43
+ endpoint_url: 'https://YOUR-APP.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-05-01-preview',
44
+ api_key: 'aabbcc00112233445566'
45
+ )
46
+ ```
47
+
48
+ ## Usage
49
+
50
+ Since this driver works with the OpenAI service, we can easily describe E2E test like below :)
51
+
52
+ ```ruby
53
+ before do
54
+ Capybara.current_driver = :charai
55
+ Capybara.javascript_driver = :charai
56
+
57
+ page.driver.additional_instruction = <<~MARKDOWN
58
+ * このページは、3ペイン構造です。ユーザが仕事を探すためのページです。
59
+ * 左ペインには仕事の絞り込みができるフィルター、中央ペインが仕事(求人)の一覧で、30件ずつ表示されます。
60
+ * 左ペインにマウスを置いてスクロールしても、中央ペインはスクロールされません。一覧をスクロールしたいときには、中央ペインの座標を確認し、その中央にマウスを置いてスクロールしてください。
61
+ * 右ペインは、広告エリアです。検索条件に応じた広告が表示されます。
62
+ MARKDOWN
63
+ end
64
+
65
+ it 'should work' do
66
+ page.driver << <<~MARKDOWN
67
+ * 仕事の一覧が表示されたら、左ペインでサーバーサイドエンジニアで「Ruby on Rails」の仕事に絞り込みをしてください。
68
+ * 左ペインで絞り込んだら、中央ペインにRuby on Railsに関する仕事が表示されていることを確認してください。
69
+ * Ruby on Railsに関係のない仕事が、検索結果件数の半分以上あるばあいには、このテスト「検索結果不適合」として失敗としてください。
70
+ MARKDOWN
71
+ end
72
+ ```
73
+
74
+ ### Report for long-running E2E tests
75
+
76
+ We often trigger E2E test during the night since it costs a lot of time. It is really boring to sit down in front of the PC during E2E testing.
77
+
78
+ This driver provides an extension (callback) feature for reporting.
79
+
80
+ First, let's prepare a report formatter like this.
81
+
82
+ ```ruby
83
+ class HtmlReport
84
+ def initialize
85
+ @content = []
86
+ end
87
+
88
+ def start(introduction)
89
+ @content << <<~HTML
90
+ <html>
91
+ <head><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mini.css/3.0.1/mini-default.min.css"></head>
92
+ <body>
93
+ <pre style="margin: 100px 75px; border-left: 0px;">#{introduction}</pre>
94
+ HTML
95
+ end
96
+
97
+ def add_conversation(content, answer)
98
+ if content.is_a?(Array)
99
+ text = content.find { |c| c[:type] == 'text' }[:text]
100
+
101
+ @content << <<~HTML
102
+ <div style="margin: 40px 25px" class="card fluid">
103
+ <h4 style="border-left: .25rem solid var(--pre-color);">user</h4>
104
+ <pre>#{text}</pre>
105
+ HTML
106
+
107
+ content.each do |c|
108
+ next unless c[:type] == 'image_url'
109
+
110
+ @content << <<~HTML
111
+ <img src="#{c[:image_url][:url]}" width="480" />
112
+ HTML
113
+ end
114
+
115
+ @content << <<~HTML
116
+ <h4 style="text-align: end; border-right: .25rem solid var(--pre-color);">assistant</h4>
117
+ <pre style="border-left: 0px; border-right: .25rem solid var(--pre-color);">#{answer}</pre>
118
+ </div>
119
+ HTML
120
+ else
121
+ @content << <<~HTML
122
+ <div style="margin: 40px 25px" class="card fluid">
123
+ <h4 style="border-left: .25rem solid var(--pre-color);">user</h4>
124
+ <pre>#{content}</pre>
125
+
126
+ <h4 style="text-align: end; border-right: .25rem solid var(--pre-color);">assistant</h4>
127
+ <pre style="border-left: 0px; border-right: .25rem solid var(--pre-color);">#{answer}</pre>
128
+ </div>
129
+ HTML
130
+ end
131
+ end
132
+
133
+ def to_html
134
+ @content << "</body></html>"
135
+ @content.join("\n")
136
+ end
137
+ end
138
+ ```
139
+
140
+ and then configure a callback for recording test-results into the report. It would be a good choice to use Allure reports's attachment feature for this.
141
+
142
+ ```ruby
143
+ config.around(:each, type: :feature) do |example|
144
+ report = HtmlReport.new
145
+ Capybara.current_session.driver.callback = {
146
+ on_chat_start: -> (introduction) {
147
+ report.start(introduction)
148
+ },
149
+ on_chat_conversation: ->(content_hash, answer) {
150
+ puts answer
151
+ report.add_conversation(content_hash, answer)
152
+ },
153
+ }
154
+
155
+ example.run
156
+
157
+ Allure.add_attachment(
158
+ name: "Chat Report",
159
+ source: report.to_html,
160
+ type: 'text/html',
161
+ )
162
+ end
163
+ ```
164
+
165
+ With this report, we can check evidences for each test and investigate failed tests (postmotem).
166
+
167
+ ## License
168
+
169
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
data/bin/console ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "charai"
6
+
7
+ require "pry"
8
+ Pry.start
data/charai.gemspec ADDED
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/charai/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "charai"
7
+ spec.version = Charai::VERSION
8
+ spec.authors = ["YusukeIwaki"]
9
+ spec.email = ["q7w8e9w8q7w8e9@yahoo.co.jp"]
10
+
11
+ spec.summary = "charai(Chat + Ruby + AI) Capybara driver"
12
+ spec.description = "Prototype impl for Kaigi on Rails 2024 presentation."
13
+ spec.homepage = "https://github.com/YusukeIwaki/charai"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.2.0"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(__dir__) do
22
+ `git ls-files -z`.split("\x0").reject do |f|
23
+ f.match(%r{^(test|spec|features)/}) || f.include?(".git")
24
+ end
25
+ end
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_dependency 'capybara'
31
+ spec.add_dependency "concurrent-ruby", ">= 1.1.6"
32
+ spec.add_dependency "websocket-driver", ">= 0.6.1"
33
+ end
@@ -0,0 +1,41 @@
1
+ module Charai
2
+ class ActionQueue
3
+ def initialize
4
+ @actions = []
5
+ end
6
+
7
+ def to_a
8
+ @actions
9
+ end
10
+
11
+ def pause(duration:)
12
+ @actions << { type: 'pause', duration: duration }
13
+ end
14
+
15
+ def key_down(value:)
16
+ @actions << { type: 'keyDown', value: value }
17
+ end
18
+
19
+ def key_up(value:)
20
+ @actions << { type: 'keyUp', value: value }
21
+ end
22
+
23
+ # button: 0 for left, 1 for middle, 2 for right
24
+ def pointer_down(button:)
25
+ @actions << { type: 'pointerDown', button: button }
26
+ end
27
+
28
+ def pointer_move(x:, y:, duration: nil)
29
+ @actions << { type: 'pointerMove', x: x, y: y, duration: duration }.compact
30
+ end
31
+
32
+ # button: 0 for left, 1 for middle, 2 for right
33
+ def pointer_up(button:)
34
+ @actions << { type: 'pointerUp', button: button }
35
+ end
36
+
37
+ def scroll(x:, y:, delta_x: 0, delta_y: 0, duration: nil)
38
+ @actions << { type: 'scroll', x: x, y: y, deltaX: delta_x, deltaY: delta_y, duration: duration }.compact
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,97 @@
1
+ module Charai
2
+ class Agent
3
+ class Message < Data.define(:text, :images)
4
+ def initialize(text:, images: [])
5
+ super(text: text, images: images)
6
+ end
7
+ end
8
+
9
+
10
+ def initialize(input_tool:, openai_chat:)
11
+ input_tool.on_send_message do |message|
12
+ send_message_to_openai_chat(message)
13
+ end
14
+ @sandbox = Sandbox.new(input_tool)
15
+ @openai_chat = openai_chat
16
+ end
17
+
18
+ def <<(text)
19
+ message = Message.new(text: text)
20
+ send_message_to_openai_chat(message)
21
+ end
22
+
23
+ attr_reader :last_message
24
+
25
+ private
26
+
27
+ def send_message_to_openai_chat(message)
28
+ if @should_use_message_queue
29
+ @message_queue << message
30
+ else
31
+ answer = @openai_chat.push(message.text, images: message.images)
32
+ @last_message = answer
33
+ handle_message_from_openai_chat(answer)
34
+ end
35
+ end
36
+
37
+ def with_aggregating_failures(&block)
38
+ if defined?(RSpec::Expectations)
39
+ label = nil
40
+ metadata = {}
41
+ RSpec::Expectations::FailureAggregator.new(label, metadata).aggregate(&block)
42
+ else
43
+ block.call
44
+ end
45
+ end
46
+
47
+ def with_message_queuing(&block)
48
+ @should_use_message_queue = true
49
+ @message_queue = []
50
+
51
+ begin
52
+ block.call
53
+ ensure
54
+ @should_use_message_queue = false
55
+ # Handle only the last message
56
+ if (message = @message_queue.last)
57
+ send_message_to_openai_chat(message)
58
+ end
59
+ end
60
+ end
61
+
62
+ class HandleMessageError < StandardError ; end
63
+
64
+ def handle_message_from_openai_chat(answer)
65
+ with_message_queuing do
66
+ with_aggregating_failures do
67
+ begin
68
+ answer.scan(/```[a-zA-Z]*\n(.*?)\n```/m).map(&:first).each do |code|
69
+ if code.include?('`') # Avoid OS shell execution.
70
+ raise HandleMessageError, "It is not allowed to use backquote"
71
+ end
72
+ @sandbox.instance_eval(code)
73
+ end
74
+ rescue HandleMessageError => e
75
+ send_message_to_openai_chat(Message.new(text: e.message))
76
+ rescue Browser::Error => e
77
+ send_message_to_openai_chat(Message.new(text: "Error: #{e.message}"))
78
+ rescue => e
79
+ send_message_to_openai_chat(Message.new(text: "ERROR: #{e.message}"))
80
+ end
81
+ end
82
+ end
83
+ end
84
+
85
+ class Sandbox
86
+ def initialize(input_tool)
87
+ @input_tool = input_tool
88
+ end
89
+
90
+ private
91
+
92
+ def driver
93
+ @input_tool
94
+ end
95
+ end
96
+ end
97
+ end
@@ -0,0 +1,142 @@
1
+ module Charai
2
+ class Browser
3
+ def self.launch(...)
4
+ BrowserLauncher.new.launch(...)
5
+ end
6
+
7
+ def initialize(web_socket, debug_protocol: false)
8
+ @web_socket = web_socket
9
+ @debug_protocol = debug_protocol
10
+ @browsing_contexts = {}
11
+
12
+ web_socket.on_message do |message|
13
+ handle_received_message_from_websocket(JSON.parse(message))
14
+ end
15
+
16
+ bidi_call_async('session.new', {
17
+ capabilities: {
18
+ alwaysMatch: {
19
+ acceptInsecureCerts: false,
20
+ webSocketUrl: true,
21
+ },
22
+ },
23
+ }).value!
24
+ sync_browsing_contexts
25
+ bidi_call_async('session.subscribe', {
26
+ events: %w[browsingContext],
27
+ }) # do no await
28
+ end
29
+
30
+ def create_browsing_context
31
+ result = bidi_call_async('browsingContext.create', { type: :tab, userContext: :default }).value!
32
+ browsing_context_id = result['context']
33
+ @browsing_contexts[browsing_context_id] ||= BrowsingContext.new(self, browsing_context_id)
34
+ end
35
+
36
+ def close
37
+ bidi_call_async('browser.close').value!
38
+ @web_socket.close
39
+ end
40
+
41
+ def bidi_call_async(method_, params = {})
42
+ with_message_id do |message_id|
43
+ @message_results[message_id] = Concurrent::Promises.resolvable_future
44
+
45
+ send_message_to_websocket({
46
+ id: message_id,
47
+ method: method_,
48
+ params: params,
49
+ })
50
+
51
+ @message_results[message_id]
52
+ end
53
+ end
54
+
55
+ private
56
+
57
+ def with_message_id(&block)
58
+ unless @message_id
59
+ @message_id = 1
60
+ @message_results = {}
61
+ end
62
+
63
+ message_id = @message_id
64
+ @message_id += 1
65
+ block.call(message_id)
66
+ end
67
+
68
+ def send_message_to_websocket(payload)
69
+ debug_print_send(payload)
70
+ message = JSON.generate(payload)
71
+ @web_socket.send_text(message)
72
+ end
73
+
74
+ def handle_received_message_from_websocket(payload)
75
+ debug_print_recv(payload)
76
+
77
+ if payload['id']
78
+ if promise = @message_results.delete(payload['id'])
79
+ case payload['type']
80
+ when 'success'
81
+ promise.fulfill(payload['result'])
82
+ when 'error'
83
+ promise.reject(Error.new("#{payload['error']}: #{payload['message']}\n#{payload['stacktrace']}"))
84
+ end
85
+ end
86
+ elsif payload['type'] == 'event'
87
+ handle_received_event(payload['method'], payload['params'])
88
+ end
89
+ end
90
+
91
+ class Error < StandardError ; end
92
+
93
+ def handle_received_event(method_, params)
94
+ case method_
95
+ when 'browsingContext.contextCreated'
96
+ browsing_context_id = params['context']
97
+ return unless browsing_context_id
98
+ return unless browsing_context_id.split("-").count == 5
99
+ @browsing_contexts[browsing_context_id] ||= BrowsingContext.new(self, browsing_context_id)
100
+ if params['url']
101
+ @browsing_contexts[browsing_context_id]._update_url(params['url'])
102
+ end
103
+ when 'browsingContext.contextDestroyed'
104
+ browsing_context_id = params['context']
105
+ @browsing_contexts.delete(browsing_context_id)
106
+ when 'browsingContext.domContentLoaded'
107
+ browsing_context_id = params['context']
108
+ if params['url']
109
+ @browsing_contexts[browsing_context_id]&._update_url(params['url'])
110
+ end
111
+ end
112
+ end
113
+
114
+ def sync_browsing_contexts
115
+ result = bidi_call_async('browsingContext.getTree').value!
116
+ browsing_contexts = result['contexts']
117
+
118
+ extra_context_ids = @browsing_contexts.keys - browsing_contexts.map { |context| context['context'] }
119
+ extra_context_ids.each do |context_id|
120
+ @browsing_contexts.delete(context_id)
121
+ end
122
+ result['contexts'].each do |context|
123
+ @browsing_contexts[context['context']] ||= BrowsingContext.new(self, context)
124
+ if context['url']
125
+ @browsing_contexts[context['context']]._update_url(context['url'])
126
+ end
127
+ end
128
+ end
129
+
130
+ def debug_print_send(hash)
131
+ return unless @debug_protocol
132
+
133
+ puts "SEND > #{hash}"
134
+ end
135
+
136
+ def debug_print_recv(hash)
137
+ return unless @debug_protocol
138
+
139
+ puts "RECV < #{hash}"
140
+ end
141
+ end
142
+ end