llm_client 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: 777149fdf2ef683ec6195bde6e601df1f7cb5c63636118549e20e7d523b622ed
4
+ data.tar.gz: 69fb1cf7477115727676d83cb1ff6e4ea17728a1cfb349a42c5e2deddf8b8d3b
5
+ SHA512:
6
+ metadata.gz: c15ac237dec34b0848f3d6024709d3eb1125e406ad3012fbf3d1ea772d623872dbc57de5cd2c3c63fbf40665c05e7d795c25dbb35c7c346454ea4063e56503aa
7
+ data.tar.gz: d6698e4feb0dfbaf72bfd644186a5a7a90b4e8ac94fdd087392647f54d9997ceb15b25efba178f7b2a6fefa85c6fb4a62af8dfb8e1b9b16daabdd9d42fdfad70
data/.rbnextrc ADDED
@@ -0,0 +1,5 @@
1
+ nextify: |
2
+ ./lib
3
+ --min-version=2.7
4
+ --edge
5
+ --proposed
data/.rubocop.yml ADDED
@@ -0,0 +1,7 @@
1
+ require: standard
2
+
3
+ inherit_gem:
4
+ standard: config/base.yml
5
+
6
+ AllCops:
7
+ TargetRubyVersion: 3.2
data/.solargraph.yml ADDED
@@ -0,0 +1,20 @@
1
+ include:
2
+ - "**/*.rb"
3
+ exclude:
4
+ - spec/**/*
5
+ - test/**/*
6
+ - vendor/**/*
7
+ - ".bundle/**/*"
8
+ require:
9
+ - actioncable
10
+ - actionmailer
11
+ - actionpack
12
+ - actionview
13
+ - activejob
14
+ - activemodel
15
+ - activerecord
16
+ - activestorage
17
+ - activesupport
18
+ plugins:
19
+ - solargraph-rails
20
+ max_files: 5000
data/.standard.yml ADDED
@@ -0,0 +1,7 @@
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: []
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-06-19
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 llm_client.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,110 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ llm_client (0.1.0)
5
+ dry-monads (~> 1.6)
6
+ http (~> 5.1, >= 5.1.1)
7
+ ruby-next (>= 0.15.0)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ addressable (2.8.4)
13
+ public_suffix (>= 2.0.2, < 6.0)
14
+ ast (2.4.2)
15
+ concurrent-ruby (1.2.2)
16
+ diff-lcs (1.5.0)
17
+ domain_name (0.5.20190701)
18
+ unf (>= 0.0.5, < 1.0.0)
19
+ dry-core (1.0.0)
20
+ concurrent-ruby (~> 1.0)
21
+ zeitwerk (~> 2.6)
22
+ dry-monads (1.6.0)
23
+ concurrent-ruby (~> 1.0)
24
+ dry-core (~> 1.0, < 2)
25
+ zeitwerk (~> 2.6)
26
+ ffi (1.15.5)
27
+ ffi-compiler (1.0.1)
28
+ ffi (>= 1.0.0)
29
+ rake
30
+ http (5.1.1)
31
+ addressable (~> 2.8)
32
+ http-cookie (~> 1.0)
33
+ http-form_data (~> 2.2)
34
+ llhttp-ffi (~> 0.4.0)
35
+ http-cookie (1.0.5)
36
+ domain_name (~> 0.5)
37
+ http-form_data (2.3.0)
38
+ json (2.6.3)
39
+ language_server-protocol (3.17.0.3)
40
+ lint_roller (1.0.0)
41
+ llhttp-ffi (0.4.0)
42
+ ffi-compiler (~> 1.0)
43
+ rake (~> 13.0)
44
+ minitest (5.18.1)
45
+ parallel (1.23.0)
46
+ parser (3.2.2.3)
47
+ ast (~> 2.4.1)
48
+ racc
49
+ public_suffix (5.0.1)
50
+ racc (1.7.1)
51
+ rainbow (3.1.1)
52
+ rake (13.0.6)
53
+ regexp_parser (2.8.1)
54
+ rexml (3.2.5)
55
+ rubocop (1.52.1)
56
+ json (~> 2.3)
57
+ parallel (~> 1.10)
58
+ parser (>= 3.2.2.3)
59
+ rainbow (>= 2.2.2, < 4.0)
60
+ regexp_parser (>= 1.8, < 3.0)
61
+ rexml (>= 3.2.5, < 4.0)
62
+ rubocop-ast (>= 1.28.0, < 2.0)
63
+ ruby-progressbar (~> 1.7)
64
+ unicode-display_width (>= 2.4.0, < 3.0)
65
+ rubocop-ast (1.29.0)
66
+ parser (>= 3.2.1.0)
67
+ rubocop-performance (1.18.0)
68
+ rubocop (>= 1.7.0, < 2.0)
69
+ rubocop-ast (>= 0.4.0)
70
+ ruby-next (0.15.3)
71
+ ruby-next-core (= 0.15.3)
72
+ ruby-next-parser (>= 3.1.1.0)
73
+ unparser (~> 0.6.0)
74
+ ruby-next-core (0.15.3)
75
+ ruby-next-parser (3.1.1.3)
76
+ parser (>= 3.0.3.1)
77
+ ruby-progressbar (1.13.0)
78
+ standard (1.29.0)
79
+ language_server-protocol (~> 3.17.0.2)
80
+ lint_roller (~> 1.0)
81
+ rubocop (~> 1.52.0)
82
+ standard-custom (~> 1.0.0)
83
+ standard-performance (~> 1.1.0)
84
+ standard-custom (1.0.1)
85
+ lint_roller (~> 1.0)
86
+ standard-performance (1.1.0)
87
+ lint_roller (~> 1.0)
88
+ rubocop-performance (~> 1.18.0)
89
+ unf (0.1.4)
90
+ unf_ext
91
+ unf_ext (0.0.8.2)
92
+ unicode-display_width (2.4.2)
93
+ unparser (0.6.8)
94
+ diff-lcs (~> 1.3)
95
+ parser (>= 3.2.0)
96
+ zeitwerk (2.6.8)
97
+
98
+ PLATFORMS
99
+ arm64-darwin-22
100
+ x86_64-linux
101
+
102
+ DEPENDENCIES
103
+ llm_client!
104
+ minitest (~> 5.0)
105
+ rake (~> 13.0)
106
+ ruby-next (>= 0.15.0)
107
+ standard (~> 1.3)
108
+
109
+ BUNDLED WITH
110
+ 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,90 @@
1
+ # Llm Client
2
+
3
+ Ruby client to connect to [LLM Server](https://github.com/mariochavez/llm_server).
4
+
5
+ ## Installation
6
+
7
+ Install the gem and add to the application's Gemfile by executing:
8
+
9
+ $ bundle add llm_client
10
+
11
+ If bundler is not being used to manage dependencies, install the gem by executing:
12
+
13
+ $ gem install llm_client
14
+
15
+ ## Usage
16
+
17
+ To start using the gem host configuration is need it. The host value is the URL where the LLM Server is running.
18
+
19
+ ```ruby
20
+ LlmClient.host = "http://localhost:9292"
21
+ ```
22
+
23
+ Optionally you can configure a Ruby Logger and log level.
24
+
25
+ ```ruby
26
+ LlmClient.logger = Logger.new(STDOUT)
27
+ LlmClient.log_level = LlmClient::LEVEL_DEBUG
28
+ ```
29
+
30
+ Valid log levels are:
31
+ - `LlmClient::LEVEL_DEBUG`
32
+ - `LlmClient::LEVEL_ERROR`
33
+ - `LlmClient::LEVEL_INFO`
34
+
35
+ With configuration ready, you can start by checking that the LLM Server is up and running.
36
+
37
+ ```ruby
38
+ result = LlmClient.heartbeat
39
+
40
+ if result.success?
41
+ puts "Server is running"
42
+ response = result.success
43
+ puts "Status: #{response.status}"
44
+ puts "Body: #{response.body}"
45
+ puts "Headers: #{response.headers}"
46
+ else
47
+ puts "Server is not responding"
48
+ error = result.failure
49
+ puts "Error: #{error}"
50
+ end
51
+ ```
52
+
53
+ Next, you can send a prompt to be completed by the LLM Server.
54
+
55
+ ```ruby
56
+ response = LlmClient.completion("Who is the creator of Ruby language?")
57
+ if result.success?
58
+ puts "Completions generated successfully"
59
+ response = result.success
60
+ puts "Status: #{response.status}"
61
+ puts "Body: #{response.body}"
62
+ puts "Headers: #{response.headers}"
63
+ calculated_response = response.body[:response]
64
+ puts "Calculated Response: #{calculated_response}"
65
+ else
66
+ puts "Failed to generate completions"
67
+ error = result.failure
68
+ puts "Error: #{error}"
69
+ end
70
+ ```
71
+
72
+ The response in both cases is a `Result` monad that wraps a `Response` struct.
73
+
74
+ ## Development
75
+
76
+ 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.
77
+
78
+ 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).
79
+
80
+ ## Contributing
81
+
82
+ Bug reports and pull requests are welcome on GitHub at https://github.com/mariochavez/llm_client. 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/mariochavez/llm_client/blob/main/CODE_OF_CONDUCT.md).
83
+
84
+ ## License
85
+
86
+ The gem is available as open source under the terms of the [MIT License](https://github.com/mariochavez/llm_client/blob/main/LICENSE.txt).
87
+
88
+ ## Code of Conduct
89
+
90
+ Everyone interacting in the LlmClient project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/mariochavez/llm_client/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,19 @@
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]
15
+
16
+ desc "Run Ruby Next nextify"
17
+ task :nextify do
18
+ sh "bundle exec ruby-next nextify -V"
19
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmClient
4
+ # The Configuration class allows you to configure the connection settings for the LlmClient.
5
+ # It can be initialized directly calling #new method.
6
+ #
7
+ # Examples
8
+ #
9
+ # configuration = LlmClient::Configuration.new
10
+ # configurarion.host = "http://localhost:9292"
11
+ #
12
+ # Or via a setup block.
13
+ #
14
+ # Examples
15
+ #
16
+ # LlmClient::Configuration.setup do |config|
17
+ # config.host = "https://localhost:9292"
18
+ # end
19
+ class Configuration
20
+ # Sets the host name for the Llm.
21
+ #
22
+ # Examples
23
+ #
24
+ # config.host = "chroma.example.com"
25
+ #
26
+ # Returns the String host name.
27
+ attr_accessor :host
28
+
29
+ # Sets the logger for the LlmClient.
30
+ #
31
+ # Examples
32
+ #
33
+ # config.logger = Logger.new(STDOUT)
34
+ #
35
+ # Returns the Logger instance.
36
+ attr_accessor :logger
37
+
38
+ # Sets the logger's log level for the LlmClient.
39
+ #
40
+ # Examples
41
+ #
42
+ # config.log_level = LlmClient::LEVEL_INFO
43
+ #
44
+ # Returns the log level constant
45
+ attr_accessor :log_level
46
+
47
+ def self.setup
48
+ new.tap do |instance|
49
+ yield(instance) if block_given?
50
+ end
51
+ end
52
+
53
+ def initialize
54
+ @log_level = LlmClient::LEVEL_INFO
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmClient
4
+ # Custom error class for connection-related errors in LLM client.
5
+ #
6
+ # This class inherits from the StandardError class and can be raised when there is an error in the connection to the LLM server.
7
+ #
8
+ class ConnectionError < StandardError
9
+ attr_reader :original_error
10
+
11
+ # Initialize a new ConnectionError object with an error message and the original error.
12
+ #
13
+ # Parameters:
14
+ # message - A String representing the error message.
15
+ # original_error - The original error object that caused the connection error.
16
+ #
17
+ # Returns a new ConnectionError object.
18
+ #
19
+ def initialize(message, original_error)
20
+ super(message)
21
+ @original_error = original_error
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmClient
4
+ # Request's response Data object.
5
+ #
6
+ # status - HTTP status code. It is zero when a request fails due to network error.
7
+ # body - Parsed JSON object or response body.
8
+ # headers - HTTP response headers.
9
+ # error - Exception if the response is not success
10
+ Response = Struct.new("Response", :status, :body, :headers, :error)
11
+
12
+ # Request class to perform HTTP requests.
13
+ class HttpClient
14
+ using RubyNext
15
+ include Dry::Monads[:result]
16
+
17
+ # Sends a heartbeat request to the LLM Server.
18
+ #
19
+ # This method is used to check the status of the LLM Server.
20
+ #
21
+ # Returns a dry-monad Result object, which can be a Success or Failure.
22
+ # If the server is running and responds successfully, a Success Result is returned.
23
+ # If there's an error or the server is not responding, a Failure Result is returned.
24
+ #
25
+ # Examples
26
+ #
27
+ # result = heartbeat
28
+ # if result.success?
29
+ # puts "Server is running"
30
+ # response = result.success
31
+ # puts "Status: #{response.status}"
32
+ # puts "Body: #{response.body}"
33
+ # puts "Headers: #{response.headers}"
34
+ # else
35
+ # puts "Server is not responding"
36
+ # error = result.failure
37
+ # puts "Error: #{error}"
38
+ # end
39
+ #
40
+ # Notes
41
+ #
42
+ # - Make sure the LLM Server is running before calling this method.
43
+ #
44
+ def heartbeat
45
+ url = "#{LlmClient.host}/heartbeat"
46
+ Util.log_debug("Sending a request", method: :GET, url:)
47
+
48
+ response = HTTP.get(url)
49
+
50
+ if response.status.success?
51
+ Util.log_info("Successful response", status: response.status)
52
+ Success(build_response(response))
53
+ else
54
+ Util.log_info("Unsuccessful response", status: response.status)
55
+ Failure(build_response(response))
56
+ end
57
+ rescue => exception
58
+ Util.log_info("heartbeat error", error: exception.message)
59
+
60
+ error = LlmClient::ConnectionError.new("heartbeat error", exception)
61
+ Failure(Response.new(status: 0, body: error.message, headers: {}, error:))
62
+ end
63
+
64
+ # Public: Sends a completion request to the LLM Server.
65
+ #
66
+ # This method is used to generate completions based on a given prompt using the LLM Server.
67
+ #
68
+ # Parameters:
69
+ # prompt - A String representing the prompt for which completions should be generated.
70
+ #
71
+ # Returns a dry-monad Result object, which can be a Success or Failure.
72
+ # If the completion request is successful, a Success Result is returned.
73
+ # If there's an error or the server fails to generate completions, a Failure Result is returned.
74
+ #
75
+ # Examples
76
+ #
77
+ # result = completion("Hello, world!")
78
+ # if result.success?
79
+ # puts "Completions generated successfully"
80
+ # response = result.success
81
+ # puts "Status: #{response.status}"
82
+ # puts "Body: #{response.body}"
83
+ # puts "Headers: #{response.headers}"
84
+ # calculated_response = response.body[:response]
85
+ # puts "Calculated Response: #{calculated_response}"
86
+ # else
87
+ # puts "Failed to generate completions"
88
+ # error = result.failure
89
+ # puts "Error: #{error}"
90
+ # end
91
+ #
92
+ # Notes
93
+ #
94
+ # - Make sure the LLM Server is running before calling this method.
95
+ #
96
+ def completion(prompt)
97
+ url = "#{LlmClient.host}/completion"
98
+ Util.log_debug("Sending a request", method: :POST, url:)
99
+
100
+ response = HTTP.headers(
101
+ "Content-Type" => "application/json",
102
+ "Accept" => "application/json"
103
+ ).post(url, json: {prompt:})
104
+
105
+ if response.status.success?
106
+ Util.log_info("Successful response", status: response.status)
107
+ Success(build_response(response, parse: true))
108
+ else
109
+ Util.log_info("Unsuccessful response", status: response.status)
110
+ Failure(build_response(response))
111
+ end
112
+ rescue => exception
113
+ Util.log_info("prompt error", error: exception.message)
114
+
115
+ error = LlmClient::ConnectionError.new("prompt error", exception)
116
+ Failure(Response.new(status: 0, body: error.message, headers: {}, error:))
117
+ end
118
+
119
+ private
120
+
121
+ def build_response(response, parse: false)
122
+ Response.new(
123
+ status: response.status,
124
+ body: parse ? parse_json(response.body.to_s) : response.body.to_s,
125
+ headers: response.headers.to_h,
126
+ error: nil
127
+ )
128
+ end
129
+
130
+ def parse_json(content)
131
+ JSON.parse(content, symbolize_keys: true)
132
+ rescue JSON::ParserError, TypeError
133
+ content
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmClient
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) || LlmClient.config
17
+ logger = config.logger || LlmClient.logger
18
+
19
+ if (!logger.nil? || !config.log_level.nil?) && config.log_level <= LlmClient::LEVEL_ERROR
20
+ log_internal(message, data, level: LlmClient::LEVEL_ERROR, logger: LlmClient.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) || LlmClient.config
36
+ logger = config.logger || LlmClient.logger
37
+
38
+ if (!logger.nil? || !config.log_level.nil?) && config.log_level <= LlmClient::LEVEL_DEBUG
39
+ log_internal(message, data, level: LlmClient::LEVEL_DEBUG, logger: LlmClient.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) || LlmClient.config
55
+ logger = config.logger || LlmClient.logger
56
+
57
+ if (!logger.nil? || !config.log_level.nil?) && config.log_level <= LlmClient::LEVEL_INFO
58
+ log_internal(message, data, level: LlmClient::LEVEL_INFO, logger: LlmClient.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&.add(level, "message=#{message} #{data_str}".strip)
66
+ end
67
+ private_class_method :log_internal
68
+ end
69
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmClient
4
+ VERSION = "0.1.0"
5
+ end
data/lib/llm_client.rb ADDED
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "http"
4
+ require "dry-monads"
5
+ require "json"
6
+ require "logger"
7
+
8
+ require "ruby-next"
9
+ require "ruby-next/language/setup"
10
+
11
+ RubyNext::Language.setup_gem_load_path(transpile: true)
12
+
13
+ require_relative "llm_client/util"
14
+ require_relative "llm_client/configuration"
15
+ require_relative "llm_client/errors"
16
+ require_relative "llm_client/http_client"
17
+ require_relative "llm_client/version"
18
+
19
+ # A module representing an LLM client.
20
+ #
21
+ # This module provides methods to interact with the LLM Server using an HTTP client.
22
+ # It can be configured with a host, a Ruby logger, a log level, and provides methods to forward heartbeat and completion requests to the HTTP client.
23
+ #
24
+ # Examples
25
+ #
26
+ # LlmClient.host = "http://localhost:9292"
27
+ # LlmClient.logger = Logger.new(STDOUT)
28
+ # LlmClient.log_level = LlmClient::LEVEL_DEBUG
29
+ #
30
+ # If logger is present and log level not set, it is LlmClientL::LEVEL_INFO by default.
31
+ #
32
+ # After LlmClient module configuration you can interact wiht the LLM Server.
33
+ #
34
+ # Examples
35
+ #
36
+ # result = LlmClient.heartbeat
37
+ # if result.success?
38
+ # puts "Server is running"
39
+ # response = result.success
40
+ # puts "Status: #{response.status}"
41
+ # puts "Body: #{response.body}"
42
+ # puts "Headers: #{response.headers}"
43
+ # else
44
+ # puts "Server is not responding"
45
+ # error = result.failure
46
+ # puts "Error: #{error}"
47
+ # end
48
+ #
49
+ # response = LlmClient.completion("Who is the creator of Ruby language?")
50
+ # if result.success?
51
+ # puts "Completions generated successfully"
52
+ # response = result.success
53
+ # puts "Status: #{response.status}"
54
+ # puts "Body: #{response.body}"
55
+ # puts "Headers: #{response.headers}"
56
+ # calculated_response = response.body[:response]
57
+ # puts "Calculated Response: #{calculated_response}"
58
+ # else
59
+ # puts "Failed to generate completions"
60
+ # error = result.failure
61
+ # puts "Error: #{error}"
62
+ # end
63
+ #
64
+ module LlmClient
65
+ # map to the same values as the standard library's logger
66
+ LEVEL_DEBUG = Logger::DEBUG
67
+ LEVEL_ERROR = Logger::ERROR
68
+ LEVEL_INFO = Logger::INFO
69
+
70
+ @config = LlmClient::Configuration.setup
71
+ @http_client = LlmClient::HttpClient.new
72
+
73
+ class << self
74
+ extend Forwardable
75
+
76
+ attr_reader :config, :http_client
77
+
78
+ # User configuration options
79
+ def_delegators :@config, :host, :host=
80
+ def_delegators :@config, :logger, :logger=
81
+ def_delegators :@config, :log_level, :log_level=
82
+
83
+ # Http client
84
+ def_delegators :@http_client, :heartbeat, :completion
85
+ end
86
+
87
+ LlmClient.log_level = ENV["LLM_CLIENT_LOG"].to_i unless ENV["LLM_CLIENT_LOG"].nil?
88
+ end
@@ -0,0 +1,4 @@
1
+ module LlmClient
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,126 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: llm_client
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-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: http
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '5.1'
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 5.1.1
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '5.1'
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 5.1.1
33
+ - !ruby/object:Gem::Dependency
34
+ name: dry-monads
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '1.6'
40
+ type: :runtime
41
+ prerelease: false
42
+ version_requirements: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '1.6'
47
+ - !ruby/object:Gem::Dependency
48
+ name: ruby-next-core
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: 0.15.0
54
+ type: :runtime
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: 0.15.0
61
+ - !ruby/object:Gem::Dependency
62
+ name: ruby-next
63
+ requirement: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: 0.15.0
68
+ type: :development
69
+ prerelease: false
70
+ version_requirements: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 0.15.0
75
+ description: Ruby client to connect to LLM Server.
76
+ email:
77
+ - mario.chavez@gmail.com
78
+ executables: []
79
+ extensions: []
80
+ extra_rdoc_files: []
81
+ files:
82
+ - ".rbnextrc"
83
+ - ".rubocop.yml"
84
+ - ".solargraph.yml"
85
+ - ".standard.yml"
86
+ - CHANGELOG.md
87
+ - CODE_OF_CONDUCT.md
88
+ - Gemfile
89
+ - Gemfile.lock
90
+ - LICENSE.txt
91
+ - README.md
92
+ - Rakefile
93
+ - lib/llm_client.rb
94
+ - lib/llm_client/configuration.rb
95
+ - lib/llm_client/errors.rb
96
+ - lib/llm_client/http_client.rb
97
+ - lib/llm_client/util.rb
98
+ - lib/llm_client/version.rb
99
+ - sig/llm_client.rbs
100
+ homepage: https://mariochavez.io
101
+ licenses:
102
+ - MIT
103
+ metadata:
104
+ homepage_uri: https://mariochavez.io
105
+ source_code_uri: https://github.com/mariochavez/llm_client
106
+ changelog_uri: https://github.com/mariochavez/llm_client/blob/main/CHANGELOG.md
107
+ post_install_message:
108
+ rdoc_options: []
109
+ require_paths:
110
+ - lib
111
+ required_ruby_version: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - ">="
114
+ - !ruby/object:Gem::Version
115
+ version: 2.7.0
116
+ required_rubygems_version: !ruby/object:Gem::Requirement
117
+ requirements:
118
+ - - ">="
119
+ - !ruby/object:Gem::Version
120
+ version: '0'
121
+ requirements: []
122
+ rubygems_version: 3.4.14
123
+ signing_key:
124
+ specification_version: 4
125
+ summary: Ruby client for LLM Server.
126
+ test_files: []