active_genie 0.0.2
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/LICENSE +201 -0
- data/README.md +136 -0
- data/VERSION +1 -0
- data/lib/active_genie/configuration.rb +32 -0
- data/lib/active_genie.rb +22 -0
- data/lib/data_extractor/README.md +103 -0
- data/lib/data_extractor/data_extractor.rb +88 -0
- data/lib/requester/openai.rb +60 -0
- data/lib/requester/requester.rb +41 -0
- data/lib/tasks/install.rake +12 -0
- data/lib/tasks/templates/active_ai.yml +7 -0
- metadata +67 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: '078409a35816dfb0870469dcf511a7b57bf216cd4665f0c50ef187e7be0c7707'
|
4
|
+
data.tar.gz: 108d56de78b375e23dfb0acc48db70175c6af0d457933cece70ff67f505c1203
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: c5e7af633c6add150d098ebcd6589c564e570d1cad73a6937a0388b36ab418b4cf17ddda0dbed61d13ff6882c4a064e376caf3015d210ec70e884cba5951d71c
|
7
|
+
data.tar.gz: decbe01929b3412127fccbf5e0c08c8f96181348c35f2c8f13117385df7dbd42298783c69a11a1d990b320f8b01eb96d962a4a9546ee6df1d073cb42a13e1f84
|
data/LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
data/README.md
ADDED
@@ -0,0 +1,136 @@
|
|
1
|
+
# ActiveGenie
|
2
|
+
Ruby gem for out of the box AI features. LLMs are just a raw tools that need to be polished and refined to be useful. This gem is a collection of tools that can be used to make LLMs more useful and easier to use.
|
3
|
+
Think this gem is like ActiveStorage but for LLMs.
|
4
|
+
|
5
|
+
[](https://badge.fury.io/rb/active_genie)
|
6
|
+
|
7
|
+
## Installation
|
8
|
+
Add this line to your application's Gemfile:
|
9
|
+
|
10
|
+
1. Add the gem to your Gemfile
|
11
|
+
```ruby
|
12
|
+
gem 'active_genie'
|
13
|
+
```
|
14
|
+
2. install the gem
|
15
|
+
```shell
|
16
|
+
bundle install
|
17
|
+
```
|
18
|
+
3. call the initializer to create default configurations
|
19
|
+
```shell
|
20
|
+
rails g active_genie:install
|
21
|
+
```
|
22
|
+
4. Add the right credentials to the `config/active_genie.yml` file
|
23
|
+
```yaml
|
24
|
+
GPT-4o-mini:
|
25
|
+
api_key: <%= ENV['OPENAI_API_KEY'] %>
|
26
|
+
provider: "openai"
|
27
|
+
```
|
28
|
+
|
29
|
+
## Quick Example
|
30
|
+
```ruby
|
31
|
+
require 'active_genie'
|
32
|
+
|
33
|
+
puts ActiveGenie::DataExtractor.call(
|
34
|
+
"Hello, my name is Radamés Roriz",
|
35
|
+
{ full_name: { type: 'string' } },
|
36
|
+
options: { model: 'gpt-4o-mini', api_key: 'your-api-key', provider: 'openai' } # Optional if has config/active_genie.yml
|
37
|
+
) # => { full_name: "Radamés Roriz" }
|
38
|
+
```
|
39
|
+
|
40
|
+
### Data Extractor
|
41
|
+
Extract structured data from text using LLM-powered analysis, handling informal language and complex expressions.
|
42
|
+
|
43
|
+
```ruby
|
44
|
+
require 'active_genie'
|
45
|
+
|
46
|
+
text = "iPhone 14 Pro Max"
|
47
|
+
schema = {
|
48
|
+
brand: { type: 'string' },
|
49
|
+
model: { type: 'string' }
|
50
|
+
}
|
51
|
+
result = ActiveGenie::DataExtractor.call(
|
52
|
+
text,
|
53
|
+
schema,
|
54
|
+
options: { model: 'GPT-4o-mini', api_key: 'your-api-key', provider: 'openai' } # Optional if
|
55
|
+
)
|
56
|
+
# => { brand: "iPhone", model: "14 Pro Max" }
|
57
|
+
```
|
58
|
+
|
59
|
+
- More examples in the [Data Extractor README](lib/data_extractor/README.md)
|
60
|
+
- Extract from ambiguous [from_informal](lib/data_extractor/README.md#extract-from-informal-text)
|
61
|
+
- Interface details in the [Interface](lib/data_extractor/README.md#interface)
|
62
|
+
|
63
|
+
### Summarizer (WIP)
|
64
|
+
The summarizer is a tool that can be used to summarize a given text. It uses a set of rules to summarize the text out of the box. Uses the best practices of prompt engineering and engineering to make the summarization as accurate as possible.
|
65
|
+
|
66
|
+
```ruby
|
67
|
+
require 'active_genie'
|
68
|
+
|
69
|
+
text = "Example text to be summarized. The fox jumps over the dog"
|
70
|
+
summarized_text = ActiveGenie::Summarizer.call(text)
|
71
|
+
puts summarized_text # => "The fox jumps over the dog"
|
72
|
+
```
|
73
|
+
|
74
|
+
### Scorer (WIP)
|
75
|
+
The scorer is a tool that can be used to score a given text. It uses a set of rules to score the text out of the box. Uses the best practices of prompt engineering and engineering to make the scoring as accurate as possible.
|
76
|
+
|
77
|
+
```ruby
|
78
|
+
require 'active_genie'
|
79
|
+
|
80
|
+
text = "Example text to be scored. The fox jumps over the dog"
|
81
|
+
criterias = 'Grammar, Relevance'
|
82
|
+
score = ActiveGenie::Scorer.call(text, criterias)
|
83
|
+
puts score # => { 'Grammar' => 0.8, 'Relevance' => 1.0, total: 0.9 }
|
84
|
+
```
|
85
|
+
|
86
|
+
### Language detector (WIP)
|
87
|
+
The language detector is a tool that can be used to detect the language of a given text. It uses a set of rules to detect the language of the text out of the box. Uses the best practices of prompt engineering and engineering to make the language detection as accurate as possible.
|
88
|
+
|
89
|
+
```ruby
|
90
|
+
require 'active_genie'
|
91
|
+
|
92
|
+
text = "Example text to be detected"
|
93
|
+
language = ActiveGenie::LanguageDetector.call(text)
|
94
|
+
puts language # => "en"
|
95
|
+
```
|
96
|
+
|
97
|
+
### Translator (WIP)
|
98
|
+
The translator is a tool that can be used to translate a given text. It uses a set of rules to translate the text out of the box. Uses the best practices of prompt engineering and engineering to make the translation as accurate as possible.
|
99
|
+
|
100
|
+
```ruby
|
101
|
+
require 'active_genie'
|
102
|
+
|
103
|
+
text = "Example text to be translated"
|
104
|
+
translated_text = ActiveGenie::Translator.call(text, from: 'en', to: 'pt')
|
105
|
+
puts translated_text # => "Exemplo de texto a ser traduzido"
|
106
|
+
```
|
107
|
+
|
108
|
+
### Sentiment analyzer (WIP)
|
109
|
+
The sentiment analyzer is a tool that can be used to analyze the sentiment of a given text. It uses a set of rules to analyze the sentiment of the text out of the box. Uses the best practices of prompt engineering and engineering to make the sentiment analysis as accurate as possible.
|
110
|
+
|
111
|
+
```ruby
|
112
|
+
require 'active_genie'
|
113
|
+
|
114
|
+
text = "Example text to be analyzed"
|
115
|
+
sentiment = ActiveGenie::SentimentAnalyzer.call(text)
|
116
|
+
puts sentiment # => "positive"
|
117
|
+
```
|
118
|
+
|
119
|
+
### Elo ranking (WIP)
|
120
|
+
The Elo ranking is a tool that can be used to rank a set of items. It uses a set of rules to rank the items out of the box. Uses the best practices of prompt engineering and engineering to make the ranking as accurate as possible.
|
121
|
+
|
122
|
+
```ruby
|
123
|
+
require 'active_genie'
|
124
|
+
|
125
|
+
items = ['Square', 'Circle', 'Triangle']
|
126
|
+
criterias = 'items that look rounded'
|
127
|
+
ranked_items = ActiveGenie::EloRanking.call(items, criterias, rounds: 10)
|
128
|
+
puts ranked_items # => [{ name: "Circle", score: 1500 }, { name: "Square", score: 800 }, { name: "Triangle", score: 800 }]
|
129
|
+
```
|
130
|
+
|
131
|
+
## Good practices
|
132
|
+
- LLMs can take a long time to respond, so avoid putting them in the main thread
|
133
|
+
- Do not use the LLMs to extract sensitive or personal data
|
134
|
+
|
135
|
+
## License
|
136
|
+
See the [LICENSE](LICENSE)
|
data/VERSION
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
0.0.2
|
@@ -0,0 +1,32 @@
|
|
1
|
+
require 'yaml'
|
2
|
+
|
3
|
+
module ActiveGenie
|
4
|
+
class Configuration
|
5
|
+
attr_accessor :path_to_config
|
6
|
+
|
7
|
+
def initialize
|
8
|
+
@path_to_config = File.join(__dir__, 'config', 'gen_ai.yml')
|
9
|
+
end
|
10
|
+
|
11
|
+
def values
|
12
|
+
return @values if @values
|
13
|
+
|
14
|
+
@values = load_values.transform_keys(&:to_sym)
|
15
|
+
@values.each do |key, _value|
|
16
|
+
@values[key][:model] = key
|
17
|
+
@values[key] = @values[key].transform_keys(&:to_sym)
|
18
|
+
end
|
19
|
+
end
|
20
|
+
|
21
|
+
private
|
22
|
+
|
23
|
+
def load_values
|
24
|
+
return {} unless File.exist?(@path_to_config)
|
25
|
+
|
26
|
+
YAML.load_file(@path_to_config) || {}
|
27
|
+
rescue Psych::SyntaxError => e
|
28
|
+
warn "ActiveGenie.warning: Config file '#{@path_to_config}' is not a valid YAML file (#{e.message}), using default configuration"
|
29
|
+
{}
|
30
|
+
end
|
31
|
+
end
|
32
|
+
end
|
data/lib/active_genie.rb
ADDED
@@ -0,0 +1,22 @@
|
|
1
|
+
module ActiveGenie
|
2
|
+
autoload :DataExtractor, File.join(__dir__, 'data_extractor/data_extractor')
|
3
|
+
autoload :Configuration, File.join(__dir__, 'active_genie/configuration')
|
4
|
+
|
5
|
+
class << self
|
6
|
+
def config
|
7
|
+
@config ||= Configuration.new
|
8
|
+
end
|
9
|
+
|
10
|
+
def configure
|
11
|
+
yield(config) if block_given?
|
12
|
+
end
|
13
|
+
|
14
|
+
def [](key)
|
15
|
+
config.values[key.to_s]
|
16
|
+
end
|
17
|
+
|
18
|
+
def config_by_model(model)
|
19
|
+
config.values[model&.to_s] || config.values.values.first || {}
|
20
|
+
end
|
21
|
+
end
|
22
|
+
end
|
@@ -0,0 +1,103 @@
|
|
1
|
+
# Data Extractor
|
2
|
+
Extract structured data from text using LLM-powered analysis, handling informal language and complex expressions.
|
3
|
+
|
4
|
+
## ✨ Features
|
5
|
+
- Simple extraction - Extract structured data from unstructured text
|
6
|
+
- Informal extraction - Identifies and handles informal language patterns
|
7
|
+
|
8
|
+
## Basic Usage
|
9
|
+
|
10
|
+
Extract structured data from text using predefined schemas:
|
11
|
+
|
12
|
+
```ruby
|
13
|
+
text = "iPhone 14 Pro Max"
|
14
|
+
schema = {
|
15
|
+
brand: { type: 'string' },
|
16
|
+
model: { type: 'string' }
|
17
|
+
}
|
18
|
+
result = ActiveGenie::DataExtractor.call(text, schema)
|
19
|
+
# => { brand: "iPhone", model: "14 Pro Max" }
|
20
|
+
|
21
|
+
product = "Nike Air Max 90 - Size 42 - $199.99"
|
22
|
+
schema = {
|
23
|
+
brand: {
|
24
|
+
type: 'string',
|
25
|
+
enum: ["Nike", "Adidas", "Puma"]
|
26
|
+
},
|
27
|
+
price: {
|
28
|
+
type: 'number',
|
29
|
+
minimum: 0
|
30
|
+
},
|
31
|
+
currency: {
|
32
|
+
type: 'string',
|
33
|
+
enum: ["USD", "EUR"]
|
34
|
+
},
|
35
|
+
size: {
|
36
|
+
type: 'integer',
|
37
|
+
minimum: 35,
|
38
|
+
maximum: 46
|
39
|
+
}
|
40
|
+
}
|
41
|
+
|
42
|
+
result = ActiveGenie::DataExtractor.call(product, schema)
|
43
|
+
# => { brand: "Nike", price: 199.99, size: 42, currency: "USD" }
|
44
|
+
```
|
45
|
+
|
46
|
+
## Informal Text Processing
|
47
|
+
|
48
|
+
The `from_informal` method helps extract structured data from casual, conversational text by interpreting common informal expressions and linguistic patterns like:
|
49
|
+
|
50
|
+
- Affirmative expressions ("sure", "no problem", "you bet")
|
51
|
+
- Negative expressions ("nah", "not really", "pass")
|
52
|
+
- Hedging ("maybe", "I guess", "probably")
|
53
|
+
- Litotes ("not bad", "not the worst")
|
54
|
+
|
55
|
+
### Example
|
56
|
+
|
57
|
+
```ruby
|
58
|
+
text = <<~TEXT
|
59
|
+
system: Would you like to proceed with the installation?
|
60
|
+
user: not bad
|
61
|
+
TEXT
|
62
|
+
|
63
|
+
data_to_extract = {
|
64
|
+
user_consent: { type: 'boolean' }
|
65
|
+
}
|
66
|
+
|
67
|
+
result = ActiveGenie::DataExtractor.from_informal(text, data_to_extract)
|
68
|
+
puts result # => { user_consent: true }
|
69
|
+
```
|
70
|
+
|
71
|
+
### Usage Notes
|
72
|
+
- Best suited for processing conversational user inputs
|
73
|
+
- Handles ambiguous or indirect responses
|
74
|
+
- Useful for chatbots and conversational interfaces
|
75
|
+
- May require more processing time and tokens
|
76
|
+
- Accuracy depends on context clarity
|
77
|
+
|
78
|
+
⚠️ Performance Impact: This method uses additional language processing, which can increase token usage and processing time.
|
79
|
+
|
80
|
+
## Interface
|
81
|
+
`.call(text, data_to_extract, options = {})`
|
82
|
+
Extracts structured data from text based on a schema.
|
83
|
+
|
84
|
+
### Parameters
|
85
|
+
| Name | Type | Description | Required | Example | Default |
|
86
|
+
| --- | --- | --- | --- | --- | --- |
|
87
|
+
| `text` | `String` | The text to extract data from. Max 1000 chars. | Yes | "These Nike shoes are red" | - |
|
88
|
+
| `data_to_extract` | `Hash` | [JSON Schema object](https://json-schema.org/understanding-json-schema/reference/object) defining data structure | Yes | `{ category: { type: 'string', enum: ["shoes"] } }` | - |
|
89
|
+
| `options` | `Hash` | Additional provider configuration options | No | `{ model: "gpt-4" }` | `{}` |
|
90
|
+
|
91
|
+
### Returns
|
92
|
+
`Hash` - Dynamic hash based on the `data_to_extract` schema.
|
93
|
+
|
94
|
+
### Options
|
95
|
+
| Name | Type | Description | Default |
|
96
|
+
| --- | --- | --- | --- |
|
97
|
+
| `model` | `String` | The model name | `YAML.load_file(config_file).first.model` |
|
98
|
+
| `api_key` | `String` | The API key to use or api_key from model on config.yml | `YAML.load_file(config_file).first.api_key` |
|
99
|
+
|
100
|
+
⚠️ Performance Considerations
|
101
|
+
- Processes may require multiple LLM calls
|
102
|
+
- Expect ~100 tokens per request + the text from input
|
103
|
+
- Consider background processing for production use
|
@@ -0,0 +1,88 @@
|
|
1
|
+
require_relative '../requester/requester.rb'
|
2
|
+
|
3
|
+
module ActiveGenie
|
4
|
+
class DataExtractor
|
5
|
+
class << self
|
6
|
+
# Extracts data from user_texts based on the schema defined in data_to_extract.
|
7
|
+
# @param text [String] The text to extract data from.
|
8
|
+
# @param data_to_extract [Hash] The schema to extract data from the text.
|
9
|
+
# @param options [Hash] The options to pass to the function.
|
10
|
+
# @return [Hash] The extracted data.
|
11
|
+
def call(text, data_to_extract, options: {})
|
12
|
+
messages = [
|
13
|
+
{ role: 'system', content: PROMPT },
|
14
|
+
{ role: 'user', content: text[0..1000] }
|
15
|
+
]
|
16
|
+
function = {
|
17
|
+
name: 'data_extractor',
|
18
|
+
description: 'Extract structured and typed data from user messages.',
|
19
|
+
schema: {
|
20
|
+
type: "object",
|
21
|
+
properties: data_to_extract_with_explaination(data_to_extract)
|
22
|
+
}
|
23
|
+
}
|
24
|
+
|
25
|
+
::ActiveGenie::Requester.function_calling(messages, function, options)
|
26
|
+
end
|
27
|
+
|
28
|
+
def from_informal(text, data_to_extract, options = {})
|
29
|
+
messages = [
|
30
|
+
{ role: 'system', content: PROMPT },
|
31
|
+
{ role: 'user', content: text }
|
32
|
+
]
|
33
|
+
properties = data_to_extract_with_explaination(data_to_extract)
|
34
|
+
properties[:message_litote] = {
|
35
|
+
type: 'boolean',
|
36
|
+
description: 'Return true if the message is a litote. A litote is a figure of speech that uses understatement to emphasize a point by stating a negative to further affirm a positive, often incorporating double negatives for effect.'
|
37
|
+
}
|
38
|
+
properties[:litote_rephrased] = {
|
39
|
+
type: 'string',
|
40
|
+
description: 'The true meaning of the litote. Rephrase the message to a positive statement.'
|
41
|
+
}
|
42
|
+
|
43
|
+
function = {
|
44
|
+
name: 'data_extractor',
|
45
|
+
description: 'Extract structured and typed data from user messages.',
|
46
|
+
schema: { type: "object", properties: }
|
47
|
+
}
|
48
|
+
|
49
|
+
::ActiveGenie::Requester.function_calling(messages, function, options)
|
50
|
+
end
|
51
|
+
|
52
|
+
private
|
53
|
+
|
54
|
+
PROMPT = <<~PROMPT
|
55
|
+
Extract structured and typed data from user messages.
|
56
|
+
Identify relevant information within user messages and categorize it into predefined data fields with specific data types.
|
57
|
+
|
58
|
+
# Steps
|
59
|
+
1. **Identify Data Types**: Determine the types of data to collect, such as names, dates, email addresses, phone numbers, etc.
|
60
|
+
2. **Extract Information**: Use pattern recognition and language understanding to identify and extract the relevant pieces of data from the user message.
|
61
|
+
3. **Categorize Data**: Assign the extracted data to the appropriate predefined fields.
|
62
|
+
4. **Structure Data**: Format the extracted and categorized data in a structured format, such as JSON.
|
63
|
+
|
64
|
+
# Output Format
|
65
|
+
The output should be a JSON object containing fields with their corresponding extracted values. If a value is not found, the field should still be included with a null value.
|
66
|
+
|
67
|
+
# Notes
|
68
|
+
- Handle missing or partial information gracefully.
|
69
|
+
- Manage multiple occurrences of similar data points by prioritizing the first one unless specified otherwise.
|
70
|
+
- Be flexible to handle variations in data format and language clues.
|
71
|
+
PROMPT
|
72
|
+
|
73
|
+
def data_to_extract_with_explaination(data_to_extract)
|
74
|
+
with_explaination = {}
|
75
|
+
|
76
|
+
data_to_extract.each do |key, value|
|
77
|
+
with_explaination[key] = value
|
78
|
+
with_explaination["#{key}_explanation"] = {
|
79
|
+
type: 'string',
|
80
|
+
description: "The chain of thought that led to the conclusion about: #{key}. Can be blank if the user didn't provide any context",
|
81
|
+
}
|
82
|
+
end
|
83
|
+
|
84
|
+
with_explaination
|
85
|
+
end
|
86
|
+
end
|
87
|
+
end
|
88
|
+
end
|
@@ -0,0 +1,60 @@
|
|
1
|
+
require 'json'
|
2
|
+
require 'net/http'
|
3
|
+
|
4
|
+
module ActiveGenie
|
5
|
+
class Openai
|
6
|
+
class << self
|
7
|
+
def function_calling(messages, function, options)
|
8
|
+
app_config = ActiveGenie.config_by_model(options[:model])
|
9
|
+
|
10
|
+
model = options[:model] || app_config[:model]
|
11
|
+
|
12
|
+
raise "Model can't be blank" if model.nil?
|
13
|
+
|
14
|
+
payload = {
|
15
|
+
messages:,
|
16
|
+
response_format: {
|
17
|
+
type: 'json_schema',
|
18
|
+
json_schema: function
|
19
|
+
},
|
20
|
+
model:,
|
21
|
+
}
|
22
|
+
|
23
|
+
api_key = options[:api_key] || app_config[:api_key]
|
24
|
+
|
25
|
+
headers = DEFAULT_HEADERS.merge(
|
26
|
+
'Authorization': "Bearer #{api_key}"
|
27
|
+
).compact
|
28
|
+
|
29
|
+
response = request(payload, headers)
|
30
|
+
|
31
|
+
JSON.parse(response.dig('choices', 0, 'message', 'content'))
|
32
|
+
rescue JSON::ParserError
|
33
|
+
nil
|
34
|
+
end
|
35
|
+
|
36
|
+
def request(payload, headers)
|
37
|
+
response = Net::HTTP.post(
|
38
|
+
URI(API_URL),
|
39
|
+
payload.to_json,
|
40
|
+
headers
|
41
|
+
)
|
42
|
+
|
43
|
+
raise OpenaiError, response.body unless response.is_a?(Net::HTTPSuccess)
|
44
|
+
return nil if response.body.empty?
|
45
|
+
|
46
|
+
JSON.parse(response.body)
|
47
|
+
end
|
48
|
+
|
49
|
+
end
|
50
|
+
|
51
|
+
|
52
|
+
API_URL = 'https://api.openai.com/v1/chat/completions'.freeze
|
53
|
+
DEFAULT_HEADERS = {
|
54
|
+
'Content-Type': 'application/json',
|
55
|
+
}
|
56
|
+
|
57
|
+
# TODO: add some more rich error handling
|
58
|
+
class OpenaiError < StandardError; end
|
59
|
+
end
|
60
|
+
end
|
@@ -0,0 +1,41 @@
|
|
1
|
+
require_relative './openai'
|
2
|
+
|
3
|
+
module ActiveGenie
|
4
|
+
class Requester
|
5
|
+
class << self
|
6
|
+
def function_calling(messages, function, options = {})
|
7
|
+
app_config = ActiveGenie.config_by_model(options[:model])
|
8
|
+
|
9
|
+
provider = options[:provider] || app_config[:provider]
|
10
|
+
provider_sdk = PROVIDER_TO_SDK[provider&.to_sym&.downcase]
|
11
|
+
raise "Provider #{provider} not supported" unless provider_sdk
|
12
|
+
|
13
|
+
response = provider_sdk.function_calling(messages, function, options)
|
14
|
+
|
15
|
+
clear_invalid_values(response)
|
16
|
+
end
|
17
|
+
|
18
|
+
private
|
19
|
+
|
20
|
+
PROVIDER_TO_SDK = {
|
21
|
+
openai: Openai,
|
22
|
+
}
|
23
|
+
|
24
|
+
INVALID_VALUES = [
|
25
|
+
'not sure',
|
26
|
+
'not clear',
|
27
|
+
'not specified',
|
28
|
+
'none',
|
29
|
+
'null',
|
30
|
+
'undefined',
|
31
|
+
].freeze
|
32
|
+
|
33
|
+
def clear_invalid_values(data)
|
34
|
+
data.reduce({}) do |acc, (field, value)|
|
35
|
+
acc[field] = value unless INVALID_VALUES.include?(value)
|
36
|
+
acc
|
37
|
+
end
|
38
|
+
end
|
39
|
+
end
|
40
|
+
end
|
41
|
+
end
|
@@ -0,0 +1,12 @@
|
|
1
|
+
require 'fileutils'
|
2
|
+
|
3
|
+
namespace :active_genie do
|
4
|
+
desc 'Install active_genie configuration file'
|
5
|
+
task :install do
|
6
|
+
source = File.join('lib', 'tasks', 'templates', 'active_genie.yml')
|
7
|
+
target = File.join('config', 'active_genie.yml')
|
8
|
+
|
9
|
+
FileUtils.cp(source, target)
|
10
|
+
puts "Successfully installed config/active_genie.yml to #{target}"
|
11
|
+
end
|
12
|
+
end
|
metadata
ADDED
@@ -0,0 +1,67 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: active_genie
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.0.2
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Radamés Roriz
|
8
|
+
autorequire:
|
9
|
+
bindir: bin
|
10
|
+
cert_chain: []
|
11
|
+
date: 2025-01-23 00:00:00.000000000 Z
|
12
|
+
dependencies: []
|
13
|
+
description: |2
|
14
|
+
ActiveGenie provides a robust toolkit for integrating AI capabilities into Ruby applications.
|
15
|
+
Features include:
|
16
|
+
* Structured data extraction from text
|
17
|
+
* Smart text summarization
|
18
|
+
* Content scoring and ranking
|
19
|
+
* AI-powered classification
|
20
|
+
email:
|
21
|
+
- radames@roriz.dev
|
22
|
+
executables: []
|
23
|
+
extensions: []
|
24
|
+
extra_rdoc_files: []
|
25
|
+
files:
|
26
|
+
- LICENSE
|
27
|
+
- README.md
|
28
|
+
- VERSION
|
29
|
+
- lib/active_genie.rb
|
30
|
+
- lib/active_genie/configuration.rb
|
31
|
+
- lib/data_extractor/README.md
|
32
|
+
- lib/data_extractor/data_extractor.rb
|
33
|
+
- lib/requester/openai.rb
|
34
|
+
- lib/requester/requester.rb
|
35
|
+
- lib/tasks/install.rake
|
36
|
+
- lib/tasks/templates/active_ai.yml
|
37
|
+
homepage: https://github.com/Roriz/active_genie
|
38
|
+
licenses:
|
39
|
+
- Apache-2.0
|
40
|
+
metadata:
|
41
|
+
homepage_uri: https://github.com/Roriz/active_genie
|
42
|
+
documentation_uri: https://github.com/Roriz/active_genie/wiki
|
43
|
+
changelog_uri: https://github.com/Roriz/active_genie/blob/master/CHANGELOG.md
|
44
|
+
source_code_uri: https://github.com/Roriz/active_genie
|
45
|
+
bug_tracker_uri: https://github.com/Roriz/active_genie/issues
|
46
|
+
rubygems_mfa_required: 'true'
|
47
|
+
post_install_message:
|
48
|
+
rdoc_options: []
|
49
|
+
require_paths:
|
50
|
+
- lib
|
51
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
52
|
+
requirements:
|
53
|
+
- - ">="
|
54
|
+
- !ruby/object:Gem::Version
|
55
|
+
version: 2.0.0
|
56
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
57
|
+
requirements:
|
58
|
+
- - ">="
|
59
|
+
- !ruby/object:Gem::Version
|
60
|
+
version: '0'
|
61
|
+
requirements: []
|
62
|
+
rubygems_version: 3.5.3
|
63
|
+
signing_key:
|
64
|
+
specification_version: 4
|
65
|
+
summary: Modules and classes to help you build AI features, like data extraction,
|
66
|
+
summarization, scoring, and ranking.
|
67
|
+
test_files: []
|