@fetchbrain.com/sdk 0.5.0 → 0.6.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/README.md +325 -162
- package/dist/index.d.mts +18 -8
- package/dist/index.d.ts +18 -8
- package/dist/index.js +90 -12
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +90 -12
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +17 -5
- package/dist/mock/index.d.ts +17 -5
- package/dist/mock/index.js +22 -12
- package/dist/mock/index.js.map +1 -1
- package/dist/mock/index.mjs +22 -12
- package/dist/mock/index.mjs.map +1 -1
- package/dist/{types-BbLgy1no.d.mts → types-B1MFygnZ.d.mts} +33 -22
- package/dist/{types-BbLgy1no.d.ts → types-B1MFygnZ.d.ts} +33 -22
- package/package.json +1 -3
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
**Make your scrapers smarter with every run.**
|
|
9
9
|
|
|
10
|
-
*Your crawler teaches it once. It
|
|
10
|
+
*Your crawler teaches it once. It recalls it on every run after.*
|
|
11
11
|
|
|
12
12
|
[](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml) [](https://www.npmjs.com/package/@fetchbrain.com/sdk) [](https://www.typescriptlang.org/) [](https://opensource.org/licenses/MIT)
|
|
13
13
|
|
|
@@ -21,28 +21,25 @@ Every scraping run re-fetches thousands of pages you already scraped last
|
|
|
21
21
|
time — paying for proxies, browsers, retries, and CAPTCHAs to learn things
|
|
22
22
|
you already know.
|
|
23
23
|
|
|
24
|
-
FetchBrain gives your scrapers a **
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
24
|
+
FetchBrain gives each of your scrapers a **memory**. Before each request, a
|
|
25
|
+
crawler asks *"do I already know this request?"* — known requests come back
|
|
26
|
+
**in milliseconds** without your scraper fetching the page; unknown ones run
|
|
27
|
+
normally and are learned. Memory grows run after run, and `ask()` answers
|
|
28
|
+
plain-English questions from what you've learned — a data asset that
|
|
29
29
|
compounds instead of costs. **Learning is always free.**
|
|
30
30
|
|
|
31
31
|
```text
|
|
32
32
|
$ node scraper.js # first run — the brain learns
|
|
33
|
-
|
|
34
|
-
● learned example.com/p/1043 2.3s
|
|
35
|
-
● learned example.com/p/1044 2.1s
|
|
33
|
+
INFO FetchBrain: 🧠 Finished! recalled: 0/3 (0.0%), learned: 3, scraped: 3, duration: 6.4s
|
|
36
34
|
|
|
37
35
|
$ node scraper.js # every run after that
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
🧠 Finished! recalled: 3/3 (100%), learned: 0, duration: 0.3s
|
|
36
|
+
INFO FetchBrain: Recalled: https://example.com/p/1042 [default]
|
|
37
|
+
INFO FetchBrain: Recalled: https://example.com/p/1043 [default]
|
|
38
|
+
INFO FetchBrain: Recalled: https://example.com/p/1044 [default]
|
|
39
|
+
INFO FetchBrain: 🧠 Finished! recalled: 3/3 (100.0%), learned: 0, scraped: 0, duration: 0.3s
|
|
43
40
|
```
|
|
44
41
|
|
|
45
|
-
### Try it
|
|
42
|
+
### Try it
|
|
46
43
|
|
|
47
44
|
```ts
|
|
48
45
|
// scraper.mjs — run this twice and watch the second run skip the fetch
|
|
@@ -58,8 +55,8 @@ const crawler = new CheerioCrawler({
|
|
|
58
55
|
FetchBrain.enhance(crawler, { apiKey: process.env.FETCHBRAIN_API_KEY });
|
|
59
56
|
|
|
60
57
|
await crawler.run(["https://example.com/"]);
|
|
61
|
-
// Run 1:
|
|
62
|
-
// Run 2:
|
|
58
|
+
// Run 1: your scraper fetches the page and teaches your brain
|
|
59
|
+
// Run 2: recalled from memory in milliseconds, no HTTP request to example.com
|
|
63
60
|
```
|
|
64
61
|
|
|
65
62
|
## One line to adopt
|
|
@@ -88,37 +85,38 @@ That's it. Your handler only runs when there's something new to learn.
|
|
|
88
85
|
|
|
89
86
|
| | Without | With FetchBrain |
|
|
90
87
|
| --- | --- | --- |
|
|
91
|
-
| **Repeat requests** | Full fetch, every run | Recalled in
|
|
88
|
+
| **Repeat requests** | Full fetch, every run | Recalled in milliseconds |
|
|
92
89
|
| **Proxy & compute spend** | Pay per fetch, every run | Pay only for what it knows |
|
|
93
|
-
| **Blocks & CAPTCHAs** | Every run risks them |
|
|
94
|
-
| **When the service is down** | — | Your crawl runs normally
|
|
90
|
+
| **Blocks & CAPTCHAs** | Every run risks them | Pre-recalled known requests skip the fetch |
|
|
91
|
+
| **When the service is down** | — | Your crawl runs normally (circuit breaker, 500ms timeout) |
|
|
95
92
|
| **Testing** | Mock it yourself | `MockFetchBrain` ships in the box |
|
|
96
93
|
|
|
97
|
-
-
|
|
98
|
-
-
|
|
99
|
-
-
|
|
100
|
-
-
|
|
101
|
-
-
|
|
102
|
-
-
|
|
103
|
-
-
|
|
104
|
-
-
|
|
94
|
+
- **Recall before you fetch** — known requests are answered from memory; when they're recalled at enqueue time, the page is never fetched ([caveats](#recall-at-enqueue-time-prerecall))
|
|
95
|
+
- **Any request, not just pages** — HTML, JSON APIs, POSTs with bodies; identity is derived from the full request
|
|
96
|
+
- **Auto-learning** — every successful scrape teaches the brain, free
|
|
97
|
+
- **Never breaks your crawl** — the circuit breaker degrades gracefully; an outage costs you optimization, not your crawl (one deliberate exception: [expired memory](#recall-at-enqueue-time-prerecall))
|
|
98
|
+
- **Built for scale** — request batching and deduping for high-concurrency crawlers
|
|
99
|
+
- **Crawlee-native** — CheerioCrawler, PlaywrightCrawler, and friends
|
|
100
|
+
- **Transparent** — see exactly [what leaves your process](#what-leaves-your-process). Telemetry is **opt-in** and pseudonymous ([details](#telemetry-opt-in))
|
|
101
|
+
- **TypeScript-first** — full types, ESM + CJS; an API key is the only required option
|
|
105
102
|
|
|
106
103
|
## Who is it for?
|
|
107
104
|
|
|
108
|
-
FetchBrain pays off wherever the **same expensive request
|
|
109
|
-
than once** — across
|
|
110
|
-
up a first-ever fetch of a brand-new URL, and it's not for
|
|
111
|
-
monitoring where you always need the live value.
|
|
105
|
+
FetchBrain pays off wherever a scraper makes the **same expensive request more
|
|
106
|
+
than once** — across runs, scheduled jobs, or the users it serves. It won't
|
|
107
|
+
speed up a first-ever fetch of a brand-new URL, and it's not for
|
|
108
|
+
freshness-critical monitoring where you always need the live value.
|
|
109
|
+
Everywhere else, it compounds:
|
|
112
110
|
|
|
113
|
-
**Data-service teams & aggregators** —
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
111
|
+
**Data-service teams & aggregators** — each scraper fetches an expensive
|
|
112
|
+
request once and recalls it on every run after, so per-run proxy and compute
|
|
113
|
+
cost falls as coverage grows — and `ask()` turns what they've collected into
|
|
114
|
+
memory you can ask questions of, with no warehouse to run.
|
|
117
115
|
|
|
118
|
-
**Product teams & AI agents** — apps and browsing agents that re-hit
|
|
116
|
+
**Product teams & AI agents** — apps and browsing agents that re-hit the same
|
|
119
117
|
requests get them back in milliseconds, straight from memory: no fetch, no
|
|
120
|
-
proxy, no block. The more
|
|
121
|
-
|
|
118
|
+
proxy, no block. The more often a scraper revisits the same requests, the more
|
|
119
|
+
its memory pays off.
|
|
122
120
|
|
|
123
121
|
**Recurring crawls of stable data** — catalogs, specs, listings, company and
|
|
124
122
|
reference data barely change between runs, so recall skips the fetch and each
|
|
@@ -126,7 +124,7 @@ scheduled run costs less. Keep volatile fields on `memory: "fresh"` so you
|
|
|
126
124
|
never trade accuracy for speed.
|
|
127
125
|
|
|
128
126
|
**Solo scraper developers** — start free: learning never costs anything, and
|
|
129
|
-
the requests you've already made come back
|
|
127
|
+
the requests you've already made come back from memory instead of getting
|
|
130
128
|
blocked or throttled. One line to add, one brain that grows with everything
|
|
131
129
|
you scrape.
|
|
132
130
|
|
|
@@ -162,14 +160,19 @@ await crawler.run(urls);
|
|
|
162
160
|
## How it works
|
|
163
161
|
|
|
164
162
|
```
|
|
165
|
-
Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data in
|
|
163
|
+
Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data in milliseconds, no fetch
|
|
166
164
|
│
|
|
167
165
|
└──▶ NO ──▶ your handler runs ──▶ brain learns, free
|
|
168
166
|
```
|
|
169
167
|
|
|
170
|
-
1. **Recall** — before each request, the SDK asks if the brain knows it
|
|
171
|
-
2. **Known** — data
|
|
172
|
-
3. **Learning** — unknown requests run through your handler as normal, and the result teaches the brain for
|
|
168
|
+
1. **Recall** — before each request (at enqueue time by default), the SDK asks if the brain knows it
|
|
169
|
+
2. **Known** — the remembered data is pushed for you and your handler is skipped; requests recalled at enqueue also skip the fetch
|
|
170
|
+
3. **Learning** — unknown requests run through your handler as normal, and the result teaches the brain for that scraper's future runs
|
|
171
|
+
|
|
172
|
+
Memory is always private to your account. Within it, scoping depends on
|
|
173
|
+
where the scraper runs ([details](#do-my-scrapers-share-memory)): on Apify
|
|
174
|
+
each actor has its own memory; everywhere else, scrapers share one default
|
|
175
|
+
memory unless you [name them](#name-your-scraper-scraper).
|
|
173
176
|
|
|
174
177
|
### Memory depth
|
|
175
178
|
|
|
@@ -182,27 +185,57 @@ How old is too old? You decide, per crawler:
|
|
|
182
185
|
| `standard` | 7 days | listings, catalogs |
|
|
183
186
|
| `deep` | 30 days | slow-changing reference data |
|
|
184
187
|
|
|
185
|
-
##
|
|
188
|
+
## Brain context in handler
|
|
186
189
|
|
|
190
|
+
With the default `alwaysRun: false`, known requests skip your handler
|
|
191
|
+
entirely. Set `alwaysRun` (see [below](#choosing-which-handlers-run)) and
|
|
187
192
|
`context.brain` puts the recall decision in your hands:
|
|
188
193
|
|
|
189
194
|
```typescript
|
|
190
|
-
|
|
195
|
+
import { FetchBrain, type FetchBrainContext } from "@fetchbrain.com/sdk";
|
|
196
|
+
import { CheerioCrawler } from "crawlee";
|
|
197
|
+
|
|
198
|
+
const crawler = FetchBrain.enhance(
|
|
199
|
+
new CheerioCrawler({
|
|
200
|
+
requestHandler: async (context) => {
|
|
201
|
+
const { $, pushData } = context;
|
|
202
|
+
// Crawlee's context types don't declare `brain`; FetchBrainContext describes it
|
|
203
|
+
const brain = (context as { brain?: FetchBrainContext }).brain;
|
|
204
|
+
if (brain?.known) {
|
|
205
|
+
// Option 1: push the remembered data and skip scraping
|
|
206
|
+
await brain.use();
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
await pushData({ title: $("h1").text() }); // scrape + learn
|
|
210
|
+
},
|
|
211
|
+
}),
|
|
212
|
+
{ apiKey: process.env.FETCHBRAIN_API_KEY, alwaysRun: true },
|
|
213
|
+
);
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Or compare what the brain remembers with what the page says now:
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
requestHandler: async (context) => {
|
|
220
|
+
const { $, pushData } = context;
|
|
221
|
+
const brain = (context as { brain?: FetchBrainContext }).brain;
|
|
222
|
+
const scraped = { title: $("h1").text() };
|
|
191
223
|
if (brain?.known) {
|
|
192
|
-
|
|
193
|
-
return;
|
|
224
|
+
console.log("Remembered:", brain.data, "Scraped:", scraped);
|
|
194
225
|
}
|
|
195
|
-
await pushData(
|
|
226
|
+
await pushData(scraped); // learned only if the request was unknown
|
|
196
227
|
},
|
|
197
228
|
```
|
|
198
229
|
|
|
230
|
+
### `context.brain` properties
|
|
231
|
+
|
|
199
232
|
| Property | Type | Description |
|
|
200
233
|
| --- | --- | --- |
|
|
201
234
|
| `known` | `boolean` | whether the brain knows this request |
|
|
202
235
|
| `data` | `object` | the remembered data (if known) |
|
|
203
|
-
| `use()` | `function` | push the
|
|
236
|
+
| `use()` | `function` | push the remembered data and skip scraping |
|
|
204
237
|
|
|
205
|
-
|
|
238
|
+
## Configuration options
|
|
206
239
|
|
|
207
240
|
```typescript
|
|
208
241
|
interface FetchBrainConfig {
|
|
@@ -210,18 +243,56 @@ interface FetchBrainConfig {
|
|
|
210
243
|
apiKey: string;
|
|
211
244
|
|
|
212
245
|
// Optional
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
246
|
+
scraper?: string; // Name this scraper so it gets its own memory (or set FETCHBRAIN_SCRAPER_ID)
|
|
247
|
+
baseUrl?: string; // API URL (default: https://api.fetchbrain.com)
|
|
248
|
+
memory?: MemoryDepth; // How far back the brain recalls (default: "recent")
|
|
249
|
+
learning?: boolean; // Teach the brain from scraped data (default: true)
|
|
250
|
+
alwaysRun?: boolean | string | string[]; // Handlers that still run when a request is known (default: false)
|
|
217
251
|
skipLabels?: string[]; // Labels that bypass FetchBrain entirely (default: none)
|
|
218
252
|
preRecall?: boolean; // Recall requests in bulk as they're enqueued (default: true)
|
|
219
|
-
onRecalled?: (event: RecalledEvent) => void | Promise<void>; // Per-record hook when
|
|
220
|
-
|
|
221
|
-
|
|
253
|
+
onRecalled?: (event: RecalledEvent) => void | Promise<void>; // Per-record hook when recalled data is delivered
|
|
254
|
+
extractForLearning?: (data: unknown) => Record<string, unknown>; // Transform each record before it is learned
|
|
255
|
+
refreshOnRebuild?: boolean; // Scope learn, recall and ask to the current build (*_BUILD_ID env var) (default: false)
|
|
256
|
+
timeout?: number; // Handler-time recall, stats and telemetry timeout in ms (default: 500)
|
|
257
|
+
batch?: { maxSize?: number; maxWait?: number }; // Request batching (default: 50 items / 50ms)
|
|
258
|
+
circuitBreaker?: {
|
|
259
|
+
failureThreshold?: number; // Failures before the circuit opens (default: 3)
|
|
260
|
+
resetTimeout?: number; // ms before a retry is allowed (default: 30000)
|
|
261
|
+
successThreshold?: number; // Successes to close it again (default: 1)
|
|
262
|
+
};
|
|
263
|
+
telemetry?: TelemetryConfig; // Opt-in telemetry (default: { enabled: false })
|
|
264
|
+
learnUrlField?: string; // Accepted but not currently applied
|
|
265
|
+
debug?: boolean; // Enable debug logging (default: false)
|
|
222
266
|
}
|
|
223
267
|
```
|
|
224
268
|
|
|
269
|
+
### Name your scraper (`scraper`)
|
|
270
|
+
|
|
271
|
+
Memory is private to your account. Outside Apify, every scraper on the
|
|
272
|
+
account shares one default memory unless you name it:
|
|
273
|
+
|
|
274
|
+
```typescript
|
|
275
|
+
FetchBrain.enhance(crawler, { apiKey, scraper: "shop-a" });
|
|
276
|
+
// or, with no code change: FETCHBRAIN_SCRAPER_ID=shop-a node crawl.js
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
- A named scraper learns and recalls only its own memory, so `shop-a` and
|
|
280
|
+
`shop-b` never see each other's pages.
|
|
281
|
+
- Names use lowercase letters, digits, `.`, `_` and `-`, up to 64 characters,
|
|
282
|
+
and must start with a letter or digit. Uppercase is lowercased. An invalid
|
|
283
|
+
name is ignored with a warning: an invalid `scraper` option falls back to
|
|
284
|
+
`FETCHBRAIN_SCRAPER_ID` if that is valid, otherwise the scraper keeps using
|
|
285
|
+
the default memory.
|
|
286
|
+
- A new name starts empty. What you learned before naming stays in the default
|
|
287
|
+
memory, which unnamed scrapers keep using.
|
|
288
|
+
- On Apify, memory is already per actor. Setting a name there replaces the
|
|
289
|
+
actor id, so that actor's existing memory goes cold.
|
|
290
|
+
- A valid `scraper` option wins over the environment variable; an empty one
|
|
291
|
+
doesn't hide it. SDK 0.3.0 and later
|
|
292
|
+
also forward `FETCHBRAIN_SCRAPER_ID`, but before this release only on a
|
|
293
|
+
best-effort basis: many other `*_ID` variables can push it out of the
|
|
294
|
+
header. Upgrade to guarantee delivery.
|
|
295
|
+
|
|
225
296
|
### Recall at enqueue time (`preRecall`)
|
|
226
297
|
|
|
227
298
|
In `HttpCrawler`/`CheerioCrawler`, Crawlee performs the HTTP request *before*
|
|
@@ -241,11 +312,20 @@ Things to know:
|
|
|
241
312
|
- **Scope** — pre-recall applies to arrays passed to `crawler.addRequests()`
|
|
242
313
|
or `crawler.run(requests)`. Crawlee's context-level `enqueueLinks()` and
|
|
243
314
|
context `addRequests()` reach the queue by other paths and are not
|
|
244
|
-
pre-recalled (they still get handler-time recall
|
|
245
|
-
enqueue follow-ups
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
315
|
+
pre-recalled (they still get handler-time recall, but the fetch has
|
|
316
|
+
already happened). Inside a handler, enqueue follow-ups through the
|
|
317
|
+
crawler to keep the benefit:
|
|
318
|
+
|
|
319
|
+
```typescript
|
|
320
|
+
requestHandler: async ({ $, request, crawler }) => {
|
|
321
|
+
const urls = $("a.product")
|
|
322
|
+
.map((_, a) => new URL($(a).attr("href") ?? "", request.url).href)
|
|
323
|
+
.get();
|
|
324
|
+
await crawler.addRequests(urls.map((url) => ({ url, label: "product" })));
|
|
325
|
+
},
|
|
326
|
+
```
|
|
327
|
+
- **Metering** — known recalls are counted at enqueue time, so a known
|
|
328
|
+
duplicate that the queue later drops still counts.
|
|
249
329
|
- **Snapshot semantics** — the recall result is as of enqueue time. Anything
|
|
250
330
|
learned between enqueue and execution isn't picked up; the request is
|
|
251
331
|
simply scraped and re-learned.
|
|
@@ -264,42 +344,55 @@ Things to know:
|
|
|
264
344
|
|
|
265
345
|
When the brain knows a request, your handler is skipped and the remembered
|
|
266
346
|
data is pushed for you — which also skips any per-record bookkeeping living
|
|
267
|
-
in that handler (
|
|
347
|
+
in that handler (metrics, counters, follow-up enqueues). `onRecalled`
|
|
268
348
|
runs once per recalled record with `{ url, label, userData, data }` — both
|
|
269
349
|
when the handler is auto-skipped and when your own handler calls
|
|
270
350
|
`context.brain.use()`:
|
|
271
351
|
|
|
272
352
|
```typescript
|
|
353
|
+
const recalledByLabel = new Map<string, number>();
|
|
354
|
+
|
|
273
355
|
FetchBrain.enhance(crawler, {
|
|
274
|
-
|
|
275
|
-
|
|
356
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
357
|
+
onRecalled: ({ label = "default" }) => {
|
|
358
|
+
recalledByLabel.set(label, (recalledByLabel.get(label) ?? 0) + 1);
|
|
276
359
|
},
|
|
277
360
|
});
|
|
278
361
|
```
|
|
279
362
|
|
|
280
363
|
Hook errors are swallowed (logged at debug) — they never break the crawl.
|
|
281
364
|
|
|
365
|
+
### Choosing which handlers run
|
|
366
|
+
|
|
282
367
|
Fine-grained routing control with `alwaysRun` — run every handler, none, or
|
|
283
368
|
only specific labels when a request is known:
|
|
284
369
|
|
|
285
370
|
```typescript
|
|
286
|
-
FetchBrain.enhance(crawler, {
|
|
371
|
+
FetchBrain.enhance(crawler, {
|
|
372
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
373
|
+
alwaysRun: ["listing", "category"],
|
|
374
|
+
});
|
|
287
375
|
```
|
|
288
376
|
|
|
289
377
|
For dynamic requests that must always run live and aren't worth remembering
|
|
290
378
|
(search results, pagination), use `skipLabels` instead: where `alwaysRun`
|
|
291
379
|
still recalls (and can learn), `skipLabels` bypasses FetchBrain entirely —
|
|
292
|
-
no recall round-trip, no learn — so those requests run at
|
|
380
|
+
no recall round-trip, no learn, no telemetry — so those requests run at
|
|
381
|
+
native speed:
|
|
293
382
|
|
|
294
383
|
```typescript
|
|
295
|
-
FetchBrain.enhance(crawler, {
|
|
384
|
+
FetchBrain.enhance(crawler, {
|
|
385
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
386
|
+
skipLabels: ["search", "pagination"],
|
|
387
|
+
});
|
|
296
388
|
```
|
|
297
389
|
|
|
298
390
|
## Ask your brain anything
|
|
299
391
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
392
|
+
`ask()` answers from what's been learned — one question, no exact URLs, no
|
|
393
|
+
warehouse. From the SDK it uses the same scope as recall (see
|
|
394
|
+
[Do my scrapers share memory?](#do-my-scrapers-share-memory)); Ask Your Brain
|
|
395
|
+
in the dashboard answers across your whole account:
|
|
303
396
|
|
|
304
397
|
```typescript
|
|
305
398
|
import { FetchBrainClient } from "@fetchbrain.com/sdk";
|
|
@@ -311,8 +404,8 @@ console.log(res.answer); // synthesized answer
|
|
|
311
404
|
console.log(res.sources); // scored sources
|
|
312
405
|
```
|
|
313
406
|
|
|
314
|
-
Pick the model that writes the answer with `model` — the default is
|
|
315
|
-
|
|
407
|
+
Pick the model that writes the answer with `model` — the default is
|
|
408
|
+
`"llama-3.3-70b"`, included on every plan. Premium models like
|
|
316
409
|
`"kimi-k2.5"` and `"kimi-k2.6"` use extra ask credits and need a paid plan,
|
|
317
410
|
and `"byok"` answers with your own linked provider model (configured in the
|
|
318
411
|
dashboard, billed to your provider):
|
|
@@ -334,70 +427,35 @@ paid plan, `"byok"` with no linked provider — the response comes back with
|
|
|
334
427
|
`status: "unavailable"`, which means the API itself is degraded or
|
|
335
428
|
unreachable.
|
|
336
429
|
|
|
337
|
-
##
|
|
338
|
-
|
|
339
|
-
Access brain data directly in your handler via `context.brain`:
|
|
430
|
+
## Learning with `Dataset.pushData`
|
|
340
431
|
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
requestHandler: async ({ $, request, brain, pushData }) => {
|
|
345
|
-
// Check if the brain already knows this page
|
|
346
|
-
if (brain?.known) {
|
|
347
|
-
console.log("Brain knows this page");
|
|
348
|
-
|
|
349
|
-
// Option 1: Use brain data directly (skip scraping)
|
|
350
|
-
await brain.use();
|
|
351
|
-
return;
|
|
352
|
-
|
|
353
|
-
// Option 2: Compare brain data with scraped data
|
|
354
|
-
// const scraped = { title: $('h1').text() };
|
|
355
|
-
// console.log('Brain:', brain.data, 'Scraped:', scraped);
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
// Scrape normally if the brain doesn't know
|
|
359
|
-
const data = { title: $("h1").text() };
|
|
360
|
-
await pushData(data);
|
|
361
|
-
},
|
|
362
|
-
}),
|
|
363
|
-
{ apiKey: "your-api-key", alwaysRun: true },
|
|
364
|
-
);
|
|
365
|
-
```
|
|
366
|
-
|
|
367
|
-
### `context.brain` Properties
|
|
368
|
-
|
|
369
|
-
| Property | Type | Description |
|
|
370
|
-
| -------- | -------- | --------------------------------- |
|
|
371
|
-
| `known` | boolean | Whether the brain knows this URL |
|
|
372
|
-
| `data` | object | Brain data (if known) |
|
|
373
|
-
| `use()` | function | Push brain data and skip scraping |
|
|
374
|
-
|
|
375
|
-
## Using Dataset.pushData
|
|
432
|
+
> **Important:** the brain learns only from `context.pushData()` or the
|
|
433
|
+
> SDK's `pushData()` wrapper below. Data written with `Dataset.pushData()`
|
|
434
|
+
> directly is not learned, so those requests stay unknown on future runs.
|
|
376
435
|
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
If you use `Dataset.pushData()` instead of `context.pushData()`, use our wrapper for automatic AI learning:
|
|
436
|
+
If you write with `Dataset.pushData()` instead of `context.pushData()`, use
|
|
437
|
+
the wrapper so the brain learns from it:
|
|
380
438
|
|
|
381
439
|
```typescript
|
|
382
440
|
import { FetchBrain, pushData } from "@fetchbrain.com/sdk";
|
|
383
|
-
import { Dataset } from "crawlee";
|
|
441
|
+
import { CheerioCrawler, Dataset } from "crawlee";
|
|
384
442
|
|
|
385
443
|
const crawler = FetchBrain.enhance(
|
|
386
444
|
new CheerioCrawler({
|
|
387
|
-
requestHandler: async ({
|
|
445
|
+
requestHandler: async ({ $ }) => {
|
|
388
446
|
const data = { title: $("h1").text() };
|
|
389
447
|
|
|
390
|
-
//
|
|
448
|
+
// Learned: the SDK wrapper
|
|
391
449
|
await pushData(data, Dataset);
|
|
392
450
|
|
|
393
|
-
//
|
|
451
|
+
// Learned: the wrapper with a named dataset
|
|
394
452
|
await pushData(data, Dataset, "products");
|
|
395
453
|
|
|
396
|
-
//
|
|
454
|
+
// Not learned:
|
|
397
455
|
// await Dataset.pushData(data);
|
|
398
456
|
},
|
|
399
457
|
}),
|
|
400
|
-
{ apiKey:
|
|
458
|
+
{ apiKey: process.env.FETCHBRAIN_API_KEY },
|
|
401
459
|
);
|
|
402
460
|
```
|
|
403
461
|
|
|
@@ -407,7 +465,7 @@ const crawler = FetchBrain.enhance(
|
|
|
407
465
|
import { FetchBrain } from "@fetchbrain.com/sdk";
|
|
408
466
|
|
|
409
467
|
const brain = new FetchBrain({
|
|
410
|
-
apiKey:
|
|
468
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
411
469
|
memory: "recent",
|
|
412
470
|
});
|
|
413
471
|
|
|
@@ -427,17 +485,75 @@ if (result.known) {
|
|
|
427
485
|
The circuit breaker is not an afterthought — it's the core design contract:
|
|
428
486
|
|
|
429
487
|
- **Healthy** → full optimization
|
|
430
|
-
- **Slow**
|
|
431
|
-
- **Down** → circuit opens
|
|
432
|
-
- **Recovered** → circuit closes
|
|
488
|
+
- **Slow** → the call times out and your crawl continues without it
|
|
489
|
+
- **Down** → after 3 consecutive failures the circuit opens and your scraper runs standalone
|
|
490
|
+
- **Recovered** → after 30 seconds the SDK tries again; on success the circuit closes and optimization resumes
|
|
491
|
+
|
|
492
|
+
Timeouts per call type:
|
|
493
|
+
|
|
494
|
+
| Call | Timeout |
|
|
495
|
+
| --- | --- |
|
|
496
|
+
| Recall in the handler (batched) | `timeout` option, default 500ms |
|
|
497
|
+
| Recall at enqueue (`preRecall`, bulk) | 3s per chunk of up to 100 requests |
|
|
498
|
+
| Learn (batched, sent in the background) | 5s |
|
|
499
|
+
| `ask()` | 10s |
|
|
500
|
+
| `stats()` and telemetry | `timeout` option, default 500ms |
|
|
433
501
|
|
|
434
|
-
A FetchBrain
|
|
435
|
-
|
|
502
|
+
A FetchBrain outage costs you *optimization*, not your crawl: SDK calls
|
|
503
|
+
degrade gracefully instead of throwing into it. The one deliberate
|
|
504
|
+
exception is [expired memory](#recall-at-enqueue-time-prerecall): a request
|
|
505
|
+
that skipped its fetch at enqueue and whose remembered data is gone fails
|
|
506
|
+
into your `failedRequestHandler` rather than disappearing silently.
|
|
507
|
+
|
|
508
|
+
## What leaves your process
|
|
509
|
+
|
|
510
|
+
Every API call (recall, learn, ask, stats, telemetry) sends these headers:
|
|
511
|
+
|
|
512
|
+
| Header | Value |
|
|
513
|
+
| --- | --- |
|
|
514
|
+
| `Authorization` | `Bearer <your API key>` |
|
|
515
|
+
| `X-FB-SDK` | `js` |
|
|
516
|
+
| `X-FB-Node` | your Node.js version (e.g. `v20.11.0`) |
|
|
517
|
+
| `X-FB-Platform` | your OS platform (e.g. `linux`) |
|
|
518
|
+
| `X-FB-Env` | the value of `NODE_ENV`, if set |
|
|
519
|
+
| `X-FB-Context` | JSON of environment variables named `*_ID`, plus `NODE_ENV`, `REGION` and `CI` (see below) |
|
|
520
|
+
| `X-FB-Crawler` | the crawler class name (e.g. `CheerioCrawler`), while a request is being handled |
|
|
521
|
+
| `X-FB-Label` | the request's Crawlee label, while a request is being handled |
|
|
522
|
+
|
|
523
|
+
`X-FB-Context` carries your platform identifiers; the API uses
|
|
524
|
+
`FETCHBRAIN_SCRAPER_ID` (your scraper name, sent first) and otherwise
|
|
525
|
+
`APIFY_ACTOR_ID` from it to scope memory per scraper (other `*_ID`
|
|
526
|
+
variables do not affect scoping) and `*BUILD_ID` for `refreshOnRebuild`. It includes
|
|
527
|
+
every environment variable whose name ends in `_ID`, plus `NODE_ENV`,
|
|
528
|
+
`REGION` and `CI`, except names containing `TOKEN`, `SECRET`, `PASSWORD`,
|
|
529
|
+
`CREDENTIAL`, `KEY`, `AUTH` or `COOKIE`, values that look like a JWT or a
|
|
530
|
+
URL with embedded `user:pass`, and values over 256 characters (2 KB total).
|
|
531
|
+
No other environment variables are sent. If you keep something private in
|
|
532
|
+
a variable ending in `_ID`, it will be sent.
|
|
533
|
+
|
|
534
|
+
Recall and learn also send the request itself: the full URL (including
|
|
535
|
+
query string), method, `uniqueKey`, label, string POST body, your
|
|
536
|
+
`userData` (minus the SDK's own keys), and the request headers **except**
|
|
537
|
+
`Authorization`, `Cookie` and `Set-Cookie`. Recall also sends your `memory`
|
|
538
|
+
depth; learn also sends the record you pushed (after `extractForLearning`).
|
|
539
|
+
|
|
540
|
+
With `refreshOnRebuild`, recall, learn and `ask()` also send a build ID: the
|
|
541
|
+
value of the first environment variable whose name ends in `BUILD_ID`. This
|
|
542
|
+
value is sent as-is — it does **not** go through the name, credential or
|
|
543
|
+
length filters `X-FB-Context` uses.
|
|
544
|
+
|
|
545
|
+
Other headers (for example
|
|
546
|
+
`Proxy-Authorization` or `X-API-Key`), `userData` values and POST bodies are
|
|
547
|
+
forwarded as-is — keep secrets out of them on requests FetchBrain handles,
|
|
548
|
+
or route those requests through `skipLabels`, which sends nothing for them.
|
|
549
|
+
|
|
550
|
+
`ask()` sends your question and options. Telemetry sends nothing unless you
|
|
551
|
+
[opt in](#telemetry-opt-in).
|
|
436
552
|
|
|
437
553
|
## Telemetry (opt-in)
|
|
438
554
|
|
|
439
|
-
Telemetry is **off by default.**
|
|
440
|
-
|
|
555
|
+
Telemetry is **off by default.** Nothing in this section is collected or
|
|
556
|
+
sent unless you opt in:
|
|
441
557
|
|
|
442
558
|
```typescript
|
|
443
559
|
FetchBrain.enhance(crawler, {
|
|
@@ -446,16 +562,57 @@ FetchBrain.enhance(crawler, {
|
|
|
446
562
|
});
|
|
447
563
|
```
|
|
448
564
|
|
|
449
|
-
**
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
565
|
+
**It's pseudonymous, not anonymous.** Entries are sent to the FetchBrain
|
|
566
|
+
API with your API key and the [headers above](#what-leaves-your-process),
|
|
567
|
+
so they're linked to your account. They're used to improve FetchBrain's
|
|
568
|
+
recommendations (proxy recommendations, block detection, configuration
|
|
569
|
+
tuning); aggregated statistics may inform recommendations for other users.
|
|
570
|
+
|
|
571
|
+
**When it's collected:** one entry per request FetchBrain handles
|
|
572
|
+
(`skipLabels` requests are excluded), after your handler finishes — or
|
|
573
|
+
whenever the request fails inside the SDK's wrapper, including failures
|
|
574
|
+
before your handler runs (e.g. [expired memory](#recall-at-enqueue-time-prerecall))
|
|
575
|
+
and on known requests. Known requests that are skipped successfully produce
|
|
576
|
+
no entry. A failure entry carries only the "always" fields (minus session),
|
|
577
|
+
`retryCount`, timing, and `blocked: true` with a `blockType` if one matches.
|
|
578
|
+
Entries are buffered in your process and sent in batches (every 50 entries,
|
|
579
|
+
every 30 seconds, and when the crawl finishes); send failures are ignored and
|
|
580
|
+
never affect your crawl.
|
|
581
|
+
|
|
582
|
+
**What's sent:**
|
|
583
|
+
|
|
584
|
+
| Field | Sent when | What it is |
|
|
585
|
+
| --- | --- | --- |
|
|
586
|
+
| `domain` | always | the URL's hostname, in plain text (e.g. `shop.example.com`) |
|
|
587
|
+
| `urlHash` | always | first 16 hex characters of an **unsalted** SHA-256 of the full URL, including the query string. Anyone with a candidate URL can compute the same hash, so it identifies URLs that are guessable. |
|
|
588
|
+
| `urlPattern` | always | the URL path with numeric segments, UUIDs and alphanumeric tokens of 20+ characters replaced by `*`; the query string is dropped. Everything else — slugs, usernames, words — is sent as-is (e.g. `/users/jane-doe/orders/*`). |
|
|
589
|
+
| `timestamp` | always | when the entry was collected |
|
|
590
|
+
| `crawlerType` | always | crawler class name, lowercased, without `Crawler` (e.g. `cheerio`) |
|
|
591
|
+
| `requestLabel` | always | the request's Crawlee label, if set |
|
|
592
|
+
| `sessionAge`, `sessionErrorScore` | on success, if the request has a Crawlee session | the session's usage count and error score |
|
|
593
|
+
| `statusCode` | `sharePerformance`, on success | HTTP status |
|
|
594
|
+
| `retryCount` | `sharePerformance` | Crawlee retry count |
|
|
595
|
+
| `responseTimeMs`, `totalTimeMs` | `sharePerformance` | time in ms from when the SDK starts handling the request (including recall) until your handler finishes or the request fails |
|
|
596
|
+
| `contentSize` | `sharePerformance`, on success | response body length, when the crawler exposes it |
|
|
597
|
+
| `blocked`, `blockType` | `shareSitePatterns` | `blocked` is true for status 403, 429 or 5xx, or when the request failed inside the SDK wrapper for any reason; `blockType` is the status code (4xx/5xx) or a category matched in the error message (`captcha`, `timeout`, `blocked`, `429` for "rate limit") — the message itself isn't sent |
|
|
598
|
+
| `proxyCountry`, `proxyType`, `proxySuccess` | `shareProxyInfo`, on success, if the request used a Crawlee proxy | the proxy's country code; `residential`, `mobile` or `datacenter`, guessed in your process from the proxy URL; and whether the status was below 400. The proxy URL, hostname, IP and credentials are not sent. |
|
|
599
|
+
|
|
600
|
+
**Sub-flags** — each defaults to `true` once telemetry is enabled; set one
|
|
601
|
+
to `false` to stop sending its fields. The "always" fields above are sent
|
|
602
|
+
whenever telemetry is enabled.
|
|
603
|
+
|
|
604
|
+
```typescript
|
|
605
|
+
telemetry: {
|
|
606
|
+
enabled: true, // default: false
|
|
607
|
+
sharePerformance: false, // default: true
|
|
608
|
+
shareSitePatterns: true, // default: true
|
|
609
|
+
shareProxyInfo: false, // default: true
|
|
610
|
+
}
|
|
611
|
+
```
|
|
455
612
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
613
|
+
**Never sent by telemetry:** the raw URL or query string, request or response
|
|
614
|
+
bodies, your scraped requests' headers or cookies, error messages, or proxy
|
|
615
|
+
URLs and IPs.
|
|
459
616
|
|
|
460
617
|
## Testing
|
|
461
618
|
|
|
@@ -465,7 +622,7 @@ buffered, best-effort, and never blocks or fails your crawl.
|
|
|
465
622
|
import { MockFetchBrain } from "@fetchbrain.com/sdk/mock";
|
|
466
623
|
|
|
467
624
|
const mock = new MockFetchBrain({
|
|
468
|
-
|
|
625
|
+
initialMemory: new Map([
|
|
469
626
|
["https://example.com/product", { title: "Known Product" }],
|
|
470
627
|
]),
|
|
471
628
|
});
|
|
@@ -474,14 +631,21 @@ const mock = new MockFetchBrain({
|
|
|
474
631
|
const result = await mock.recall({ url: "https://example.com/product" });
|
|
475
632
|
expect(result.known).toBe(true);
|
|
476
633
|
|
|
477
|
-
// Ask a natural-language question against seeded
|
|
478
|
-
const answer = await mock.ask("
|
|
634
|
+
// Ask a natural-language question against seeded memory
|
|
635
|
+
const answer = await mock.ask("known product");
|
|
479
636
|
expect(answer.sources.length).toBeGreaterThan(0);
|
|
480
637
|
console.log(answer.sources);
|
|
481
638
|
```
|
|
482
639
|
|
|
483
|
-
|
|
484
|
-
|
|
640
|
+
`initialMemory` replaces the older `initialKnowledge` option (still
|
|
641
|
+
accepted, deprecated), and `getMemorySize()` replaces `getKnowledgeSize()`.
|
|
642
|
+
Pass `learnCap: N` to make the mock reject learns after N entries, to test
|
|
643
|
+
how your crawl behaves at the monthly learning limit.
|
|
644
|
+
|
|
645
|
+
If you clone this repository, there's also a local mock **server**
|
|
646
|
+
(`npm run mock-server`) for running real crawlers against
|
|
647
|
+
`http://localhost:3456` without an API key (set `FB_MOCK_LEARN_CAP=N` to
|
|
648
|
+
simulate the learning limit). It isn't included in the npm package.
|
|
485
649
|
|
|
486
650
|
## Examples
|
|
487
651
|
|
|
@@ -491,30 +655,29 @@ real crawlers against `http://localhost:3456` without an API key.
|
|
|
491
655
|
| [`manual-recall`](./examples/manual-recall) | recall/learn without Crawlee |
|
|
492
656
|
| [`with-mock`](./examples/with-mock) | unit testing with `MockFetchBrain` |
|
|
493
657
|
|
|
494
|
-
- **basic-cheerio** - CheerioCrawler with FetchBrain
|
|
495
|
-
- **manual-recall** - Direct API usage without Crawlee
|
|
496
|
-
- **with-mock** - Unit testing with MockFetchBrain
|
|
497
|
-
|
|
498
658
|
## FAQ
|
|
499
659
|
|
|
500
|
-
**Does my scraped data train anyone else's brain?**
|
|
501
|
-
No. Everything your scrapers teach is scoped to your API key. Your data
|
|
502
|
-
answers only your recalls.
|
|
503
|
-
|
|
504
660
|
**Do my scrapers share memory?**
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
661
|
+
It depends on where they run. Memory is always private to your account.
|
|
662
|
+
- **On Apify**, each actor (`APIFY_ACTOR_ID`) has its own memory: recall and
|
|
663
|
+
SDK `ask()` calls from inside an actor only see what that actor learned.
|
|
664
|
+
- **Everywhere else**, scrapers share one default memory, so scraper A can
|
|
665
|
+
recall what scraper B learned, unless you name them with `scraper` /
|
|
666
|
+
`FETCHBRAIN_SCRAPER_ID` (see [Name your scraper](#name-your-scraper-scraper)).
|
|
667
|
+
- **A named scraper** (anywhere, including Apify) only sees its own memory.
|
|
668
|
+
- **Ask Your Brain in the dashboard** (and `ask()` calls with no platform
|
|
669
|
+
context) answers across everything your account has indexed.
|
|
509
670
|
|
|
510
671
|
**What leaves my process?**
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
672
|
+
Your requests (minus `Authorization`, `Cookie` and `Set-Cookie` headers),
|
|
673
|
+
the data you choose to learn, your API key, and a small set of `X-FB-*`
|
|
674
|
+
headers including platform identifiers (env vars ending in `_ID`, plus
|
|
675
|
+
`NODE_ENV`/`REGION`/`CI`). The full list is in
|
|
676
|
+
[What leaves your process](#what-leaves-your-process). If you opt into
|
|
677
|
+
telemetry, the fields in [Telemetry](#telemetry-opt-in) too.
|
|
515
678
|
|
|
516
679
|
**What does learning cost?**
|
|
517
|
-
Nothing. Learning is always free — you pay only for known
|
|
680
|
+
Nothing. Learning is always free — you pay only for known recalls.
|
|
518
681
|
|
|
519
682
|
**What if the data changed since the brain learned it?**
|
|
520
683
|
That's what memory depth is for: pick `fresh` (1h) for volatile data, or
|
|
@@ -523,8 +686,8 @@ set `refreshOnRebuild` to re-learn whenever you ship a new scraper build.
|
|
|
523
686
|
## Contributing
|
|
524
687
|
|
|
525
688
|
Issues and PRs welcome — see [open issues](https://github.com/fetchbrain-com/sdk/issues).
|
|
526
|
-
If FetchBrain saves your crawler time or money,
|
|
527
|
-
developers find it
|
|
689
|
+
If FetchBrain saves your crawler time or money, a GitHub star helps other
|
|
690
|
+
scraper developers find it.
|
|
528
691
|
|
|
529
692
|
## License
|
|
530
693
|
|