pikuri-core 0.0.5 → 0.0.7
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 +4 -4
- data/README.md +5 -3
- data/lib/pikuri/agent/chat_transport.rb +135 -11
- data/lib/pikuri/agent/configurator.rb +4 -4
- data/lib/pikuri/agent/context_window_detector.rb +103 -52
- data/lib/pikuri/agent/control/step_limit.rb +39 -7
- data/lib/pikuri/agent/event.rb +43 -16
- data/lib/pikuri/agent/extension.rb +31 -17
- data/lib/pikuri/agent/extension_context.rb +147 -0
- data/lib/pikuri/agent/listener/terminal.rb +30 -37
- data/lib/pikuri/agent/listener/token_log.rb +60 -13
- data/lib/pikuri/agent/listener.rb +12 -5
- data/lib/pikuri/agent/listener_list.rb +7 -17
- data/lib/pikuri/agent/synthesizer.rb +93 -67
- data/lib/pikuri/agent.rb +358 -403
- data/lib/pikuri/extractor/html.rb +303 -0
- data/lib/pikuri/extractor/passthrough.rb +64 -0
- data/lib/pikuri/extractor.rb +314 -0
- data/lib/pikuri/file_type.rb +74 -266
- data/lib/pikuri/sanitizer.rb +179 -0
- data/lib/pikuri/subprocess.rb +73 -2
- data/lib/pikuri/tool/calculator.rb +213 -41
- data/lib/pikuri/tool/fetch.rb +10 -9
- data/lib/pikuri/tool/parameters.rb +65 -2
- data/lib/pikuri/tool/scraper.rb +186 -0
- data/lib/pikuri/tool/search/brave.rb +32 -18
- data/lib/pikuri/tool/search/duckduckgo.rb +18 -7
- data/lib/pikuri/tool/search/engines.rb +72 -49
- data/lib/pikuri/tool/search/exa.rb +34 -22
- data/lib/pikuri/tool/web_scrape.rb +5 -5
- data/lib/pikuri/tool/web_search.rb +45 -26
- data/lib/pikuri/version.rb +1 -1
- data/lib/pikuri-core.rb +11 -10
- metadata +9 -66
- data/lib/pikuri/tool/scraper/fetch_error.rb +0 -16
- data/lib/pikuri/tool/scraper/html.rb +0 -285
- data/lib/pikuri/tool/scraper/pdf.rb +0 -54
- data/lib/pikuri/tool/scraper/simple.rb +0 -183
data/lib/pikuri/subprocess.rb
CHANGED
|
@@ -7,8 +7,10 @@ module Pikuri
|
|
|
7
7
|
# Chokepoint for *all* subprocess spawning in pikuri. Forces a new
|
|
8
8
|
# process group for each invocation, tracks pgids so descendants of
|
|
9
9
|
# the direct child (commands backgrounded with +&+) can be cleaned
|
|
10
|
-
# up at process exit
|
|
11
|
-
# single pipe
|
|
10
|
+
# up at process exit. Two front doors: {.spawn} (combined
|
|
11
|
+
# stdout+stderr through a single pipe — the shell-command shape) and
|
|
12
|
+
# {.run} (stdin fed from a String or streamed from an IO, stdout
|
|
13
|
+
# redirected to a file, stderr captured — the filter shape).
|
|
12
14
|
#
|
|
13
15
|
# == Seam discipline
|
|
14
16
|
#
|
|
@@ -91,6 +93,75 @@ module Pikuri
|
|
|
91
93
|
new(io: io, wait_thr: wait_thr)
|
|
92
94
|
end
|
|
93
95
|
|
|
96
|
+
# Run +argv+ as a one-shot *filter*: feed it +stdin_data+, redirect
|
|
97
|
+
# its stdout straight to +stdout+ (an open +File+), capture stderr
|
|
98
|
+
# through a pipe, and block until it exits. Built for the
|
|
99
|
+
# stdin→markdown document converters (pikuri-extractors), where
|
|
100
|
+
# {.spawn}'s shape is wrong twice over: it closes the child's stdin
|
|
101
|
+
# immediately, and it merges stderr onto stdout — fatal when stdout
|
|
102
|
+
# *is* the payload and a converter's warnings would corrupt it.
|
|
103
|
+
#
|
|
104
|
+
# Redirecting stdout to a file (not a pipe) is also what makes the
|
|
105
|
+
# I/O deadlock-free with one writer thread: the child never blocks
|
|
106
|
+
# writing output, so it keeps draining stdin, while the parent
|
|
107
|
+
# drains the (low-volume) stderr pipe. The returned
|
|
108
|
+
# {Result#output} is the captured *stderr* — the diagnostics — not
|
|
109
|
+
# the payload; the payload is in +stdout+, whose file offset is
|
|
110
|
+
# shared with the child, so rewind before reading it back.
|
|
111
|
+
#
|
|
112
|
+
# Same discipline as {.spawn}: new process group, registered for
|
|
113
|
+
# the exit sweep, no built-in timeout (wrap +argv+ with coreutils'
|
|
114
|
+
# +timeout+ — see the class docs).
|
|
115
|
+
#
|
|
116
|
+
# @param argv [Array<String>] command and arguments, passed to
|
|
117
|
+
# +exec+ directly — no implicit shell.
|
|
118
|
+
# @param stdin_data [String, IO, StringIO] the child's stdin: a
|
|
119
|
+
# String is written as-is, an IO is streamed through
|
|
120
|
+
# +IO.copy_stream+ (so a large source file never materialises in
|
|
121
|
+
# the Ruby heap) and read from its current position. Either way
|
|
122
|
+
# stdin is closed (EOF) afterwards. May be empty.
|
|
123
|
+
# @param stdout [File] open writable file the child's stdout is
|
|
124
|
+
# redirected to.
|
|
125
|
+
# @param chdir [String, Pathname] working directory.
|
|
126
|
+
# @param env [Hash{String=>String}] extra environment variables,
|
|
127
|
+
# as for {.spawn}.
|
|
128
|
+
# @return [Result] +output+ is the captured stderr; +status+ the
|
|
129
|
+
# child's exit status.
|
|
130
|
+
# @raise [SystemCallError] whatever an IO +stdin_data+ raises
|
|
131
|
+
# mid-stream (disk error, closed handle) — re-raised here after
|
|
132
|
+
# the child has been reaped.
|
|
133
|
+
def self.run(*argv, stdin_data:, stdout:, chdir:, env: {})
|
|
134
|
+
in_r, in_w = IO.pipe
|
|
135
|
+
err_r, err_w = IO.pipe
|
|
136
|
+
pid = Process.spawn(env, *argv, chdir: chdir.to_s, pgroup: true,
|
|
137
|
+
in: in_r, out: stdout, err: err_w)
|
|
138
|
+
in_r.close
|
|
139
|
+
err_w.close
|
|
140
|
+
register(pid)
|
|
141
|
+
writer = Thread.new do
|
|
142
|
+
in_w.binmode
|
|
143
|
+
if stdin_data.respond_to?(:read)
|
|
144
|
+
IO.copy_stream(stdin_data, in_w)
|
|
145
|
+
else
|
|
146
|
+
in_w.write(stdin_data)
|
|
147
|
+
end
|
|
148
|
+
rescue Errno::EPIPE
|
|
149
|
+
nil # child exited without draining stdin; its status tells the story
|
|
150
|
+
ensure
|
|
151
|
+
in_w.close
|
|
152
|
+
end
|
|
153
|
+
stderr = err_r.read
|
|
154
|
+
err_r.close
|
|
155
|
+
# Reap before joining the writer: if an IO source raised
|
|
156
|
+
# mid-stream, #join re-raises it, and the child (already exited —
|
|
157
|
+
# err_r hit EOF) must not be left a zombie.
|
|
158
|
+
_, status = Process.waitpid2(pid)
|
|
159
|
+
writer.join
|
|
160
|
+
Result.new(output: stderr, status: status)
|
|
161
|
+
ensure
|
|
162
|
+
prune(pid) if pid
|
|
163
|
+
end
|
|
164
|
+
|
|
94
165
|
# @return [Integer] direct child's pid
|
|
95
166
|
attr_reader :pid
|
|
96
167
|
|
|
@@ -1,63 +1,235 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require 'dentaku'
|
|
4
|
-
|
|
5
3
|
module Pikuri
|
|
6
4
|
class Tool
|
|
7
|
-
# Evaluates a basic arithmetic expression
|
|
8
|
-
#
|
|
9
|
-
#
|
|
5
|
+
# Evaluates a basic arithmetic expression with Python operator
|
|
6
|
+
# syntax and semantics, via the hand-rolled recursive-descent
|
|
7
|
+
# {Parser} below.
|
|
8
|
+
#
|
|
9
|
+
# Why hand-rolled rather than a gem: the previous backend, dentaku,
|
|
10
|
+
# pulled in concurrent-ruby (~16k lines of Ruby — the single
|
|
11
|
+
# heaviest audit item in pikuri's whole dependency closure) plus
|
|
12
|
+
# bigdecimal and tsort, all to evaluate four-function arithmetic.
|
|
13
|
+
# The ~100 lines here implement Python's expression grammar
|
|
14
|
+
# directly, which also retires the old preprocessing step that
|
|
15
|
+
# rewrote Python's +**+ into dentaku's +^+ dialect — the model's
|
|
16
|
+
# native syntax is now simply the grammar.
|
|
10
17
|
#
|
|
11
|
-
# Scope is intentionally narrow: operators (+, -, *, /,
|
|
12
|
-
# parentheses, and
|
|
13
|
-
# booleans — those would mean
|
|
14
|
-
# specifically want to avoid
|
|
18
|
+
# Scope is intentionally narrow: operators (+, -, *, /, //, %, **),
|
|
19
|
+
# unary minus, parentheses, and integer / decimal / e-notation
|
|
20
|
+
# literals. No variables, functions, or booleans — those would mean
|
|
21
|
+
# teaching the model a dialect, which we specifically want to avoid
|
|
22
|
+
# for this tool.
|
|
15
23
|
module Calculator
|
|
16
|
-
#
|
|
17
|
-
#
|
|
18
|
-
#
|
|
19
|
-
#
|
|
20
|
-
#
|
|
21
|
-
|
|
22
|
-
def self.normalize(expression)
|
|
23
|
-
expression.gsub('**', '^')
|
|
24
|
-
end
|
|
24
|
+
# Raised internally for anything {.calculate} should hand back to
|
|
25
|
+
# the model as an +"Error: ..."+ observation rather than crash
|
|
26
|
+
# the agent loop: parse failures, division by zero, complex or
|
|
27
|
+
# non-finite results. The message always names the offending
|
|
28
|
+
# token or operands.
|
|
29
|
+
class Error < StandardError; end
|
|
25
30
|
|
|
26
|
-
# Evaluate +expression+ and return the result formatted as a
|
|
27
|
-
# Parse
|
|
28
|
-
#
|
|
29
|
-
#
|
|
30
|
-
# crashing the
|
|
31
|
+
# Evaluate +expression+ and return the result formatted as a
|
|
32
|
+
# String. Parse and arithmetic failures (division by zero,
|
|
33
|
+
# overflow to infinity, complex results) are caught and returned
|
|
34
|
+
# as +"Error: ..."+ strings so the model can read the failure as
|
|
35
|
+
# the next observation and self-correct rather than crashing the
|
|
36
|
+
# agent loop.
|
|
31
37
|
#
|
|
32
|
-
# @param expression [String]
|
|
38
|
+
# @param expression [String] Python-syntax arithmetic expression
|
|
33
39
|
# @return [String] numeric result, or +"Error: ..."+ on failure
|
|
34
40
|
def self.calculate(expression)
|
|
35
|
-
result =
|
|
41
|
+
result = Parser.new(expression).parse
|
|
42
|
+
if result.is_a?(Float) && !result.finite?
|
|
43
|
+
raise Error, "result of #{expression.inspect} is not a finite number"
|
|
44
|
+
end
|
|
45
|
+
|
|
36
46
|
format_result(result)
|
|
37
|
-
rescue
|
|
38
|
-
'Error: division by zero'
|
|
39
|
-
rescue Dentaku::Error => e
|
|
47
|
+
rescue Error => e
|
|
40
48
|
"Error: #{e.message}"
|
|
41
49
|
end
|
|
42
50
|
|
|
43
|
-
#
|
|
44
|
-
#
|
|
45
|
-
#
|
|
46
|
-
#
|
|
47
|
-
#
|
|
51
|
+
# Integers (never produced by division — +/+ is Python-3-style
|
|
52
|
+
# true division) pass through exact. Floats are rounded to 3
|
|
53
|
+
# places so the model sees a short readable number, and
|
|
54
|
+
# whole-valued floats drop the trailing +.0+ (+4 / 2+ renders as
|
|
55
|
+
# +"2"+, not +"2.0"+).
|
|
48
56
|
def self.format_result(result)
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
57
|
+
return result.to_s if result.is_a?(Integer)
|
|
58
|
+
|
|
59
|
+
rounded = result.round(3)
|
|
60
|
+
rounded == rounded.truncate ? rounded.truncate.to_s : rounded.to_s
|
|
53
61
|
end
|
|
54
62
|
private_class_method :format_result
|
|
63
|
+
|
|
64
|
+
# Recursive-descent parser-evaluator for Python's arithmetic
|
|
65
|
+
# expression grammar:
|
|
66
|
+
#
|
|
67
|
+
# additive := multiplicative (('+' | '-') multiplicative)*
|
|
68
|
+
# multiplicative := unary (('*' | '/' | '//' | '%') unary)*
|
|
69
|
+
# unary := ('+' | '-') unary | power
|
|
70
|
+
# power := atom ('**' unary)?
|
|
71
|
+
# atom := NUMBER | '(' additive ')'
|
|
72
|
+
#
|
|
73
|
+
# The +power+ → +unary+ recursion on the right operand is what
|
|
74
|
+
# makes +**+ right-associative (+2**3**2+ is 512) and lets a sign
|
|
75
|
+
# follow it (+2**-3+); +unary+ sitting *above* +power+ on the
|
|
76
|
+
# left is what makes +-2**2+ evaluate to -4 — both exactly as
|
|
77
|
+
# Python parses them.
|
|
78
|
+
#
|
|
79
|
+
# Semantics follow Python 3 where Ruby differs: +/+ is always
|
|
80
|
+
# true (float) division, +//+ floors, +2**-1+ is the Float 0.5
|
|
81
|
+
# (Ruby would return a Rational), and a negative base under a
|
|
82
|
+
# fractional exponent is rejected (Ruby would return a Complex).
|
|
83
|
+
class Parser
|
|
84
|
+
# One number or operator. +**+ / +//+ listed before their
|
|
85
|
+
# single-character prefixes so the two-character operators win;
|
|
86
|
+
# number literals cover +42+, +4.2+, +5.+, +.5+, and e-notation
|
|
87
|
+
# on any of them. +\G+ anchors each match at the scan position
|
|
88
|
+
# so nothing between tokens goes unnoticed.
|
|
89
|
+
TOKEN_RE = %r{\G\s*(\*\*|//|\d+(?:\.\d*)?(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?|[-+*/%()])}
|
|
90
|
+
|
|
91
|
+
# @param expression [String] raw expression as the model wrote it
|
|
92
|
+
# @raise [Error] when +expression+ contains a character no token matches
|
|
93
|
+
def initialize(expression)
|
|
94
|
+
@tokens = tokenize(expression)
|
|
95
|
+
@pos = 0
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# Parse and evaluate the whole token stream.
|
|
99
|
+
#
|
|
100
|
+
# @return [Integer, Float] the value of the expression
|
|
101
|
+
# @raise [Error] on syntax errors, division by zero, or a complex result
|
|
102
|
+
def parse
|
|
103
|
+
value = additive
|
|
104
|
+
raise Error, "unexpected #{peek.inspect} after expression" if peek
|
|
105
|
+
|
|
106
|
+
value
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
private
|
|
110
|
+
|
|
111
|
+
# @param expression [String]
|
|
112
|
+
# @return [Array<String>] token strings in source order
|
|
113
|
+
def tokenize(expression)
|
|
114
|
+
tokens = []
|
|
115
|
+
pos = 0
|
|
116
|
+
while (match = TOKEN_RE.match(expression, pos))
|
|
117
|
+
tokens << match[1]
|
|
118
|
+
pos = match.end(0)
|
|
119
|
+
end
|
|
120
|
+
rest = expression[pos..].to_s.strip
|
|
121
|
+
raise Error, "unexpected character #{rest[0].inspect} in #{expression.inspect}" unless rest.empty?
|
|
122
|
+
|
|
123
|
+
tokens
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def additive
|
|
127
|
+
value = multiplicative
|
|
128
|
+
while (op = accept('+', '-'))
|
|
129
|
+
rhs = multiplicative
|
|
130
|
+
value = op == '+' ? value + rhs : value - rhs
|
|
131
|
+
end
|
|
132
|
+
value
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def multiplicative
|
|
136
|
+
value = unary
|
|
137
|
+
while (op = accept('*', '/', '//', '%'))
|
|
138
|
+
value = apply_multiplicative(op, value, unary)
|
|
139
|
+
end
|
|
140
|
+
value
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def unary
|
|
144
|
+
op = accept('+', '-')
|
|
145
|
+
return power unless op
|
|
146
|
+
|
|
147
|
+
value = unary
|
|
148
|
+
op == '-' ? -value : value
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def power
|
|
152
|
+
base = atom
|
|
153
|
+
return base unless accept('**')
|
|
154
|
+
|
|
155
|
+
apply_power(base, unary)
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
def atom
|
|
159
|
+
return parenthesized if accept('(')
|
|
160
|
+
|
|
161
|
+
token = peek
|
|
162
|
+
unless token&.match?(/\A[.\d]/)
|
|
163
|
+
raise Error, token ? "unexpected #{token.inspect}" : 'unexpected end of expression'
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
@pos += 1
|
|
167
|
+
token.match?(/[.eE]/) ? token.to_f : token.to_i
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
def parenthesized
|
|
171
|
+
value = additive
|
|
172
|
+
raise Error, 'missing closing parenthesis' unless accept(')')
|
|
173
|
+
|
|
174
|
+
value
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# @return [String, nil] the next token without consuming it
|
|
178
|
+
def peek
|
|
179
|
+
@tokens[@pos]
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# Consume and return the next token if it is one of +expected+.
|
|
183
|
+
#
|
|
184
|
+
# @return [String, nil] the consumed token, or nil on no match
|
|
185
|
+
def accept(*expected)
|
|
186
|
+
token = peek
|
|
187
|
+
return nil unless expected.include?(token)
|
|
188
|
+
|
|
189
|
+
@pos += 1
|
|
190
|
+
token
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
# +/+ is Python-3 true division (always Float); +//+ floors
|
|
194
|
+
# (kept exact in Ruby's arbitrary-precision Integer division
|
|
195
|
+
# when both operands are Integers — Ruby's +Integer#/+ already
|
|
196
|
+
# floors like Python's +//+); +%+ delegates to Ruby's +%+,
|
|
197
|
+
# whose sign-of-divisor semantics match Python's exactly.
|
|
198
|
+
def apply_multiplicative(op, lhs, rhs)
|
|
199
|
+
return lhs * rhs if op == '*'
|
|
200
|
+
raise Error, 'division by zero' if rhs.zero?
|
|
201
|
+
|
|
202
|
+
case op
|
|
203
|
+
when '/' then lhs.fdiv(rhs)
|
|
204
|
+
when '//' then lhs.is_a?(Integer) && rhs.is_a?(Integer) ? lhs / rhs : lhs.fdiv(rhs).floor
|
|
205
|
+
when '%' then lhs % rhs
|
|
206
|
+
end
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
# Two Python-compatibility shims over Ruby's +**+: an Integer
|
|
210
|
+
# raised to a negative Integer yields a Float (Ruby would
|
|
211
|
+
# return a Rational), and a Complex result — negative base
|
|
212
|
+
# under a fractional exponent — is rejected loudly.
|
|
213
|
+
def apply_power(base, exponent)
|
|
214
|
+
if base.is_a?(Integer) && exponent.is_a?(Integer) && exponent.negative?
|
|
215
|
+
raise Error, 'division by zero' if base.zero?
|
|
216
|
+
|
|
217
|
+
return base.to_f**exponent
|
|
218
|
+
end
|
|
219
|
+
result = base**exponent
|
|
220
|
+
if result.is_a?(Complex)
|
|
221
|
+
raise Error, "(#{base})**(#{exponent}) is a complex number; only real arithmetic is supported"
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
result
|
|
225
|
+
end
|
|
226
|
+
end
|
|
55
227
|
end
|
|
56
228
|
|
|
57
229
|
# Arithmetic-evaluation tool backed by {Tool::Calculator.calculate}.
|
|
58
|
-
# Accepts Python
|
|
59
|
-
# exponentiation,
|
|
60
|
-
# syntax it already knows.
|
|
230
|
+
# Accepts Python expression syntax (+, -, *, /, //, %, ** for
|
|
231
|
+
# exponentiation, unary minus, parentheses, decimals) so the model
|
|
232
|
+
# can emit the syntax it already knows.
|
|
61
233
|
#
|
|
62
234
|
# @return [Tool]
|
|
63
235
|
CALCULATOR = new(
|
|
@@ -67,7 +239,7 @@ module Pikuri
|
|
|
67
239
|
|
|
68
240
|
Usage:
|
|
69
241
|
- Use this for any arithmetic beyond simple mental math — do not eyeball multi-digit work.
|
|
70
|
-
-
|
|
242
|
+
- Python expression syntax: +, -, *, / (true division), // (floor division), % (modulo), ** (exponentiation), unary minus, parentheses, decimal numbers.
|
|
71
243
|
- Decimal results are rounded to 3 places; integer results are exact.
|
|
72
244
|
- Failures (parse error, division by zero) come back as "Error: ..." — read the message and re-call with a corrected expression.
|
|
73
245
|
DESC
|
data/lib/pikuri/tool/fetch.rb
CHANGED
|
@@ -3,13 +3,14 @@
|
|
|
3
3
|
module Pikuri
|
|
4
4
|
class Tool
|
|
5
5
|
# Truncation policy and Tool spec for the +fetch+ tool. The HTTP work
|
|
6
|
-
# lives in {Tool::Scraper
|
|
6
|
+
# lives in {Tool::Scraper.fetch}; this module is a thin
|
|
7
7
|
# wrapper that accepts only textual content-types, applies a character
|
|
8
8
|
# cap so the LLM doesn't drown in long-form bodies, and exposes the
|
|
9
9
|
# result to the agent loop in OpenAI tool-call shape.
|
|
10
10
|
#
|
|
11
|
-
# Sister of {Tool::WebScrape}, but
|
|
12
|
-
#
|
|
11
|
+
# Sister of {Tool::WebScrape}, but with no extraction pass
|
|
12
|
+
# (HTML→Markdown, or whatever plug-in extractors are registered):
|
|
13
|
+
# bodies are returned verbatim. Useful for raw textual
|
|
13
14
|
# data — JSON APIs, CSV files, +robots.txt+, sitemaps, source files —
|
|
14
15
|
# where any rendering pass would corrupt the payload.
|
|
15
16
|
module Fetch
|
|
@@ -56,7 +57,7 @@ module Pikuri
|
|
|
56
57
|
CACHE
|
|
57
58
|
end
|
|
58
59
|
|
|
59
|
-
# Download +url+ via {Tool::Scraper
|
|
60
|
+
# Download +url+ via {Tool::Scraper.fetch} and return the
|
|
60
61
|
# response body verbatim, provided the content-type is one we deem
|
|
61
62
|
# textual (any +text/*+, plus the formats listed in
|
|
62
63
|
# {TEXTUAL_APPLICATION_TYPES}). Anything else — PDFs, images, other
|
|
@@ -100,16 +101,16 @@ module Pikuri
|
|
|
100
101
|
# redirect-loop exhaustion, missing +Location+ on a 3xx, or a
|
|
101
102
|
# non-textual content-type
|
|
102
103
|
def self.download(url)
|
|
103
|
-
fetched = Scraper
|
|
104
|
+
fetched = Scraper.fetch(url)
|
|
104
105
|
return fetched.body if textual?(fetched.content_type)
|
|
105
106
|
|
|
106
107
|
raise Scraper::FetchError,
|
|
107
108
|
"refused to fetch #{url}: content-type #{fetched.content_type.inspect} " \
|
|
108
|
-
'is not textual (use web_scrape for
|
|
109
|
+
'is not textual (use web_scrape for rendered pages)'
|
|
109
110
|
end
|
|
110
111
|
|
|
111
112
|
# @param content_type [String] normalized content-type (no +charset+
|
|
112
|
-
# parameter, lowercased) as produced by {Scraper
|
|
113
|
+
# parameter, lowercased) as produced by {Scraper.fetch}
|
|
113
114
|
# @return [Boolean] true when the content-type is +text/*+ or one
|
|
114
115
|
# of {TEXTUAL_APPLICATION_TYPES}
|
|
115
116
|
def self.textual?(content_type)
|
|
@@ -138,7 +139,7 @@ module Pikuri
|
|
|
138
139
|
# Verbatim URL download tool. Thin wrapper over {Tool::Fetch.fetch}
|
|
139
140
|
# that exposes it to the agent loop in OpenAI tool-call shape. Use for
|
|
140
141
|
# raw textual payloads (JSON APIs, CSV files, +robots.txt+, source
|
|
141
|
-
# files); use {Tool::WEB_SCRAPE} for rendered web pages
|
|
142
|
+
# files); use {Tool::WEB_SCRAPE} for rendered web pages where
|
|
142
143
|
# readability extraction makes the result usable.
|
|
143
144
|
#
|
|
144
145
|
# @return [Tool]
|
|
@@ -149,7 +150,7 @@ module Pikuri
|
|
|
149
150
|
|
|
150
151
|
Usage:
|
|
151
152
|
- Use for raw textual payloads: JSON APIs, CSV files, robots.txt, sitemaps, source files — anywhere a rendering pass would corrupt the data.
|
|
152
|
-
- For rendered HTML pages
|
|
153
|
+
- For rendered HTML pages, use web_scrape — it extracts readable content; fetch returns the raw HTML bytes unchanged.
|
|
153
154
|
- Accepts text/* and common textual application/* types (JSON, XML, JS, XHTML, RSS, Atom). Refuses PDFs, images, and other binaries.
|
|
154
155
|
DESC
|
|
155
156
|
parameters: Parameters.build { |p|
|
|
@@ -68,6 +68,36 @@ module Pikuri
|
|
|
68
68
|
add(name, 'string', description, required: false)
|
|
69
69
|
end
|
|
70
70
|
|
|
71
|
+
# Add a required +array+-of-+string+ property — JSON-Schema
|
|
72
|
+
# +{type: 'array', items: {type: 'string'}}+. The LLM sends a
|
|
73
|
+
# native JSON array in the tool-call arguments (the shape its
|
|
74
|
+
# training data overwhelmingly uses for list-valued parameters),
|
|
75
|
+
# so there is no in-band encoding for it to get wrong.
|
|
76
|
+
# The value must arrive as an Array — no
|
|
77
|
+
# JSON-encoded-array-in-a-string fallback. Element coercion
|
|
78
|
+
# mirrors the scalar fields' one documented leniency, in
|
|
79
|
+
# reverse: Integers and finite Floats are converted to their
|
|
80
|
+
# +to_s+ form (a model emitting +["Fix issue 12", 42]+ meant a
|
|
81
|
+
# string list — the conversion is unambiguous), while booleans,
|
|
82
|
+
# +nil+, and nested structures are rejected — those signal a
|
|
83
|
+
# genuinely wrong call shape, not a representational quirk.
|
|
84
|
+
# An empty array is type-valid; rejecting it (if the tool needs
|
|
85
|
+
# at least one element) is the tool's job, with a tool-specific
|
|
86
|
+
# error message.
|
|
87
|
+
#
|
|
88
|
+
# @param name [Symbol] property name
|
|
89
|
+
# @param description [String] human-readable description shown to the LLM
|
|
90
|
+
# @return [self]
|
|
91
|
+
def required_string_array(name, description)
|
|
92
|
+
@properties[name] = {
|
|
93
|
+
type: 'array',
|
|
94
|
+
items: { type: 'string' },
|
|
95
|
+
description: description
|
|
96
|
+
}
|
|
97
|
+
@required << name.to_s
|
|
98
|
+
self
|
|
99
|
+
end
|
|
100
|
+
|
|
71
101
|
# Add a required +integer+ property. Accepts Integers, Floats with a
|
|
72
102
|
# zero fractional part (e.g. +1.0+), and base-10 numeric Strings (after
|
|
73
103
|
# trimming) that resolve to whole numbers; rejects everything else.
|
|
@@ -260,9 +290,35 @@ module Pikuri
|
|
|
260
290
|
coerce_number(value)
|
|
261
291
|
when 'boolean'
|
|
262
292
|
coerce_boolean(value)
|
|
293
|
+
when 'array'
|
|
294
|
+
coerce_string_array(value)
|
|
295
|
+
end
|
|
296
|
+
end
|
|
297
|
+
|
|
298
|
+
def coerce_string_array(value)
|
|
299
|
+
raise CoercionError, "must be an array of strings (got #{value.class}: #{value.inspect})" unless value.is_a?(Array)
|
|
300
|
+
|
|
301
|
+
value.each_with_index.map do |element, i|
|
|
302
|
+
case element
|
|
303
|
+
when String
|
|
304
|
+
element
|
|
305
|
+
when Integer
|
|
306
|
+
element.to_s
|
|
307
|
+
when Float
|
|
308
|
+
raise CoercionError, array_element_message(i, element) unless element.finite?
|
|
309
|
+
|
|
310
|
+
element.to_s
|
|
311
|
+
else
|
|
312
|
+
raise CoercionError, array_element_message(i, element)
|
|
313
|
+
end
|
|
263
314
|
end
|
|
264
315
|
end
|
|
265
316
|
|
|
317
|
+
def array_element_message(index, element)
|
|
318
|
+
"must be an array of strings (element #{index} is #{element.class}: #{element.inspect}; " \
|
|
319
|
+
'numbers are auto-converted, other types are not)'
|
|
320
|
+
end
|
|
321
|
+
|
|
266
322
|
def coerce_boolean(value)
|
|
267
323
|
return value if value == true || value == false
|
|
268
324
|
|
|
@@ -341,7 +397,14 @@ module Pikuri
|
|
|
341
397
|
|
|
342
398
|
def missing_required_message(name, schema)
|
|
343
399
|
enum_part = schema[:enum] ? ", one of: #{schema[:enum].map { |v| "`#{v}`" }.join(', ')}" : ''
|
|
344
|
-
"Missing required parameter `#{name}` (#{schema
|
|
400
|
+
"Missing required parameter `#{name}` (#{type_label(schema)}#{enum_part}): #{schema[:description]}"
|
|
401
|
+
end
|
|
402
|
+
|
|
403
|
+
# Human/LLM-facing label for a property's type in error messages:
|
|
404
|
+
# +"array of strings"+ for array properties, the bare JSON-Schema
|
|
405
|
+
# type name otherwise.
|
|
406
|
+
def type_label(schema)
|
|
407
|
+
schema[:items] ? "array of #{schema[:items][:type]}s" : schema[:type]
|
|
345
408
|
end
|
|
346
409
|
|
|
347
410
|
def unknown_key_error(unknown)
|
|
@@ -366,7 +429,7 @@ module Pikuri
|
|
|
366
429
|
*@properties.map { |name, prop|
|
|
367
430
|
req = @required.include?(name.to_s) ? 'required' : 'optional'
|
|
368
431
|
enum_part = prop[:enum] ? ", one of: #{prop[:enum].map { |v| "`#{v}`" }.join(', ')}" : ''
|
|
369
|
-
" - `#{name}` (#{prop
|
|
432
|
+
" - `#{name}` (#{type_label(prop)}, #{req}#{enum_part}): #{prop[:description]}"
|
|
370
433
|
}
|
|
371
434
|
].join("\n")
|
|
372
435
|
end
|