@hamzaahmadaslam/schema-truth 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 +21 -0
- package/README.md +239 -2
- package/bin/schema-truth.mjs +4 -0
- package/package.json +39 -4
- package/src/check.mjs +213 -0
- package/src/claims.mjs +252 -0
- package/src/cli.mjs +128 -0
- package/src/errors.mjs +7 -0
- package/src/fetch.mjs +338 -0
- package/src/html.mjs +337 -0
- package/src/jev.mjs +92 -0
- package/src/load.mjs +130 -0
- package/src/report.mjs +190 -0
- package/src/version.mjs +6 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hamza Ahmad Aslam
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,240 @@
|
|
|
1
|
-
#
|
|
1
|
+
# schema-truth
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Checks whether the values in a page's JSON-LD (prices, availability, ratings, reviews, authors, dates, headlines, FAQ
|
|
4
|
+
answers, addresses and phone numbers) are shown in the text visitors see; for SEO specialists and developers who
|
|
5
|
+
look after structured data.
|
|
6
|
+
|
|
7
|
+
Google's [structured data policies](https://developers.google.com/search/docs/appearance/structured-data/sd-policies)
|
|
8
|
+
rule out marking up content that readers of the page cannot see, and ask that markup be "a true representation of
|
|
9
|
+
the page content". Markup drifts from the page: a sale changes the price on the page but not in the JSON-LD, a
|
|
10
|
+
plugin keeps last year's FAQ answer, a rating count comes from another system. Schema validators check that the
|
|
11
|
+
markup is well formed and has the required properties; they do not compare its values with the page. A string match
|
|
12
|
+
cannot tell that "2 March 2026" on the page is the `2026-03-02` in the markup, or that "$109.00" is not the
|
|
13
|
+
`129.00 USD` it claims. A text-generating model can judge that, but it returns prose to parse and no measure of how
|
|
14
|
+
sure it is. schema-truth asks one yes/no question per value and gets a probability back, so code makes the call and
|
|
15
|
+
unclear values go to a review list.
|
|
16
|
+
|
|
17
|
+
## How it uses Jev
|
|
18
|
+
|
|
19
|
+
Jev is TypeSafe AI's System One model: it answers typed questions with probabilities and writes no text.
|
|
20
|
+
|
|
21
|
+
Code does the reading. For each page, schema-truth extracts every `<script type="application/ld+json">` block,
|
|
22
|
+
follows `@graph` and `@id` links, and turns the values worth checking into claims:
|
|
23
|
+
|
|
24
|
+
| Markup | Claims |
|
|
25
|
+
| ------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
26
|
+
| `Offer`, `AggregateOffer`, `PriceSpecification` | price with its currency, lowest and highest price, list price, availability |
|
|
27
|
+
| `AggregateRating`, `Review` | average rating, number of ratings, number of reviews, each review's author and rating |
|
|
28
|
+
| `Article`, `BlogPosting`, `Event` and other items | headline, author, date published, date modified, start date, end date |
|
|
29
|
+
| `FAQPage`, `QAPage` | each question, and its accepted answer |
|
|
30
|
+
| `Organization`, `LocalBusiness`, `ContactPoint` | address, phone number |
|
|
31
|
+
|
|
32
|
+
It also extracts the text a visitor sees. Left out: scripts, styles, the `<head>`, `<noscript>`, `<template>`, inline
|
|
33
|
+
SVG, closed `<dialog>` elements, and anything inside an element with the `hidden` attribute or an inline
|
|
34
|
+
`display: none` or `visibility: hidden` style. Image alt text is kept as `[image: ...]`, and table cells are joined
|
|
35
|
+
with `|`.
|
|
36
|
+
|
|
37
|
+
Then it sends one request per page. The visible text is the state, and each claim is one noul (a yes/no question),
|
|
38
|
+
with the claim passed as data next to a fixed question:
|
|
39
|
+
|
|
40
|
+
```json
|
|
41
|
+
{
|
|
42
|
+
"state": { "visible_text": "Northfield Outfitters Shoes Delivery\nTrail Runner 2\nWas $129.00, now $109.00 until Sunday\n..." },
|
|
43
|
+
"questions": {
|
|
44
|
+
"c1": {
|
|
45
|
+
"type": "noul",
|
|
46
|
+
"instructions": {
|
|
47
|
+
"claim": { "item": "Trail Runner 2 (Product)", "property": "price", "value": "129.00 USD" },
|
|
48
|
+
"question": "Is the value in `claim` supported by `visible_text`, the text a visitor sees on the page?"
|
|
49
|
+
},
|
|
50
|
+
"criteria": {
|
|
51
|
+
"true": "`visible_text` shows this value for this property of this item. It may be written another way: ...",
|
|
52
|
+
"false": "`visible_text` does not show this value, shows a different value for this property, or ..."
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Before a value is sent, code rewrites ISO dates in words ("2 March 2026") and availability URLs as words ("in
|
|
60
|
+
stock"), the way pages show them. TypeSafe's notes on jev-1.13 advise doing such conversions in code rather than
|
|
61
|
+
leaving them to the model. The full wording is in `src/check.mjs`, and `--dry-run --json` prints every request
|
|
62
|
+
body.
|
|
63
|
+
|
|
64
|
+
The verdict is made in code with one threshold, `--threshold` (default 0.8):
|
|
65
|
+
|
|
66
|
+
| Verdict | When |
|
|
67
|
+
| ----------- | ---------------------------------------------------------------------------------- |
|
|
68
|
+
| supported | the probability is at least the threshold |
|
|
69
|
+
| unsupported | the probability is at most 1 minus the threshold (0.2 by default) |
|
|
70
|
+
| review | anything in between, a missing answer, or a page with no visible text in its HTML |
|
|
71
|
+
|
|
72
|
+
A page whose visible text is longer than about 16,000 tokens is sent in parts, each with every claim, and a claim
|
|
73
|
+
counts as supported when any part shows it. The report prints the probability next to every claim. Every word in it
|
|
74
|
+
comes from your pages or from fixed text in the code.
|
|
75
|
+
|
|
76
|
+
## Install
|
|
77
|
+
|
|
78
|
+
Needs Node.js 20 or later. It has no dependencies.
|
|
79
|
+
|
|
80
|
+
```sh
|
|
81
|
+
npm install -g @hamzaahmadaslam/schema-truth
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Usage
|
|
85
|
+
|
|
86
|
+
```sh
|
|
87
|
+
export TYPESAFE_API_KEY=<your-key>
|
|
88
|
+
schema-truth https://shop.example/trail-runner-2
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
In PowerShell, set the key with `$env:TYPESAFE_API_KEY = "<your-key>"`.
|
|
92
|
+
|
|
93
|
+
```sh
|
|
94
|
+
schema-truth https://shop.example/a https://shop.example/b # several pages in one run
|
|
95
|
+
schema-truth saved-pages/ # every .html, .htm and .xhtml file below a folder
|
|
96
|
+
schema-truth page.html --dry-run # the claims, the question and a token estimate; nothing sent to TypeSafe
|
|
97
|
+
schema-truth https://shop.example/a --json > report.json
|
|
98
|
+
schema-truth saved-pages/ --threshold 0.9 # stricter: more claims go to review
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
| Option | Default | What it does |
|
|
102
|
+
| --------------------- | ------- | ------------------------------------------------------------------------------------------------ |
|
|
103
|
+
| `--threshold <p>` | `0.8` | Probability needed to call a claim supported or unsupported. Above 0.5, at most 1. |
|
|
104
|
+
| `--timeout <seconds>` | `10` | Time limit for each page and each TypeSafe request. Rate limits (429) and overload (529) are retried three times. |
|
|
105
|
+
| `--json` | off | Print JSON: every page, every claim, its verdict and the raw probability. |
|
|
106
|
+
| `--dry-run` | off | Read the pages and print the claims and a token estimate. Needs no key; sends nothing to TypeSafe. |
|
|
107
|
+
|
|
108
|
+
Environment: `TYPESAFE_API_KEY` (not needed for `--dry-run`, or when no page has claims to check) and
|
|
109
|
+
`TYPESAFE_MODEL` (default `jev-latest`).
|
|
110
|
+
|
|
111
|
+
Exit codes: `0` when no claim is unsupported, `1` when at least one is, so it can fail a CI job, and `2` on an error
|
|
112
|
+
or when a page could not be read. Claims in review do not change the exit code. JSON-LD blocks that are not valid
|
|
113
|
+
JSON are listed in the report but do not change it either.
|
|
114
|
+
|
|
115
|
+
### Fetching pages
|
|
116
|
+
|
|
117
|
+
- Only `http` and `https` URLs.
|
|
118
|
+
- Before connecting, schema-truth resolves the host name and checks every address it gets back. Loopback, private,
|
|
119
|
+
link-local, cloud metadata (such as `169.254.169.254` and `fd00:ec2::254`), multicast and other reserved ranges,
|
|
120
|
+
IPv4 and IPv6, are refused, including addresses written into the URL itself. The connection then goes only to the
|
|
121
|
+
addresses that passed, so a second DNS answer cannot point it somewhere else. The same checks run again on every
|
|
122
|
+
redirect, and it follows at most 3.
|
|
123
|
+
- A 10 second limit per page (`--timeout`), and at most 2 MB of HTML. Compressed pages (gzip, deflate, br) are
|
|
124
|
+
decompressed and the limit applies to the result.
|
|
125
|
+
- The User-Agent is `schema-truth/1.0.0 (+https://github.com/hamzaahmadaslam/schema-truth)`.
|
|
126
|
+
- To check a page on your own machine or network, or one the site does not serve to tools, save it from your browser
|
|
127
|
+
and pass the file.
|
|
128
|
+
|
|
129
|
+
## Example
|
|
130
|
+
|
|
131
|
+
`examples/pages` holds three short pages for a made-up shop, written for this example: a product page, a delivery
|
|
132
|
+
FAQ and an article. The probabilities below come from `examples/fixture-answers.json`: they were written by hand for
|
|
133
|
+
the tests, not recorded from TypeSafe, and show the report format. Your numbers will differ.
|
|
134
|
+
`node examples/run.mjs` prints this report without a key or a network call.
|
|
135
|
+
|
|
136
|
+
```text
|
|
137
|
+
schema-truth: 20 claims on 3 pages
|
|
138
|
+
Model jev-1.13.0, 3 requests, 3,420 input tokens, threshold 0.8
|
|
139
|
+
|
|
140
|
+
supported 12 unsupported 6 review 2
|
|
141
|
+
|
|
142
|
+
delivery-faq.html
|
|
143
|
+
1 JSON-LD block (FAQPage); 6 claims: unsupported 1, review 1, supported 4
|
|
144
|
+
unsupported 0.04 answer to "Can I return shoes I have worn?": Yes, within 60 days of delivery.
|
|
145
|
+
FAQPage; block 1, mainEntity[1].acceptedAnswer.text
|
|
146
|
+
review 0.46 answer to "Do you ship to Canada?": Yes, we ship to every province.
|
|
147
|
+
FAQPage; block 1, mainEntity[2].acceptedAnswer.text
|
|
148
|
+
supported 0.98 question: How long does delivery take?
|
|
149
|
+
supported 0.95 answer to "How long does delivery take?": Orders arrive in 2 to 4 working days.
|
|
150
|
+
supported 0.97 question: Can I return shoes I have worn?
|
|
151
|
+
supported 0.94 question: Do you ship to Canada?
|
|
152
|
+
|
|
153
|
+
shoe-care-guide.html
|
|
154
|
+
2 JSON-LD blocks (BlogPosting, Person, Organization), 1 not valid JSON; 6 claims: unsupported 2, supported 4
|
|
155
|
+
block 2 (line 41) is not valid JSON; its claims were not checked
|
|
156
|
+
unsupported 0.06 date modified: 19 August 2026
|
|
157
|
+
How to dry wet trail shoes (BlogPosting); block 1, @graph[0].dateModified
|
|
158
|
+
unsupported 0.03 phone number: +1-415-555-0142
|
|
159
|
+
Northfield Outfitters (Organization); block 1, @graph[2].telephone
|
|
160
|
+
supported 0.98 headline: How to dry wet trail shoes
|
|
161
|
+
supported 0.96 author: Rosa Lind
|
|
162
|
+
supported 0.93 date published: 2 March 2026
|
|
163
|
+
supported 0.87 address: 14 Quarry Lane, Sampleton, 00014, US
|
|
164
|
+
|
|
165
|
+
trail-runner.html
|
|
166
|
+
1 JSON-LD block (Product); 8 claims: unsupported 3, review 1, supported 4
|
|
167
|
+
unsupported 0.08 number of ratings: 312
|
|
168
|
+
Trail Runner 2 (Product); block 1, aggregateRating.ratingCount
|
|
169
|
+
unsupported 0.05 review author: Sam P.
|
|
170
|
+
Trail Runner 2 (Product); block 1, review[1].author
|
|
171
|
+
unsupported 0.04 rating in the review by Sam P.: 2 out of 5
|
|
172
|
+
Trail Runner 2 (Product); block 1, review[1].reviewRating.ratingValue
|
|
173
|
+
review 0.41 price: 129.00 USD
|
|
174
|
+
Trail Runner 2 (Product); block 1, offers.price
|
|
175
|
+
supported 0.95 availability: in stock
|
|
176
|
+
supported 0.97 average rating: 4.6 out of 5
|
|
177
|
+
supported 0.96 review author: Dana K.
|
|
178
|
+
supported 0.93 rating in the review by Dana K.: 5 out of 5
|
|
179
|
+
|
|
180
|
+
supported: the visible text shows the value (probability at or above 0.8).
|
|
181
|
+
unsupported: the visible text does not show it (probability at or below 0.2). Google asks that structured
|
|
182
|
+
data describe only content visible to readers of the page:
|
|
183
|
+
https://developers.google.com/search/docs/appearance/structured-data/sd-policies
|
|
184
|
+
review: Jev was not sure either way, or had no text to read. Check these on the page yourself.
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
The FAQ markup promises returns within 60 days while the page says 30 days and unworn shoes only. The article's
|
|
188
|
+
markup has a modified date the page never shows and a phone number that differs from the one in the footer, and its
|
|
189
|
+
breadcrumb block has a trailing comma. The product markup counts 312 ratings where the page shows 48 reviews, and it
|
|
190
|
+
lists a review by Sam P. that sits in a `hidden` element. The price sits in the middle: `129.00` is on the page, but
|
|
191
|
+
struck through next to the $109.00 sale price, so it goes to review. The same run with `--json` is in
|
|
192
|
+
`examples/report.json`, and the dry run in `examples/dry-run.txt`.
|
|
193
|
+
|
|
194
|
+
## What leaves your machine
|
|
195
|
+
|
|
196
|
+
Two kinds of requests, and no others:
|
|
197
|
+
|
|
198
|
+
- To each URL you pass, and to the redirects it sends (at most 3): a `GET` request with the User-Agent above and
|
|
199
|
+
standard `Accept` headers. No cookies. Saved files are read from disk and nothing is fetched for them.
|
|
200
|
+
- To `https://api.typesafe.ai/v1/systemone`, only when you run it with a key and without `--dry-run`: the visible
|
|
201
|
+
text of each page as extracted (at most about 16,000 tokens of it per request), each claim (the item's name, the
|
|
202
|
+
property and the value), the fixed question text, question ids such as `c1`, and the model name. Your API key goes
|
|
203
|
+
in the `Authorization` header.
|
|
204
|
+
|
|
205
|
+
TypeSafe does not receive a page's URL or file name, its raw HTML, the JSON-LD blocks themselves or the paths inside
|
|
206
|
+
them. The tool writes nothing to disk and makes no other network requests, for telemetry, updates or anything else.
|
|
207
|
+
|
|
208
|
+
## Limits
|
|
209
|
+
|
|
210
|
+
- It reads the HTML as served. Scripts do not run, so content a script adds is missed; save the rendered page from
|
|
211
|
+
your browser if the site builds it that way. Stylesheets are not loaded either, so text hidden only by a CSS class
|
|
212
|
+
(a closed accordion or tab, screen-reader-only text) counts as visible. Text inside `<details>` counts as visible.
|
|
213
|
+
- Only JSON-LD. Microdata and RDFa are not read.
|
|
214
|
+
- Only the claims in the table above are checked. Brand, SKU, opening hours, images and breadcrumb names are not.
|
|
215
|
+
- "unsupported" means the visible text does not show the value. How much that matters depends on the property: a
|
|
216
|
+
price or review the page does not show is a bigger problem than a modified date.
|
|
217
|
+
- Jev reads numbers and dates as text, and the tool does no arithmetic, so a rating shown as a percentage or a price
|
|
218
|
+
shown in another currency will usually go to review or come back unsupported.
|
|
219
|
+
- On a page checked in parts, a value whose context falls in another part may be judged wrongly.
|
|
220
|
+
- English is where Jev is most accurate. The token estimate assumes four characters per token, which fits English.
|
|
221
|
+
- Text written to steer a model, in the page or in the markup, can move Jev's answers.
|
|
222
|
+
- The tool reports and never edits anything. Read the review list yourself, and check a sample of verdicts on your
|
|
223
|
+
own pages before you rely on a threshold.
|
|
224
|
+
|
|
225
|
+
## Token use
|
|
226
|
+
|
|
227
|
+
The visible text is most of each request, and each claim adds about 160 tokens. By the tool's own estimate (four
|
|
228
|
+
characters per token):
|
|
229
|
+
|
|
230
|
+
| Run | Requests | Input tokens |
|
|
231
|
+
| --------------------------------------------------------------- | -------- | ------------------ |
|
|
232
|
+
| The example: 20 claims on 3 short pages | 3 | about 3,400 |
|
|
233
|
+
| A product page with about 9,300 tokens of text and 11 claims | 1 | about 11,100 |
|
|
234
|
+
| 1,000 pages like that one | 1,000 | about 11.1 million |
|
|
235
|
+
|
|
236
|
+
`--dry-run` prints the estimate for your own pages before anything is sent.
|
|
237
|
+
|
|
238
|
+
## License
|
|
239
|
+
|
|
240
|
+
MIT. Made by [Hamza Ahmad Aslam](https://hamzaahmadaslam.com), WordPress and web performance engineer.
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hamzaahmadaslam/schema-truth",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Checks whether the values in a page's JSON-LD (prices, ratings, reviews, authors, dates, FAQ answers, addresses) are shown in the text visitors see, using TypeSafe's Jev model.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"schema-truth": "bin/schema-truth.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=20"
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"test": "node --test"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"json-ld",
|
|
21
|
+
"structured-data",
|
|
22
|
+
"schema-org",
|
|
23
|
+
"seo",
|
|
24
|
+
"rich-results",
|
|
25
|
+
"typesafe",
|
|
26
|
+
"jev"
|
|
27
|
+
],
|
|
28
|
+
"author": "Hamza Ahmad Aslam (https://hamzaahmadaslam.com)",
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/hamzaahmadaslam/schema-truth.git"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://hamzaahmadaslam.com/open-source/schema-truth",
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/hamzaahmadaslam/schema-truth/issues"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/check.mjs
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Builds the requests (a page's visible text as the state, one yes/no question per claim), sends them to Jev, and
|
|
2
|
+
// turns each answer into a verdict: supported, unsupported or review. The threshold is applied here, in code.
|
|
3
|
+
import { askJev, DEFAULT_MODEL, noul } from "./jev.mjs";
|
|
4
|
+
import { mapLimit } from "./load.mjs";
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_THRESHOLD = 0.8;
|
|
7
|
+
export const DEFAULT_TIMEOUT_SECONDS = 10;
|
|
8
|
+
/** Estimated tokens of state per request. TypeSafe allows 32k for the state plus the longest question. */
|
|
9
|
+
export const STATE_BUDGET = 16_000;
|
|
10
|
+
/** Estimated tokens of state plus questions per request. TypeSafe allows 64k for the state plus all questions. */
|
|
11
|
+
export const REQUEST_BUDGET = 48_000;
|
|
12
|
+
const CONCURRENCY = 4;
|
|
13
|
+
|
|
14
|
+
/** A rough token count: about four characters per token, which fits English prose. Used for budgets and estimates. */
|
|
15
|
+
export const estimateTokens = (text) => Math.ceil(text.length / 4);
|
|
16
|
+
|
|
17
|
+
export const QUESTION = "Is the value in `claim` supported by `visible_text`, the text a visitor sees on the page?";
|
|
18
|
+
export const CRITERIA = {
|
|
19
|
+
true:
|
|
20
|
+
"`visible_text` shows this value for this property of this item. It may be written another way: a different " +
|
|
21
|
+
"date or number format, a currency symbol instead of a currency code, or other words with the same meaning.",
|
|
22
|
+
false:
|
|
23
|
+
"`visible_text` does not show this value, shows a different value for this property, or shows it only for " +
|
|
24
|
+
"another item or property.",
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** The one question asked about a claim. The claim travels as data next to the question, not inside its wording. */
|
|
28
|
+
export function questionFor(claim) {
|
|
29
|
+
return noul({ claim: { item: claim.item, property: claim.property, value: claim.value }, question: QUESTION }, CRITERIA);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const STATE_OVERHEAD = JSON.stringify({ visible_text: "" }).length;
|
|
33
|
+
const escapedLength = (text) => JSON.stringify(text).length - 2;
|
|
34
|
+
|
|
35
|
+
/** Cuts one over-long line between words into pieces that each fit `maxChars` once escaped. */
|
|
36
|
+
function cutLine(line, maxChars) {
|
|
37
|
+
const pieces = [];
|
|
38
|
+
let current = "";
|
|
39
|
+
for (const word of line.split(" ")) {
|
|
40
|
+
const next = current ? `${current} ${word}` : word;
|
|
41
|
+
if (escapedLength(next) <= maxChars) {
|
|
42
|
+
current = next;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (current) pieces.push(current);
|
|
46
|
+
current = word;
|
|
47
|
+
while (escapedLength(current) > maxChars) {
|
|
48
|
+
let end = maxChars;
|
|
49
|
+
while (end > 1 && escapedLength(current.slice(0, end)) > maxChars) end = Math.floor(end * 0.9);
|
|
50
|
+
pieces.push(current.slice(0, end));
|
|
51
|
+
current = current.slice(end);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (current) pieces.push(current);
|
|
55
|
+
return pieces;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Splits a page's visible text at line breaks into parts whose state stays within `budget` estimated tokens. Most
|
|
60
|
+
* pages are one part; each part of a longer page is sent with every claim.
|
|
61
|
+
*/
|
|
62
|
+
export function splitText(text, budget = STATE_BUDGET) {
|
|
63
|
+
const maxChars = budget * 4 - STATE_OVERHEAD;
|
|
64
|
+
if (escapedLength(text) <= maxChars) return [text];
|
|
65
|
+
const parts = [];
|
|
66
|
+
let current = [];
|
|
67
|
+
let size = 0;
|
|
68
|
+
for (const line of text.split("\n")) {
|
|
69
|
+
for (const piece of escapedLength(line) <= maxChars ? [line] : cutLine(line, maxChars)) {
|
|
70
|
+
const cost = escapedLength(piece) + (current.length ? 2 : 0); // "\n" is two characters once escaped
|
|
71
|
+
if (current.length && size + cost > maxChars) {
|
|
72
|
+
parts.push(current.join("\n"));
|
|
73
|
+
current = [];
|
|
74
|
+
size = 0;
|
|
75
|
+
}
|
|
76
|
+
size += escapedLength(piece) + (current.length ? 2 : 0);
|
|
77
|
+
current.push(piece);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (current.length) parts.push(current.join("\n"));
|
|
81
|
+
return parts;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Plans the requests: for each page with claims and visible text, one request per part of the text, holding every
|
|
86
|
+
* claim (split further only if the questions would pass REQUEST_BUDGET). Returns { pages, requests, parts } where
|
|
87
|
+
* `parts` maps each page to its number of text parts.
|
|
88
|
+
*/
|
|
89
|
+
export function planRequests(pages, { model = DEFAULT_MODEL } = {}) {
|
|
90
|
+
const requests = [];
|
|
91
|
+
const parts = new Map();
|
|
92
|
+
for (const page of pages) {
|
|
93
|
+
if (page.error || !page.claims.length || !page.text) continue;
|
|
94
|
+
const texts = splitText(page.text);
|
|
95
|
+
parts.set(page, texts.length);
|
|
96
|
+
texts.forEach((text, part) => {
|
|
97
|
+
const state = { visible_text: text };
|
|
98
|
+
// Each piece is rounded up, so the sum is never below the estimate for the whole body.
|
|
99
|
+
const base = estimateTokens(JSON.stringify({ model, state, questions: {} }));
|
|
100
|
+
let group = [];
|
|
101
|
+
let tokens = base;
|
|
102
|
+
const flush = () => {
|
|
103
|
+
if (!group.length) return;
|
|
104
|
+
const questions = Object.fromEntries(group.map((claim) => [claim.id, questionFor(claim)]));
|
|
105
|
+
requests.push({ page, part, claims: group, body: { model, state, questions } });
|
|
106
|
+
group = [];
|
|
107
|
+
tokens = base;
|
|
108
|
+
};
|
|
109
|
+
for (const claim of page.claims) {
|
|
110
|
+
const size = estimateTokens(`${JSON.stringify(claim.id)}:${JSON.stringify(questionFor(claim))},`);
|
|
111
|
+
if (group.length && tokens + size > REQUEST_BUDGET) flush();
|
|
112
|
+
group.push(claim);
|
|
113
|
+
tokens += size;
|
|
114
|
+
}
|
|
115
|
+
flush();
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
return { pages, requests, parts };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Estimated input tokens of a plan, per request and in total, for --dry-run. */
|
|
122
|
+
export function estimatePlan(plan) {
|
|
123
|
+
const perRequest = plan.requests.map((request) => estimateTokens(JSON.stringify(request.body)));
|
|
124
|
+
const tokens = perRequest.reduce((sum, n) => sum + n, 0);
|
|
125
|
+
return { perRequest, tokens };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Rounding keeps float noise (1 - 0.8 is 0.19999999999999996) from moving an answer that sits on the threshold.
|
|
129
|
+
const round = (value) => Math.round(value * 1e6) / 1e6;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* A verdict from the probability that the visible text supports the claim: supported at or above `threshold`,
|
|
133
|
+
* unsupported at or below 1 - `threshold`, review in between.
|
|
134
|
+
*/
|
|
135
|
+
export function decide(probability, threshold = DEFAULT_THRESHOLD) {
|
|
136
|
+
if (round(probability) >= threshold) return "supported";
|
|
137
|
+
if (round(1 - probability) >= threshold) return "unsupported";
|
|
138
|
+
return "review";
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const isProbability = (value) => typeof value === "number" && value >= 0 && value <= 1;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Sends every request in the plan (four at a time) and returns the verdicts by page:
|
|
145
|
+
* { model, threshold, pages: [{ ...page, parts, claims: [{ ...claim, probability, verdict, reason }] }], summary,
|
|
146
|
+
* usage }. A claim's probability is the highest over the parts of its page, so it is supported when any part of the
|
|
147
|
+
* page shows it. Any TypeSafe error (missing key, 401, 422, 429 or 529 after retries, timeout) stops the run with a
|
|
148
|
+
* JevError.
|
|
149
|
+
*/
|
|
150
|
+
export async function runPlan(plan, options = {}) {
|
|
151
|
+
const {
|
|
152
|
+
threshold = DEFAULT_THRESHOLD,
|
|
153
|
+
apiKey,
|
|
154
|
+
model = DEFAULT_MODEL,
|
|
155
|
+
timeoutSeconds = DEFAULT_TIMEOUT_SECONDS,
|
|
156
|
+
retries = 3,
|
|
157
|
+
fetchImpl,
|
|
158
|
+
onProgress,
|
|
159
|
+
} = options;
|
|
160
|
+
let done = 0;
|
|
161
|
+
const responses = await mapLimit(plan.requests, CONCURRENCY, async (request) => {
|
|
162
|
+
const response = await askJev(request.body.state, request.body.questions, {
|
|
163
|
+
apiKey,
|
|
164
|
+
model,
|
|
165
|
+
timeoutMs: timeoutSeconds * 1000,
|
|
166
|
+
retries,
|
|
167
|
+
fetchImpl,
|
|
168
|
+
});
|
|
169
|
+
onProgress?.(++done, plan.requests.length);
|
|
170
|
+
return response;
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
const answers = new Map();
|
|
174
|
+
plan.requests.forEach((request, i) => {
|
|
175
|
+
for (const claim of request.claims) {
|
|
176
|
+
const entry = answers.get(claim) ?? { values: [], missing: false };
|
|
177
|
+
const value = responses[i].answers?.[claim.id]?.noul;
|
|
178
|
+
if (isProbability(value)) entry.values.push(value);
|
|
179
|
+
else entry.missing = true;
|
|
180
|
+
answers.set(claim, entry);
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
const pages = plan.pages.map((page) => ({
|
|
185
|
+
...page,
|
|
186
|
+
parts: plan.parts.get(page) ?? 0,
|
|
187
|
+
claims: page.claims.map((claim) => {
|
|
188
|
+
if (!page.text) return { ...claim, probability: null, verdict: "review", reason: "no_visible_text" };
|
|
189
|
+
const entry = answers.get(claim);
|
|
190
|
+
const probability = entry?.values.length ? Math.max(...entry.values) : null;
|
|
191
|
+
if (probability !== null && decide(probability, threshold) === "supported") {
|
|
192
|
+
return { ...claim, probability, verdict: "supported", reason: null };
|
|
193
|
+
}
|
|
194
|
+
if (!entry || entry.missing) return { ...claim, probability, verdict: "review", reason: "no_answer" };
|
|
195
|
+
const verdict = decide(probability, threshold);
|
|
196
|
+
return { ...claim, probability, verdict, reason: verdict === "review" ? "unsure" : null };
|
|
197
|
+
}),
|
|
198
|
+
}));
|
|
199
|
+
const summary = { pages: pages.length, pages_not_read: 0, claims: 0, supported: 0, unsupported: 0, review: 0 };
|
|
200
|
+
for (const page of pages) {
|
|
201
|
+
if (page.error) summary.pages_not_read++;
|
|
202
|
+
for (const claim of page.claims) {
|
|
203
|
+
summary.claims++;
|
|
204
|
+
summary[claim.verdict]++;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const usage = {
|
|
208
|
+
requests: responses.length,
|
|
209
|
+
input_tokens: responses.reduce((sum, r) => sum + (Number(r.usage?.input_tokens) || 0), 0),
|
|
210
|
+
output_tokens: responses.reduce((sum, r) => sum + (Number(r.usage?.output_tokens) || 0), 0),
|
|
211
|
+
};
|
|
212
|
+
return { model: responses[0]?.model ?? model, threshold, pages, summary, usage };
|
|
213
|
+
}
|