@nakshi/genui-eval 0.0.0-stage → 1.0.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.
- package/LICENSE +202 -0
- package/README.md +51 -2
- package/dist/cases.d.ts +22 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +266 -0
- package/dist/run.d.ts +89 -0
- package/dist/score.d.ts +56 -0
- package/package.json +36 -4
package/LICENSE
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,52 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@nakshi/genui-eval`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Measure how a model writes [`@nakshi/genui`](https://www.npmjs.com/package/@nakshi/genui) answer blocks. Point it at your catalog, your guide and any model.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @nakshi/genui @nakshi/genui-eval
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { cases, runEval } from '@nakshi/genui-eval';
|
|
11
|
+
import { createDefaultCatalog, defaultGuide } from '@nakshi/genui-blocks';
|
|
12
|
+
|
|
13
|
+
const catalog = createDefaultCatalog('ui');
|
|
14
|
+
const { summary, results } = await runEval({
|
|
15
|
+
catalog,
|
|
16
|
+
cases, // or your own
|
|
17
|
+
guide: defaultGuide(catalog),
|
|
18
|
+
repeat: 3,
|
|
19
|
+
// Any model: yield the answer's text as it streams.
|
|
20
|
+
generate: async function* ({ system, user, reminder }) {
|
|
21
|
+
for await (const delta of myModel.stream([
|
|
22
|
+
{ role: 'system', content: system },
|
|
23
|
+
{ role: 'user', content: user },
|
|
24
|
+
{ role: 'system', content: reminder },
|
|
25
|
+
]))
|
|
26
|
+
yield delta;
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
console.log(summary.overall, summary.byCategory, summary.timing);
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## What it scores
|
|
33
|
+
|
|
34
|
+
For each answer, against its case:
|
|
35
|
+
|
|
36
|
+
- **Expected blocks present.** Each `expect` entry lists alternatives; `table` means a Markdown table.
|
|
37
|
+
- **No block in a prose case:** small talk, a fact, a definition, a short why, code.
|
|
38
|
+
- **Every block reads and closes.** A failure reports the field and the rule, never the body.
|
|
39
|
+
- **Repaired.** The block reads only thanks to repairs: the body as written was not valid JSON or a well-formed call.
|
|
40
|
+
- **The answer does not open on a block.**
|
|
41
|
+
- **Within budget:** at most `maxBlocks` blocks (default 3).
|
|
42
|
+
- **Grounded figures.** For cases with `sources`, every chart value and stat number must be found in them, as written or rounded.
|
|
43
|
+
|
|
44
|
+
An answer passes when its expected blocks are present, every block reads and closes, no block opens the answer, and none sits in a prose answer. It is clean when it also stays within budget and every figure is grounded.
|
|
45
|
+
|
|
46
|
+
Timing per answer: the first token, the first words a person can read outside any fence, and the first block with something to draw.
|
|
47
|
+
|
|
48
|
+
## The cases
|
|
49
|
+
|
|
50
|
+
There are 32 public cases, one chat turn each, across ten categories: `howto`, `process`, `checklist`, `recipe`, `data`, `compare`, `options`, `sections`, `warning` and `prose`. Prose is the category where the right answer has no block. Data cases carry illustrative source fixtures, so a chart is checked against what it was given. Keep the set fixed while comparing runs.
|
|
51
|
+
|
|
52
|
+
License: Apache-2.0
|
package/dist/cases.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A public set of cases for the default blocks (@nakshi/genui-blocks), one
|
|
3
|
+
* chat turn each. Categories:
|
|
4
|
+
* howto, process — things done or happening in order: `steps`
|
|
5
|
+
* checklist — a list to tick off: `checklist`
|
|
6
|
+
* recipe — `recipe` for the ingredients and `steps` for the method
|
|
7
|
+
* data — a series is a `chart`, headline figures are `stats`, and
|
|
8
|
+
* every figure comes from the sources given
|
|
9
|
+
* compare — options on the same attributes: `compare`, or a Markdown table
|
|
10
|
+
* options — options that each need their own words: `cards`
|
|
11
|
+
* sections — only when asked: `tabs`, `accordion`
|
|
12
|
+
* warning — a real hazard: `callout`
|
|
13
|
+
* prose — small talk, a fact, a definition, feelings, a short why,
|
|
14
|
+
* code: no block at all
|
|
15
|
+
*
|
|
16
|
+
* Sources are fixtures, not facts: the figures are illustrative, and a case
|
|
17
|
+
* checks that a chart repeats its sources, not that the sources are right.
|
|
18
|
+
* Keep the set fixed while comparing runs; a new case makes old rates
|
|
19
|
+
* incomparable.
|
|
20
|
+
*/
|
|
21
|
+
import type { EvalCase } from './score.js';
|
|
22
|
+
export declare const cases: readonly EvalCase[];
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @nakshi/genui-eval — measure how a model writes answer blocks.
|
|
3
|
+
*
|
|
4
|
+
* For a catalog and a set of cases: does the model use a block where the
|
|
5
|
+
* content has that shape and none where it is prose, does every block read and
|
|
6
|
+
* close, how many read only thanks to repairs, are its figures in the sources,
|
|
7
|
+
* and how soon do the first words and the first block arrive.
|
|
8
|
+
*/
|
|
9
|
+
export { readStrictly, scoreAnswer, type EvalCase, type ShapeScore } from './score.js';
|
|
10
|
+
export { buildPrompt, percentile, runEval, summarize, timeStream, type EvalResult, type EvalSummary, type PromptParts, type Rates, type RunOptions, type StreamTiming, } from './run.js';
|
|
11
|
+
export { cases } from './cases.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// packages/genui-eval/src/score.ts
|
|
2
|
+
import {
|
|
3
|
+
compactToJson,
|
|
4
|
+
looksLikeCompactBlock,
|
|
5
|
+
ungroundedFigures
|
|
6
|
+
} from "@nakshi/genui";
|
|
7
|
+
function bracketsWellFormed(body) {
|
|
8
|
+
const open = [];
|
|
9
|
+
let quote = null;
|
|
10
|
+
let escaped = false;
|
|
11
|
+
const pairs = { "(": ")", "[": "]", "{": "}" };
|
|
12
|
+
for (const ch of body) {
|
|
13
|
+
if (quote) {
|
|
14
|
+
if (escaped)
|
|
15
|
+
escaped = false;
|
|
16
|
+
else if (ch === "\\")
|
|
17
|
+
escaped = true;
|
|
18
|
+
else if (ch === quote)
|
|
19
|
+
quote = null;
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
if (ch === '"' || ch === "'")
|
|
23
|
+
quote = ch;
|
|
24
|
+
else if (pairs[ch])
|
|
25
|
+
open.push(pairs[ch]);
|
|
26
|
+
else if (ch === ")" || ch === "]" || ch === "}") {
|
|
27
|
+
if (open.pop() !== ch)
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return open.length === 0 && quote === null;
|
|
32
|
+
}
|
|
33
|
+
function readStrictly(body) {
|
|
34
|
+
const trimmed = body.trim();
|
|
35
|
+
try {
|
|
36
|
+
if (trimmed[0] === "{" || trimmed[0] === "[")
|
|
37
|
+
return JSON.parse(trimmed);
|
|
38
|
+
if (!looksLikeCompactBlock(trimmed) || !bracketsWellFormed(trimmed))
|
|
39
|
+
return null;
|
|
40
|
+
const json = compactToJson(trimmed, { finish: false });
|
|
41
|
+
return json == null ? null : JSON.parse(json);
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
var TABLE = /^\s*\|.*\|\s*\n\s*\|?\s*:?-{3,}/m;
|
|
47
|
+
function scoreAnswer(catalog, answer, expected) {
|
|
48
|
+
const parts = catalog.split(answer);
|
|
49
|
+
const blocks = {};
|
|
50
|
+
const failed = [];
|
|
51
|
+
let unclosed = 0;
|
|
52
|
+
let repaired = 0;
|
|
53
|
+
for (const part of parts) {
|
|
54
|
+
if (part.kind !== "block")
|
|
55
|
+
continue;
|
|
56
|
+
if (part.open) {
|
|
57
|
+
unclosed += 1;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const block = catalog.parse(part.type, part.body);
|
|
61
|
+
if (!block) {
|
|
62
|
+
failed.push({ type: part.type, issue: catalog.issue(part.type, part.body) ?? "does not read" });
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
blocks[part.type] = (blocks[part.type] ?? 0) + 1;
|
|
66
|
+
const strict = readStrictly(part.body);
|
|
67
|
+
const fits = strict !== null && catalog.parse(part.type, JSON.stringify(strict)) !== null;
|
|
68
|
+
if (!fits)
|
|
69
|
+
repaired += 1;
|
|
70
|
+
}
|
|
71
|
+
const firstContent = parts.find((p) => p.kind !== "markdown" || p.text.trim() !== "");
|
|
72
|
+
const opensWithBlock = firstContent?.kind === "block";
|
|
73
|
+
const markdownTable = parts.some((p) => p.kind === "markdown" && TABLE.test(p.text));
|
|
74
|
+
const has = (type) => type === "table" ? markdownTable : (blocks[type] ?? 0) > 0;
|
|
75
|
+
const expectedMet = (expected.expect ?? []).every((alternatives) => alternatives.some(has));
|
|
76
|
+
const count = Object.values(blocks).reduce((n, k) => n + k, 0) + failed.length + unclosed;
|
|
77
|
+
const blockInProse = Boolean(expected.prose) && count > 0;
|
|
78
|
+
const overBudget = count > (expected.maxBlocks ?? 3);
|
|
79
|
+
const ungrounded = expected.sources?.length ? ungroundedFigures(catalog.figures(answer), expected.sources) : [];
|
|
80
|
+
const pass = expectedMet && failed.length === 0 && unclosed === 0 && !opensWithBlock && !blockInProse;
|
|
81
|
+
return {
|
|
82
|
+
blocks,
|
|
83
|
+
failed,
|
|
84
|
+
unclosed,
|
|
85
|
+
repaired,
|
|
86
|
+
opensWithBlock,
|
|
87
|
+
markdownTable,
|
|
88
|
+
expectedMet,
|
|
89
|
+
blockInProse,
|
|
90
|
+
overBudget,
|
|
91
|
+
ungrounded,
|
|
92
|
+
pass,
|
|
93
|
+
clean: pass && !overBudget && ungrounded.length === 0
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
// packages/genui-eval/src/run.ts
|
|
97
|
+
function buildPrompt(catalog, c, guide) {
|
|
98
|
+
const sources = c.sources?.length ? `
|
|
99
|
+
|
|
100
|
+
What a search returned for this (use these figures, and no others):
|
|
101
|
+
${c.sources.map((s) => `- ${s}`).join(`
|
|
102
|
+
`)}` : "";
|
|
103
|
+
return { system: guide ?? catalog.guide(), user: `${c.prompt}${sources}`, reminder: catalog.reminder() };
|
|
104
|
+
}
|
|
105
|
+
function visibleWords(catalog, text) {
|
|
106
|
+
return catalog.split(text).some((p) => p.kind === "markdown" && /\p{L}{2,}/u.test(p.text.replace(/```[\s\S]*?(```|$)/g, "")));
|
|
107
|
+
}
|
|
108
|
+
function drawableBlock(catalog, text) {
|
|
109
|
+
return catalog.split(text).some((p) => p.kind === "block" && (p.open ? catalog.parsePartial(p.type, p.body) : catalog.parse(p.type, p.body)) !== null);
|
|
110
|
+
}
|
|
111
|
+
async function timeStream(catalog, stream, now = () => performance.now()) {
|
|
112
|
+
const started = now();
|
|
113
|
+
let text = "";
|
|
114
|
+
let firstTokenMs = null;
|
|
115
|
+
let firstWordsMs = null;
|
|
116
|
+
let firstBlockMs = null;
|
|
117
|
+
for await (const chunk of stream) {
|
|
118
|
+
if (!chunk)
|
|
119
|
+
continue;
|
|
120
|
+
const t = now() - started;
|
|
121
|
+
firstTokenMs ??= t;
|
|
122
|
+
text += chunk;
|
|
123
|
+
if (firstWordsMs === null && visibleWords(catalog, text))
|
|
124
|
+
firstWordsMs = t;
|
|
125
|
+
if (firstBlockMs === null && drawableBlock(catalog, text))
|
|
126
|
+
firstBlockMs = t;
|
|
127
|
+
}
|
|
128
|
+
return { text, timing: { firstTokenMs, firstWordsMs, firstBlockMs, totalMs: now() - started } };
|
|
129
|
+
}
|
|
130
|
+
async function runEval(options) {
|
|
131
|
+
const jobs = [];
|
|
132
|
+
for (let run = 0;run < (options.repeat ?? 1); run += 1)
|
|
133
|
+
for (const c of options.cases)
|
|
134
|
+
jobs.push({ c, run });
|
|
135
|
+
const results = [];
|
|
136
|
+
let next = 0;
|
|
137
|
+
const worker = async () => {
|
|
138
|
+
while (next < jobs.length) {
|
|
139
|
+
const { c, run } = jobs[next++];
|
|
140
|
+
let result;
|
|
141
|
+
try {
|
|
142
|
+
const { text, timing } = await timeStream(options.catalog, options.generate(buildPrompt(options.catalog, c, options.guide), c));
|
|
143
|
+
result = { case: c, run, text, timing, score: scoreAnswer(options.catalog, text, c) };
|
|
144
|
+
} catch (err) {
|
|
145
|
+
const score = scoreAnswer(options.catalog, "", c);
|
|
146
|
+
result = {
|
|
147
|
+
case: c,
|
|
148
|
+
run,
|
|
149
|
+
text: "",
|
|
150
|
+
timing: { firstTokenMs: null, firstWordsMs: null, firstBlockMs: null, totalMs: 0 },
|
|
151
|
+
score: { ...score, pass: false, clean: false },
|
|
152
|
+
error: err instanceof Error ? err.message : String(err)
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
results.push(result);
|
|
156
|
+
options.onResult?.(result);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
await Promise.all(Array.from({ length: Math.max(1, options.concurrency ?? 4) }, worker));
|
|
160
|
+
return { results, summary: summarize(results) };
|
|
161
|
+
}
|
|
162
|
+
function percentile(values, p) {
|
|
163
|
+
if (values.length === 0)
|
|
164
|
+
return null;
|
|
165
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
166
|
+
const rank = Math.min(sorted.length - 1, Math.max(0, Math.ceil(p / 100 * sorted.length) - 1));
|
|
167
|
+
return sorted[rank];
|
|
168
|
+
}
|
|
169
|
+
function rates(results) {
|
|
170
|
+
const n = results.length || 1;
|
|
171
|
+
const share = (count) => count / n;
|
|
172
|
+
const blocksRead = results.reduce((s, r) => s + Object.values(r.score.blocks).reduce((a, b) => a + b, 0), 0);
|
|
173
|
+
const repaired = results.reduce((s, r) => s + r.score.repaired, 0);
|
|
174
|
+
return {
|
|
175
|
+
n: results.length,
|
|
176
|
+
pass: share(results.filter((r) => r.score.pass).length),
|
|
177
|
+
clean: share(results.filter((r) => r.score.clean).length),
|
|
178
|
+
brokenBlock: share(results.filter((r) => r.score.failed.length > 0 || r.score.unclosed > 0).length),
|
|
179
|
+
repairedShare: blocksRead ? repaired / blocksRead : 0,
|
|
180
|
+
blocksRead,
|
|
181
|
+
blockInProse: share(results.filter((r) => r.score.blockInProse).length),
|
|
182
|
+
opensWithBlock: share(results.filter((r) => r.score.opensWithBlock).length),
|
|
183
|
+
ungroundedReplies: share(results.filter((r) => r.score.ungrounded.length > 0).length),
|
|
184
|
+
errors: results.filter((r) => r.error).length
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
function summarize(results) {
|
|
188
|
+
const byCategory = {};
|
|
189
|
+
for (const category of [...new Set(results.map((r) => r.case.category))]) {
|
|
190
|
+
byCategory[category] = rates(results.filter((r) => r.case.category === category));
|
|
191
|
+
}
|
|
192
|
+
const pick = (key) => results.map((r) => r.timing[key]).filter((v) => typeof v === "number");
|
|
193
|
+
const p = (key) => ({ p50: percentile(pick(key), 50), p90: percentile(pick(key), 90) });
|
|
194
|
+
return { overall: rates(results), byCategory, timing: { firstWordsMs: p("firstWordsMs"), firstBlockMs: p("firstBlockMs"), totalMs: p("totalMs") } };
|
|
195
|
+
}
|
|
196
|
+
// packages/genui-eval/src/cases.ts
|
|
197
|
+
var cases = [
|
|
198
|
+
{ id: "howto-tyre", category: "howto", prompt: "How do I change a flat tyre on a car?", expect: [["steps"]] },
|
|
199
|
+
{ id: "howto-router", category: "howto", prompt: "How do I reset my Wi-Fi router to factory settings?", expect: [["steps"]] },
|
|
200
|
+
{ id: "howto-repot", category: "howto", prompt: "How do I repot a houseplant without hurting it?", expect: [["steps"]] },
|
|
201
|
+
{ id: "howto-tie", category: "howto", prompt: "how to tie a tie (a simple knot)", expect: [["steps"]] },
|
|
202
|
+
{ id: "process-law", category: "process", prompt: "How does a bill become a law in the United States?", expect: [["steps"]] },
|
|
203
|
+
{ id: "process-url", category: "process", prompt: "What happens, step by step, when I type a web address into a browser and press enter?", expect: [["steps"]] },
|
|
204
|
+
{ id: "process-coffee", category: "process", prompt: "How do coffee beans get from the farm to my cup?", expect: [["steps"]] },
|
|
205
|
+
{ id: "checklist-beach", category: "checklist", prompt: "What should I pack for a three-day beach trip?", expect: [["checklist"]] },
|
|
206
|
+
{ id: "checklist-rent", category: "checklist", prompt: "What documents do I usually need to rent an apartment?", expect: [["checklist"]] },
|
|
207
|
+
{ id: "checklist-move", category: "checklist", prompt: "Give me a checklist for moving house.", expect: [["checklist"]] },
|
|
208
|
+
{ id: "recipe-pasta", category: "recipe", prompt: "How do I make a simple tomato pasta for four people?", expect: [["recipe"], ["steps"]], maxBlocks: 3 },
|
|
209
|
+
{ id: "recipe-pancakes", category: "recipe", prompt: "Recipe for banana pancakes, please.", expect: [["recipe"], ["steps"]], maxBlocks: 3 },
|
|
210
|
+
{
|
|
211
|
+
id: "data-temperature",
|
|
212
|
+
category: "data",
|
|
213
|
+
prompt: "How has the global average temperature changed since the 1980s?",
|
|
214
|
+
sources: [
|
|
215
|
+
"Global surface temperature anomaly by decade, relative to the 1951–1980 average: 1980s +0.26 °C, 1990s +0.43 °C, 2000s +0.62 °C, 2010s +0.87 °C, 2020–2024 +1.12 °C."
|
|
216
|
+
],
|
|
217
|
+
expect: [["chart", "stats"]]
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
id: "data-cities",
|
|
221
|
+
category: "data",
|
|
222
|
+
prompt: "What are the populations of the five largest cities in Japan?",
|
|
223
|
+
sources: ["City populations (2024 estimates): Tokyo special wards 9.73 million, Yokohama 3.77 million, Osaka 2.75 million, Nagoya 2.33 million, Sapporo 1.96 million."],
|
|
224
|
+
expect: [["chart", "stats", "table"]]
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
id: "data-revenue",
|
|
228
|
+
category: "data",
|
|
229
|
+
prompt: "Show me how Acme Robotics’ revenue grew from 2020 to 2024.",
|
|
230
|
+
sources: ["Acme Robotics annual revenue: 2020 $12.4M, 2021 $18.9M, 2022 $27.3M, 2023 $35.1M, 2024 $41.8M."],
|
|
231
|
+
expect: [["chart"]]
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
id: "data-survey",
|
|
235
|
+
category: "data",
|
|
236
|
+
prompt: "What are the headline numbers from this commuter survey?",
|
|
237
|
+
sources: ["Commuter survey 2025: 1,250 people surveyed; 72% commute by public transport; the median commute is 34 minutes; satisfaction rose 6 points from 2024."],
|
|
238
|
+
expect: [["stats"]]
|
|
239
|
+
},
|
|
240
|
+
{ id: "compare-db", category: "compare", prompt: "PostgreSQL or MySQL for a small web app? Compare them.", expect: [["compare", "table"]] },
|
|
241
|
+
{ id: "compare-rent", category: "compare", prompt: "Compare renting and buying a home on cost, flexibility and risk.", expect: [["compare", "table"]] },
|
|
242
|
+
{ id: "compare-ebook", category: "compare", prompt: "Kindle or Kobo — how do they compare for someone who reads a lot?", expect: [["compare", "table"]] },
|
|
243
|
+
{ id: "options-spanish", category: "options", prompt: "Give me three different ways to learn Spanish, each with its trade-offs.", expect: [["cards", "compare"]] },
|
|
244
|
+
{ id: "options-woodwork", category: "options", prompt: "Suggest four weekend projects for a beginner woodworker.", expect: [["cards"]] },
|
|
245
|
+
{ id: "sections-node", category: "sections", prompt: "Explain how to install Node.js, with separate tabs for Windows, macOS and Linux.", expect: [["tabs"]] },
|
|
246
|
+
{ id: "sections-faq", category: "sections", prompt: "Write an FAQ I can open and close about returning items to an online shop.", expect: [["accordion"]] },
|
|
247
|
+
{ id: "warning-bleach", category: "warning", prompt: "Can I mix bleach and vinegar to clean my bathroom?", expect: [["callout"]] },
|
|
248
|
+
{ id: "warning-generator", category: "warning", prompt: "Is it fine to run a petrol generator in my garage with the door half open?", expect: [["callout"]] },
|
|
249
|
+
{ id: "prose-thanks", category: "prose", prompt: "Thanks, that helped a lot!", prose: true },
|
|
250
|
+
{ id: "prose-capital", category: "prose", prompt: "What is the capital of Australia?", prose: true },
|
|
251
|
+
{ id: "prose-word", category: "prose", prompt: 'What does "ephemeral" mean?', prose: true },
|
|
252
|
+
{ id: "prose-nervous", category: "prose", prompt: "I am nervous about my job interview tomorrow.", prose: true },
|
|
253
|
+
{ id: "prose-opinion", category: "prose", prompt: "Is it better to be an early bird or a night owl?", prose: true },
|
|
254
|
+
{ id: "prose-code", category: "prose", prompt: "How do I reverse a list in Python?", prose: true },
|
|
255
|
+
{ id: "prose-why", category: "prose", prompt: "Why is the sky blue?", prose: true }
|
|
256
|
+
];
|
|
257
|
+
export {
|
|
258
|
+
buildPrompt,
|
|
259
|
+
cases,
|
|
260
|
+
percentile,
|
|
261
|
+
readStrictly,
|
|
262
|
+
runEval,
|
|
263
|
+
scoreAnswer,
|
|
264
|
+
summarize,
|
|
265
|
+
timeStream
|
|
266
|
+
};
|
package/dist/run.d.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Running cases against a model and summarising: each case is asked with the
|
|
3
|
+
* catalog's guide, its stream is timed (first token, first words, first block
|
|
4
|
+
* that can be drawn), and its answer scored. `generate` is yours: any model,
|
|
5
|
+
* any provider, a recorded fixture.
|
|
6
|
+
*/
|
|
7
|
+
import type { BlockDefinition, BlockSchema, Catalog } from '@nakshi/genui';
|
|
8
|
+
import { type EvalCase, type ShapeScore } from './score.js';
|
|
9
|
+
type AnyBlocks = readonly BlockDefinition<string, BlockSchema>[];
|
|
10
|
+
export interface PromptParts {
|
|
11
|
+
/** The system prompt: the catalog's guide (or yours). */
|
|
12
|
+
readonly system: string;
|
|
13
|
+
/** The person's message, with the case's sources when it has any. */
|
|
14
|
+
readonly user: string;
|
|
15
|
+
/** To say last in the turn, after the message. */
|
|
16
|
+
readonly reminder: string;
|
|
17
|
+
}
|
|
18
|
+
export interface StreamTiming {
|
|
19
|
+
readonly firstTokenMs: number | null;
|
|
20
|
+
/** The first words a person can read outside any fence. */
|
|
21
|
+
readonly firstWordsMs: number | null;
|
|
22
|
+
/** The first block with something to draw (finished items, or the finished block). */
|
|
23
|
+
readonly firstBlockMs: number | null;
|
|
24
|
+
readonly totalMs: number;
|
|
25
|
+
}
|
|
26
|
+
export interface EvalResult {
|
|
27
|
+
readonly case: EvalCase;
|
|
28
|
+
readonly run: number;
|
|
29
|
+
readonly text: string;
|
|
30
|
+
readonly score: ShapeScore;
|
|
31
|
+
readonly timing: StreamTiming;
|
|
32
|
+
/** Set when generate threw: the case counts as failed. */
|
|
33
|
+
readonly error?: string;
|
|
34
|
+
}
|
|
35
|
+
export declare function buildPrompt<Blocks extends AnyBlocks>(catalog: Catalog<Blocks>, c: EvalCase, guide?: string): PromptParts;
|
|
36
|
+
/** Reads a stream of text deltas, noting when each milestone arrives. */
|
|
37
|
+
export declare function timeStream<Blocks extends AnyBlocks>(catalog: Catalog<Blocks>, stream: AsyncIterable<string>, now?: () => number): Promise<{
|
|
38
|
+
text: string;
|
|
39
|
+
timing: StreamTiming;
|
|
40
|
+
}>;
|
|
41
|
+
export interface RunOptions<Blocks extends AnyBlocks> {
|
|
42
|
+
readonly catalog: Catalog<Blocks>;
|
|
43
|
+
readonly cases: readonly EvalCase[];
|
|
44
|
+
readonly generate: (prompt: PromptParts, c: EvalCase) => AsyncIterable<string>;
|
|
45
|
+
/** Replaces the catalog's default guide. */
|
|
46
|
+
readonly guide?: string;
|
|
47
|
+
readonly repeat?: number;
|
|
48
|
+
readonly concurrency?: number;
|
|
49
|
+
readonly onResult?: (result: EvalResult) => void;
|
|
50
|
+
}
|
|
51
|
+
export declare function runEval<Blocks extends AnyBlocks>(options: RunOptions<Blocks>): Promise<{
|
|
52
|
+
results: EvalResult[];
|
|
53
|
+
summary: EvalSummary;
|
|
54
|
+
}>;
|
|
55
|
+
export interface Rates {
|
|
56
|
+
readonly n: number;
|
|
57
|
+
readonly pass: number;
|
|
58
|
+
readonly clean: number;
|
|
59
|
+
/** Replies with a block that did not read or close. */
|
|
60
|
+
readonly brokenBlock: number;
|
|
61
|
+
/** Blocks read only thanks to repairs, out of all blocks that read. */
|
|
62
|
+
readonly repairedShare: number;
|
|
63
|
+
readonly blocksRead: number;
|
|
64
|
+
readonly blockInProse: number;
|
|
65
|
+
readonly opensWithBlock: number;
|
|
66
|
+
readonly ungroundedReplies: number;
|
|
67
|
+
readonly errors: number;
|
|
68
|
+
}
|
|
69
|
+
export interface EvalSummary {
|
|
70
|
+
readonly overall: Rates;
|
|
71
|
+
readonly byCategory: Readonly<Record<string, Rates>>;
|
|
72
|
+
readonly timing: {
|
|
73
|
+
readonly firstWordsMs: {
|
|
74
|
+
p50: number | null;
|
|
75
|
+
p90: number | null;
|
|
76
|
+
};
|
|
77
|
+
readonly firstBlockMs: {
|
|
78
|
+
p50: number | null;
|
|
79
|
+
p90: number | null;
|
|
80
|
+
};
|
|
81
|
+
readonly totalMs: {
|
|
82
|
+
p50: number | null;
|
|
83
|
+
p90: number | null;
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
export declare function percentile(values: readonly number[], p: number): number | null;
|
|
88
|
+
export declare function summarize(results: readonly EvalResult[]): EvalSummary;
|
|
89
|
+
export {};
|
package/dist/score.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scoring one answer's shape against what its case expects: the blocks it
|
|
3
|
+
* should have, a prose answer with none, every block reading and closing, not
|
|
4
|
+
* opening on a block, staying within a block budget, and figures found in the
|
|
5
|
+
* sources. Pure, so the rules are testable apart from any model.
|
|
6
|
+
*/
|
|
7
|
+
import { type BlockDefinition, type BlockSchema, type Catalog, type Figure } from '@nakshi/genui';
|
|
8
|
+
type AnyBlocks = readonly BlockDefinition<string, BlockSchema>[];
|
|
9
|
+
export interface EvalCase {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly category: string;
|
|
12
|
+
readonly prompt: string;
|
|
13
|
+
/** What a search returned, given to the model; figures are checked against these. */
|
|
14
|
+
readonly sources?: readonly string[];
|
|
15
|
+
/** Each entry lists alternatives; the answer needs one of every entry. `table` is a Markdown table. */
|
|
16
|
+
readonly expect?: ReadonlyArray<readonly string[]>;
|
|
17
|
+
/** The right answer has no block at all. */
|
|
18
|
+
readonly prose?: boolean;
|
|
19
|
+
/** At most this many blocks for a clean answer. Default 3. */
|
|
20
|
+
readonly maxBlocks?: number;
|
|
21
|
+
}
|
|
22
|
+
export interface ShapeScore {
|
|
23
|
+
/** Finished blocks that read, by type. */
|
|
24
|
+
readonly blocks: Readonly<Record<string, number>>;
|
|
25
|
+
/** Finished blocks that do not read: their type and the issue (never the body). */
|
|
26
|
+
readonly failed: ReadonlyArray<{
|
|
27
|
+
type: string;
|
|
28
|
+
issue: string;
|
|
29
|
+
}>;
|
|
30
|
+
/** Blocks whose fence never closed. */
|
|
31
|
+
readonly unclosed: number;
|
|
32
|
+
/** Blocks that read only after repairs: the body as written was not valid JSON or a well-formed call. */
|
|
33
|
+
readonly repaired: number;
|
|
34
|
+
readonly opensWithBlock: boolean;
|
|
35
|
+
readonly markdownTable: boolean;
|
|
36
|
+
readonly expectedMet: boolean;
|
|
37
|
+
/** A prose case that got a block. */
|
|
38
|
+
readonly blockInProse: boolean;
|
|
39
|
+
readonly overBudget: boolean;
|
|
40
|
+
/** Figures no source states, with their block's type (only when the case has sources). */
|
|
41
|
+
readonly ungrounded: ReadonlyArray<Figure & {
|
|
42
|
+
readonly type: string;
|
|
43
|
+
}>;
|
|
44
|
+
/** Expected blocks present; every block reads and closes; no block opens the answer or sits in a prose answer. */
|
|
45
|
+
readonly pass: boolean;
|
|
46
|
+
/** Pass, within budget, and every figure grounded. */
|
|
47
|
+
readonly clean: boolean;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A body read with no repair: JSON that JSON.parse takes as written, or a
|
|
51
|
+
* call whose brackets close in order and whose JSON form parses as is.
|
|
52
|
+
* Null when it does not read that way.
|
|
53
|
+
*/
|
|
54
|
+
export declare function readStrictly(body: string): unknown | null;
|
|
55
|
+
export declare function scoreAnswer<Blocks extends AnyBlocks>(catalog: Catalog<Blocks>, answer: string, expected: EvalCase): ShapeScore;
|
|
56
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nakshi/genui-eval",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Measure how a model writes @nakshi/genui answer blocks: shape, validity, repairs, grounding and time to first block",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js",
|
|
14
|
+
"default": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"LICENSE",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"homepage": "https://nakshi.ai/blog/generative-ui",
|
|
23
|
+
"keywords": [
|
|
24
|
+
"generative-ui",
|
|
25
|
+
"genui",
|
|
26
|
+
"llm",
|
|
27
|
+
"streaming",
|
|
28
|
+
"markdown",
|
|
29
|
+
"components",
|
|
30
|
+
"ai"
|
|
31
|
+
],
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@nakshi/genui": "^1.0.0"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
}
|
|
38
|
+
}
|