opokay 0.1.0-arm64-darwin
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 +7 -0
- data/LICENSE-APACHE +202 -0
- data/LICENSE-MIT +21 -0
- data/README.md +35 -0
- data/exe/opokay-review +11 -0
- data/exe/opokay-summarize +11 -0
- data/lib/opokay/command.rb +156 -0
- data/lib/opokay/commands.rb +12 -0
- data/lib/opokay/documents.rb +78 -0
- data/lib/opokay/gen.rb +62 -0
- data/lib/opokay/load_options.rb +28 -0
- data/lib/opokay/prompts/review.md +37 -0
- data/lib/opokay/review.rb +103 -0
- data/lib/opokay/run_log.rb +38 -0
- data/lib/opokay/summarize.rb +111 -0
- data/lib/opokay/version.rb +7 -0
- data/lib/opokay/worker.rb +244 -0
- data/lib/opokay.rb +10 -0
- data/libexec/opokay +4 -0
- metadata +59 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: cc9d0d7d701661988c63854becea826da0bf661629c84ad72c53fa58d30a73f1
|
|
4
|
+
data.tar.gz: d9f3008ee6871433de046eb398b6296783f764d29103fe2d95211ff0add3550e
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: c447de9e6f777909c9d4258ad38087084a72b639b9f9f6541da6a564933b8d1a8b6ef6518eac0eb45c08252dece81b3551e0091af1eb3d222a4d60b217035588
|
|
7
|
+
data.tar.gz: b4371ffaacbf28e97c06bcc6f5eb0e6b08ddc5980c87eeb9967b3a6e6b370bd1a85fe6f548747596f6eb2452ca74621388c0bc7368d8afc649fcf4a5d55ed7b7
|
data/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
data/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Masayoshi Takahashi
|
|
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,35 @@
|
|
|
1
|
+
# opokay の Ruby 版
|
|
2
|
+
|
|
3
|
+
モデルは `opokay worker` (Rust、子プロセス) が動かし、Ruby とは標準入出力の JSON の行でやり取りする (ネットワークは
|
|
4
|
+
使わない)。`require "opokay"` が読むのはその要求 (`Opokay::Worker`) だけで、プロンプトを自分で書くプログラムは
|
|
5
|
+
これだけを使う。
|
|
6
|
+
文書のコマンドは `require "opokay/commands"` で、プロンプト、部分への分け方、出力の形、並べ方は Ruby の側にある。
|
|
7
|
+
|
|
8
|
+
worker の本体は `OPOKAY_BIN`、なければリポジトリのリリースビルド (`target/release/opokay`)、なければ gem が持つもの
|
|
9
|
+
(`libexec/opokay`)、なければ PATH の `opokay`。
|
|
10
|
+
gem が持つものは PATH より先なので、PATH に置いた新しい `opokay` を使うときは `OPOKAY_BIN` で指す (gem のものが動かない機械、AVX2 のない CPU や古い glibc では、`--version` が通らないので PATH に回る)。
|
|
11
|
+
gem は arm64-darwin と x86_64-linux-gnu の platform gem が同じ版の本体を持ち、それ以外の platform の gem (`ruby`) は持たない。
|
|
12
|
+
gem は `.github/workflows/release.yml` がタグで作る (`script/build_gem.rb`。本体の `--version` が gem の版と違えば作らない)。
|
|
13
|
+
RubyGems へ出すのは、変数 `PUBLISH_GEMS` が `true` のときのタグか、手で起動して `publish_gems` を選んだときだけ。
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
cargo build --release -p opokay # worker を含む本体
|
|
17
|
+
ruby/exe/opokay-summarize MODEL.gguf BOOK.pdf -o OUT.md # opokay summarize と同じ要約 (オプションも同じ)
|
|
18
|
+
ruby/exe/opokay-review MODEL.gguf ARTICLE.md [--prompt P.md] # opokay review と同じ (既定のプロンプトは lib/opokay/prompts/review.md)
|
|
19
|
+
scripts/docs.sh run DIR review MODEL --ruby # docs.sh から Ruby 版で (bwrap の中で Ruby ごと動く)
|
|
20
|
+
ruby -Iruby/lib ruby/test/test_worker.rb # worker の要求のテスト (0.8B、CPU、約 2 秒)
|
|
21
|
+
ruby -Iruby/lib ruby/test/test_bin.rb # 本体の探し方、require の範囲、gem の組み立て (モデル不要)
|
|
22
|
+
ruby ruby/script/build_gem.rb arm64-darwin target/release/opokay -o pkg # 本体を持つ gem (pkg/opokay-0.1.0-arm64-darwin.gem)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
- `lib/opokay/worker.rb`: `Opokay::Worker` (子プロセスと要求)。`extract`、`count`、`tokenize` (トークン列)、`split`、`render` (`generation_prompt: false` で assistant の始まりを付けない)、`load`、
|
|
26
|
+
`submit` / `generate` (ブロックで生成中の文字)、`Reply#cancel`。要求はどのスレッドからでも出せ、生成中のものは
|
|
27
|
+
エンジンがスロットの数まで並べる。
|
|
28
|
+
- `lib/opokay/commands.rb`: 文書のコマンドで使う以下のものをまとめて読む (`exe/` はこれを読む)。
|
|
29
|
+
- `lib/opokay/gen.rb`: 1 文書の問い合わせ (システムプロンプトの状態の使い回し、ログ、メモ)。
|
|
30
|
+
- `lib/opokay/command.rb`: 文書のコマンドの共通部分 (オプション、読み込む前に文書を開いて分ける、KV の大きさ、文書を並べる)。
|
|
31
|
+
- `lib/opokay/summarize.rb`、`review.rb`: 要約と講評のプロンプトと段取り (Rust の `summarize.rs`、`review.rs` を写したもの)。
|
|
32
|
+
講評の既定のプロンプトは `lib/opokay/prompts/review.md` (Rust の `review_prompt.md` の写し。これから先は Ruby の側を直す)。
|
|
33
|
+
- `lib/opokay/documents.rb`: 出力の置き場所、書名。`lib/opokay/run_log.rb`: `--log` (Rust と同じ形、`impl: "ruby"`)。
|
|
34
|
+
|
|
35
|
+
要求と応答の形は `crates/opokay/src/worker.rs` の冒頭にある。
|
data/exe/opokay-review
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "optparse"
|
|
4
|
+
|
|
5
|
+
module Opokay
|
|
6
|
+
# What the document commands share (as opokay's summarize and review): the options, the
|
|
7
|
+
# documents opened and split before loading, the KV cache sized from them, and the documents
|
|
8
|
+
# read side by side on one worker. A command defines #suffix, #parts_of(w, doc), #need(w,
|
|
9
|
+
# longest), #settings(doc_tokens, parts, slots), #system and #write(g, file, doc, parts).
|
|
10
|
+
class Command
|
|
11
|
+
Options = Struct.new(:think, :style, :temp, :seed, :out, :out_dir, :skip_existing, :dry_run, :log,
|
|
12
|
+
:parallel, :kv_tokens, :cpu, :mtp, :load_args, :extra, keyword_init: true)
|
|
13
|
+
|
|
14
|
+
def self.main(argv)
|
|
15
|
+
o = Options.new(think: false, style: "です・ます調(敬体)", temp: 0.7, seed: 0, skip_existing: false,
|
|
16
|
+
dry_run: false, parallel: 1, cpu: false, mtp: false, load_args: [], extra: {})
|
|
17
|
+
parser = OptionParser.new
|
|
18
|
+
parser.banner = "usage: #{File.basename($PROGRAM_NAME)} MODEL FILE... [options]"
|
|
19
|
+
define_options(parser, o.extra)
|
|
20
|
+
parser.on("--think", "let the model think first (slower)") { o.think = true }
|
|
21
|
+
parser.on("--style TEXT", "the style asked of the output (empty: none)") { o.style = _1 }
|
|
22
|
+
parser.on("--temp T", Float, "(0.7)") { o.temp = _1 }
|
|
23
|
+
parser.on("--seed N", Integer, "(0)") { o.seed = _1 }
|
|
24
|
+
parser.on("-o", "--out FILE", "the Markdown here (one file)") { o.out = _1 }
|
|
25
|
+
parser.on("--out-dir DIR", "each document's Markdown here, as NAME.#{suffix}.md") { o.out_dir = _1 }
|
|
26
|
+
parser.on("--skip-existing", "leave out the documents whose output exists") { o.skip_existing = true }
|
|
27
|
+
parser.on("--dry-run", "only show the parts (without loading the model)") { o.dry_run = true }
|
|
28
|
+
parser.on("--log FILE", "a line of JSON per reply") { o.log = _1 }
|
|
29
|
+
parser.on("--parallel N", Integer, "parts (and documents) side by side (1)") { o.parallel = _1 }
|
|
30
|
+
parser.on("--kv-tokens N", Integer, "the KV cache (by default what the longest prompt needs)") { o.kv_tokens = _1 }
|
|
31
|
+
LoadOptions.define(parser, o)
|
|
32
|
+
model, *files = parser.parse(argv)
|
|
33
|
+
raise Error, parser.banner if model.nil? || files.empty?
|
|
34
|
+
|
|
35
|
+
new(model, files, o).run
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def self.define_options(_parser, _extra) = nil
|
|
39
|
+
|
|
40
|
+
def self.suffix = raise(NotImplementedError)
|
|
41
|
+
|
|
42
|
+
def initialize(model, files, opts)
|
|
43
|
+
@model = model
|
|
44
|
+
@files = files
|
|
45
|
+
@o = opts
|
|
46
|
+
@x = opts.extra
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def suffix = self.class.suffix
|
|
50
|
+
|
|
51
|
+
def run
|
|
52
|
+
many = @files.size > 1
|
|
53
|
+
raise Error, "-o is for one file; give --out-dir for many" if many && @o.out
|
|
54
|
+
|
|
55
|
+
Worker.open(@model, *@o.load_args) do |w|
|
|
56
|
+
return dry_run(w) if @o.dry_run
|
|
57
|
+
|
|
58
|
+
todo = Documents.outputs(@files, out: @o.out, out_dir: @o.out_dir, suffix:, skip: @o.skip_existing)
|
|
59
|
+
if todo.empty?
|
|
60
|
+
$stderr.puts "[nothing to do: every output exists]"
|
|
61
|
+
return
|
|
62
|
+
end
|
|
63
|
+
# (the documents read before loading, for the KV cache their longest part needs)
|
|
64
|
+
# (with many, one that fails to open, a scanned PDF without text say, left out and counted)
|
|
65
|
+
unread = 0
|
|
66
|
+
docs = todo.filter_map do |file, out|
|
|
67
|
+
doc = w.extract(file)
|
|
68
|
+
{file:, out:, doc:, parts: parts_of(w, doc)}
|
|
69
|
+
rescue StandardError => e
|
|
70
|
+
raise unless many
|
|
71
|
+
|
|
72
|
+
$stderr.puts "[#{File.basename(file)}] failed: #{e.message}"
|
|
73
|
+
unread += 1
|
|
74
|
+
nil
|
|
75
|
+
end
|
|
76
|
+
raise Error, "#{unread} of #{todo.size} documents failed" if docs.empty?
|
|
77
|
+
|
|
78
|
+
longest = docs.flat_map { |d| d[:parts].map { _1["tokens"] } }.max || 0
|
|
79
|
+
most = docs.sum { |d| d[:parts].size }
|
|
80
|
+
kv, slots = Command.load_for(@o.kv_tokens, need(w, longest), @o.parallel, most)
|
|
81
|
+
w.load(kv_tokens: kv, slots:, snapshots: 1)
|
|
82
|
+
read_all(w, docs, slots, many, unread)
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# The KV cache and the slots for prompts of up to `need` tokens, `most` of them, `parallel`
|
|
87
|
+
# side by side at most (as opokay's load_for).
|
|
88
|
+
def self.load_for(kv_tokens, need, parallel, most)
|
|
89
|
+
side = [[parallel, most].min, 1].max
|
|
90
|
+
if kv_tokens
|
|
91
|
+
raise Error, "the longest prompt and its output need --kv-tokens of at least #{need}" if need > kv_tokens
|
|
92
|
+
|
|
93
|
+
fit = [kv_tokens / [need, 1].max, 1].max
|
|
94
|
+
$stderr.puts "[--parallel #{side}: the KV cache holds #{fit} (--kv-tokens #{kv_tokens}, #{need} tokens each)]" if side > fit
|
|
95
|
+
[kv_tokens, side.clamp(1, fit)]
|
|
96
|
+
else
|
|
97
|
+
kv = ((need * side + 1023) / 1024) * 1024
|
|
98
|
+
$stderr.puts "[KV cache: #{kv} tokens, #{side} prompt(s) of up to #{need} with the output]"
|
|
99
|
+
[kv, side]
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
private
|
|
104
|
+
|
|
105
|
+
# The documents, `slots` at a time with many (each on a thread of its own), one failing
|
|
106
|
+
# without stopping the others.
|
|
107
|
+
def read_all(w, docs, slots, many, unread = 0)
|
|
108
|
+
queue = Queue.new
|
|
109
|
+
docs.each { queue << _1 }
|
|
110
|
+
queue.close
|
|
111
|
+
failed = unread
|
|
112
|
+
lock = Mutex.new
|
|
113
|
+
Array.new([many ? slots : 1, docs.size].min) do
|
|
114
|
+
Thread.new do
|
|
115
|
+
while (d = queue.pop)
|
|
116
|
+
name = many ? File.basename(d[:file]) : nil
|
|
117
|
+
begin
|
|
118
|
+
read_file(w, d, slots, name)
|
|
119
|
+
rescue StandardError => e
|
|
120
|
+
raise unless many
|
|
121
|
+
|
|
122
|
+
$stderr.puts "[#{name}] failed: #{e.message}"
|
|
123
|
+
lock.synchronize { failed += 1 }
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
end.each(&:join)
|
|
128
|
+
raise Error, "#{failed} of #{docs.size + unread} documents failed" if failed > 0
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def read_file(w, d, slots, name)
|
|
132
|
+
file, out, doc, parts = d.values_at(:file, :out, :doc, :parts)
|
|
133
|
+
total = parts.sum { _1["tokens"] }
|
|
134
|
+
log = @o.log && RunLog.new(@o.log, command: self.class.command, document: file, worker: w, mtp: @o.mtp,
|
|
135
|
+
cpu: @o.cpu, settings: settings(total, parts, slots))
|
|
136
|
+
g = Gen.new(w, system:, think: @o.think, temp: @o.temp, seed: @o.seed, log:, parallel: slots, name:)
|
|
137
|
+
g.note(note_of(file, doc, total, parts))
|
|
138
|
+
Documents.write_out(g, out, write(g, file, doc, parts))
|
|
139
|
+
ensure
|
|
140
|
+
log&.close
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def dry_run(w)
|
|
144
|
+
@files.each do |f|
|
|
145
|
+
doc = w.extract(f)
|
|
146
|
+
parts = parts_of(w, doc)
|
|
147
|
+
puts dry_head(f, doc, parts.sum { _1["tokens"] }, parts)
|
|
148
|
+
parts.each_with_index do |p, i|
|
|
149
|
+
puts "#{i + 1}. #{p["label"]} (#{p["tokens"]} tokens): #{p["text"][0, 60].tr("\n", " ")}…"
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def style = @o.style.empty? ? "" : "文体は#{@o.style}で統一してください。"
|
|
155
|
+
end
|
|
156
|
+
end
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# The document commands (`opokay-summarize`, `opokay-review`): the prompts, the parts and the
|
|
4
|
+
# outputs, written here, with the model in the worker.
|
|
5
|
+
require_relative "../opokay"
|
|
6
|
+
require_relative "run_log"
|
|
7
|
+
require_relative "gen"
|
|
8
|
+
require_relative "documents"
|
|
9
|
+
require_relative "load_options"
|
|
10
|
+
require_relative "command"
|
|
11
|
+
require_relative "summarize"
|
|
12
|
+
require_relative "review"
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
|
|
5
|
+
module Opokay
|
|
6
|
+
# What the document commands share: where outputs go, and a document's title.
|
|
7
|
+
module Documents
|
|
8
|
+
module_function
|
|
9
|
+
|
|
10
|
+
# [file, out] for each of `files`: with one, `out` (or `out_dir`, or nil: stdout); with many,
|
|
11
|
+
# out_dir/NAME.SUFFIX.md (NAME: the file's stem, its whole name when another file has the
|
|
12
|
+
# same stem). With `skip`, the files whose output exists are left out.
|
|
13
|
+
def outputs(files, out:, out_dir:, suffix:, skip:)
|
|
14
|
+
raise Error, "many files need --out-dir" unless files.size == 1 || out_dir
|
|
15
|
+
|
|
16
|
+
FileUtils.mkdir_p(out_dir) if out_dir
|
|
17
|
+
stem = ->(f) { File.basename(f, ".*") }
|
|
18
|
+
files.filter_map do |f|
|
|
19
|
+
dest =
|
|
20
|
+
if out then out
|
|
21
|
+
elsif out_dir
|
|
22
|
+
base = files.count { |g| stem.(g) == stem.(f) } > 1 ? File.basename(f) : stem.(f)
|
|
23
|
+
File.join(out_dir, "#{base}.#{suffix}.md")
|
|
24
|
+
end
|
|
25
|
+
if skip && dest && File.exist?(dest)
|
|
26
|
+
$stderr.puts "[#{f}: skipped, #{dest} exists]"
|
|
27
|
+
next
|
|
28
|
+
end
|
|
29
|
+
[f, dest]
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# The title in quotes, marked when it is a guess.
|
|
34
|
+
def shown_title(doc) = doc["title_known"] ? "「#{doc["title"]}」" : "「#{doc["title"]}」 (a guess)"
|
|
35
|
+
|
|
36
|
+
# The document's title: its own, else the model's answer to the worker's title_prompt
|
|
37
|
+
# (greedy, without thinking), else the guess.
|
|
38
|
+
def title_of(gen, doc)
|
|
39
|
+
return doc["title"] if doc["title_known"]
|
|
40
|
+
|
|
41
|
+
saved = [gen.think, gen.temp]
|
|
42
|
+
gen.think, gen.temp = false, 0.0
|
|
43
|
+
r = begin
|
|
44
|
+
gen.ask(doc["title_prompt"], 128, kind: "title")
|
|
45
|
+
ensure
|
|
46
|
+
gen.think, gen.temp = saved
|
|
47
|
+
end
|
|
48
|
+
if (t = title_from_reply(r.text))
|
|
49
|
+
gen.note(format("[title: 「%s」 (%.1f s)]", t, r.total_s))
|
|
50
|
+
t
|
|
51
|
+
else
|
|
52
|
+
gen.note(format("[title: no answer (%.1f s), 「%s」 kept]", r.total_s, doc["title"]))
|
|
53
|
+
doc["title"]
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# The title in a reply: its first line, without quotes or a label, or nil.
|
|
58
|
+
def title_from_reply(reply)
|
|
59
|
+
l = reply.lines.map(&:strip).find { |x| !x.empty? } or return nil
|
|
60
|
+
l = l.sub(/\A#+/, "").strip.delete_prefix("**").delete_suffix("**").strip
|
|
61
|
+
l = l.gsub(/\A\*+|\*+\z/, "").strip
|
|
62
|
+
%w[書名: 書名: タイトル: タイトル:].each { |p| l = l.delete_prefix(p) }
|
|
63
|
+
l = l.strip.gsub(/\A[「」『』"“”]+|[「」『』"“”]+\z/, "").strip
|
|
64
|
+
l.empty? || l.length > 120 ? nil : l
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Writes `md` to `out` (or stdout).
|
|
68
|
+
def write_out(gen, out, md)
|
|
69
|
+
if out
|
|
70
|
+
File.write(out, md)
|
|
71
|
+
gen.note("[written to #{out}]")
|
|
72
|
+
else
|
|
73
|
+
$stdout.write(md)
|
|
74
|
+
$stdout.flush
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
data/lib/opokay/gen.rb
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Opokay
|
|
4
|
+
# The replies of one document: asks with a system prompt (whose state the worker keeps for the
|
|
5
|
+
# later asks), logged, with notes on stderr after the document's name when many are read.
|
|
6
|
+
class Gen
|
|
7
|
+
attr_accessor :think, :temp
|
|
8
|
+
attr_reader :worker, :system, :name
|
|
9
|
+
|
|
10
|
+
Ask = Data.define(:user, :max_new, :kind, :label)
|
|
11
|
+
|
|
12
|
+
def initialize(worker, system:, think: false, temp: 0.7, seed: 0, log: nil, parallel: 1, name: nil)
|
|
13
|
+
@worker = worker
|
|
14
|
+
@system = system
|
|
15
|
+
@think = think
|
|
16
|
+
@temp = temp
|
|
17
|
+
@seed = seed
|
|
18
|
+
@log = log
|
|
19
|
+
@parallel = parallel
|
|
20
|
+
@name = name
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def note(msg) = Gen.note_as(@name, msg)
|
|
24
|
+
|
|
25
|
+
def self.note_as(name, msg) = $stderr.puts(name ? "[#{name}] #{msg}" : msg)
|
|
26
|
+
|
|
27
|
+
# The reply to `user` (a Worker::Result).
|
|
28
|
+
def ask(user, max_new, kind: "whole", label: "")
|
|
29
|
+
ask_many([Ask.new(user:, max_new:, kind:, label:)]).first
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# The replies to `asks`, submitted together (the engine generates up to its slots side by
|
|
33
|
+
# side); the block gets each (index, result) as it ends.
|
|
34
|
+
def ask_many(asks)
|
|
35
|
+
replies = asks.map do |a|
|
|
36
|
+
@worker.submit(messages: [{role: "system", content: @system}, {role: "user", content: a.user}],
|
|
37
|
+
max_new: a.max_new, think: @think, temp: @temp, top_p: 0.8, top_k: 20, seed: @seed,
|
|
38
|
+
keep: "system")
|
|
39
|
+
end
|
|
40
|
+
done = Queue.new
|
|
41
|
+
waits = replies.each_with_index.map { |r, i| Thread.new { done << [i, (r.value rescue $!)] } }
|
|
42
|
+
results = Array.new(asks.size)
|
|
43
|
+
asks.size.times do
|
|
44
|
+
i, r = done.pop
|
|
45
|
+
raise r if r.is_a?(Exception)
|
|
46
|
+
|
|
47
|
+
results[i] = r
|
|
48
|
+
yield i, r if block_given?
|
|
49
|
+
end
|
|
50
|
+
waits.each(&:join)
|
|
51
|
+
asks.zip(results).each { |a, r| @log&.record(r, kind: a.kind, label: a.label, together: asks.size) }
|
|
52
|
+
results
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# The replies to `asks`: one at a time, or with `parallel` > 1 all together (#ask_many).
|
|
56
|
+
def ask_each(asks, &on_done)
|
|
57
|
+
return ask_many(asks, &on_done) if @parallel > 1
|
|
58
|
+
|
|
59
|
+
asks.each_with_index.map { |a, i| ask_many([a]) { |_, r| on_done&.call(i, r) }.first }
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Opokay
|
|
4
|
+
# opokay's options for loading a model (LoadArgs in crates/opokay/src/main.rs), passed to the
|
|
5
|
+
# worker as they are; --kv-tokens, --slots and --snapshots go with the `load` request instead.
|
|
6
|
+
module LoadOptions
|
|
7
|
+
WITH_VALUE = {"--mtp" => "PATH", "--drafts" => "N", "--context-drafts" => "N", "--output-quant" => "Q",
|
|
8
|
+
"--mix" => "auto|on|off"}.freeze
|
|
9
|
+
FLAGS = %w[--cpu --fixed-drafts --argmax-drafts --mtp-q4k --kv-f32 --exact-head].freeze
|
|
10
|
+
|
|
11
|
+
# Adds them to `parser`, collected in o.load_args (and o.cpu, o.mtp set).
|
|
12
|
+
def self.define(parser, o)
|
|
13
|
+
parser.separator("opokay's load options (see opokay summarize --help):")
|
|
14
|
+
WITH_VALUE.each do |flag, arg|
|
|
15
|
+
parser.on("#{flag} #{arg}") do |v|
|
|
16
|
+
o.load_args.push(flag, v)
|
|
17
|
+
o.mtp = true if flag == "--mtp"
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
FLAGS.each do |flag|
|
|
21
|
+
parser.on(flag) do
|
|
22
|
+
o.load_args << flag
|
|
23
|
+
o.cpu = true if flag == "--cpu"
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
あなたは技術記事の下読みを担当するリサーチアシスタントです。
|
|
2
|
+
|
|
3
|
+
この記事は、あとで人間の編集者が実際に読み、評価します。あなたの役割は記事の採点や評価の確定ではなく、人間が読む際に参考になる観点や着眼点を幅広く洗い出すことです。
|
|
4
|
+
|
|
5
|
+
**基本方針**
|
|
6
|
+
|
|
7
|
+
- 記事のよいところや興味深い点を積極的に探してください。
|
|
8
|
+
- 一つの解釈や評価に絞らず、複数の可能性を挙げてください。
|
|
9
|
+
- 想定読者を一つに決めず、さまざまな読者層を検討してください。
|
|
10
|
+
- 著者が明示していない価値や、別の文脈での読み方も考えてください。
|
|
11
|
+
- 技術的な正確性の厳密な検証は不要です。
|
|
12
|
+
- 改善点や欠点を探す必要はありません。
|
|
13
|
+
- 可能性や仮説は、確定的な事実と区別して提示してください。
|
|
14
|
+
- もっともらしい一般論で項目を埋めず、記事の具体的な内容に結びつけてください。
|
|
15
|
+
- 結論を急いだり、候補を過度に絞り込んだりしないでください。
|
|
16
|
+
|
|
17
|
+
**出力内容**
|
|
18
|
+
|
|
19
|
+
### 1. 記事の概要
|
|
20
|
+
何について書かれた記事か、簡潔に説明してください。
|
|
21
|
+
|
|
22
|
+
### 2. 注目したいところ
|
|
23
|
+
人間が読む際に注目するとよさそうな箇所や考え方を、できるだけ幅広く挙げてください。
|
|
24
|
+
|
|
25
|
+
### 3. 記事のよいところ・価値の候補
|
|
26
|
+
技術的、実践的、教育的、歴史的、設計的など、さまざまな観点から考察してください。
|
|
27
|
+
|
|
28
|
+
### 4. 想定読者の候補
|
|
29
|
+
どのような経験、関心、課題を持つ人にとって面白い記事になりそうか、複数の候補を挙げてください。それぞれについて理由も説明してください。
|
|
30
|
+
|
|
31
|
+
### 5. 別の読み方や関連する論点
|
|
32
|
+
記事の主題以外にも、関連する技術、設計思想、開発文化、教育などの観点から読める可能性があれば挙げてください。
|
|
33
|
+
|
|
34
|
+
### 6. 人間が読むときに確かめたいこと
|
|
35
|
+
記事を実際に読む際、注目したり検討したりすると面白そうな疑問を挙げてください。
|
|
36
|
+
|
|
37
|
+
全体として、完成したレビューではなく、人間の読解を助けるための豊富な検討材料を作成してください。
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Opokay
|
|
4
|
+
# `opokay-review MODEL FILE... [--prompt PROMPT.md]`: the model reads a document with a prompt
|
|
5
|
+
# of one's own (the system prompt; by default a technical article's first reading for an
|
|
6
|
+
# editor, prompts/review.md) and writes what it asks for, as `opokay review` does. A document
|
|
7
|
+
# longer than one part gives notes part by part, and the notes together the output.
|
|
8
|
+
class Review < Command
|
|
9
|
+
DEFAULT_PROMPT = File.expand_path("prompts/review.md", __dir__)
|
|
10
|
+
# The longest document `auto` reads in one prompt (HISTORY 8.67), and the parts of a longer one.
|
|
11
|
+
ONE_PROMPT = 64_000
|
|
12
|
+
AUTO_PART = 16_000
|
|
13
|
+
|
|
14
|
+
def self.command = "review"
|
|
15
|
+
def self.suffix = "review"
|
|
16
|
+
|
|
17
|
+
def self.define_options(p, x)
|
|
18
|
+
x.merge!(prompt: nil, part_tokens: "auto", max_tokens: 6000, chars: 4000)
|
|
19
|
+
p.on("--prompt FILE", "the instructions (the system prompt; by default an article's first reading)") { x[:prompt] = _1 }
|
|
20
|
+
p.on("--part-tokens N", "tokens read in one prompt, or auto (the whole up to 64000, else parts of 16000)") do |v|
|
|
21
|
+
x[:part_tokens] = v == "auto" ? "auto" : Integer(v)
|
|
22
|
+
end
|
|
23
|
+
p.on("--max-tokens N", Integer, "at most this many tokens of output (6000)") { x[:max_tokens] = _1 }
|
|
24
|
+
p.on("--chars N", Integer, "about how many characters the output has (4000; 0: not asked)") { x[:chars] = _1 }
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
private
|
|
28
|
+
|
|
29
|
+
def prompt = @prompt ||= File.read(@x[:prompt] || DEFAULT_PROMPT)
|
|
30
|
+
|
|
31
|
+
def think_tokens = @o.think ? 8192 : 0
|
|
32
|
+
|
|
33
|
+
def parts_of(w, doc)
|
|
34
|
+
limit = @x[:part_tokens]
|
|
35
|
+
if limit == "auto"
|
|
36
|
+
total = w.count(doc["sections"].map { _1["text"] }).sum
|
|
37
|
+
limit = total <= ONE_PROMPT ? [total, 1].max : AUTO_PART
|
|
38
|
+
end
|
|
39
|
+
w.split(doc["sections"], limit)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def need(w, longest) = longest + w.count([prompt]).first + 512 + @x[:max_tokens] + think_tokens
|
|
43
|
+
|
|
44
|
+
def settings(total, parts, slots)
|
|
45
|
+
{temp: @o.temp, think: @o.think, style: @o.style, seed: @o.seed, part_tokens: @x[:part_tokens],
|
|
46
|
+
max_tokens: @x[:max_tokens], chars: @x[:chars], doc_tokens: total, parts: parts.size, parallel: slots,
|
|
47
|
+
prompt: @x[:prompt] && File.basename(@x[:prompt])}
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def system = prompt
|
|
51
|
+
|
|
52
|
+
def note_of(file, doc, total, parts) = "[#{file}: #{Documents.shown_title(doc)}, #{total} tokens in #{parts.size} part(s)]"
|
|
53
|
+
|
|
54
|
+
def dry_head(file, doc, total, parts) = "#{file}: #{Documents.shown_title(doc)}, #{total} tokens in #{parts.size} part(s)"
|
|
55
|
+
|
|
56
|
+
# The request for an output of about `chars` characters (none for 0).
|
|
57
|
+
def length(chars) = chars.zero? ? "" : "出力は全体で#{chars}字程度にしてください。"
|
|
58
|
+
|
|
59
|
+
# The length asked of the whole from the parts' notes: half of --chars (HISTORY 8.68).
|
|
60
|
+
def whole_length(chars) = chars.zero? ? "" : "メモの量にかかわらず、出力は全体で#{chars / 2}字程度に収めてください。"
|
|
61
|
+
|
|
62
|
+
def write(g, file, doc, parts)
|
|
63
|
+
title = Documents.title_of(g, doc)
|
|
64
|
+
total = parts.sum { _1["tokens"] }
|
|
65
|
+
md = +"# 「#{title}」\n\n(#{File.basename(file)}、#{total} トークン)\n\n"
|
|
66
|
+
body =
|
|
67
|
+
if parts.size == 1
|
|
68
|
+
user = "以下が対象の文書「#{title}」です。指示に従って出力してください。#{length(@x[:chars])}#{style}\n\n---\n" \
|
|
69
|
+
"#{parts[0]["text"]}"
|
|
70
|
+
r = g.ask(user, @x[:max_tokens] + think_tokens)
|
|
71
|
+
g.note(format("[%d tokens read: %d characters in %.1f s]", parts[0]["tokens"], r.text.length, r.total_s))
|
|
72
|
+
r.text
|
|
73
|
+
else
|
|
74
|
+
notes_to_whole(g, title, parts)
|
|
75
|
+
end
|
|
76
|
+
md << body << "\n"
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def notes_to_whole(g, title, parts)
|
|
80
|
+
asks = parts.each_with_index.map do |p, i|
|
|
81
|
+
Gen::Ask.new(
|
|
82
|
+
user: "以下は対象の文書「#{title}」の一部(#{i + 1}/#{parts.size}:#{p["label"]})です。文書は長いので部分ごとに" \
|
|
83
|
+
"読んでいます。この部分について、指示の出力内容の各項目に使えそうな材料(具体的な記述、主張、例、数値、コード、" \
|
|
84
|
+
"印象的な箇所)を、項目ごとに箇条書きのメモにしてください。文書全体についての結論はまだ出さないでください。" \
|
|
85
|
+
"#{length(@x[:chars] / 2)}\n\n---\n#{p["text"]}",
|
|
86
|
+
max_new: @x[:max_tokens] / 2 + think_tokens, kind: "part", label: p["label"]
|
|
87
|
+
)
|
|
88
|
+
end
|
|
89
|
+
replies = g.ask_each(asks) do |i, r|
|
|
90
|
+
p = parts[i]
|
|
91
|
+
g.note(format("[%d/%d] %s: %d tokens -> %d characters of notes (%.1f s)", i + 1, parts.size, p["label"],
|
|
92
|
+
p["tokens"], r.text.length, r.total_s))
|
|
93
|
+
end
|
|
94
|
+
notes = replies.each_with_index.map { |r, i| "### 部分 #{i + 1}(#{parts[i]["label"]})のメモ\n#{r.text}" }
|
|
95
|
+
user = "対象の文書「#{title}」は長いため、部分ごとに読んでメモを取りました。以下がそのメモです。これをもとに、" \
|
|
96
|
+
"文書全体について指示に従って出力してください。メモは部分ごとに細かく取ってあるので、すべてを盛り込まず、" \
|
|
97
|
+
"文書全体にとって重要なものを選んでください。#{whole_length(@x[:chars])}#{style}\n\n---\n#{notes.join("\n\n")}"
|
|
98
|
+
r = g.ask(user, @x[:max_tokens] + think_tokens)
|
|
99
|
+
g.note(format("[the whole from %d parts' notes: %d characters in %.1f s]", parts.size, r.text.length, r.total_s))
|
|
100
|
+
r.text
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module Opokay
|
|
6
|
+
# `--log FILE.jsonl`: a line of JSON per reply, as opokay's own (crates/opokay/src/runlog.rs),
|
|
7
|
+
# so that scripts/docs.sh status reads both.
|
|
8
|
+
class RunLog
|
|
9
|
+
def initialize(path, command:, document:, worker:, mtp:, cpu:, settings:)
|
|
10
|
+
@file = File.open(path, "a")
|
|
11
|
+
@lock = Mutex.new
|
|
12
|
+
@base = {
|
|
13
|
+
"command" => command, "document" => File.basename(document.to_s), "model" => worker.model,
|
|
14
|
+
"mtp" => mtp, "device" => cpu ? "cpu" : "gpu", "impl" => "ruby", **settings.transform_keys(&:to_s)
|
|
15
|
+
}
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Records reply `r` (a Worker::Result) of `kind` (whole, part, group, title) and `label`,
|
|
19
|
+
# one of `together` asked together.
|
|
20
|
+
def record(r, kind:, label: "", together: 1)
|
|
21
|
+
decode_s = [r.total_s - r.first_token_s, 0.0].max
|
|
22
|
+
line = @base.merge(
|
|
23
|
+
"time" => Time.now.to_i, "kind" => kind, "label" => label,
|
|
24
|
+
"prompt_tokens" => r.prompt_tokens, "reused_tokens" => r.reused_tokens, "output_tokens" => r.output_tokens,
|
|
25
|
+
"chars" => r.text.length, "first_token_s" => r.first_token_s.round(3), "total_s" => r.total_s.round(3),
|
|
26
|
+
"together" => together,
|
|
27
|
+
"prefill_tok_s" => ((r.prompt_tokens - r.reused_tokens) / [r.first_token_s, 1e-9].max).round(3)
|
|
28
|
+
)
|
|
29
|
+
line["decode_tok_s"] = ((r.output_tokens - 1) / decode_s).round(3) if r.output_tokens > 1 && decode_s > 0
|
|
30
|
+
@lock.synchronize do
|
|
31
|
+
@file.puts(JSON.generate(line))
|
|
32
|
+
@file.flush
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def close = @file.close
|
|
37
|
+
end
|
|
38
|
+
end
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Opokay
|
|
4
|
+
# `opokay-summarize MODEL FILE...`: the summary of PDF, EPUB or text files in Markdown (the
|
|
5
|
+
# whole, then part by part), as `opokay summarize` writes it; the prompts are here.
|
|
6
|
+
class Summarize < Command
|
|
7
|
+
SYSTEM = "あなたは文書を正確に要約するアシスタントです。本文に書かれていないことは書かず、固有名詞や数値は本文のとおりに書いてください。"
|
|
8
|
+
|
|
9
|
+
def self.command = "summarize"
|
|
10
|
+
def self.suffix = "summary"
|
|
11
|
+
|
|
12
|
+
def self.define_options(p, x)
|
|
13
|
+
x.merge!(part_tokens: 12_000, part_chars: 400, summary_chars: 800, instruction: nil)
|
|
14
|
+
p.on("--part-tokens N", Integer, "tokens of the document in one part (12000)") { x[:part_tokens] = _1 }
|
|
15
|
+
p.on("--part-chars N", Integer, "about how many characters a part's summary takes (400)") { x[:part_chars] = _1 }
|
|
16
|
+
p.on("--summary-chars N", Integer, "about how many characters the whole's takes (800)") { x[:summary_chars] = _1 }
|
|
17
|
+
p.on("--instruction TEXT", "more to ask of every summary") { x[:instruction] = _1 }
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
private
|
|
21
|
+
|
|
22
|
+
def parts_of(w, doc) = w.split(doc["sections"], @x[:part_tokens])
|
|
23
|
+
|
|
24
|
+
# (the longest prompt: a part and the instructions, with its output)
|
|
25
|
+
def need(_w, longest) = longest + 1024 + max_new(@x[:summary_chars])
|
|
26
|
+
|
|
27
|
+
def settings(total, parts, slots)
|
|
28
|
+
{temp: @o.temp, think: @o.think, style: @o.style, seed: @o.seed, part_tokens: @x[:part_tokens],
|
|
29
|
+
part_chars: @x[:part_chars], summary_chars: @x[:summary_chars], doc_tokens: total, parts: parts.size,
|
|
30
|
+
parallel: slots}
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def system = "#{SYSTEM}#{style}"
|
|
34
|
+
|
|
35
|
+
def note_of(file, doc, total, parts)
|
|
36
|
+
"[#{file}: #{Documents.shown_title(doc)}, #{doc["sections"].size} sections, #{total} tokens in " \
|
|
37
|
+
"#{parts.size} part#{parts.size == 1 ? "" : "s"}]"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def dry_head(file, doc, total, parts)
|
|
41
|
+
"#{file}: #{Documents.shown_title(doc)}, #{doc["sections"].size} sections, #{total} tokens in #{parts.size} parts"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# Tokens a summary of about `chars` characters may take, with room for the thinking.
|
|
45
|
+
def max_new(chars) = chars * 2 + 512 + (@o.think ? 4096 : 0)
|
|
46
|
+
|
|
47
|
+
def extra = @x[:instruction] ? "\n#{@x[:instruction]}" : ""
|
|
48
|
+
|
|
49
|
+
def whole(chars)
|
|
50
|
+
"文書全体の要約を#{chars}字程度で書いてください。続けて、主な論点や出来事を5〜10項目の箇条書きにしてください。" \
|
|
51
|
+
"見出し(「要約」「箇条書き」など)は付けず、要約の段落、空行、箇条書きの順に書いてください。"
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def write(g, file, doc, parts)
|
|
55
|
+
title = Documents.title_of(g, doc)
|
|
56
|
+
total = parts.sum { _1["tokens"] }
|
|
57
|
+
md = +"# 「#{title}」の要約\n\n(#{File.basename(file)}、#{total} トークン、#{parts.size} 部分)\n\n"
|
|
58
|
+
if parts.size == 1
|
|
59
|
+
user = "以下は「#{title}」の本文です。#{whole(@x[:summary_chars])}#{extra}\n\n---\n#{parts[0]["text"]}"
|
|
60
|
+
r = g.ask(user, max_new(@x[:summary_chars]))
|
|
61
|
+
g.note(format("[the whole, %d tokens: %d characters in %.1f s]", parts[0]["tokens"], r.text.length, r.total_s))
|
|
62
|
+
return md << r.text << "\n"
|
|
63
|
+
end
|
|
64
|
+
asks = parts.each_with_index.map do |p, i|
|
|
65
|
+
Gen::Ask.new(
|
|
66
|
+
user: "以下は「#{title}」の一部(#{i + 1}/#{parts.size}:#{p["label"]})です。この部分の内容を、話の流れや主張、" \
|
|
67
|
+
"重要な事実・数値・人物を落とさずに、#{@x[:part_chars]}字程度で要約してください。前置きや見出しは不要です。" \
|
|
68
|
+
"#{extra}\n\n---\n#{p["text"]}",
|
|
69
|
+
max_new: max_new(@x[:part_chars]), kind: "part", label: p["label"]
|
|
70
|
+
)
|
|
71
|
+
end
|
|
72
|
+
replies = g.ask_each(asks) do |i, r|
|
|
73
|
+
p = parts[i]
|
|
74
|
+
g.note(format("[%d/%d] %s: %d tokens -> %d characters (%.1f s)", i + 1, parts.size, p["label"], p["tokens"],
|
|
75
|
+
r.text.length, r.total_s))
|
|
76
|
+
end
|
|
77
|
+
sums = parts.zip(replies).map { |p, r| [p["label"], r.text] }
|
|
78
|
+
# The whole from the parts' summaries; in rounds while they are too long for one prompt.
|
|
79
|
+
level = sums
|
|
80
|
+
loop do
|
|
81
|
+
joined = level.map { |l, s| "### #{l}\n#{s}" }.join("\n\n")
|
|
82
|
+
n = g.worker.count([joined]).first
|
|
83
|
+
if n <= @x[:part_tokens] || level.size <= 2
|
|
84
|
+
user = "以下は「#{title}」を前から順に区切って要約したものです。これをもとに#{whole(@x[:summary_chars])}" \
|
|
85
|
+
"部分要約にないことは書かないでください。#{extra}\n\n---\n#{joined}"
|
|
86
|
+
r = g.ask(user, max_new(@x[:summary_chars]))
|
|
87
|
+
g.note(format("[the whole from %d summaries: %d characters in %.1f s]", level.size, r.text.length, r.total_s))
|
|
88
|
+
md << "## 全体\n\n" << r.text << "\n\n## 部分ごとの要約\n"
|
|
89
|
+
sums.each_with_index { |(l, s), i| md << "\n### #{i + 1}. #{l}\n\n#{s}\n" }
|
|
90
|
+
return md
|
|
91
|
+
end
|
|
92
|
+
# (groups of summaries that fit in a prompt, each summarized again)
|
|
93
|
+
groups = g.worker.split(level.map { |l, s| {title: l, text: s} }, @x[:part_tokens] / 2)
|
|
94
|
+
asks = groups.map do |grp|
|
|
95
|
+
Gen::Ask.new(
|
|
96
|
+
user: "以下は「#{title}」の一部(#{grp["label"]})を区切って要約したものです。これらをまとめて" \
|
|
97
|
+
"#{@x[:part_chars] * 2}字程度の要約にしてください。前置きや見出しは不要です。#{extra}\n\n---\n#{grp["text"]}",
|
|
98
|
+
max_new: max_new(@x[:part_chars] * 2), kind: "group", label: grp["label"]
|
|
99
|
+
)
|
|
100
|
+
end
|
|
101
|
+
replies = g.ask_each(asks) do |i, r|
|
|
102
|
+
g.note(format("[%s: %d characters in %.1f s]", groups[i]["label"], r.text.length, r.total_s))
|
|
103
|
+
end
|
|
104
|
+
nxt = groups.zip(replies).map { |grp, r| [grp["label"], r.text] }
|
|
105
|
+
raise Error, "the summaries do not get shorter" unless nxt.size < level.size
|
|
106
|
+
|
|
107
|
+
level = nxt
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
end
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "open3"
|
|
5
|
+
|
|
6
|
+
module Opokay
|
|
7
|
+
class Error < StandardError; end
|
|
8
|
+
|
|
9
|
+
# `opokay worker`: the model in a child process, JSON lines through its stdin and stdout
|
|
10
|
+
# (crates/opokay/src/worker.rs). Requests can be made from many threads; replies in flight
|
|
11
|
+
# are generated side by side by the engine, up to its slots.
|
|
12
|
+
#
|
|
13
|
+
# Opokay::Worker.open(model, "--mtp", model) do |w|
|
|
14
|
+
# w.load(kv_tokens: 32768, slots: 2)
|
|
15
|
+
# r = w.generate(messages: [{role: "user", content: "..."}], max_new: 500) { |t| print t }
|
|
16
|
+
# r.text
|
|
17
|
+
# end
|
|
18
|
+
class Worker
|
|
19
|
+
PROTOCOL = 2
|
|
20
|
+
|
|
21
|
+
# What a reply gave (the worker's `done`).
|
|
22
|
+
Result = Data.define(:text, :reasoning, :stop, :prompt_tokens, :reused_tokens, :output_tokens,
|
|
23
|
+
:first_token_s, :total_s)
|
|
24
|
+
|
|
25
|
+
# A reply in flight: #value waits for it (calling the block given to #submit with its
|
|
26
|
+
# text as it comes, on the waiting thread).
|
|
27
|
+
class Reply
|
|
28
|
+
attr_reader :id
|
|
29
|
+
|
|
30
|
+
def initialize(worker, id, queue, on_delta)
|
|
31
|
+
@worker = worker
|
|
32
|
+
@id = id
|
|
33
|
+
@queue = queue
|
|
34
|
+
@on_delta = on_delta
|
|
35
|
+
@lock = Mutex.new
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def value
|
|
39
|
+
@lock.synchronize do
|
|
40
|
+
return @value if defined?(@value)
|
|
41
|
+
|
|
42
|
+
loop do
|
|
43
|
+
msg = @queue.pop
|
|
44
|
+
case msg["event"]
|
|
45
|
+
when "delta" then @on_delta&.call(msg["text"])
|
|
46
|
+
when "done"
|
|
47
|
+
@value = Result.new(**Result.members.to_h { |k| [k, msg[k.to_s]] })
|
|
48
|
+
return @value
|
|
49
|
+
else raise Error, msg["message"] || "unexpected answer #{msg}"
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def cancel = @worker.send(:write, op: "cancel", target: @id)
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# The repository's release build, for a checkout.
|
|
59
|
+
BUILT = File.expand_path("../../../target/release/opokay", __dir__)
|
|
60
|
+
|
|
61
|
+
# The binary a platform gem carries (script/build_gem.rb), of this gem's version.
|
|
62
|
+
BUNDLED = File.expand_path("../../libexec/opokay", __dir__)
|
|
63
|
+
|
|
64
|
+
# The opokay binary: $OPOKAY_BIN, else the repository's release build (a checkout), else the
|
|
65
|
+
# one this gem carries (a platform gem), else `opokay` on PATH. The one carried comes before
|
|
66
|
+
# PATH because it is the version this gem was released with (a newer `opokay` on PATH is
|
|
67
|
+
# used by setting OPOKAY_BIN). It is skipped when it does not run here (a CPU without AVX2,
|
|
68
|
+
# an older glibc), so that PATH still gets its turn. The release build when none of them is
|
|
69
|
+
# there, for the error to name.
|
|
70
|
+
def self.bin(env: ENV, built: BUILT, bundled: BUNDLED)
|
|
71
|
+
given = env["OPOKAY_BIN"]
|
|
72
|
+
return given if given && !given.empty?
|
|
73
|
+
return built if File.executable?(built)
|
|
74
|
+
return bundled if File.file?(bundled) && File.executable?(bundled) && runs?(bundled)
|
|
75
|
+
|
|
76
|
+
dirs = env.fetch("PATH", "").split(File::PATH_SEPARATOR)
|
|
77
|
+
dirs.map { |d| File.join(d, "opokay") }.find { |p| File.file?(p) && File.executable?(p) } || built
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# Whether `bin --version` runs and succeeds (the binary a platform gem carries may not run on
|
|
81
|
+
# this machine).
|
|
82
|
+
def self.runs?(bin)
|
|
83
|
+
_out, status = Open3.capture2e(bin, "--version")
|
|
84
|
+
status.success?
|
|
85
|
+
rescue SystemCallError
|
|
86
|
+
false
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# A worker on `model` (`args`: opokay's load options, as `"--mtp", path`), closed after
|
|
90
|
+
# the block if one is given. `log` gets the worker's notes (stderr).
|
|
91
|
+
def self.open(model, *args, log: $stderr, bin: self.bin)
|
|
92
|
+
w = new(model, *args, log:, bin:)
|
|
93
|
+
return w unless block_given?
|
|
94
|
+
|
|
95
|
+
begin
|
|
96
|
+
yield w
|
|
97
|
+
ensure
|
|
98
|
+
w.close
|
|
99
|
+
end
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
attr_reader :info
|
|
103
|
+
|
|
104
|
+
def initialize(model, *args, log: $stderr, bin: Worker.bin)
|
|
105
|
+
unless File.executable?(bin)
|
|
106
|
+
raise Error, "no opokay binary at #{bin} (the gems for arm64-darwin and x86_64-linux-gnu carry one; " \
|
|
107
|
+
"elsewhere cargo build --release -p opokay, then opokay on PATH or set OPOKAY_BIN)"
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
@stdin, @stdout, @stderr, @process = Open3.popen3(bin, "worker", model.to_s, *args.map(&:to_s))
|
|
111
|
+
@lock = Mutex.new
|
|
112
|
+
@pending = {}
|
|
113
|
+
@next = 0
|
|
114
|
+
@events = Queue.new
|
|
115
|
+
@notes = Thread.new { @stderr.each_line { |l| log&.write(l) } }
|
|
116
|
+
@reader = Thread.new { read_answers }
|
|
117
|
+
@info = @events.pop
|
|
118
|
+
unless @info["event"] == "ready" && @info["protocol"] == PROTOCOL
|
|
119
|
+
close
|
|
120
|
+
# A worker that started and answers another protocol is another version of opokay; one
|
|
121
|
+
# that ended before it was ready says why on stderr (`log`).
|
|
122
|
+
if @info["event"] == "ready"
|
|
123
|
+
raise Error, "#{bin} speaks protocol #{@info["protocol"].inspect}, this gem #{PROTOCOL} " \
|
|
124
|
+
"(another version of opokay)"
|
|
125
|
+
end
|
|
126
|
+
raise Error, "the worker did not start (#{bin}): #{@info}"
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# The model's chat format: "qwen" or "gemma4".
|
|
131
|
+
def format = @info["format"]
|
|
132
|
+
|
|
133
|
+
# The model's file name.
|
|
134
|
+
def model = @info["model"]
|
|
135
|
+
|
|
136
|
+
# A document's title, sections ({"title", "text"}) and, when it has no title of its own,
|
|
137
|
+
# the request for one ("title_prompt").
|
|
138
|
+
def extract(path) = call(op: "extract", path: path.to_s)
|
|
139
|
+
|
|
140
|
+
# The token counts of `texts`.
|
|
141
|
+
def count(texts) = call(op: "count", texts:)["counts"]
|
|
142
|
+
|
|
143
|
+
# The token ids of each of `texts` (what `count` counts: added tokens such as `<|im_start|>` are
|
|
144
|
+
# recognised, no BOS or EOS is added).
|
|
145
|
+
def tokenize(texts) = call(op: "tokenize", texts:)["ids"]
|
|
146
|
+
|
|
147
|
+
# `sections` ({title:, text:}) in parts of at most `limit` tokens, as summarize reads them
|
|
148
|
+
# ({"label", "text", "tokens"}).
|
|
149
|
+
def split(sections, limit) = call(op: "split", sections:, limit:)["parts"]
|
|
150
|
+
|
|
151
|
+
# The prompt of `messages` in the model's chat template ({"text", "tokens"}); without
|
|
152
|
+
# `generation_prompt` it ends with the last message, not with the start of the assistant's turn.
|
|
153
|
+
def render(messages, think: false, generation_prompt: true) =
|
|
154
|
+
call(op: "render", messages:, think:, generation_prompt:)
|
|
155
|
+
|
|
156
|
+
# Loads the model, with a KV cache of `kv_tokens` over `slots` replies at once.
|
|
157
|
+
def load(kv_tokens: nil, slots: nil, snapshots: nil)
|
|
158
|
+
call(op: "load", kv_tokens:, slots:, snapshots:).compact
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
# Starts a reply to `messages` ([{role:, content:}]) or a rendered `prompt`. Options:
|
|
162
|
+
# max_new, think, effort, temp, top_p, top_k, seed, keep ("system": the state after the
|
|
163
|
+
# system prompt is kept for later asks). The block gets the text as it comes.
|
|
164
|
+
def submit(messages: nil, prompt: nil, **opts, &on_delta)
|
|
165
|
+
req = {op: "generate", messages:, prompt:, stream: !on_delta.nil?, **opts}.compact
|
|
166
|
+
id, queue = enqueue
|
|
167
|
+
write(id:, **req)
|
|
168
|
+
Reply.new(self, id, queue, on_delta)
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
# The reply (a Result) to a request as #submit takes it.
|
|
172
|
+
def generate(...) = submit(...).value
|
|
173
|
+
|
|
174
|
+
# Ends the worker (after the replies in flight).
|
|
175
|
+
def close
|
|
176
|
+
return if @closed
|
|
177
|
+
|
|
178
|
+
@closed = true
|
|
179
|
+
begin
|
|
180
|
+
write(op: "shutdown")
|
|
181
|
+
@stdin.close
|
|
182
|
+
rescue IOError, Errno::EPIPE
|
|
183
|
+
nil
|
|
184
|
+
end
|
|
185
|
+
@reader.join
|
|
186
|
+
@notes.join
|
|
187
|
+
@process.value
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
private
|
|
191
|
+
|
|
192
|
+
def call(**req)
|
|
193
|
+
id, queue = enqueue
|
|
194
|
+
write(id:, **req)
|
|
195
|
+
msg = queue.pop
|
|
196
|
+
raise Error, msg["message"] if msg["event"] == "error" || msg["event"] == "fatal"
|
|
197
|
+
|
|
198
|
+
msg
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
def enqueue
|
|
202
|
+
@lock.synchronize do
|
|
203
|
+
id = (@next += 1)
|
|
204
|
+
queue = Queue.new
|
|
205
|
+
@pending[id] = queue
|
|
206
|
+
[id, queue]
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
def write(**req)
|
|
211
|
+
line = JSON.generate(req)
|
|
212
|
+
@lock.synchronize do
|
|
213
|
+
raise Error, "the worker is closed" if @stdin.closed?
|
|
214
|
+
|
|
215
|
+
@stdin.write(line, "\n")
|
|
216
|
+
@stdin.flush
|
|
217
|
+
end
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
def read_answers
|
|
221
|
+
@stdout.each_line do |line|
|
|
222
|
+
msg = JSON.parse(line)
|
|
223
|
+
id = msg["id"]
|
|
224
|
+
if msg["event"] == "fatal"
|
|
225
|
+
fail_all(msg)
|
|
226
|
+
elsif id.nil?
|
|
227
|
+
@events << msg
|
|
228
|
+
else
|
|
229
|
+
final = msg["event"] != "delta"
|
|
230
|
+
queue = @lock.synchronize { final ? @pending.delete(id) : @pending[id] }
|
|
231
|
+
queue&.push(msg)
|
|
232
|
+
end
|
|
233
|
+
end
|
|
234
|
+
ensure
|
|
235
|
+
fail_all("event" => "error", "message" => "the worker ended")
|
|
236
|
+
@events << {"event" => "ended"}
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
def fail_all(msg)
|
|
240
|
+
queues = @lock.synchronize { @pending.values.tap { @pending.clear } }
|
|
241
|
+
queues.each { |q| q << msg }
|
|
242
|
+
end
|
|
243
|
+
end
|
|
244
|
+
end
|
data/lib/opokay.rb
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# opokay from Ruby: the model runs in `opokay worker` (Rust, a child process), and
|
|
4
|
+
# `Opokay::Worker` is the requests to it. That is all `require "opokay"` loads, for a program
|
|
5
|
+
# that writes its own prompts; the document commands are `require "opokay/commands"`.
|
|
6
|
+
module Opokay
|
|
7
|
+
end
|
|
8
|
+
|
|
9
|
+
require_relative "opokay/version"
|
|
10
|
+
require_relative "opokay/worker"
|
data/libexec/opokay
ADDED
metadata
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: opokay
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: arm64-darwin
|
|
6
|
+
authors:
|
|
7
|
+
- takahashim
|
|
8
|
+
bindir: exe
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
executables:
|
|
13
|
+
- opokay-review
|
|
14
|
+
- opokay-summarize
|
|
15
|
+
extensions: []
|
|
16
|
+
extra_rdoc_files: []
|
|
17
|
+
files:
|
|
18
|
+
- LICENSE-APACHE
|
|
19
|
+
- LICENSE-MIT
|
|
20
|
+
- README.md
|
|
21
|
+
- exe/opokay-review
|
|
22
|
+
- exe/opokay-summarize
|
|
23
|
+
- lib/opokay.rb
|
|
24
|
+
- lib/opokay/command.rb
|
|
25
|
+
- lib/opokay/commands.rb
|
|
26
|
+
- lib/opokay/documents.rb
|
|
27
|
+
- lib/opokay/gen.rb
|
|
28
|
+
- lib/opokay/load_options.rb
|
|
29
|
+
- lib/opokay/prompts/review.md
|
|
30
|
+
- lib/opokay/review.rb
|
|
31
|
+
- lib/opokay/run_log.rb
|
|
32
|
+
- lib/opokay/summarize.rb
|
|
33
|
+
- lib/opokay/version.rb
|
|
34
|
+
- lib/opokay/worker.rb
|
|
35
|
+
- libexec/opokay
|
|
36
|
+
homepage: https://github.com/takahashim/opokay
|
|
37
|
+
licenses:
|
|
38
|
+
- MIT OR Apache-2.0
|
|
39
|
+
metadata:
|
|
40
|
+
rubygems_mfa_required: 'true'
|
|
41
|
+
rdoc_options: []
|
|
42
|
+
require_paths:
|
|
43
|
+
- lib
|
|
44
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
45
|
+
requirements:
|
|
46
|
+
- - ">="
|
|
47
|
+
- !ruby/object:Gem::Version
|
|
48
|
+
version: '3.3'
|
|
49
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
50
|
+
requirements:
|
|
51
|
+
- - ">="
|
|
52
|
+
- !ruby/object:Gem::Version
|
|
53
|
+
version: '0'
|
|
54
|
+
requirements: []
|
|
55
|
+
rubygems_version: 3.6.9
|
|
56
|
+
specification_version: 4
|
|
57
|
+
summary: 'opokay from Ruby: requests to `opokay worker`, and the document commands
|
|
58
|
+
on it'
|
|
59
|
+
test_files: []
|