aoororachain 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: 284ff16b017b5f61a4308863affa07001b954330ecba1dafd50b1712d1b37d0f
4
+ data.tar.gz: f9ab6347628e62ed16ea0c5083eb58d5f0ee731a76446b16991e253302532ba6
5
+ SHA512:
6
+ metadata.gz: 789f73b9acb88506caf3744d0c2c769c4cd2838bbfdd42f29cf11b9c0b7df7e8b248cc4283e54fb795a195270c274a1a6ef3efd354c1c80e3947f53e3dbc33a7
7
+ data.tar.gz: 3c99aa8e13512d8aaef08fafa2804e104769d0b02d78afed69c80b6824a210e19295ac079998bdf139a9c0c754ac9bf125e6678d597c524b2a6207ae7016e841
data/.rubocop.yml ADDED
@@ -0,0 +1 @@
1
+ /Users/mariochavez/Development/neovim-files/.rubocop.yml
data/.solargraph.yml ADDED
@@ -0,0 +1 @@
1
+ /Users/mariochavez/Development/neovim-files/.solargraph.yml
data/.standard.yml ADDED
@@ -0,0 +1,8 @@
1
+ fix: true # default: false
2
+ parallel: true # default: false
3
+ format: progress # default: Standard::Formatter
4
+ ruby_version: 3.2.2 # default: RUBY_VERSION
5
+ default_ignores: false # default: true
6
+
7
+ ignore: # default: []
8
+ - 'tmp/**/*'
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-05-24
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 mario.chavez@gmail.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,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in aoororachain.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "standard", "~> 1.3"
data/Gemfile.lock ADDED
@@ -0,0 +1,124 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ aoororachain (0.1.0)
5
+ chroma-db (~> 0.5.0)
6
+ llm_client (~> 0.1.2)
7
+ pdf-reader (~> 2.11)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ Ascii85 (1.1.0)
13
+ addressable (2.8.4)
14
+ public_suffix (>= 2.0.2, < 6.0)
15
+ afm (0.2.2)
16
+ ast (2.4.2)
17
+ chroma-db (0.5.0)
18
+ dry-monads (~> 1.6)
19
+ ruby-next (>= 0.15.0)
20
+ concurrent-ruby (1.2.2)
21
+ diff-lcs (1.5.0)
22
+ domain_name (0.5.20190701)
23
+ unf (>= 0.0.5, < 1.0.0)
24
+ dry-core (1.0.0)
25
+ concurrent-ruby (~> 1.0)
26
+ zeitwerk (~> 2.6)
27
+ dry-monads (1.6.0)
28
+ concurrent-ruby (~> 1.0)
29
+ dry-core (~> 1.0, < 2)
30
+ zeitwerk (~> 2.6)
31
+ ffi (1.15.5)
32
+ ffi-compiler (1.0.1)
33
+ ffi (>= 1.0.0)
34
+ rake
35
+ hashery (2.1.2)
36
+ http (5.1.1)
37
+ addressable (~> 2.8)
38
+ http-cookie (~> 1.0)
39
+ http-form_data (~> 2.2)
40
+ llhttp-ffi (~> 0.4.0)
41
+ http-cookie (1.0.5)
42
+ domain_name (~> 0.5)
43
+ http-form_data (2.3.0)
44
+ json (2.6.3)
45
+ language_server-protocol (3.17.0.3)
46
+ lint_roller (1.0.0)
47
+ llhttp-ffi (0.4.0)
48
+ ffi-compiler (~> 1.0)
49
+ rake (~> 13.0)
50
+ llm_client (0.1.2)
51
+ dry-monads (~> 1.6)
52
+ http (~> 5.1, >= 5.1.1)
53
+ ruby-next (>= 0.15.0)
54
+ minitest (5.18.0)
55
+ parallel (1.23.0)
56
+ parser (3.2.2.1)
57
+ ast (~> 2.4.1)
58
+ pdf-reader (2.11.0)
59
+ Ascii85 (~> 1.0)
60
+ afm (~> 0.2.1)
61
+ hashery (~> 2.0)
62
+ ruby-rc4
63
+ ttfunk
64
+ public_suffix (5.0.1)
65
+ rainbow (3.1.1)
66
+ rake (13.0.6)
67
+ regexp_parser (2.8.0)
68
+ rexml (3.2.5)
69
+ rubocop (1.50.2)
70
+ json (~> 2.3)
71
+ parallel (~> 1.10)
72
+ parser (>= 3.2.0.0)
73
+ rainbow (>= 2.2.2, < 4.0)
74
+ regexp_parser (>= 1.8, < 3.0)
75
+ rexml (>= 3.2.5, < 4.0)
76
+ rubocop-ast (>= 1.28.0, < 2.0)
77
+ ruby-progressbar (~> 1.7)
78
+ unicode-display_width (>= 2.4.0, < 3.0)
79
+ rubocop-ast (1.28.1)
80
+ parser (>= 3.2.1.0)
81
+ rubocop-performance (1.16.0)
82
+ rubocop (>= 1.7.0, < 2.0)
83
+ rubocop-ast (>= 0.4.0)
84
+ ruby-next (0.15.3)
85
+ ruby-next-core (= 0.15.3)
86
+ ruby-next-parser (>= 3.1.1.0)
87
+ unparser (~> 0.6.0)
88
+ ruby-next-core (0.15.3)
89
+ ruby-next-parser (3.1.1.3)
90
+ parser (>= 3.0.3.1)
91
+ ruby-progressbar (1.13.0)
92
+ ruby-rc4 (0.1.5)
93
+ standard (1.28.3)
94
+ language_server-protocol (~> 3.17.0.2)
95
+ lint_roller (~> 1.0)
96
+ rubocop (~> 1.50.2)
97
+ standard-custom (~> 1.0.0)
98
+ standard-performance (~> 1.0.1)
99
+ standard-custom (1.0.0)
100
+ lint_roller (~> 1.0)
101
+ standard-performance (1.0.1)
102
+ lint_roller (~> 1.0)
103
+ rubocop-performance (~> 1.16.0)
104
+ ttfunk (1.7.0)
105
+ unf (0.1.4)
106
+ unf_ext
107
+ unf_ext (0.0.8.2)
108
+ unicode-display_width (2.4.2)
109
+ unparser (0.6.7)
110
+ diff-lcs (~> 1.3)
111
+ parser (>= 3.2.0)
112
+ zeitwerk (2.6.8)
113
+
114
+ PLATFORMS
115
+ arm64-darwin-22
116
+
117
+ DEPENDENCIES
118
+ aoororachain!
119
+ minitest (~> 5.0)
120
+ rake (~> 13.0)
121
+ standard (~> 1.3)
122
+
123
+ BUNDLED WITH
124
+ 2.4.12
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Mario Alberto Chávez
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,36 @@
1
+ # Aoororachain
2
+
3
+
4
+ Aoororachain is Ruby chain tool to work with LLMs
5
+
6
+ ## Installation
7
+
8
+ Install the gem and add to the application's Gemfile by executing:
9
+
10
+ $ bundle add aoororachain
11
+
12
+ If bundler is not being used to manage dependencies, install the gem by executing:
13
+
14
+ $ gem install aoororachain
15
+
16
+ ## Usage
17
+
18
+ TODO: Write usage instructions here
19
+
20
+ ## Development
21
+
22
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
23
+
24
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, 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).
25
+
26
+ ## Contributing
27
+
28
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/aoororachain. 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/[USERNAME]/aoororachain/blob/main/CODE_OF_CONDUCT.md).
29
+
30
+ ## License
31
+
32
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
33
+
34
+ ## Code of Conduct
35
+
36
+ Everyone interacting in the Aoororachain project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/aoororachain/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,14 @@
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
+ require "standard/rake"
13
+
14
+ task default: %i[test standard]
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ module Chains
5
+ class RetrievalQA
6
+ def initialize(llm, retriever, type: :stuff)
7
+ @llm = llm
8
+ @retriever = retriever
9
+ @type = type
10
+ end
11
+
12
+ def complete(prompt:)
13
+ context = @retriever.search(prompt)
14
+
15
+ system_prompt = "Una conversación entre un humano y un asistente de inteligencia artificial. El asistente response usando el contexto la pregunta. Si no sabes la respuesta, simplemente di que no sabes, no trates de inventar una."
16
+ context_prompt = "Contexto: #{context.map(&:document).join(" ").tr("\n", " ")}"
17
+ question_prompt = "Pregunta: #{prompt}"
18
+
19
+ stuff_prompt = [system_prompt, context_prompt, question_prompt]
20
+ success, response = @llm.complete(prompt: stuff_prompt.join(". "))
21
+
22
+ if success
23
+ completion = {
24
+ response:,
25
+ sources: context.map(&:metadata)
26
+ }
27
+ else
28
+ completion = {
29
+ response: "Sorry we had a problem with the LLM",
30
+ sources: []
31
+ }
32
+ Aoororachain::Util.log_error("Failed to complete", message: response)
33
+ end
34
+
35
+ completion
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ # The Configuration class allows you to configure Aoororachain
5
+ # It can be initialized directly calling #new method.
6
+ #
7
+ # Examples
8
+ #
9
+ # configuration = Aoororachain::Configuration.new
10
+ # configurarion.logger = Logger.new($stdout)
11
+ #
12
+ # Or via a setup block.
13
+ #
14
+ # Examples
15
+ #
16
+ # Aoororachain::Configuration.setup do |config|
17
+ # config.logger = Logger.new($stdout)
18
+ # end
19
+ class Configuration
20
+ # Sets the logger for the Aoororachain service client.
21
+ #
22
+ # Examples
23
+ #
24
+ # config.logger = Logger.new(STDOUT)
25
+ #
26
+ # Returns the Logger instance.
27
+ attr_accessor :logger
28
+ # Sets the logger's log level for the Aoororachain service client.
29
+ #
30
+ # Examples
31
+ #
32
+ # config.log_level = Aoororachain::LEVEL_INFO
33
+ #
34
+ # Returns the log level constant
35
+ attr_accessor :log_level
36
+
37
+ def self.setup
38
+ new.tap do |instance|
39
+ yield(instance) if block_given?
40
+ end
41
+ end
42
+
43
+ def initialize
44
+ @log_level = Aoororachain::LEVEL_INFO
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ class Document
5
+ attr_reader :content, :metadata
6
+
7
+ def initialize(content, metadata = {})
8
+ @content = content
9
+ @metadata = metadata
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ module Embeddings
5
+ class LocalPythonEmbedding
6
+ MODEL_INSTRUCTOR_L = "hkunlp/instructor-large"
7
+ MODEL_INSTRUCTOR_XL = "hkunlp/instructor-xl"
8
+ MODEL_ALL_MPNET = "sentence-transformers/all-mpnet-base-v2"
9
+
10
+ def initialize(options = {})
11
+ @model = options.delete(:model) || MODEL_ALL_MPNET
12
+ @device = options.delete(:device) || "cpu"
13
+
14
+ Aoororachain::Util.log_info("Using", data: {model: @model, device: @device})
15
+ Aoororachain::Util.log_info("This embedding calls Python code using system call. First time initialization might take long due to Python dependencies installation.")
16
+
17
+ install_python_dependencies
18
+ end
19
+
20
+ def embed_documents(documents, include_metadata: false)
21
+ texts = documents.map { |document| "#{document.content} #{include_metadata ? document.metadata.to_json : ""}.strip" }
22
+
23
+ embeddings = embed_texts(texts)
24
+ embeddings || []
25
+ end
26
+
27
+ def embed_texts(texts)
28
+ return if texts.empty?
29
+
30
+ Aoororachain::Util.log_info("First time usage might take long time due to models download.")
31
+ texts_file_path = save_texts_to_file(texts)
32
+
33
+ embeddings_file_path = embed_texts_python(texts_file_path)
34
+
35
+ embeddings = load_embeddings(embeddings_file_path) if !embeddings_file_path.nil?
36
+ embeddings || []
37
+ end
38
+
39
+ def embed_query(text)
40
+ return [] if text.nil? || text.strip == ""
41
+
42
+ Aoororachain::Util.log_info("First time usage might take long time due to models download.")
43
+ [embed_text_python(text)]
44
+ end
45
+
46
+ def to_s
47
+ "#{self.class} : #{@model} : #{@device}"
48
+ end
49
+
50
+ private
51
+
52
+ def run_system(command)
53
+ _, stdout, stderr, wait_thr = Open3.popen3(command)
54
+ stdout_data = stdout.gets(nil)
55
+ stdout.close
56
+ stderr_data = stderr.gets(nil)
57
+ stderr.close
58
+ exit_code = wait_thr.value
59
+
60
+ [stdout_data, stderr_data, exit_code]
61
+ end
62
+
63
+ def load_embeddings(file_path)
64
+ embeddings = JSON.parse(File.read(file_path))
65
+ delete_file(file_path)
66
+
67
+ embeddings
68
+ end
69
+
70
+ def parse_output(data)
71
+ delimiter = "========"
72
+ parsed_text = data.split(delimiter).last.strip
73
+
74
+ return nil if parsed_text.nil?
75
+ JSON.parse(parsed_text)
76
+ end
77
+
78
+ def embed_text_python(text)
79
+ command = <<~PYTHON
80
+ python - << EOF
81
+ from InstructorEmbedding import INSTRUCTOR
82
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
83
+
84
+ instructor_embeddings = HuggingFaceInstructEmbeddings(model_name="#{@model}",
85
+ model_kwargs={"device": "#{@device}"})
86
+
87
+ embeddings = instructor_embeddings.embed_query("#{text}")
88
+ print("========")
89
+ print(embeddings)
90
+ PYTHON
91
+
92
+ stdout_data, stderr_data, exit_code = run_system(command)
93
+
94
+ if exit_code != 0
95
+ Aoororachain::Util.log_error("Failed to embed documents: #{stderr_data}")
96
+ return nil
97
+ end
98
+
99
+ Aoororachain::Util.log_debug("Text embedded")
100
+ parse_output(stdout_data)
101
+ end
102
+
103
+ def embed_texts_python(texts_file_path)
104
+ embeddings_file_path = "#{texts_file_path}.emb"
105
+
106
+ command = <<~PYTHON
107
+ python - << EOF
108
+ import json
109
+ from InstructorEmbedding import INSTRUCTOR
110
+ from langchain.embeddings import HuggingFaceInstructEmbeddings
111
+
112
+ instructor_embeddings = HuggingFaceInstructEmbeddings(model_name="#{@model}",
113
+ model_kwargs={"device": "#{@device}"})
114
+
115
+ with open("#{texts_file_path}") as f:
116
+ file_content = f.read()
117
+
118
+ documents = json.loads(file_content)
119
+
120
+ embeddings = instructor_embeddings.embed_documents(list(documents))
121
+
122
+ with open("#{embeddings_file_path}", "w", encoding="utf-8") as file:
123
+ json.dump(embeddings, file, ensure_ascii=False, indent=4)
124
+ EOF
125
+ PYTHON
126
+
127
+ _, stderr_data, exit_code = run_system(command)
128
+
129
+ if exit_code != 0
130
+ Aoororachain::Util.log_error("Failed to embed documents: #{stderr_data}")
131
+ return nil
132
+ end
133
+
134
+ Aoororachain::Util.log_debug("Documents embedded")
135
+ embeddings_file_path
136
+ end
137
+
138
+ def delete_file(file_path)
139
+ File.delete(file_path)
140
+ rescue => ex
141
+ Aoororachain::Util.log_error("Failed delete file #{file_path}", data: {exception: ex.to_s})
142
+ end
143
+
144
+ def save_texts_to_file(texts)
145
+ temp_file = Tempfile.new("Aoororachain.embeddings")
146
+ temp_file.write(texts.to_json)
147
+ temp_file.close
148
+
149
+ file_path = temp_file.path
150
+ Aoororachain::Util.log_debug("Texts saved to #{file_path}.")
151
+
152
+ file_path
153
+ end
154
+
155
+ def install_python_dependencies
156
+ stdout_data, stderr_data, exit_code = run_system("pip -q install langchain sentence_transformers InstructorEmbedding")
157
+
158
+ if exit_code != 0
159
+ Aoororachain.log_error("Failed to install Python dependencies: #{stderr_data}")
160
+ return false
161
+ end
162
+
163
+ Aoororachain::Util.log_debug("Python installed dependencies: #{stdout_data}")
164
+ true
165
+ end
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "llm_client"
4
+
5
+ module Aoororachain
6
+ module Llms
7
+ class LlamaServer
8
+ def initialize(host)
9
+ LlmClient.host = host
10
+ LlmClient.logger = Aoororachain.logger
11
+ LlmClient.log_level = Aoororachain.log_level
12
+ end
13
+
14
+ def complete(prompt:)
15
+ result = LlmClient.completion(prompt)
16
+
17
+ [result.success?, result.success? ? result.success.body["response"].gsub(/Usuario:.*Asistente:/, "") : result.failure.message]
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ module Loaders
5
+ class DirectoryLoader
6
+ def initialize(path:, glob:, loader:, parser: nil)
7
+ @path = path
8
+ @glob = glob
9
+ @loader = loader
10
+ @parser = parser
11
+ end
12
+
13
+ def load
14
+ Dir.glob("#{@path}/#{@glob}").map { |file| @loader.load(file, parser: @parser) }
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ module Loaders
5
+ class FileLoader
6
+ def self.load(file, parser: nil)
7
+ text = File.read(file)
8
+ metadata = {source: file}
9
+
10
+ if !parser.nil?
11
+ text, additional_metadata = parser.parse(text)
12
+ Aoororachain::Util.log_debug("Extracted metadata using parser #{parser.class}", {additional_metadata:})
13
+ metadata.merge!(additional_metadata)
14
+ end
15
+
16
+ Aoororachain::Util.log_debug("File loaded", {file:})
17
+ [Document.new(text, metadata)]
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,33 @@
1
+ ## frozen_string_literal: true
2
+
3
+ require "pdf/reader"
4
+
5
+ module Aoororachain
6
+ module Loaders
7
+ class PDFLoader
8
+ def self.load(file, parser: nil)
9
+ reader = PDF::Reader.new(file)
10
+ documents = []
11
+
12
+ base_metadata = {source: file, pages: reader.page_count}
13
+
14
+ reader.pages.each do |page|
15
+ metadata = base_metadata.dup
16
+ metadata[:page] = page.number
17
+ text = page.text
18
+
19
+ if !parser.nil?
20
+ text, additional_metadata = parser.parse(text)
21
+ Aoororachain::Util.log_debug("Extracted metadata using parser #{parser.class}", {additional_metadata:})
22
+ metadata.merge!(additional_metadata)
23
+ end
24
+
25
+ documents << Document.new(text, metadata)
26
+ end
27
+
28
+ Aoororachain::Util.log_debug("File loaded", {file:})
29
+ documents
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ class RecursiveTextSplitter
5
+ def initialize(size: 1024, overlap: 200)
6
+ @size = size
7
+ @overlap = overlap
8
+ end
9
+
10
+ def split_documents(documents)
11
+ original_documents = Array(documents)
12
+
13
+ new_documents = []
14
+ original_documents.each do |document|
15
+ texts = split_text(document.content)
16
+ texts.each do |text|
17
+ new_documents << Document.new(text, document.metadata)
18
+ end
19
+ end
20
+
21
+ new_documents
22
+ end
23
+
24
+ def split_text(text)
25
+ split_recursive(text, 0, [])
26
+ end
27
+
28
+ private
29
+
30
+ def split_recursive(text, start_index, chunks)
31
+ # Base case: If the remaining word count is less than the chunk size, return the chunks
32
+ if start_index + @size > text.length
33
+ chunks << text[start_index..]
34
+ return chunks
35
+ end
36
+
37
+ # Calculate the end index of the current chunk
38
+ end_index = start_index + @size
39
+ end_index += @overlap if start_index != 0
40
+
41
+ # Add the current chunk to the array
42
+ chunk = text[start_index...end_index]
43
+
44
+ # Correct start and end indexes
45
+ start_index_corrected = (start_index == 0) ? start_index : detect_first_whitespace_or_line_return_position(chunk)
46
+ end_index_corrected = detect_last_whitespace_or_line_return_position(chunk)
47
+
48
+ if start_index_corrected == end_index_corrected
49
+ end_index_corrected = end_index
50
+ chunks << chunk
51
+ else
52
+ chunks << chunk[start_index_corrected..end_index_corrected]&.strip
53
+ end
54
+
55
+ # Calculate the next start index with overlap
56
+ next_start_index = end_index - @overlap - (@size - end_index_corrected)
57
+
58
+ # Recursively split the remaining words
59
+ split_recursive(text, next_start_index, chunks)
60
+ end
61
+
62
+ def detect_first_whitespace_or_line_return_position(string)
63
+ position = string.index(/\s|\n/)
64
+ position.nil? ? 0 : position
65
+ end
66
+
67
+ def detect_last_whitespace_or_line_return_position(string)
68
+ position = string.rindex(/\s|\n/)
69
+ position.nil? ? -1 : position
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ module Util
5
+ # Logs an error message with the given data using the provided Logger instance.
6
+ #
7
+ # message - A String message to be logged.
8
+ # data - A Hash of additional data to be included in the log entry.
9
+ #
10
+ # Examples
11
+ #
12
+ # Util.log_error("An error occurred", { user_id: 123, error_code: "404" })
13
+ #
14
+ # Returns nothing.
15
+ def self.log_error(message, data = {})
16
+ config = data.delete(:config) || Aoororachain.config
17
+ logger = config.logger || Aoororachain.logger
18
+
19
+ if (!logger.nil? || !config.log_level.nil?) && config.log_level <= Aoororachain::LEVEL_ERROR
20
+ log_internal(message, data, level: Aoororachain::LEVEL_ERROR, logger: Aoororachain.logger)
21
+ end
22
+ end
23
+
24
+ # Logs a debug message with the given data using the provided Logger instance.
25
+ #
26
+ # message - A String message to be logged.
27
+ # data - A Hash of additional data to be included in the log entry.
28
+ #
29
+ # Examples
30
+ #
31
+ # Util.log_debug("Debugging information", { user_id: 123, action: "update" })
32
+ #
33
+ # Returns nothing.
34
+ def self.log_debug(message, data = {})
35
+ config = data.delete(:config) || Aoororachain.config
36
+ logger = config.logger || Aoororachain.logger
37
+
38
+ if (!logger.nil? || !config.log_level.nil?) && config.log_level <= Aoororachain::LEVEL_DEBUG
39
+ log_internal(message, data, level: Aoororachain::LEVEL_DEBUG, logger: Aoororachain.logger)
40
+ end
41
+ end
42
+
43
+ # Logs an informational message with the given data using the provided Logger instance.
44
+ #
45
+ # message - A String message to be logged.
46
+ # data - A Hash of additional data to be included in the log entry.
47
+ #
48
+ # Examples
49
+ #
50
+ # Util.log_info("Processing request", { request_id: "abc123", route: "/users" })
51
+ #
52
+ # Returns nothing.
53
+ def self.log_info(message, data = {})
54
+ config = data.delete(:config) || Aoororachain.config
55
+ logger = config.logger || Aoororachain.logger
56
+
57
+ if (!logger.nil? || !config.log_level.nil?) && config.log_level <= Aoororachain::LEVEL_INFO
58
+ log_internal(message, data, level: Aoororachain::LEVEL_INFO, logger: Aoororachain.logger)
59
+ end
60
+ end
61
+
62
+ def self.log_internal(message, data = {}, level:, logger:)
63
+ data_str = data.reject { |_k, v| v.nil? }.map { |(k, v)| "#{k}=#{v}" }.join(" ")
64
+
65
+ logger&.log(level, "message=#{message} #{data_str}".strip)
66
+ end
67
+ private_class_method :log_internal
68
+ end
69
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "chroma-db"
4
+
5
+ module Aoororachain
6
+ module VectorStores
7
+ class Chroma
8
+ DEFAULT_RESULTS = 3
9
+
10
+ def initialize(embedder:, options: {})
11
+ ::Chroma.connect_host = options.delete(:host)
12
+ ::Chroma.logger = options.delete(:logger) || Aoororachain.logger
13
+ ::Chroma.log_level = options.delete(:log_level) || Aoororachain.log_level
14
+
15
+ @embedder = embedder
16
+ end
17
+
18
+ def from_documents(documents, index:, include_metadata: false)
19
+ @store = ::Chroma::Resources::Collection.get_or_create(index, {embedder: @embedder.to_s})
20
+
21
+ documents_embeddings = embed_documents(documents, include_metadata:)
22
+
23
+ documents_embeddings.each do |batch|
24
+ Aoororachain::Util.log_debug("Storing embeddings")
25
+ @store.add(batch)
26
+ end
27
+
28
+ true
29
+ end
30
+
31
+ def from_index(index)
32
+ @store = ::Chroma::Resources::Collection.get_or_create(index, {embedder: @embedder.to_s})
33
+
34
+ true
35
+ end
36
+
37
+ def add(documents, include_metadata: false)
38
+ documents_embeddings = embed_documents(documents, include_metadata:)
39
+
40
+ documents_embeddings.each do |batch|
41
+ Aoororachain::Util.log_debug("Storing embeddings")
42
+ @store.add(batch)
43
+ end
44
+
45
+ true
46
+ end
47
+
48
+ def as_retriever(search_type: :similarity, results: DEFAULT_RESULTS)
49
+ Aoororachain::VectorStores::Retriever.new(self, search_type:, similarity:, results:)
50
+ end
51
+
52
+ def similarity_search_by_vector(query, results: DEFAULT_RESULTS, filter: {})
53
+ query(query_texts: query, results:, where: filter, include: %w[metadatas documents])
54
+ end
55
+
56
+ def similarity_search_with_score(query, results: DEFAULT_RESULTS, filter: {})
57
+ query(query_texts: query, results:, where: filter)
58
+ end
59
+ alias_method :similarity_search, :similarity_search_with_score
60
+
61
+ private
62
+
63
+ def query(query_texts: "", results: DEFAULT_RESULTS, where: {}, include: %w[metadatas documents distances])
64
+ embeddings = @embedder.embed_query(query_texts)
65
+ Aoororachain::Util.log_debug("Query embeddings #{query_texts}", data: {embeddings:, results:, where:, include:})
66
+
67
+ @store.query(query_embeddings: embeddings, results:, where:, include:)
68
+ end
69
+
70
+ def embed_documents(documents, include_metadata: false)
71
+ documents_embeddings = @embedder.embed_documents(documents, include_metadata:)
72
+
73
+ batch_size = 3_000
74
+ index = 0
75
+
76
+ documents.each_slice(batch_size).map do |batch|
77
+ batch.map do |document|
78
+ element = ::Chroma::Resources::Embedding.new(id: SecureRandom.uuid, embedding: documents_embeddings[index], metadata: document.metadata, document: document.content)
79
+ index += 1
80
+ element
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ module VectorStores
5
+ class Retriever
6
+ attr_accessor :search_type, :results
7
+
8
+ def initialize(vector_store, search_type: :similarity, results: 3)
9
+ @vector_store = vector_store
10
+ @search_type = search_type
11
+ @results = results
12
+ end
13
+
14
+ def search(query, **options)
15
+ results = options.delete(:results) || @results
16
+ filter = options.delete(:filter) || {}
17
+
18
+ if @search_type == :similarity
19
+ @vector_store.similarity_search(query, results:, filter:)
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aoororachain
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+ require "json"
5
+ require "logger"
6
+ require "forwardable"
7
+ require "tempfile"
8
+
9
+ require_relative "aoororachain/version"
10
+ require_relative "aoororachain/util"
11
+ require_relative "aoororachain/configuration"
12
+ require_relative "aoororachain/document"
13
+ require_relative "aoororachain/loaders/directory_loader"
14
+ require_relative "aoororachain/loaders/file_loader"
15
+ require_relative "aoororachain/loaders/pdf_loader"
16
+ require_relative "aoororachain/recursive_text_splitter"
17
+ require_relative "aoororachain/embeddings/local_python_embedding"
18
+ require_relative "aoororachain/vector_stores/chroma"
19
+ require_relative "aoororachain/vector_stores/retriever"
20
+ require_relative "aoororachain/llms/llama_server"
21
+ require_relative "aoororachain/chains/retrieval_qa"
22
+
23
+ module Aoororachain
24
+ # map to the same values as the standard library's logger
25
+ LEVEL_DEBUG = Logger::DEBUG
26
+ LEVEL_ERROR = Logger::ERROR
27
+ LEVEL_INFO = Logger::INFO
28
+
29
+ @config = Aoororachain::Configuration.setup
30
+
31
+ class << self
32
+ extend Forwardable
33
+
34
+ attr_reader :config
35
+
36
+ # User configuration options
37
+ def_delegators :@config, :log_level, :log_level=
38
+ def_delegators :@config, :logger, :logger=
39
+ end
40
+
41
+ Aoororachain.log_level = ENV["AOORORACHAIN_LOG"].to_i unless ENV["AOORORACHAIN_LOG"].nil?
42
+ end
@@ -0,0 +1,4 @@
1
+ module Aoororachain
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: aoororachain
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mario Alberto Chávez
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-06-25 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: chroma-db
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.5.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.5.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: pdf-reader
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.11'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.11'
41
+ - !ruby/object:Gem::Dependency
42
+ name: llm_client
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 0.1.2
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 0.1.2
55
+ description: Ruby chain tools to work with LLMs
56
+ email:
57
+ - mario.chavez@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rubocop.yml"
63
+ - ".solargraph.yml"
64
+ - ".standard.yml"
65
+ - CHANGELOG.md
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - Gemfile.lock
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - lib/aoororachain.rb
73
+ - lib/aoororachain/chains/retrieval_qa.rb
74
+ - lib/aoororachain/configuration.rb
75
+ - lib/aoororachain/document.rb
76
+ - lib/aoororachain/embeddings/local_python_embedding.rb
77
+ - lib/aoororachain/llms/llama_server.rb
78
+ - lib/aoororachain/loaders/directory_loader.rb
79
+ - lib/aoororachain/loaders/file_loader.rb
80
+ - lib/aoororachain/loaders/pdf_loader.rb
81
+ - lib/aoororachain/recursive_text_splitter.rb
82
+ - lib/aoororachain/util.rb
83
+ - lib/aoororachain/vector_stores/chroma.rb
84
+ - lib/aoororachain/vector_stores/retriever.rb
85
+ - lib/aoororachain/version.rb
86
+ - sig/aoororachain.rbs
87
+ homepage: https://mariochavez.io
88
+ licenses:
89
+ - MIT
90
+ metadata:
91
+ homepage_uri: https://mariochavez.io
92
+ source_code_uri: https://mariochavez.io
93
+ changelog_uri: https://mariochavez.io
94
+ post_install_message:
95
+ rdoc_options: []
96
+ require_paths:
97
+ - lib
98
+ required_ruby_version: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: 2.6.0
103
+ required_rubygems_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ requirements: []
109
+ rubygems_version: 3.4.14
110
+ signing_key:
111
+ specification_version: 4
112
+ summary: Aoororachain for working with LLMs
113
+ test_files: []