@fetchbrain.com/sdk 0.5.0 → 0.5.1
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 +294 -162
- package/dist/index.d.mts +16 -8
- package/dist/index.d.ts +16 -8
- package/dist/index.js +52 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +52 -4
- 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-BMwfPE5J.d.mts} +24 -22
- package/dist/{types-BbLgy1no.d.ts → types-BMwfPE5J.d.ts} +24 -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, all scrapers under one API
|
|
175
|
+
key share one memory.
|
|
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,15 +243,25 @@ interface FetchBrainConfig {
|
|
|
210
243
|
apiKey: string;
|
|
211
244
|
|
|
212
245
|
// Optional
|
|
213
|
-
baseUrl?: string; // API URL (default:
|
|
214
|
-
memory?: MemoryDepth; // How far back the brain recalls
|
|
215
|
-
learning?: boolean; //
|
|
216
|
-
alwaysRun?: boolean | string | string[]; //
|
|
246
|
+
baseUrl?: string; // API URL (default: https://api.fetchbrain.com)
|
|
247
|
+
memory?: MemoryDepth; // How far back the brain recalls (default: "recent")
|
|
248
|
+
learning?: boolean; // Teach the brain from scraped data (default: true)
|
|
249
|
+
alwaysRun?: boolean | string | string[]; // Handlers that still run when a request is known (default: false)
|
|
217
250
|
skipLabels?: string[]; // Labels that bypass FetchBrain entirely (default: none)
|
|
218
251
|
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
|
-
|
|
252
|
+
onRecalled?: (event: RecalledEvent) => void | Promise<void>; // Per-record hook when recalled data is delivered
|
|
253
|
+
extractForLearning?: (data: unknown) => Record<string, unknown>; // Transform each record before it is learned
|
|
254
|
+
refreshOnRebuild?: boolean; // Scope learn, recall and ask to the current build (*_BUILD_ID env var) (default: false)
|
|
255
|
+
timeout?: number; // Handler-time recall, stats and telemetry timeout in ms (default: 500)
|
|
256
|
+
batch?: { maxSize?: number; maxWait?: number }; // Request batching (default: 50 items / 50ms)
|
|
257
|
+
circuitBreaker?: {
|
|
258
|
+
failureThreshold?: number; // Failures before the circuit opens (default: 3)
|
|
259
|
+
resetTimeout?: number; // ms before a retry is allowed (default: 30000)
|
|
260
|
+
successThreshold?: number; // Successes to close it again (default: 1)
|
|
261
|
+
};
|
|
262
|
+
telemetry?: TelemetryConfig; // Opt-in telemetry (default: { enabled: false })
|
|
263
|
+
learnUrlField?: string; // Accepted but not currently applied
|
|
264
|
+
debug?: boolean; // Enable debug logging (default: false)
|
|
222
265
|
}
|
|
223
266
|
```
|
|
224
267
|
|
|
@@ -241,11 +284,20 @@ Things to know:
|
|
|
241
284
|
- **Scope** — pre-recall applies to arrays passed to `crawler.addRequests()`
|
|
242
285
|
or `crawler.run(requests)`. Crawlee's context-level `enqueueLinks()` and
|
|
243
286
|
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
|
-
|
|
287
|
+
pre-recalled (they still get handler-time recall, but the fetch has
|
|
288
|
+
already happened). Inside a handler, enqueue follow-ups through the
|
|
289
|
+
crawler to keep the benefit:
|
|
290
|
+
|
|
291
|
+
```typescript
|
|
292
|
+
requestHandler: async ({ $, request, crawler }) => {
|
|
293
|
+
const urls = $("a.product")
|
|
294
|
+
.map((_, a) => new URL($(a).attr("href") ?? "", request.url).href)
|
|
295
|
+
.get();
|
|
296
|
+
await crawler.addRequests(urls.map((url) => ({ url, label: "product" })));
|
|
297
|
+
},
|
|
298
|
+
```
|
|
299
|
+
- **Metering** — known recalls are counted at enqueue time, so a known
|
|
300
|
+
duplicate that the queue later drops still counts.
|
|
249
301
|
- **Snapshot semantics** — the recall result is as of enqueue time. Anything
|
|
250
302
|
learned between enqueue and execution isn't picked up; the request is
|
|
251
303
|
simply scraped and re-learned.
|
|
@@ -264,42 +316,55 @@ Things to know:
|
|
|
264
316
|
|
|
265
317
|
When the brain knows a request, your handler is skipped and the remembered
|
|
266
318
|
data is pushed for you — which also skips any per-record bookkeeping living
|
|
267
|
-
in that handler (
|
|
319
|
+
in that handler (metrics, counters, follow-up enqueues). `onRecalled`
|
|
268
320
|
runs once per recalled record with `{ url, label, userData, data }` — both
|
|
269
321
|
when the handler is auto-skipped and when your own handler calls
|
|
270
322
|
`context.brain.use()`:
|
|
271
323
|
|
|
272
324
|
```typescript
|
|
325
|
+
const recalledByLabel = new Map<string, number>();
|
|
326
|
+
|
|
273
327
|
FetchBrain.enhance(crawler, {
|
|
274
|
-
|
|
275
|
-
|
|
328
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
329
|
+
onRecalled: ({ label = "default" }) => {
|
|
330
|
+
recalledByLabel.set(label, (recalledByLabel.get(label) ?? 0) + 1);
|
|
276
331
|
},
|
|
277
332
|
});
|
|
278
333
|
```
|
|
279
334
|
|
|
280
335
|
Hook errors are swallowed (logged at debug) — they never break the crawl.
|
|
281
336
|
|
|
337
|
+
### Choosing which handlers run
|
|
338
|
+
|
|
282
339
|
Fine-grained routing control with `alwaysRun` — run every handler, none, or
|
|
283
340
|
only specific labels when a request is known:
|
|
284
341
|
|
|
285
342
|
```typescript
|
|
286
|
-
FetchBrain.enhance(crawler, {
|
|
343
|
+
FetchBrain.enhance(crawler, {
|
|
344
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
345
|
+
alwaysRun: ["listing", "category"],
|
|
346
|
+
});
|
|
287
347
|
```
|
|
288
348
|
|
|
289
349
|
For dynamic requests that must always run live and aren't worth remembering
|
|
290
350
|
(search results, pagination), use `skipLabels` instead: where `alwaysRun`
|
|
291
351
|
still recalls (and can learn), `skipLabels` bypasses FetchBrain entirely —
|
|
292
|
-
no recall round-trip, no learn — so those requests run at
|
|
352
|
+
no recall round-trip, no learn, no telemetry — so those requests run at
|
|
353
|
+
native speed:
|
|
293
354
|
|
|
294
355
|
```typescript
|
|
295
|
-
FetchBrain.enhance(crawler, {
|
|
356
|
+
FetchBrain.enhance(crawler, {
|
|
357
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
358
|
+
skipLabels: ["search", "pagination"],
|
|
359
|
+
});
|
|
296
360
|
```
|
|
297
361
|
|
|
298
362
|
## Ask your brain anything
|
|
299
363
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
364
|
+
`ask()` answers from what's been learned — one question, no exact URLs, no
|
|
365
|
+
warehouse. From the SDK it uses the same scope as recall (see
|
|
366
|
+
[Do my scrapers share memory?](#do-my-scrapers-share-memory)); Ask Your Brain
|
|
367
|
+
in the dashboard answers across your whole account:
|
|
303
368
|
|
|
304
369
|
```typescript
|
|
305
370
|
import { FetchBrainClient } from "@fetchbrain.com/sdk";
|
|
@@ -311,8 +376,8 @@ console.log(res.answer); // synthesized answer
|
|
|
311
376
|
console.log(res.sources); // scored sources
|
|
312
377
|
```
|
|
313
378
|
|
|
314
|
-
Pick the model that writes the answer with `model` — the default is
|
|
315
|
-
|
|
379
|
+
Pick the model that writes the answer with `model` — the default is
|
|
380
|
+
`"llama-3.3-70b"`, included on every plan. Premium models like
|
|
316
381
|
`"kimi-k2.5"` and `"kimi-k2.6"` use extra ask credits and need a paid plan,
|
|
317
382
|
and `"byok"` answers with your own linked provider model (configured in the
|
|
318
383
|
dashboard, billed to your provider):
|
|
@@ -334,70 +399,35 @@ paid plan, `"byok"` with no linked provider — the response comes back with
|
|
|
334
399
|
`status: "unavailable"`, which means the API itself is degraded or
|
|
335
400
|
unreachable.
|
|
336
401
|
|
|
337
|
-
##
|
|
338
|
-
|
|
339
|
-
Access brain data directly in your handler via `context.brain`:
|
|
340
|
-
|
|
341
|
-
```typescript
|
|
342
|
-
const crawler = FetchBrain.enhance(
|
|
343
|
-
new CheerioCrawler({
|
|
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
|
|
402
|
+
## Learning with `Dataset.pushData`
|
|
376
403
|
|
|
377
|
-
>
|
|
404
|
+
> **Important:** the brain learns only from `context.pushData()` or the
|
|
405
|
+
> SDK's `pushData()` wrapper below. Data written with `Dataset.pushData()`
|
|
406
|
+
> directly is not learned, so those requests stay unknown on future runs.
|
|
378
407
|
|
|
379
|
-
If you
|
|
408
|
+
If you write with `Dataset.pushData()` instead of `context.pushData()`, use
|
|
409
|
+
the wrapper so the brain learns from it:
|
|
380
410
|
|
|
381
411
|
```typescript
|
|
382
412
|
import { FetchBrain, pushData } from "@fetchbrain.com/sdk";
|
|
383
|
-
import { Dataset } from "crawlee";
|
|
413
|
+
import { CheerioCrawler, Dataset } from "crawlee";
|
|
384
414
|
|
|
385
415
|
const crawler = FetchBrain.enhance(
|
|
386
416
|
new CheerioCrawler({
|
|
387
|
-
requestHandler: async ({
|
|
417
|
+
requestHandler: async ({ $ }) => {
|
|
388
418
|
const data = { title: $("h1").text() };
|
|
389
419
|
|
|
390
|
-
//
|
|
420
|
+
// Learned: the SDK wrapper
|
|
391
421
|
await pushData(data, Dataset);
|
|
392
422
|
|
|
393
|
-
//
|
|
423
|
+
// Learned: the wrapper with a named dataset
|
|
394
424
|
await pushData(data, Dataset, "products");
|
|
395
425
|
|
|
396
|
-
//
|
|
426
|
+
// Not learned:
|
|
397
427
|
// await Dataset.pushData(data);
|
|
398
428
|
},
|
|
399
429
|
}),
|
|
400
|
-
{ apiKey:
|
|
430
|
+
{ apiKey: process.env.FETCHBRAIN_API_KEY },
|
|
401
431
|
);
|
|
402
432
|
```
|
|
403
433
|
|
|
@@ -407,7 +437,7 @@ const crawler = FetchBrain.enhance(
|
|
|
407
437
|
import { FetchBrain } from "@fetchbrain.com/sdk";
|
|
408
438
|
|
|
409
439
|
const brain = new FetchBrain({
|
|
410
|
-
apiKey:
|
|
440
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
411
441
|
memory: "recent",
|
|
412
442
|
});
|
|
413
443
|
|
|
@@ -427,17 +457,74 @@ if (result.known) {
|
|
|
427
457
|
The circuit breaker is not an afterthought — it's the core design contract:
|
|
428
458
|
|
|
429
459
|
- **Healthy** → full optimization
|
|
430
|
-
- **Slow**
|
|
431
|
-
- **Down** → circuit opens
|
|
432
|
-
- **Recovered** → circuit closes
|
|
460
|
+
- **Slow** → the call times out and your crawl continues without it
|
|
461
|
+
- **Down** → after 3 consecutive failures the circuit opens and your scraper runs standalone
|
|
462
|
+
- **Recovered** → after 30 seconds the SDK tries again; on success the circuit closes and optimization resumes
|
|
463
|
+
|
|
464
|
+
Timeouts per call type:
|
|
465
|
+
|
|
466
|
+
| Call | Timeout |
|
|
467
|
+
| --- | --- |
|
|
468
|
+
| Recall in the handler (batched) | `timeout` option, default 500ms |
|
|
469
|
+
| Recall at enqueue (`preRecall`, bulk) | 3s per chunk of up to 100 requests |
|
|
470
|
+
| Learn (batched, sent in the background) | 5s |
|
|
471
|
+
| `ask()` | 10s |
|
|
472
|
+
| `stats()` and telemetry | `timeout` option, default 500ms |
|
|
433
473
|
|
|
434
|
-
A FetchBrain
|
|
435
|
-
|
|
474
|
+
A FetchBrain outage costs you *optimization*, not your crawl: SDK calls
|
|
475
|
+
degrade gracefully instead of throwing into it. The one deliberate
|
|
476
|
+
exception is [expired memory](#recall-at-enqueue-time-prerecall): a request
|
|
477
|
+
that skipped its fetch at enqueue and whose remembered data is gone fails
|
|
478
|
+
into your `failedRequestHandler` rather than disappearing silently.
|
|
479
|
+
|
|
480
|
+
## What leaves your process
|
|
481
|
+
|
|
482
|
+
Every API call (recall, learn, ask, stats, telemetry) sends these headers:
|
|
483
|
+
|
|
484
|
+
| Header | Value |
|
|
485
|
+
| --- | --- |
|
|
486
|
+
| `Authorization` | `Bearer <your API key>` |
|
|
487
|
+
| `X-FB-SDK` | `js` |
|
|
488
|
+
| `X-FB-Node` | your Node.js version (e.g. `v20.11.0`) |
|
|
489
|
+
| `X-FB-Platform` | your OS platform (e.g. `linux`) |
|
|
490
|
+
| `X-FB-Env` | the value of `NODE_ENV`, if set |
|
|
491
|
+
| `X-FB-Context` | JSON of environment variables named `*_ID`, plus `NODE_ENV`, `REGION` and `CI` (see below) |
|
|
492
|
+
| `X-FB-Crawler` | the crawler class name (e.g. `CheerioCrawler`), while a request is being handled |
|
|
493
|
+
| `X-FB-Label` | the request's Crawlee label, while a request is being handled |
|
|
494
|
+
|
|
495
|
+
`X-FB-Context` carries your platform identifiers; the API uses
|
|
496
|
+
`APIFY_ACTOR_ID` from it to scope memory per Apify actor (other `*_ID`
|
|
497
|
+
variables do not affect scoping) and `*BUILD_ID` for `refreshOnRebuild`. It includes
|
|
498
|
+
every environment variable whose name ends in `_ID`, plus `NODE_ENV`,
|
|
499
|
+
`REGION` and `CI`, except names containing `TOKEN`, `SECRET`, `PASSWORD`,
|
|
500
|
+
`CREDENTIAL`, `KEY`, `AUTH` or `COOKIE`, values that look like a JWT or a
|
|
501
|
+
URL with embedded `user:pass`, and values over 256 characters (2 KB total).
|
|
502
|
+
No other environment variables are sent. If you keep something private in
|
|
503
|
+
a variable ending in `_ID`, it will be sent.
|
|
504
|
+
|
|
505
|
+
Recall and learn also send the request itself: the full URL (including
|
|
506
|
+
query string), method, `uniqueKey`, label, string POST body, your
|
|
507
|
+
`userData` (minus the SDK's own keys), and the request headers **except**
|
|
508
|
+
`Authorization`, `Cookie` and `Set-Cookie`. Recall also sends your `memory`
|
|
509
|
+
depth; learn also sends the record you pushed (after `extractForLearning`).
|
|
510
|
+
|
|
511
|
+
With `refreshOnRebuild`, recall, learn and `ask()` also send a build ID: the
|
|
512
|
+
value of the first environment variable whose name ends in `BUILD_ID`. This
|
|
513
|
+
value is sent as-is — it does **not** go through the name, credential or
|
|
514
|
+
length filters `X-FB-Context` uses.
|
|
515
|
+
|
|
516
|
+
Other headers (for example
|
|
517
|
+
`Proxy-Authorization` or `X-API-Key`), `userData` values and POST bodies are
|
|
518
|
+
forwarded as-is — keep secrets out of them on requests FetchBrain handles,
|
|
519
|
+
or route those requests through `skipLabels`, which sends nothing for them.
|
|
520
|
+
|
|
521
|
+
`ask()` sends your question and options. Telemetry sends nothing unless you
|
|
522
|
+
[opt in](#telemetry-opt-in).
|
|
436
523
|
|
|
437
524
|
## Telemetry (opt-in)
|
|
438
525
|
|
|
439
|
-
Telemetry is **off by default.**
|
|
440
|
-
|
|
526
|
+
Telemetry is **off by default.** Nothing in this section is collected or
|
|
527
|
+
sent unless you opt in:
|
|
441
528
|
|
|
442
529
|
```typescript
|
|
443
530
|
FetchBrain.enhance(crawler, {
|
|
@@ -446,16 +533,57 @@ FetchBrain.enhance(crawler, {
|
|
|
446
533
|
});
|
|
447
534
|
```
|
|
448
535
|
|
|
449
|
-
**
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
536
|
+
**It's pseudonymous, not anonymous.** Entries are sent to the FetchBrain
|
|
537
|
+
API with your API key and the [headers above](#what-leaves-your-process),
|
|
538
|
+
so they're linked to your account. They're used to improve FetchBrain's
|
|
539
|
+
recommendations (proxy recommendations, block detection, configuration
|
|
540
|
+
tuning); aggregated statistics may inform recommendations for other users.
|
|
541
|
+
|
|
542
|
+
**When it's collected:** one entry per request FetchBrain handles
|
|
543
|
+
(`skipLabels` requests are excluded), after your handler finishes — or
|
|
544
|
+
whenever the request fails inside the SDK's wrapper, including failures
|
|
545
|
+
before your handler runs (e.g. [expired memory](#recall-at-enqueue-time-prerecall))
|
|
546
|
+
and on known requests. Known requests that are skipped successfully produce
|
|
547
|
+
no entry. A failure entry carries only the "always" fields (minus session),
|
|
548
|
+
`retryCount`, timing, and `blocked: true` with a `blockType` if one matches.
|
|
549
|
+
Entries are buffered in your process and sent in batches (every 50 entries,
|
|
550
|
+
every 30 seconds, and when the crawl finishes); send failures are ignored and
|
|
551
|
+
never affect your crawl.
|
|
552
|
+
|
|
553
|
+
**What's sent:**
|
|
554
|
+
|
|
555
|
+
| Field | Sent when | What it is |
|
|
556
|
+
| --- | --- | --- |
|
|
557
|
+
| `domain` | always | the URL's hostname, in plain text (e.g. `shop.example.com`) |
|
|
558
|
+
| `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. |
|
|
559
|
+
| `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/*`). |
|
|
560
|
+
| `timestamp` | always | when the entry was collected |
|
|
561
|
+
| `crawlerType` | always | crawler class name, lowercased, without `Crawler` (e.g. `cheerio`) |
|
|
562
|
+
| `requestLabel` | always | the request's Crawlee label, if set |
|
|
563
|
+
| `sessionAge`, `sessionErrorScore` | on success, if the request has a Crawlee session | the session's usage count and error score |
|
|
564
|
+
| `statusCode` | `sharePerformance`, on success | HTTP status |
|
|
565
|
+
| `retryCount` | `sharePerformance` | Crawlee retry count |
|
|
566
|
+
| `responseTimeMs`, `totalTimeMs` | `sharePerformance` | time in ms from when the SDK starts handling the request (including recall) until your handler finishes or the request fails |
|
|
567
|
+
| `contentSize` | `sharePerformance`, on success | response body length, when the crawler exposes it |
|
|
568
|
+
| `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 |
|
|
569
|
+
| `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. |
|
|
570
|
+
|
|
571
|
+
**Sub-flags** — each defaults to `true` once telemetry is enabled; set one
|
|
572
|
+
to `false` to stop sending its fields. The "always" fields above are sent
|
|
573
|
+
whenever telemetry is enabled.
|
|
574
|
+
|
|
575
|
+
```typescript
|
|
576
|
+
telemetry: {
|
|
577
|
+
enabled: true, // default: false
|
|
578
|
+
sharePerformance: false, // default: true
|
|
579
|
+
shareSitePatterns: true, // default: true
|
|
580
|
+
shareProxyInfo: false, // default: true
|
|
581
|
+
}
|
|
582
|
+
```
|
|
455
583
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
584
|
+
**Never sent by telemetry:** the raw URL or query string, request or response
|
|
585
|
+
bodies, your scraped requests' headers or cookies, error messages, or proxy
|
|
586
|
+
URLs and IPs.
|
|
459
587
|
|
|
460
588
|
## Testing
|
|
461
589
|
|
|
@@ -465,7 +593,7 @@ buffered, best-effort, and never blocks or fails your crawl.
|
|
|
465
593
|
import { MockFetchBrain } from "@fetchbrain.com/sdk/mock";
|
|
466
594
|
|
|
467
595
|
const mock = new MockFetchBrain({
|
|
468
|
-
|
|
596
|
+
initialMemory: new Map([
|
|
469
597
|
["https://example.com/product", { title: "Known Product" }],
|
|
470
598
|
]),
|
|
471
599
|
});
|
|
@@ -474,14 +602,21 @@ const mock = new MockFetchBrain({
|
|
|
474
602
|
const result = await mock.recall({ url: "https://example.com/product" });
|
|
475
603
|
expect(result.known).toBe(true);
|
|
476
604
|
|
|
477
|
-
// Ask a natural-language question against seeded
|
|
478
|
-
const answer = await mock.ask("
|
|
605
|
+
// Ask a natural-language question against seeded memory
|
|
606
|
+
const answer = await mock.ask("known product");
|
|
479
607
|
expect(answer.sources.length).toBeGreaterThan(0);
|
|
480
608
|
console.log(answer.sources);
|
|
481
609
|
```
|
|
482
610
|
|
|
483
|
-
|
|
484
|
-
|
|
611
|
+
`initialMemory` replaces the older `initialKnowledge` option (still
|
|
612
|
+
accepted, deprecated), and `getMemorySize()` replaces `getKnowledgeSize()`.
|
|
613
|
+
Pass `learnCap: N` to make the mock reject learns after N entries, to test
|
|
614
|
+
how your crawl behaves at the monthly learning limit.
|
|
615
|
+
|
|
616
|
+
If you clone this repository, there's also a local mock **server**
|
|
617
|
+
(`npm run mock-server`) for running real crawlers against
|
|
618
|
+
`http://localhost:3456` without an API key (set `FB_MOCK_LEARN_CAP=N` to
|
|
619
|
+
simulate the learning limit). It isn't included in the npm package.
|
|
485
620
|
|
|
486
621
|
## Examples
|
|
487
622
|
|
|
@@ -491,30 +626,27 @@ real crawlers against `http://localhost:3456` without an API key.
|
|
|
491
626
|
| [`manual-recall`](./examples/manual-recall) | recall/learn without Crawlee |
|
|
492
627
|
| [`with-mock`](./examples/with-mock) | unit testing with `MockFetchBrain` |
|
|
493
628
|
|
|
494
|
-
- **basic-cheerio** - CheerioCrawler with FetchBrain
|
|
495
|
-
- **manual-recall** - Direct API usage without Crawlee
|
|
496
|
-
- **with-mock** - Unit testing with MockFetchBrain
|
|
497
|
-
|
|
498
629
|
## FAQ
|
|
499
630
|
|
|
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
631
|
**Do my scrapers share memory?**
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
632
|
+
It depends on where they run. Memory is always private to your account.
|
|
633
|
+
- **On Apify**, each actor (`APIFY_ACTOR_ID`) has its own memory: recall and
|
|
634
|
+
SDK `ask()` calls from inside an actor only see what that actor learned.
|
|
635
|
+
- **Everywhere else**, all scrapers using the same API key share one memory —
|
|
636
|
+
scraper A can recall what scraper B learned.
|
|
637
|
+
- **Ask Your Brain in the dashboard** (and `ask()` calls with no platform
|
|
638
|
+
context) answers across everything your account has indexed.
|
|
509
639
|
|
|
510
640
|
**What leaves my process?**
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
641
|
+
Your requests (minus `Authorization`, `Cookie` and `Set-Cookie` headers),
|
|
642
|
+
the data you choose to learn, your API key, and a small set of `X-FB-*`
|
|
643
|
+
headers including platform identifiers (env vars ending in `_ID`, plus
|
|
644
|
+
`NODE_ENV`/`REGION`/`CI`). The full list is in
|
|
645
|
+
[What leaves your process](#what-leaves-your-process). If you opt into
|
|
646
|
+
telemetry, the fields in [Telemetry](#telemetry-opt-in) too.
|
|
515
647
|
|
|
516
648
|
**What does learning cost?**
|
|
517
|
-
Nothing. Learning is always free — you pay only for known
|
|
649
|
+
Nothing. Learning is always free — you pay only for known recalls.
|
|
518
650
|
|
|
519
651
|
**What if the data changed since the brain learned it?**
|
|
520
652
|
That's what memory depth is for: pick `fresh` (1h) for volatile data, or
|
|
@@ -523,8 +655,8 @@ set `refreshOnRebuild` to re-learn whenever you ship a new scraper build.
|
|
|
523
655
|
## Contributing
|
|
524
656
|
|
|
525
657
|
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
|
|
658
|
+
If FetchBrain saves your crawler time or money, a GitHub star helps other
|
|
659
|
+
scraper developers find it.
|
|
528
660
|
|
|
529
661
|
## License
|
|
530
662
|
|