@fetchbrain.com/sdk 0.1.7 → 0.3.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 CHANGED
@@ -1,64 +1,188 @@
1
- # @fetchbrain.com/sdk
1
+ <div align="center">
2
2
 
3
- > **The AI That Already Knows The Web** - AI-powered scraping optimization for Crawlee
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="logo/fetchbrain-logo-reversed.svg">
5
+ <img src="logo/fetchbrain-logo-primary.svg" alt="FetchBrain" width="340">
6
+ </picture>
4
7
 
5
- [![CI](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml) [![npm version](https://badge.fury.io/js/@fetchbrain.com%2Fsdk.svg)](https://www.npmjs.com/package/@fetchbrain/sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+ **Make your scrapers smarter with every run.**
6
9
 
7
- FetchBrain uses a neural network continuously trained on millions of web pages. Ask first → Get instant results. AI doesn't know? → We fetch & learn for next time.
10
+ *Your crawler teaches it once. It recognizes forever.*
8
11
 
9
- ## Features
12
+ [![CI](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml) [![npm version](https://badge.fury.io/js/@fetchbrain.com%2Fsdk.svg)](https://www.npmjs.com/package/@fetchbrain.com/sdk) [![TypeScript](https://img.shields.io/badge/TypeScript-first-3178C6.svg)](https://www.typescriptlang.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
10
13
 
11
- - 🚀 **Instant Results** - Skip redundant HTTP requests with pre-trained knowledge
12
- - 🔄 **Auto-Learning** - AI automatically learns from scraped pages
13
- - 🛡️ **Graceful Degradation** - Circuit breaker ensures your scraper never fails
14
- - 📦 **Request Batching** - Optimized for high-concurrency scrapers
15
- - 🔌 **Crawlee Compatible** - Works with CheerioCrawler, PlaywrightCrawler, and more
14
+ [Quick start](#quick-start) · [How it works](#how-it-works) · [Docs](https://docs.fetchbrain.com) · [Examples](./examples) · [Changelog](./CHANGELOG.md)
16
15
 
17
- ## Installation
16
+ </div>
17
+
18
+ ---
19
+
20
+ Every scraping run re-fetches thousands of pages you already scraped last
21
+ time — paying for proxies, browsers, retries, and CAPTCHAs to learn things
22
+ you already know.
23
+
24
+ FetchBrain gives your scrapers a **shared memory pool**. Before each
25
+ request, a crawler asks *"do I already know this request?"* — known
26
+ requests come back in **~50ms** without touching the network; unknown ones
27
+ run normally and are learned. Everything every scraper learns accumulates under
28
+ your API key, run after run, scraper after scraper — a data asset that
29
+ compounds instead of costs. **Learning is always free.**
30
+
31
+ ```text
32
+ $ node scraper.js # first run — the brain learns
33
+ ● learned example.com/p/1042 1.9s
34
+ ● learned example.com/p/1043 2.3s
35
+ ● learned example.com/p/1044 2.1s
36
+
37
+ $ node scraper.js # every run after that
38
+ ● known example.com/p/1042 0.05s ⚡ no fetch
39
+ ● known example.com/p/1043 0.04s ⚡ no fetch
40
+ ● known example.com/p/1044 0.05s ⚡ no fetch
41
+
42
+ 🧠 Finished! recalled: 3/3 (100%), learned: 0, duration: 0.3s
43
+ ```
44
+
45
+ ## One line to adopt
46
+
47
+ FetchBrain wraps your existing [Crawlee](https://crawlee.dev) crawler — no
48
+ rewrites, no new framework, no pipeline changes:
49
+
50
+ ```diff
51
+ + import { FetchBrain } from "@fetchbrain.com/sdk";
52
+ import { CheerioCrawler } from "crawlee";
53
+
54
+ - const crawler = new CheerioCrawler({
55
+ + const crawler = FetchBrain.enhance(new CheerioCrawler({
56
+ requestHandler: async ({ $, pushData }) => {
57
+ await pushData({ title: $("h1").text(), price: $(".price").text() });
58
+ },
59
+ - });
60
+ + }), { apiKey: process.env.FETCHBRAIN_API_KEY });
61
+
62
+ await crawler.run(urls);
63
+ ```
64
+
65
+ That's it. Your handler only runs when there's something new to learn.
66
+
67
+ ## Why FetchBrain
68
+
69
+ | | Without | With FetchBrain |
70
+ | --- | --- | --- |
71
+ | **Repeat requests** | Full fetch, every run | Recalled in ~50ms, zero HTTP |
72
+ | **Proxy & compute spend** | Pay per fetch, every run | Pay only for what it knows |
73
+ | **Blocks & CAPTCHAs** | Every run risks them | Known requests never touch the site |
74
+ | **When the service is down** | — | Your crawl runs normally — guaranteed |
75
+ | **Testing** | Mock it yourself | `MockFetchBrain` ships in the box |
76
+
77
+ - ⚡ **Instant recall** — known requests skip the network entirely
78
+ - 🌐 **Any request, not just pages** — HTML, JSON APIs, POSTs with bodies; identity is derived from the full request
79
+ - 🎓 **Auto-learning** — every successful scrape teaches the brain, free
80
+ - 🛡️ **Never breaks your crawl** — circuit breaker degrades gracefully; a FetchBrain outage costs you optimization, never data
81
+ - 📦 **Built for scale** — request batching and deduping for high-concurrency crawlers
82
+ - 🔌 **Crawlee-native** — CheerioCrawler, PlaywrightCrawler, and friends
83
+ - 🔒 **Private by design** — your data is scoped to your key; only your requests, what you choose to learn, and platform identifiers (`*_ID` env vars) leave your process. Anonymized telemetry is **opt-in** ([opt-in telemetry](#telemetry-opt-in))
84
+ - 🧪 **TypeScript-first** — full types, ESM + CJS, zero config
85
+
86
+ ## Who is it for?
87
+
88
+ FetchBrain pays off wherever the **same expensive request gets made more
89
+ than once** — across a fleet, across users, or across runs. It won't speed
90
+ up a first-ever fetch of a brand-new URL, and it's not for freshness-critical
91
+ monitoring where you always need the live value. Everywhere else, it compounds:
92
+
93
+ **Data-service teams & aggregators** — fetch an expensive request once, serve
94
+ it to every client and job. Overlapping crawls draw from one shared pool, so
95
+ per-run proxy and compute cost falls as coverage grows — and `ask()` turns
96
+ everything you've collected into a queryable corpus, with no warehouse to run.
97
+
98
+ **Product teams & AI agents** — apps and browsing agents that re-hit popular
99
+ requests get them back in milliseconds, straight from memory: no fetch, no
100
+ proxy, no block. The more your users (or agents) converge on the same
101
+ requests, the more the pool pays off.
102
+
103
+ **Recurring crawls of stable data** — catalogs, specs, listings, company and
104
+ reference data barely change between runs, so recall skips the fetch and each
105
+ scheduled run costs less. Keep volatile fields on `memory: "fresh"` so you
106
+ never trade accuracy for speed.
107
+
108
+ **Solo scraper developers** — start free: learning never costs anything, and
109
+ the requests you've already made come back instantly instead of getting
110
+ blocked or throttled. One line to add, one brain that grows with everything
111
+ you scrape.
112
+
113
+ ## Quick start
18
114
 
19
115
  ```bash
20
116
  npm install @fetchbrain.com/sdk
21
117
  ```
22
118
 
23
- ## Quick Start
24
-
25
119
  ```typescript
26
120
  import { FetchBrain } from "@fetchbrain.com/sdk";
27
121
  import { CheerioCrawler } from "crawlee";
28
122
 
29
123
  const crawler = FetchBrain.enhance(
30
124
  new CheerioCrawler({
31
- requestHandler: async ({ $, request, pushData }) => {
32
- // This only runs when AI needs to "learn" (new page)
33
- const data = {
125
+ requestHandler: async ({ $, pushData }) => {
126
+ // Runs only when the brain needs to learn (new request)
127
+ await pushData({
34
128
  title: $("h1").text(),
35
129
  price: $(".price").text(),
36
- };
37
- await pushData(data);
130
+ });
38
131
  },
39
132
  }),
40
133
  {
41
134
  apiKey: process.env.FETCHBRAIN_API_KEY,
42
- intelligence: "high", // High confidence AI responses
43
- learning: true, // AI learns from scraped pages
135
+ memory: "recent", // how far back the brain recalls (see below)
44
136
  },
45
137
  );
46
138
 
47
139
  await crawler.run(urls);
48
140
  ```
49
141
 
50
- ## How It Works
51
-
52
- 1. **Before each request**, FetchBrain queries the AI if it "knows" the URL
53
- 2. **AI knows**: Return data instantly from neural inference, skip HTTP request
54
- 3. **AI learning**: Run your scraper normally, then teach the AI
142
+ ## How it works
55
143
 
56
144
  ```
57
- Your Scraper → FetchBrain SDK → AI knows? → YES → Return AI knowledge (skip request)
58
- → NO → Run scraper → AI learns for next time
145
+ Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data in ~50ms, no fetch
146
+ │
147
+ └──▶ NO ──▶ your handler runs ──▶ brain learns, free
59
148
  ```
60
149
 
61
- ## Configuration
150
+ 1. **Recall** — before each request, the SDK asks if the brain knows it
151
+ 2. **Known** — data returns instantly and the fetch is skipped
152
+ 3. **Learning** — unknown requests run through your handler as normal, and the result teaches the brain for every future run
153
+
154
+ ### Memory depth
155
+
156
+ How old is too old? You decide, per crawler:
157
+
158
+ | Depth | Window | Use for |
159
+ | --- | --- | --- |
160
+ | `fresh` | 1 hour | prices, stock, anything volatile |
161
+ | `recent` | 24 hours | **default** — daily crawl cycles |
162
+ | `standard` | 7 days | listings, catalogs |
163
+ | `deep` | 30 days | slow-changing reference data |
164
+
165
+ ## Take control in your handler
166
+
167
+ `context.brain` puts the recall decision in your hands:
168
+
169
+ ```typescript
170
+ requestHandler: async ({ $, brain, pushData }) => {
171
+ if (brain?.known) {
172
+ await brain.use(); // push the brain's data, skip scraping
173
+ return;
174
+ }
175
+ await pushData({ title: $("h1").text() }); // scrape + learn
176
+ },
177
+ ```
178
+
179
+ | Property | Type | Description |
180
+ | --- | --- | --- |
181
+ | `known` | `boolean` | whether the brain knows this request |
182
+ | `data` | `object` | the remembered data (if known) |
183
+ | `use()` | `function` | push the brain's data and skip scraping |
184
+
185
+ ### Configuration Options
62
186
 
63
187
  ```typescript
64
188
  interface FetchBrainConfig {
@@ -67,7 +191,7 @@ interface FetchBrainConfig {
67
191
 
68
192
  // Optional
69
193
  baseUrl?: string; // API URL (default: production)
70
- intelligence?: IntelligenceLevel; // AI accuracy level
194
+ memory?: MemoryDepth; // How far back the brain recalls
71
195
  learning?: boolean; // Enable AI learning (default: true)
72
196
  alwaysRun?: boolean | string | string[]; // Which handlers to run (default: false)
73
197
  timeout?: number; // Request timeout in ms (default: 500)
@@ -75,62 +199,51 @@ interface FetchBrainConfig {
75
199
  }
76
200
  ```
77
201
 
78
- ### Intelligence Levels
202
+ Fine-grained routing control with `alwaysRun` — run every handler, none, or
203
+ only specific labels when a request is known:
79
204
 
80
- | Level | Description |
81
- | ---------- | ----------------------------------- |
82
- | `realtime` | Live AI inference, highest accuracy |
83
- | `high` | High confidence responses |
84
- | `standard` | Balanced accuracy and speed |
85
- | `deep` | Deep knowledge, broader coverage |
205
+ ```typescript
206
+ FetchBrain.enhance(crawler, { alwaysRun: ["listing", "category"] });
207
+ ```
86
208
 
87
- ### Always Run Mode
209
+ ## Ask your brain anything
88
210
 
89
- Control which handlers run when AI knows the page. Useful for routers with multiple handlers:
211
+ This is where the pool pays off twice: `ask()` searches across everything
212
+ **all** your scrapers have ever learned — one question, your whole corpus,
213
+ no exact URLs, no warehouse:
90
214
 
91
215
  ```typescript
92
- // Skip all handlers when AI knows (default)
93
- FetchBrain.enhance(crawler, { alwaysRun: false });
94
-
95
- // Always run all handlers
96
- FetchBrain.enhance(crawler, { alwaysRun: true });
216
+ import { FetchBrainClient } from "@fetchbrain.com/sdk";
97
217
 
98
- // Only run 'listing' handler (skip 'detail' when AI knows)
99
- FetchBrain.enhance(crawler, { alwaysRun: "listing" });
218
+ const client = new FetchBrainClient({ apiKey: process.env.FETCHBRAIN_API_KEY });
219
+ const res = await client.ask("blue widgets under $50", { answer: true });
100
220
 
101
- // Run multiple specific handlers
102
- FetchBrain.enhance(crawler, { alwaysRun: ["listing", "category"] });
221
+ console.log(res.answer); // synthesized answer
222
+ console.log(res.sources); // scored sources
103
223
  ```
104
224
 
105
- | Value | Behavior |
106
- | ------------------------- | ------------------------------------- |
107
- | `false` (default) | Auto-skip all handlers when AI knows |
108
- | `true` | Always run all handlers |
109
- | `'listing'` | Only run handler with label 'listing' |
110
- | `['listing', 'category']` | Run handlers with these labels |
225
+ ## Brain Context in Handler
111
226
 
112
- ## AI Context in Handler
113
-
114
- Access AI data directly in your handler via `context.ai`:
227
+ Access brain data directly in your handler via `context.brain`:
115
228
 
116
229
  ```typescript
117
230
  const crawler = FetchBrain.enhance(
118
231
  new CheerioCrawler({
119
- requestHandler: async ({ $, request, ai, pushData }) => {
120
- // Check if AI already knows this page
121
- if (ai?.known && ai.confidence! > 0.9) {
122
- console.log("AI knows this page with high confidence");
232
+ requestHandler: async ({ $, request, brain, pushData }) => {
233
+ // Check if the brain already knows this page
234
+ if (brain?.known) {
235
+ console.log("Brain knows this page");
123
236
 
124
- // Option 1: Use AI data directly (skip scraping)
125
- await ai.useAIData();
237
+ // Option 1: Use brain data directly (skip scraping)
238
+ await brain.use();
126
239
  return;
127
240
 
128
- // Option 2: Compare AI data with scraped data
241
+ // Option 2: Compare brain data with scraped data
129
242
  // const scraped = { title: $('h1').text() };
130
- // console.log('AI:', ai.data, 'Scraped:', scraped);
243
+ // console.log('Brain:', brain.data, 'Scraped:', scraped);
131
244
  }
132
245
 
133
- // Scrape normally if AI doesn't know
246
+ // Scrape normally if the brain doesn't know
134
247
  const data = { title: $("h1").text() };
135
248
  await pushData(data);
136
249
  },
@@ -139,15 +252,13 @@ const crawler = FetchBrain.enhance(
139
252
  );
140
253
  ```
141
254
 
142
- ### `context.ai` Properties
255
+ ### `context.brain` Properties
143
256
 
144
- | Property | Type | Description |
145
- | ------------- | -------- | ------------------------------ |
146
- | `known` | boolean | Whether AI knows this URL |
147
- | `data` | object | AI data (if known) |
148
- | `confidence` | number | Confidence score 0-1 |
149
- | `learnedAt` | string | When AI learned this |
150
- | `useAIData()` | function | Push AI data and skip scraping |
257
+ | Property | Type | Description |
258
+ | --------- | -------- | ---------------------------------- |
259
+ | `known` | boolean | Whether the brain knows this URL |
260
+ | `data` | object | Brain data (if known) |
261
+ | `use()` | function | Push brain data and skip scraping |
151
262
 
152
263
  ## Using Dataset.pushData
153
264
 
@@ -178,60 +289,65 @@ const crawler = FetchBrain.enhance(
178
289
  );
179
290
  ```
180
291
 
181
- ## Manual API
182
-
183
- For custom integrations without Crawlee:
292
+ ## No Crawlee? No problem
184
293
 
185
294
  ```typescript
186
295
  import { FetchBrain } from "@fetchbrain.com/sdk";
187
296
 
188
- const ai = new FetchBrain({
297
+ const brain = new FetchBrain({
189
298
  apiKey: "your-api-key",
190
- intelligence: "high",
299
+ memory: "recent",
191
300
  });
192
301
 
193
- // Check if AI knows a URL
194
- const result = await ai.query({ url: "https://example.com/product/123" });
195
-
302
+ // Check if the brain knows a URL
303
+ const result = await brain.recall({ url: "https://example.com/product/123" });
196
304
  if (result.known) {
197
- console.log("AI knows:", result.data);
198
- console.log("Confidence:", result.confidence);
305
+ console.log("Brain knows:", result.data);
199
306
  } else {
200
307
  // Fetch and teach
201
- const data = await scrapeUrl("https://example.com/product/123");
202
- await ai.learn({ url: "https://example.com/product/123", data });
308
+ const data = await scrapeYourWay("https://example.com/product/123");
309
+ await brain.learn({ url: "https://example.com/product/123", data }); // free
203
310
  }
204
311
  ```
205
312
 
206
- ## Graceful Degradation
207
-
208
- FetchBrain includes a circuit breaker that ensures your scraper continues even if the API is unavailable:
313
+ ## It will never break your crawl
209
314
 
210
- - **API healthy**: Normal operation with AI optimization
211
- - **API slow (>500ms)**: Timeout, continue without AI
212
- - **API down**: Circuit opens, scraper runs standalone
213
- - **API recovers**: Circuit closes, AI optimization resumes
315
+ The circuit breaker is not an afterthought — it's the core design contract:
214
316
 
215
- Your scraper will **never fail** due to FetchBrain issues.
317
+ - **Healthy** → full optimization
318
+ - **Slow** (>500ms) → time out, continue without recall
319
+ - **Down** → circuit opens, your scraper runs standalone
320
+ - **Recovered** → circuit closes, optimization resumes
216
321
 
217
- ## Local Development
322
+ A FetchBrain problem can cost you *optimization*, never *data*. Every SDK
323
+ call degrades gracefully; none of them throw into your crawl.
218
324
 
219
- ### Mock Server
325
+ ## Telemetry (opt-in)
220
326
 
221
- For local testing without the production API:
327
+ Telemetry is **off by default.** You can opt in to send anonymized
328
+ operational diagnostics that help improve FetchBrain:
222
329
 
223
- ```bash
224
- # Start mock server
225
- npm run mock-server
226
-
227
- # In your code, use localhost
228
- const crawler = FetchBrain.enhance(crawler, {
229
- apiKey: 'test_local_key',
230
- baseUrl: 'http://localhost:3456',
330
+ ```typescript
331
+ FetchBrain.enhance(crawler, {
332
+ apiKey: process.env.FETCHBRAIN_API_KEY,
333
+ telemetry: { enabled: true },
231
334
  });
232
335
  ```
233
336
 
234
- ### Mock Client for Testing
337
+ **What's sent** (all anonymized): domain (e.g. `walmart.com`), a SHA-256
338
+ **hash** of the full URL, a generalized path pattern, timing and status
339
+ codes, retry counts, proxy **country/type** and success, coarse session
340
+ aggregates (age, error rate, cookie *count*), block indicators, and crawler
341
+ type. **Never:** raw URLs, request/response bodies, cookies or their values,
342
+ proxy IPs, credentials, or any PII.
343
+
344
+ Share selectively with the sub-flags — e.g.
345
+ `telemetry: { enabled: true, shareProxyInfo: false }`. Collection is
346
+ buffered, best-effort, and never blocks or fails your crawl.
347
+
348
+ ## Testing
349
+
350
+ `MockFetchBrain` ships with the SDK — seed it, run your tests, no network:
235
351
 
236
352
  ```typescript
237
353
  import { MockFetchBrain } from "@fetchbrain.com/sdk/mock";
@@ -243,40 +359,65 @@ const mock = new MockFetchBrain({
243
359
  });
244
360
 
245
361
  // Use in tests
246
- const result = await mock.query("https://example.com/product");
362
+ const result = await mock.recall({ url: "https://example.com/product" });
247
363
  expect(result.known).toBe(true);
364
+
365
+ // Ask a natural-language question against seeded knowledge
366
+ const answer = await mock.ask("what is the price?");
367
+ expect(answer.sources.length).toBeGreaterThan(0);
368
+ console.log(answer.sources);
248
369
  ```
249
370
 
371
+ There's also a local mock **server** (`npm run mock-server`) for running
372
+ real crawlers against `http://localhost:3456` without an API key.
373
+
250
374
  ## Examples
251
375
 
252
- See the [examples](./examples) directory:
376
+ | Example | Shows |
377
+ | --- | --- |
378
+ | [`basic-cheerio`](./examples/basic-cheerio) | CheerioCrawler + FetchBrain in ~40 lines |
379
+ | [`manual-recall`](./examples/manual-recall) | recall/learn without Crawlee |
380
+ | [`with-mock`](./examples/with-mock) | unit testing with `MockFetchBrain` |
253
381
 
254
382
  - **basic-cheerio** - CheerioCrawler with FetchBrain
255
- - **manual-query** - Direct API usage without Crawlee
383
+ - **manual-recall** - Direct API usage without Crawlee
256
384
  - **with-mock** - Unit testing with MockFetchBrain
257
385
 
258
- ## API Reference
259
-
260
- ### `FetchBrain.enhance(crawler, config)`
386
+ ## FAQ
261
387
 
262
- Wraps a Crawlee crawler with FetchBrain optimization.
388
+ **Does my scraped data train anyone else's brain?**
389
+ No. Everything your scrapers teach is scoped to your API key. Your data
390
+ answers only your recalls.
263
391
 
264
- ### `FetchBrain.query({ url, intelligence? })`
392
+ **Do my scrapers share memory?**
393
+ Yes — that's the point. Everything learned under your API key accumulates
394
+ in one brain, and `ask()` searches across all of it. Recall is namespaced
395
+ per scraper identity, so one scraper's responses never pollute
396
+ another's results.
265
397
 
266
- Check if FetchBrain knows a URL.
398
+ **What leaves my process?**
399
+ By default: your requests, the data you choose to learn, and platform
400
+ identifiers (env vars ending in `_ID`, plus `NODE_ENV`/`REGION`/`CI`). Never
401
+ your general environment, credentials, or anything credential-shaped. If you
402
+ opt into telemetry, anonymized access signal too — [see what](#telemetry-opt-in).
267
403
 
268
- ### `FetchBrain.learn({ url, data })`
404
+ **What does learning cost?**
405
+ Nothing. Learning is always free — you pay only for known queries.
269
406
 
270
- Teach FetchBrain new data.
407
+ **What if the data changed since the brain learned it?**
408
+ That's what memory depth is for: pick `fresh` (1h) for volatile data, or
409
+ set `refreshOnRebuild` to re-learn whenever you ship a new scraper build.
271
410
 
272
- ### `FetchBrain.stats()`
411
+ ## Contributing
273
412
 
274
- Get usage statistics.
413
+ Issues and PRs welcome — see [open issues](https://github.com/fetchbrain-com/sdk/issues).
414
+ If FetchBrain saves your crawler time or money, **a ⭐ helps other scraper
415
+ developers find it**.
275
416
 
276
417
  ## License
277
418
 
278
- MIT © FetchBrain
419
+ MIT © [FetchBrain](https://fetchbrain.com)
279
420
 
280
421
  ---
281
422
 
282
- **Need help?** [Open an issue](https://github.com/fetchbrain-com/fetchbrain-sdk/issues) or check our [documentation](https://docs.fetchbrain.com).
423
+ **Need help?** [Open an issue](https://github.com/fetchbrain-com/sdk/issues) · [Read the docs](https://docs.fetchbrain.com)