llms-tool 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 070d8ae6a371038ba6c46569ab65a0cc894df15fe1d67a3bda48e8f00fd20e46
4
+ data.tar.gz: e6b6876a663ba7873d13eb1c87798062545415fd5fcb5c05758a87eeb3c993f8
5
+ SHA512:
6
+ metadata.gz: 611bd79059dba5040db249e8348bb32d3df414cfc276c413709c36984ec5bd18eac66a5ab747d7976ea5fd4cf6511a5cf250171352ae1058bf46eb0133785ce7
7
+ data.tar.gz: 5250ede90c87392625bc47f18215cb0bb11f33ab8d5f2911d59c41f5acba1a58faebd1bf4f201b0df743f5da9a8eb518d70ec4c204cc8ea7b820f2b64f256862
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 LLMs::Tool Contributors
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,200 @@
1
+ # LLMs::Tool
2
+
3
+ A Ruby gem for defining LLM tools via a simple DSL. Works well with [llms](https://github.com/benlund/llms) but can be used independently too.
4
+
5
+ See also llms-agent (coming soon) which ties this all together.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'llms-tool'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ ```bash
18
+ $ bundle install
19
+ ```
20
+
21
+ Or install it yourself as:
22
+
23
+ ```bash
24
+ $ gem install llms-tool
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ### Basic Tool Definition
30
+
31
+ Create a simple tool by inheriting from `LLMs::Tool::Base`:
32
+
33
+ ```ruby
34
+ class LetterCounter < LLMs::Tool::Base
35
+ tool_name :letter_counter
36
+ description "Count the number of letters in a word"
37
+
38
+ parameter :word, String, "The word to count the letters of", required: true
39
+ parameter :letter, String, "The letter to count", required: true
40
+
41
+ def run(*)
42
+ @word.count(@letter)
43
+ end
44
+ end
45
+
46
+ pp LetterCounter.tool_schema # Hash suitable for conversion into the JSON schema for the tool
47
+ ```
48
+
49
+ Or if you just want to use the DSL you can just include the LLMs::Tool::Definition module in any class.
50
+
51
+ ```ruby
52
+ class MyTool
53
+ include LLMs::Tool::Definition
54
+
55
+ tool_name :my_tool
56
+ description "tool description"
57
+ parameter :name, String, "parameter description"
58
+ end
59
+
60
+ pp MyTool.tool_schema
61
+ # => {:name=>:my_tool, :description=>"tool description", :parameters=>{:type=>"object",
62
+ # :properties=>{:name=>{:type=>"string", :description=>"parameter description"}}, :required=>[]}}
63
+ ```
64
+
65
+ ### Using Tools with an LLM
66
+
67
+ Tools can easily be called by LLMs using the [llms](https://github.com/benlund/llms) gem
68
+
69
+ ```ruby
70
+ executor = LLMs::Executors.instance(
71
+ model_name: 'claude-sonnet-4-0',
72
+ temperature: 0.0,
73
+ max_completion_tokens: 2048,
74
+ )
75
+
76
+ conversation = LLMs::Conversation.new.tap do |c|
77
+ c.set_available_tools([LLMs::Tool::Calculator]) # Calculator is a simple example tool included in the llms-tool gem
78
+ c.set_system_message("Always use the available tools to answer the question.")
79
+ c.add_user_message("What is (two plus three) times four?")
80
+ end
81
+
82
+ response = executor.execute_conversation(conversation)
83
+ puts response.text
84
+ # => I'll calculate (two plus three) times four for you.
85
+
86
+ pp response.tool_calls
87
+ # => [#<LLMs::ConversationToolCall:0x00000001010474a8
88
+ # @arguments={"expression"=>"(2 + 3) * 4"}, @index=0, @name="calculator",
89
+ # @tool_call_id="toolu_01G3LVCEV1XJ7hwEhzCnrz6J", @tool_call_type="tool_use">]
90
+
91
+ tools = LLMs::Tool::Calculator.new(response.tool_calls.first.arguments)
92
+ pp tools.run
93
+ # => "20.0"
94
+ ```
95
+
96
+ See `examples/llm_tool_use.rb` for a more complete example.
97
+
98
+ ### Complex Parameters
99
+
100
+ You can define complex nested parameters:
101
+
102
+ ```ruby
103
+ class PageDetails < LLMs::Tool::Base
104
+ tool_name :page_details
105
+ description "Describe structured details about a product on a web page"
106
+
107
+ parameter :title, String, "The title of the product", required: true
108
+ parameter :description, String, "The description of the product"
109
+ parameter :dimensions, Hash, "The dimensions of the product" do
110
+ parameter :length, Float, "The length of the product", required: true
111
+ parameter :width, Float, "The width of the product", required: true
112
+ parameter :height, Float, "The height of the product", required: true
113
+ end
114
+ parameter :prices, Array, "List of prices by quantity" do
115
+ parameter :currency, String, "The currency of the price", required: true
116
+ parameter :amount, Float, "The amount of the price", required: true
117
+ parameter :order_quantity_range, String, "The quantity range of the price e.g. '1-99', '100+'", required: false
118
+ end
119
+
120
+ # By default run method will return the parameter values assigned by the LLM, which is what we want
121
+ end
122
+
123
+ pp PageDetails.tool_schema
124
+
125
+ # =>
126
+ # {:name=>:page_details,
127
+ # :description=>"Describe structured details about a product on a web page",
128
+ # :parameters=>
129
+ # {:type=>"object",
130
+ # :properties=>
131
+ # {:title=>{:type=>"string", :description=>"The title of the product"},
132
+ # :description=>{:type=>"string", :description=>"The description of the product"},
133
+ # :dimensions=>
134
+ # {:type=>"object",
135
+ # :description=>"The dimensions of the product",
136
+ # :properties=>
137
+ # {:length=>{:type=>"number", :description=>"The length of the product"},
138
+ # :width=>{:type=>"number", :description=>"The width of the product"},
139
+ # :height=>{:type=>"number", :description=>"The height of the product"}},
140
+ # :required=>["length", "width", "height"]},
141
+ # :prices=>
142
+ # {:type=>"array",
143
+ # :description=>"List of prices by quantity",
144
+ # :items=>
145
+ # {:type=>"object",
146
+ # :properties=>
147
+ # {:currency=>{:type=>"string", :description=>"The currency of the price"},
148
+ # :amount=>{:type=>"number", :description=>"The amount of the price"},
149
+ # :order_quantity_range=>{:type=>"string", :description=>"The quantity range of the price e.g. '1-99', '100+'"}},
150
+ # :required=>["currency", "amount"]}}},
151
+ # :required=>["title"]}}
152
+ ```
153
+
154
+ See the `examples/` directory for runnable examples.
155
+
156
+ ## API Reference
157
+
158
+ ### LLMs::Tool::Base
159
+
160
+ The base class for all tools. Includes the Definition module and provides a default constructor.
161
+
162
+ #### Methods
163
+
164
+ - `initialize(arguments)` - Initialize the tool with arguments object as supplied by an LLM
165
+ - `run(*)` - Placeholder method that subclasses should implement. By default just returns the parameter values
166
+
167
+
168
+ ### LLMs::Tool::Definition
169
+
170
+ A module that provides the DSL for defining tool parameters and generating JSON schemas.
171
+
172
+ #### Class Methods
173
+
174
+ - `tool_name(name = nil)` - Set or get the tool name
175
+ - `description(text = nil)` - Set or get the tool description
176
+ - `parameter(name, type, description, required: false, default: nil, &block)` - Define a parameter
177
+ - `tool_schema` - Generate the JSON schema for the tool
178
+
179
+ #### Instance Methods
180
+
181
+ - `parameter_values` - Get a hash of all parameter values
182
+
183
+ ### Parameter Types
184
+
185
+ The following Ruby types are supported and mapped to JSON schema types:
186
+
187
+ - `String` → `"string"`
188
+ - `Integer` → `"integer"`
189
+ - `Float` → `"number"`
190
+ - `Array` → `"array"`
191
+ - `Hash` → `"object"`
192
+ - `Boolean` → `"boolean"`
193
+
194
+ ## Contributing
195
+
196
+ Bug reports and pull requests are welcome on GitHub at https://github.com/benlund/llms-tool.
197
+
198
+ ## License
199
+
200
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,21 @@
1
+ require_relative 'definition'
2
+
3
+ module LLMs
4
+ module Tool
5
+ class Base
6
+ include Definition
7
+
8
+ def initialize(args)
9
+ ## TODO convert nested hashes to symbol keys too?
10
+ ## TODO validate args against the tool schema and raise an error if they don't match
11
+ initialize_parameters(args.transform_keys(&:to_sym))
12
+ end
13
+
14
+ def run(*)
15
+ # Default implementation is to return the parameter values as a hash
16
+ # subclasses which need to take action should override this
17
+ parameter_values
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,126 @@
1
+ require_relative 'base'
2
+
3
+ module LLMs
4
+ module Tool
5
+ class Calculator < Base
6
+ tool_name "calculator"
7
+ description "A simple calculator that evaluates arithmetic expressions"
8
+
9
+ parameter :expression, String, "The arithmetic expression to evaluate (e.g., '2 + 3 * 4', '(5 + 3) / 2')", required: true
10
+
11
+ def run(*)
12
+ unless valid_expression?(@expression)
13
+ raise ReportableError, "Invalid expression: only numbers, operators (+, -, *, /), parentheses, and spaces are allowed"
14
+ end
15
+ evaluate_expression(@expression).to_s
16
+ end
17
+
18
+ private
19
+
20
+ def valid_expression?(expr)
21
+ # Only allow numbers, operators, parentheses, and spaces
22
+ expr.match?(/^[\d\s\+\-\*\/\(\)\.]+$/)
23
+ end
24
+
25
+ def evaluate_expression(expr)
26
+ # Remove all spaces
27
+ expr = expr.gsub(/\s+/, '')
28
+
29
+ # Simple recursive descent parser for basic arithmetic
30
+ tokens = tokenize(expr)
31
+ parse_expression(tokens)
32
+ end
33
+
34
+ def tokenize(expr)
35
+ tokens = []
36
+ i = 0
37
+
38
+ while i < expr.length
39
+ char = expr[i]
40
+
41
+ case char
42
+ when /\d/
43
+ # Parse number (including decimals)
44
+ num_str = ""
45
+ while i < expr.length && (expr[i] =~ /\d/ || expr[i] == '.')
46
+ num_str += expr[i]
47
+ i += 1
48
+ end
49
+ tokens << { type: :number, value: num_str.to_f }
50
+ next
51
+ when '+', '-', '*', '/', '(', ')'
52
+ tokens << { type: :operator, value: char }
53
+ end
54
+
55
+ i += 1
56
+ end
57
+
58
+ tokens
59
+ end
60
+
61
+ def parse_expression(tokens)
62
+ left = parse_term(tokens)
63
+
64
+ while !tokens.empty? && ['+', '-'].include?(tokens.first[:value])
65
+ op = tokens.shift[:value]
66
+ right = parse_term(tokens)
67
+
68
+ case op
69
+ when '+'
70
+ left += right
71
+ when '-'
72
+ left -= right
73
+ end
74
+ end
75
+
76
+ left
77
+ end
78
+
79
+ def parse_term(tokens)
80
+ left = parse_factor(tokens)
81
+
82
+ while !tokens.empty? && ['*', '/'].include?(tokens.first[:value])
83
+ op = tokens.shift[:value]
84
+ right = parse_factor(tokens)
85
+
86
+ case op
87
+ when '*'
88
+ left *= right
89
+ when '/'
90
+ if right == 0
91
+ raise ArgumentError, "Division by zero"
92
+ end
93
+ left /= right
94
+ end
95
+ end
96
+
97
+ left
98
+ end
99
+
100
+ def parse_factor(tokens)
101
+ if tokens.empty?
102
+ raise ArgumentError, "Unexpected end of expression"
103
+ end
104
+
105
+ token = tokens.shift
106
+
107
+ case token[:type]
108
+ when :number
109
+ token[:value]
110
+ when :operator
111
+ if token[:value] == '('
112
+ result = parse_expression(tokens)
113
+
114
+ if tokens.empty? || tokens.shift[:value] != ')'
115
+ raise ArgumentError, "Missing closing parenthesis"
116
+ end
117
+
118
+ result
119
+ else
120
+ raise ArgumentError, "Unexpected operator: #{token[:value]}"
121
+ end
122
+ end
123
+ end
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,138 @@
1
+ module LLMs
2
+ module Tool
3
+ module Definition
4
+ def self.included(base)
5
+ base.extend(ClassMethods)
6
+ end
7
+
8
+ class PropertyDefinitionSet
9
+ attr_reader :property_definitions
10
+
11
+ def initialize
12
+ @property_definitions = {}
13
+ end
14
+
15
+ def parameter(name, value_type, description, required: false, default: nil, &block)
16
+ @property_definitions[name] = PropertyDefinition.new.tap do |d|
17
+ d.name = name
18
+ d.description = description + (default ? " (default #{default})" : "")
19
+ d.value_type = value_type
20
+ d.is_required = required
21
+ d.default = default
22
+
23
+ if block_given?
24
+ d.value_definition = PropertyDefinitionSet.new.tap do |nested_set|
25
+ nested_set.instance_eval(&block)
26
+ end
27
+ end
28
+ end
29
+ end
30
+
31
+ def to_json_schema
32
+ {
33
+ type: 'object',
34
+ properties: property_definitions.transform_values(&:to_json_schema),
35
+ required: property_definitions.select { |_, prop| prop.is_required }.keys.map(&:to_s)
36
+ }
37
+ end
38
+ end
39
+
40
+ class PropertyDefinition
41
+ attr_accessor :name, :description, :value_type, :is_required, :value_definition, :default
42
+
43
+ def to_json_schema
44
+ schema = {
45
+ type: json_type,
46
+ description: description
47
+ }
48
+
49
+ if value_definition
50
+ if value_type.to_s == 'Array'
51
+ schema[:items] = value_definition.to_json_schema
52
+ else
53
+ schema.merge!(value_definition.to_json_schema)
54
+ end
55
+ end
56
+
57
+ schema
58
+ end
59
+
60
+ private
61
+
62
+ def json_type
63
+ case value_type.to_s
64
+ when 'String' then 'string'
65
+ when 'Integer' then 'integer'
66
+ when 'Float' then 'number'
67
+ when 'Array' then 'array'
68
+ when 'Hash' then 'object'
69
+ when 'TrueClass', 'FalseClass', 'Boolean' then 'boolean'
70
+ else 'string'
71
+ end
72
+ end
73
+ end
74
+
75
+ module ClassMethods
76
+ def property_definition_set
77
+ @property_definition_set ||= PropertyDefinitionSet.new
78
+ end
79
+
80
+ def tool_name(name = nil)
81
+ if name.nil?
82
+ @tool_name ||= (self.name ? self.name.split('::').last.downcase : 'class')
83
+ else
84
+ @tool_name = name
85
+ end
86
+ end
87
+
88
+ def description(text = nil)
89
+ if text.nil?
90
+ @description
91
+ else
92
+ @description = text
93
+ end
94
+ end
95
+
96
+ def parameter(name, type, description, required: false, default: nil, &block)
97
+ property_definition_set.parameter(name, type, description, required: required, default: default, &block)
98
+ end
99
+
100
+ def tool_schema
101
+ {
102
+ name: self.tool_name,
103
+ description: self.description,
104
+ parameters: self.property_definition_set.to_json_schema
105
+ }
106
+ end
107
+ end
108
+
109
+ def initialize_parameters(args)
110
+ # Validate required parameters
111
+ missing = self.class.property_definition_set.property_definitions.select { |_, prop| prop.is_required }.keys.select { |param| !args.key?(param) }
112
+ unless missing.empty?
113
+ raise ArgumentError, "Missing required parameters: #{missing.join(', ')}"
114
+ end
115
+
116
+ # Store parameters as instance variables
117
+ self.class.property_definition_set.property_definitions.each do |param, definition|
118
+ value = args[param]
119
+ value = definition.default if value.nil? && !definition.default.nil?
120
+ instance_variable_set("@#{param}", value)
121
+
122
+ # Define accessor method for this parameter
123
+ self.class.class_eval do
124
+ attr_reader param
125
+ end
126
+ end
127
+ end
128
+
129
+ def parameter_values
130
+ {}.tap do |values|
131
+ self.class.property_definition_set.property_definitions.each do |param, definition|
132
+ values[param.to_s] = instance_variable_get("@#{param}")
133
+ end
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,6 @@
1
+ module LLMs
2
+ module Tool
3
+ class ReportableError < StandardError
4
+ end
5
+ end
6
+ end
data/lib/llms-tool.rb ADDED
@@ -0,0 +1,10 @@
1
+ module LLMs
2
+ module Tool
3
+ VERSION = '0.1.0'
4
+ end
5
+ end
6
+
7
+ require_relative 'llms-tool/definition'
8
+ require_relative 'llms-tool/reportable_error'
9
+ require_relative 'llms-tool/base'
10
+ require_relative 'llms-tool/calculator'
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: llms-tool
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ben Lund
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2025-07-26 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rspec
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3.12'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '3.12'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '13.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '13.0'
41
+ description: LLMs::Tool provides a simple DSL for defining tools that can be serialized
42
+ to the correct JSON schema to be used with LLM systems
43
+ email:
44
+ - ben@benlund.com
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - LICENSE
50
+ - README.md
51
+ - lib/llms-tool.rb
52
+ - lib/llms-tool/base.rb
53
+ - lib/llms-tool/calculator.rb
54
+ - lib/llms-tool/definition.rb
55
+ - lib/llms-tool/reportable_error.rb
56
+ homepage: https://github.com/benlund/llms-tool
57
+ licenses:
58
+ - MIT
59
+ metadata:
60
+ homepage_uri: https://github.com/benlund/llms-tool
61
+ source_code_uri: https://github.com/benlund/llms-tool
62
+ changelog_uri: https://github.com/benlund/llms-tool/blob/main/CHANGELOG.md
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: 2.6.0
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubygems_version: 3.5.11
79
+ signing_key:
80
+ specification_version: 4
81
+ summary: Ruby library for creating LLM tools with a simple DSL
82
+ test_files: []