praxo-core 0.2.0 → 0.3.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.
@@ -1,122 +1,122 @@
1
- require_relative 'json'
2
-
3
- module Praxo
4
- module JsonSchema
5
- ValidationError = Struct.new(:path, :message, keyword_init: true)
6
-
7
- module_function
8
-
9
- def validate(schema, data)
10
- errors = []
11
- visit(schema, data, '$', errors)
12
- errors
13
- end
14
-
15
- def visit(schema, data, path, errors)
16
- return unless schema.is_a?(Hash)
17
- type = schema['type'].is_a?(String) ? schema['type'] : ''
18
- if data.nil?
19
- errors << ValidationError.new(path: path, message: "expected #{type}, got null") unless type.empty?
20
- return
21
- end
22
- case type
23
- when 'object' then visit_object(schema, data, path, errors)
24
- when 'array' then visit_array(schema, data, path, errors)
25
- when 'string' then visit_string(schema, data, path, errors)
26
- when 'number', 'integer' then visit_number(schema, type, data, path, errors)
27
- when 'boolean' then visit_boolean(schema, data, path, errors)
28
- end
29
- end
30
-
31
- def visit_object(schema, data, path, errors)
32
- unless data.is_a?(Hash)
33
- errors << ValidationError.new(path: path, message: 'expected object')
34
- return
35
- end
36
- Array(schema['required']).each do |name|
37
- next unless name.is_a?(String)
38
- unless data.key?(name)
39
- errors << ValidationError.new(path: "#{path}.#{name}", message: 'required field missing')
40
- end
41
- end
42
- properties = schema['properties']
43
- if properties.is_a?(Hash)
44
- properties.each do |name, child|
45
- visit(child, data[name], "#{path}.#{name}", errors) if data.key?(name)
46
- end
47
- end
48
- end
49
-
50
- def visit_array(schema, data, path, errors)
51
- unless data.is_a?(Array)
52
- errors << ValidationError.new(path: path, message: 'expected array')
53
- return
54
- end
55
- items = schema['items']
56
- return unless items.is_a?(Hash)
57
- data.each_with_index { |value, index| visit(items, value, "#{path}[#{index}]", errors) }
58
- end
59
-
60
- def visit_string(schema, data, path, errors)
61
- unless data.is_a?(String)
62
- errors << ValidationError.new(path: path, message: 'expected string')
63
- return
64
- end
65
- length = data.length
66
- min = schema['minLength'].is_a?(Numeric) ? schema['minLength'].to_i : 0
67
- max = schema['maxLength'].is_a?(Numeric) ? schema['maxLength'].to_i : 0
68
- if min.positive? && length < min
69
- errors << ValidationError.new(path: path, message: "min length #{min}, got #{length}")
70
- end
71
- if max.positive? && length > max
72
- errors << ValidationError.new(path: path, message: "max length #{max}, got #{length}")
73
- end
74
- if schema['pattern'].is_a?(String)
75
- begin
76
- regex = Regexp.new(schema['pattern'])
77
- unless regex.match?(data)
78
- errors << ValidationError.new(path: path,
79
- message: "pattern '#{schema['pattern']}' not matched")
80
- end
81
- rescue RegexpError
82
- errors << ValidationError.new(path: path,
83
- message: "invalid pattern '#{schema['pattern']}'")
84
- end
85
- end
86
- check_enum(schema, data, path, errors)
87
- end
88
-
89
- def visit_number(schema, type, data, path, errors)
90
- unless data.is_a?(Numeric)
91
- errors << ValidationError.new(path: path, message: 'expected number')
92
- return
93
- end
94
- if type == 'integer' && data.to_i != data
95
- errors << ValidationError.new(path: path, message: "expected integer, got #{data}")
96
- return
97
- end
98
- check_enum(schema, data, path, errors)
99
- if schema['minimum'].is_a?(Numeric) && schema['minimum'] != 0 && data < schema['minimum']
100
- errors << ValidationError.new(path: path, message: 'value below minimum')
101
- end
102
- if schema['maximum'].is_a?(Numeric) && schema['maximum'] != 0 && data > schema['maximum']
103
- errors << ValidationError.new(path: path, message: 'value above maximum')
104
- end
105
- end
106
-
107
- def visit_boolean(schema, data, path, errors)
108
- unless data == true || data == false
109
- errors << ValidationError.new(path: path, message: 'expected boolean')
110
- return
111
- end
112
- check_enum(schema, data, path, errors)
113
- end
114
-
115
- def check_enum(schema, data, path, errors)
116
- values = schema['enum']
117
- return unless values.is_a?(Array) && !values.empty?
118
- return if values.any? { |value| Json.equals(value, data) }
119
- errors << ValidationError.new(path: path, message: 'value not in enum')
120
- end
121
- end
122
- end
1
+ require_relative 'json'
2
+
3
+ module Praxo
4
+ module JsonSchema
5
+ ValidationError = Struct.new(:path, :message, keyword_init: true)
6
+
7
+ module_function
8
+
9
+ def validate(schema, data)
10
+ errors = []
11
+ visit(schema, data, '$', errors)
12
+ errors
13
+ end
14
+
15
+ def visit(schema, data, path, errors)
16
+ return unless schema.is_a?(Hash)
17
+ type = schema['type'].is_a?(String) ? schema['type'] : ''
18
+ if data.nil?
19
+ errors << ValidationError.new(path: path, message: "expected #{type}, got null") unless type.empty?
20
+ return
21
+ end
22
+ case type
23
+ when 'object' then visit_object(schema, data, path, errors)
24
+ when 'array' then visit_array(schema, data, path, errors)
25
+ when 'string' then visit_string(schema, data, path, errors)
26
+ when 'number', 'integer' then visit_number(schema, type, data, path, errors)
27
+ when 'boolean' then visit_boolean(schema, data, path, errors)
28
+ end
29
+ end
30
+
31
+ def visit_object(schema, data, path, errors)
32
+ unless data.is_a?(Hash)
33
+ errors << ValidationError.new(path: path, message: 'expected object')
34
+ return
35
+ end
36
+ Array(schema['required']).each do |name|
37
+ next unless name.is_a?(String)
38
+ unless data.key?(name)
39
+ errors << ValidationError.new(path: "#{path}.#{name}", message: 'required field missing')
40
+ end
41
+ end
42
+ properties = schema['properties']
43
+ if properties.is_a?(Hash)
44
+ properties.each do |name, child|
45
+ visit(child, data[name], "#{path}.#{name}", errors) if data.key?(name)
46
+ end
47
+ end
48
+ end
49
+
50
+ def visit_array(schema, data, path, errors)
51
+ unless data.is_a?(Array)
52
+ errors << ValidationError.new(path: path, message: 'expected array')
53
+ return
54
+ end
55
+ items = schema['items']
56
+ return unless items.is_a?(Hash)
57
+ data.each_with_index { |value, index| visit(items, value, "#{path}[#{index}]", errors) }
58
+ end
59
+
60
+ def visit_string(schema, data, path, errors)
61
+ unless data.is_a?(String)
62
+ errors << ValidationError.new(path: path, message: 'expected string')
63
+ return
64
+ end
65
+ length = data.length
66
+ min = schema['minLength'].is_a?(Numeric) ? schema['minLength'].to_i : 0
67
+ max = schema['maxLength'].is_a?(Numeric) ? schema['maxLength'].to_i : 0
68
+ if min.positive? && length < min
69
+ errors << ValidationError.new(path: path, message: "min length #{min}, got #{length}")
70
+ end
71
+ if max.positive? && length > max
72
+ errors << ValidationError.new(path: path, message: "max length #{max}, got #{length}")
73
+ end
74
+ if schema['pattern'].is_a?(String)
75
+ begin
76
+ regex = Regexp.new(schema['pattern'])
77
+ unless regex.match?(data)
78
+ errors << ValidationError.new(path: path,
79
+ message: "pattern '#{schema['pattern']}' not matched")
80
+ end
81
+ rescue RegexpError
82
+ errors << ValidationError.new(path: path,
83
+ message: "invalid pattern '#{schema['pattern']}'")
84
+ end
85
+ end
86
+ check_enum(schema, data, path, errors)
87
+ end
88
+
89
+ def visit_number(schema, type, data, path, errors)
90
+ unless data.is_a?(Numeric)
91
+ errors << ValidationError.new(path: path, message: 'expected number')
92
+ return
93
+ end
94
+ if type == 'integer' && data.to_i != data
95
+ errors << ValidationError.new(path: path, message: "expected integer, got #{data}")
96
+ return
97
+ end
98
+ check_enum(schema, data, path, errors)
99
+ if schema['minimum'].is_a?(Numeric) && schema['minimum'] != 0 && data < schema['minimum']
100
+ errors << ValidationError.new(path: path, message: 'value below minimum')
101
+ end
102
+ if schema['maximum'].is_a?(Numeric) && schema['maximum'] != 0 && data > schema['maximum']
103
+ errors << ValidationError.new(path: path, message: 'value above maximum')
104
+ end
105
+ end
106
+
107
+ def visit_boolean(schema, data, path, errors)
108
+ unless data == true || data == false
109
+ errors << ValidationError.new(path: path, message: 'expected boolean')
110
+ return
111
+ end
112
+ check_enum(schema, data, path, errors)
113
+ end
114
+
115
+ def check_enum(schema, data, path, errors)
116
+ values = schema['enum']
117
+ return unless values.is_a?(Array) && !values.empty?
118
+ return if values.any? { |value| Json.equals(value, data) }
119
+ errors << ValidationError.new(path: path, message: 'value not in enum')
120
+ end
121
+ end
122
+ end
@@ -1,133 +1,138 @@
1
- require_relative 'errors'
2
- require_relative 'json'
3
- require_relative 'jsonschema'
4
- require_relative 'models'
5
-
6
- module Praxo
7
- module Middleware
8
- class PiiRedactor
9
- RULES = [
10
- [/[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/, '[REDACTED:email]'],
11
- [/\b\d{3}-\d{2}-\d{4}\b/, '[REDACTED:ssn]'],
12
- [/\b(?:\d{4}[ -]?){3}\d{4}\b/, '[REDACTED:credit_card]']
13
- ].freeze
14
-
15
- def redact(text)
16
- output = text.to_s.dup
17
- RULES.each { |pattern, replacement| output.gsub!(pattern, replacement) }
18
- output
19
- end
20
-
21
- def redact_value(value)
22
- case value
23
- when String then redact(value)
24
- when Array then value.map { |item| redact_value(item) }
25
- when Hash then value.transform_values { |item| redact_value(item) }
26
- else value
27
- end
28
- end
29
- end
30
-
31
- class StructuredOutput
32
- def initialize(schema:, max_repairs: 0, repairer: nil)
33
- @schema = schema
34
- @max_repairs = max_repairs
35
- @repairer = repairer
36
- end
37
-
38
- def apply(text)
39
- output = text.to_s
40
- (0..@max_repairs).each do |attempt|
41
- begin
42
- data = Middleware.extract_json(output)
43
- return [output, nil] if JsonSchema.validate(@schema, data).empty?
44
- rescue StandardError
45
- nil
46
- end
47
- break if attempt == @max_repairs && @repairer.nil?
48
- break unless @repairer
49
- repaired = @repairer.call(output)
50
- break if repaired.nil? || repaired.strip.empty?
51
- output = repaired
52
- end
53
- [nil, 'AGENT_STRUCTURED_OUTPUT']
54
- end
55
- end
56
-
57
- class CallLimit
58
- def initialize(model_limit:, tool_limit:)
59
- @model_limit = model_limit
60
- @tool_limit = tool_limit
61
- @models = 0
62
- @tools = 0
63
- end
64
-
65
- def before_model
66
- @models += 1
67
- if @model_limit.positive? && @models > @model_limit
68
- Praxo.error('AGENT_MODEL_CALL_LIMIT', 'model call limit')
69
- end
70
- end
71
-
72
- def before_tool
73
- @tools += 1
74
- if @tool_limit.positive? && @tools > @tool_limit
75
- Praxo.error('AGENT_TOOL_CALL_LIMIT', 'tool call limit')
76
- end
77
- end
78
- end
79
-
80
- class ToolSelection
81
- def initialize(selected)
82
- @selected = selected.to_h { |name| [name, true] }
83
- end
84
-
85
- def filter(tools)
86
- tools.select { |tool| @selected[tool.name] }
87
- end
88
-
89
- def reject(name)
90
- Praxo.error('AGENT_TOOL_NOT_SELECTED', 'tool not selected') unless @selected[name]
91
- end
92
- end
93
-
94
- module_function
95
-
96
- def extract_json(text)
97
- value = text.to_s.strip
98
- if value.start_with?('```')
99
- newline = value.index("\n")
100
- value = value[(newline + 1)..] if newline
101
- value = value.gsub(/\A`+/, '').gsub(/`+\z/, '').strip
102
- end
103
- start = [value.index('{'), value.index('[')].compact.min
104
- raise Praxo::Error.new('AGENT_STRUCTURED_OUTPUT', 'output does not contain JSON') if start.nil?
105
- Json.parse(value[start..])
106
- end
107
-
108
- def redact(text)
109
- PiiRedactor.new.redact(text)
110
- end
111
-
112
- def redact_value(value)
113
- PiiRedactor.new.redact_value(value)
114
- end
115
-
116
- def structured_apply(schema, text, max_repairs = 0, repairer = nil)
117
- StructuredOutput.new(schema: schema, max_repairs: max_repairs, repairer: repairer).apply(text)
118
- end
119
-
120
- def fallback_model(fallback)
121
- lambda do |next_handler|
122
- lambda do |request|
123
- begin
124
- next_handler.call(request)
125
- rescue StandardError
126
- raise unless fallback
127
- fallback.call(request)
128
- end
129
- end
130
- end
131
- end
132
- end
133
- end
1
+ require_relative 'errors'
2
+ require_relative 'json'
3
+ require_relative 'jsonschema'
4
+ require_relative 'models'
5
+
6
+ module Praxo
7
+ module Middleware
8
+ class PiiRedactor
9
+ RULES = [
10
+ [/[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/, '[REDACTED:email]'],
11
+ [/\b\d{3}-\d{2}-\d{4}\b/, '[REDACTED:ssn]'],
12
+ [/\b(?:\d{4}[ -]?){3}\d{4}\b/, '[REDACTED:credit_card]']
13
+ ].freeze
14
+
15
+ def redact(text)
16
+ output = text.to_s.dup
17
+ RULES.each { |pattern, replacement| output.gsub!(pattern, replacement) }
18
+ output
19
+ end
20
+
21
+ def redact_value(value)
22
+ case value
23
+ when String then redact(value)
24
+ when Array then value.map { |item| redact_value(item) }
25
+ when Hash then value.transform_values { |item| redact_value(item) }
26
+ else value
27
+ end
28
+ end
29
+ end
30
+
31
+ class StructuredOutput
32
+ def initialize(schema:, max_repairs: 0, repairer: nil)
33
+ @schema = schema
34
+ @max_repairs = max_repairs
35
+ @repairer = repairer
36
+ end
37
+
38
+ def apply(text)
39
+ output = text.to_s
40
+ (0..@max_repairs).each do |attempt|
41
+ begin
42
+ data = Middleware.extract_json(output)
43
+ return [output, nil] if JsonSchema.validate(@schema, data).empty?
44
+ rescue StandardError
45
+ nil
46
+ end
47
+ break if attempt == @max_repairs && @repairer.nil?
48
+ break unless @repairer
49
+ repaired = @repairer.call(output)
50
+ break if repaired.nil? || repaired.strip.empty?
51
+ output = repaired
52
+ end
53
+ [nil, 'AGENT_STRUCTURED_OUTPUT']
54
+ end
55
+ end
56
+
57
+ class CallLimit
58
+ def initialize(model_limit:, tool_limit:)
59
+ @model_limit = model_limit
60
+ @tool_limit = tool_limit
61
+ @runs = Hash.new { |hash, key| hash[key] = { models: 0, tools: 0 } }
62
+ end
63
+
64
+ def before_run(state)
65
+ @runs[state[:run_id]] = { models: 0, tools: 0 }
66
+ end
67
+
68
+ def before_model(run_id = :default)
69
+ counts = @runs[run_id]
70
+ counts[:models] += 1
71
+ if @model_limit.positive? && counts[:models] > @model_limit
72
+ Praxo.error('AGENT_MODEL_CALL_LIMIT', 'model call limit')
73
+ end
74
+ end
75
+
76
+ def before_tool(run_id = :default)
77
+ counts = @runs[run_id]
78
+ counts[:tools] += 1
79
+ if @tool_limit.positive? && counts[:tools] > @tool_limit
80
+ Praxo.error('AGENT_TOOL_CALL_LIMIT', 'tool call limit')
81
+ end
82
+ end
83
+ end
84
+
85
+ class ToolSelection
86
+ def initialize(selected)
87
+ @selected = selected.to_h { |name| [name, true] }
88
+ end
89
+
90
+ def filter(tools)
91
+ tools.select { |tool| @selected[tool.name] }
92
+ end
93
+
94
+ def reject(name)
95
+ Praxo.error('AGENT_TOOL_NOT_SELECTED', 'tool not selected') unless @selected[name]
96
+ end
97
+ end
98
+
99
+ module_function
100
+
101
+ def extract_json(text)
102
+ value = text.to_s.strip
103
+ if value.start_with?('```')
104
+ newline = value.index("\n")
105
+ value = value[(newline + 1)..] if newline
106
+ value = value.gsub(/\A`+/, '').gsub(/`+\z/, '').strip
107
+ end
108
+ start = [value.index('{'), value.index('[')].compact.min
109
+ raise Praxo::Error.new('AGENT_STRUCTURED_OUTPUT', 'output does not contain JSON') if start.nil?
110
+ Json.parse(value[start..])
111
+ end
112
+
113
+ def redact(text)
114
+ PiiRedactor.new.redact(text)
115
+ end
116
+
117
+ def redact_value(value)
118
+ PiiRedactor.new.redact_value(value)
119
+ end
120
+
121
+ def structured_apply(schema, text, max_repairs = 0, repairer = nil)
122
+ StructuredOutput.new(schema: schema, max_repairs: max_repairs, repairer: repairer).apply(text)
123
+ end
124
+
125
+ def fallback_model(fallback)
126
+ lambda do |next_handler|
127
+ lambda do |request|
128
+ begin
129
+ next_handler.call(request)
130
+ rescue StandardError
131
+ raise unless fallback
132
+ fallback.call(request)
133
+ end
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end