@fetchbrain.com/sdk 0.2.0 → 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 +259 -122
- package/dist/index.d.mts +26 -22
- package/dist/index.d.ts +26 -22
- package/dist/index.js +109 -63
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +110 -63
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +19 -7
- package/dist/mock/index.d.ts +19 -7
- package/dist/mock/index.js +35 -15
- package/dist/mock/index.js.map +1 -1
- package/dist/mock/index.mjs +35 -15
- package/dist/mock/index.mjs.map +1 -1
- package/dist/{types-Ddu_K1Nn.d.mts → types-CSX4KGoU.d.mts} +30 -30
- package/dist/{types-Ddu_K1Nn.d.ts → types-CSX4KGoU.d.ts} +30 -30
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,68 +1,188 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
**
|
|
8
|
+
**Make your scrapers smarter with every run.**
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
*Your crawler teaches it once. It recognizes forever.*
|
|
8
11
|
|
|
9
|
-
[](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml) [](https://www.npmjs.com/package/@fetchbrain.com/sdk) [](https://opensource.org/licenses/MIT)
|
|
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)
|
|
10
13
|
|
|
11
|
-
|
|
14
|
+
[Quick start](#quick-start) · [How it works](#how-it-works) · [Docs](https://docs.fetchbrain.com) · [Examples](./examples) · [Changelog](./CHANGELOG.md)
|
|
12
15
|
|
|
13
|
-
|
|
16
|
+
</div>
|
|
14
17
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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 |
|
|
20
76
|
|
|
21
|
-
|
|
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
|
|
22
114
|
|
|
23
115
|
```bash
|
|
24
116
|
npm install @fetchbrain.com/sdk
|
|
25
117
|
```
|
|
26
118
|
|
|
27
|
-
## Quick Start
|
|
28
|
-
|
|
29
119
|
```typescript
|
|
30
120
|
import { FetchBrain } from "@fetchbrain.com/sdk";
|
|
31
121
|
import { CheerioCrawler } from "crawlee";
|
|
32
122
|
|
|
33
123
|
const crawler = FetchBrain.enhance(
|
|
34
124
|
new CheerioCrawler({
|
|
35
|
-
requestHandler: async ({ $,
|
|
36
|
-
//
|
|
37
|
-
|
|
125
|
+
requestHandler: async ({ $, pushData }) => {
|
|
126
|
+
// Runs only when the brain needs to learn (new request)
|
|
127
|
+
await pushData({
|
|
38
128
|
title: $("h1").text(),
|
|
39
129
|
price: $(".price").text(),
|
|
40
|
-
};
|
|
41
|
-
await pushData(data);
|
|
130
|
+
});
|
|
42
131
|
},
|
|
43
132
|
}),
|
|
44
133
|
{
|
|
45
134
|
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
46
|
-
|
|
47
|
-
learning: true, // AI learns from scraped pages
|
|
135
|
+
memory: "recent", // how far back the brain recalls (see below)
|
|
48
136
|
},
|
|
49
137
|
);
|
|
50
138
|
|
|
51
139
|
await crawler.run(urls);
|
|
52
140
|
```
|
|
53
141
|
|
|
54
|
-
## How
|
|
55
|
-
|
|
56
|
-
1. **Before each request**, FetchBrain queries the AI if it "knows" the URL
|
|
57
|
-
2. **AI knows**: Return data instantly from neural inference, skip HTTP request
|
|
58
|
-
3. **AI learning**: Run your scraper normally, then teach the AI
|
|
142
|
+
## How it works
|
|
59
143
|
|
|
60
144
|
```
|
|
61
|
-
Your
|
|
62
|
-
|
|
145
|
+
Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data in ~50ms, no fetch
|
|
146
|
+
│
|
|
147
|
+
└──▶ NO ──▶ your handler runs ──▶ brain learns, free
|
|
63
148
|
```
|
|
64
149
|
|
|
65
|
-
|
|
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
|
|
66
186
|
|
|
67
187
|
```typescript
|
|
68
188
|
interface FetchBrainConfig {
|
|
@@ -71,7 +191,7 @@ interface FetchBrainConfig {
|
|
|
71
191
|
|
|
72
192
|
// Optional
|
|
73
193
|
baseUrl?: string; // API URL (default: production)
|
|
74
|
-
|
|
194
|
+
memory?: MemoryDepth; // How far back the brain recalls
|
|
75
195
|
learning?: boolean; // Enable AI learning (default: true)
|
|
76
196
|
alwaysRun?: boolean | string | string[]; // Which handlers to run (default: false)
|
|
77
197
|
timeout?: number; // Request timeout in ms (default: 500)
|
|
@@ -79,62 +199,51 @@ interface FetchBrainConfig {
|
|
|
79
199
|
}
|
|
80
200
|
```
|
|
81
201
|
|
|
82
|
-
|
|
202
|
+
Fine-grained routing control with `alwaysRun` — run every handler, none, or
|
|
203
|
+
only specific labels when a request is known:
|
|
83
204
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
| `high` | High confidence responses |
|
|
88
|
-
| `standard` | Balanced accuracy and speed |
|
|
89
|
-
| `deep` | Deep knowledge, broader coverage |
|
|
205
|
+
```typescript
|
|
206
|
+
FetchBrain.enhance(crawler, { alwaysRun: ["listing", "category"] });
|
|
207
|
+
```
|
|
90
208
|
|
|
91
|
-
|
|
209
|
+
## Ask your brain anything
|
|
92
210
|
|
|
93
|
-
|
|
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:
|
|
94
214
|
|
|
95
215
|
```typescript
|
|
96
|
-
|
|
97
|
-
FetchBrain.enhance(crawler, { alwaysRun: false });
|
|
216
|
+
import { FetchBrainClient } from "@fetchbrain.com/sdk";
|
|
98
217
|
|
|
99
|
-
|
|
100
|
-
|
|
218
|
+
const client = new FetchBrainClient({ apiKey: process.env.FETCHBRAIN_API_KEY });
|
|
219
|
+
const res = await client.ask("blue widgets under $50", { answer: true });
|
|
101
220
|
|
|
102
|
-
//
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
// Run multiple specific handlers
|
|
106
|
-
FetchBrain.enhance(crawler, { alwaysRun: ["listing", "category"] });
|
|
221
|
+
console.log(res.answer); // synthesized answer
|
|
222
|
+
console.log(res.sources); // scored sources
|
|
107
223
|
```
|
|
108
224
|
|
|
109
|
-
|
|
110
|
-
| ------------------------- | ------------------------------------- |
|
|
111
|
-
| `false` (default) | Auto-skip all handlers when AI knows |
|
|
112
|
-
| `true` | Always run all handlers |
|
|
113
|
-
| `'listing'` | Only run handler with label 'listing' |
|
|
114
|
-
| `['listing', 'category']` | Run handlers with these labels |
|
|
115
|
-
|
|
116
|
-
## AI Context in Handler
|
|
225
|
+
## Brain Context in Handler
|
|
117
226
|
|
|
118
|
-
Access
|
|
227
|
+
Access brain data directly in your handler via `context.brain`:
|
|
119
228
|
|
|
120
229
|
```typescript
|
|
121
230
|
const crawler = FetchBrain.enhance(
|
|
122
231
|
new CheerioCrawler({
|
|
123
|
-
requestHandler: async ({ $, request,
|
|
124
|
-
// Check if
|
|
125
|
-
if (
|
|
126
|
-
console.log("
|
|
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");
|
|
127
236
|
|
|
128
|
-
// Option 1: Use
|
|
129
|
-
await
|
|
237
|
+
// Option 1: Use brain data directly (skip scraping)
|
|
238
|
+
await brain.use();
|
|
130
239
|
return;
|
|
131
240
|
|
|
132
|
-
// Option 2: Compare
|
|
241
|
+
// Option 2: Compare brain data with scraped data
|
|
133
242
|
// const scraped = { title: $('h1').text() };
|
|
134
|
-
// console.log('
|
|
243
|
+
// console.log('Brain:', brain.data, 'Scraped:', scraped);
|
|
135
244
|
}
|
|
136
245
|
|
|
137
|
-
// Scrape normally if
|
|
246
|
+
// Scrape normally if the brain doesn't know
|
|
138
247
|
const data = { title: $("h1").text() };
|
|
139
248
|
await pushData(data);
|
|
140
249
|
},
|
|
@@ -143,15 +252,13 @@ const crawler = FetchBrain.enhance(
|
|
|
143
252
|
);
|
|
144
253
|
```
|
|
145
254
|
|
|
146
|
-
### `context.
|
|
255
|
+
### `context.brain` Properties
|
|
147
256
|
|
|
148
|
-
| Property
|
|
149
|
-
|
|
|
150
|
-
| `known`
|
|
151
|
-
| `data`
|
|
152
|
-
| `
|
|
153
|
-
| `learnedAt` | string | When AI learned this |
|
|
154
|
-
| `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 |
|
|
155
262
|
|
|
156
263
|
## Using Dataset.pushData
|
|
157
264
|
|
|
@@ -182,60 +289,65 @@ const crawler = FetchBrain.enhance(
|
|
|
182
289
|
);
|
|
183
290
|
```
|
|
184
291
|
|
|
185
|
-
##
|
|
186
|
-
|
|
187
|
-
For custom integrations without Crawlee:
|
|
292
|
+
## No Crawlee? No problem
|
|
188
293
|
|
|
189
294
|
```typescript
|
|
190
295
|
import { FetchBrain } from "@fetchbrain.com/sdk";
|
|
191
296
|
|
|
192
|
-
const
|
|
297
|
+
const brain = new FetchBrain({
|
|
193
298
|
apiKey: "your-api-key",
|
|
194
|
-
|
|
299
|
+
memory: "recent",
|
|
195
300
|
});
|
|
196
301
|
|
|
197
|
-
// Check if
|
|
198
|
-
const result = await
|
|
199
|
-
|
|
302
|
+
// Check if the brain knows a URL
|
|
303
|
+
const result = await brain.recall({ url: "https://example.com/product/123" });
|
|
200
304
|
if (result.known) {
|
|
201
|
-
console.log("
|
|
202
|
-
console.log("Confidence:", result.confidence);
|
|
305
|
+
console.log("Brain knows:", result.data);
|
|
203
306
|
} else {
|
|
204
307
|
// Fetch and teach
|
|
205
|
-
const data = await
|
|
206
|
-
await
|
|
308
|
+
const data = await scrapeYourWay("https://example.com/product/123");
|
|
309
|
+
await brain.learn({ url: "https://example.com/product/123", data }); // free
|
|
207
310
|
}
|
|
208
311
|
```
|
|
209
312
|
|
|
210
|
-
##
|
|
211
|
-
|
|
212
|
-
FetchBrain includes a circuit breaker that ensures your scraper continues even if the API is unavailable:
|
|
313
|
+
## It will never break your crawl
|
|
213
314
|
|
|
214
|
-
|
|
215
|
-
- **API slow (>500ms)**: Timeout, continue without AI
|
|
216
|
-
- **API down**: Circuit opens, scraper runs standalone
|
|
217
|
-
- **API recovers**: Circuit closes, AI optimization resumes
|
|
315
|
+
The circuit breaker is not an afterthought — it's the core design contract:
|
|
218
316
|
|
|
219
|
-
|
|
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
|
|
220
321
|
|
|
221
|
-
|
|
322
|
+
A FetchBrain problem can cost you *optimization*, never *data*. Every SDK
|
|
323
|
+
call degrades gracefully; none of them throw into your crawl.
|
|
222
324
|
|
|
223
|
-
|
|
325
|
+
## Telemetry (opt-in)
|
|
224
326
|
|
|
225
|
-
|
|
327
|
+
Telemetry is **off by default.** You can opt in to send anonymized
|
|
328
|
+
operational diagnostics that help improve FetchBrain:
|
|
226
329
|
|
|
227
|
-
```
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
# In your code, use localhost
|
|
232
|
-
const crawler = FetchBrain.enhance(crawler, {
|
|
233
|
-
apiKey: 'test_local_key',
|
|
234
|
-
baseUrl: 'http://localhost:3456',
|
|
330
|
+
```typescript
|
|
331
|
+
FetchBrain.enhance(crawler, {
|
|
332
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
333
|
+
telemetry: { enabled: true },
|
|
235
334
|
});
|
|
236
335
|
```
|
|
237
336
|
|
|
238
|
-
|
|
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:
|
|
239
351
|
|
|
240
352
|
```typescript
|
|
241
353
|
import { MockFetchBrain } from "@fetchbrain.com/sdk/mock";
|
|
@@ -247,40 +359,65 @@ const mock = new MockFetchBrain({
|
|
|
247
359
|
});
|
|
248
360
|
|
|
249
361
|
// Use in tests
|
|
250
|
-
const result = await mock.
|
|
362
|
+
const result = await mock.recall({ url: "https://example.com/product" });
|
|
251
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);
|
|
252
369
|
```
|
|
253
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
|
+
|
|
254
374
|
## Examples
|
|
255
375
|
|
|
256
|
-
|
|
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` |
|
|
257
381
|
|
|
258
382
|
- **basic-cheerio** - CheerioCrawler with FetchBrain
|
|
259
|
-
- **manual-
|
|
383
|
+
- **manual-recall** - Direct API usage without Crawlee
|
|
260
384
|
- **with-mock** - Unit testing with MockFetchBrain
|
|
261
385
|
|
|
262
|
-
##
|
|
263
|
-
|
|
264
|
-
### `FetchBrain.enhance(crawler, config)`
|
|
386
|
+
## FAQ
|
|
265
387
|
|
|
266
|
-
|
|
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.
|
|
267
391
|
|
|
268
|
-
|
|
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.
|
|
269
397
|
|
|
270
|
-
|
|
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).
|
|
271
403
|
|
|
272
|
-
|
|
404
|
+
**What does learning cost?**
|
|
405
|
+
Nothing. Learning is always free — you pay only for known queries.
|
|
273
406
|
|
|
274
|
-
|
|
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.
|
|
275
410
|
|
|
276
|
-
|
|
411
|
+
## Contributing
|
|
277
412
|
|
|
278
|
-
|
|
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**.
|
|
279
416
|
|
|
280
417
|
## License
|
|
281
418
|
|
|
282
|
-
MIT © FetchBrain
|
|
419
|
+
MIT © [FetchBrain](https://fetchbrain.com)
|
|
283
420
|
|
|
284
421
|
---
|
|
285
422
|
|
|
286
|
-
**Need help?** [Open an issue](https://github.com/fetchbrain-com/sdk/issues)
|
|
423
|
+
**Need help?** [Open an issue](https://github.com/fetchbrain-com/sdk/issues) · [Read the docs](https://docs.fetchbrain.com)
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { F as FetchBrainConfig, R as RawRequest,
|
|
2
|
-
export {
|
|
1
|
+
import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-CSX4KGoU.mjs';
|
|
2
|
+
export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as TelemetryRequest, k as TelemetryResponse } from './types-CSX4KGoU.mjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* FetchBrain API Client
|
|
@@ -17,13 +17,13 @@ declare class FetchBrainClient {
|
|
|
17
17
|
private logger;
|
|
18
18
|
constructor(config: FetchBrainConfig);
|
|
19
19
|
/**
|
|
20
|
-
*
|
|
20
|
+
* Recall if FetchBrain "knows" a request
|
|
21
21
|
*/
|
|
22
|
-
|
|
22
|
+
recall(request: RawRequest): Promise<RecallResult>;
|
|
23
23
|
/**
|
|
24
|
-
*
|
|
24
|
+
* Recall multiple requests at once — returns ordered array matching input order
|
|
25
25
|
*/
|
|
26
|
-
|
|
26
|
+
recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
|
|
27
27
|
/**
|
|
28
28
|
* "Teach" FetchBrain new data (batched for high-concurrency)
|
|
29
29
|
*/
|
|
@@ -32,6 +32,13 @@ declare class FetchBrainClient {
|
|
|
32
32
|
* Get usage statistics
|
|
33
33
|
*/
|
|
34
34
|
stats(): Promise<StatsResponse | null>;
|
|
35
|
+
/**
|
|
36
|
+
* Ask a natural-language question against learned knowledge
|
|
37
|
+
*/
|
|
38
|
+
ask(question: string, opts?: {
|
|
39
|
+
answer?: boolean;
|
|
40
|
+
limit?: number;
|
|
41
|
+
}): Promise<AskResponse>;
|
|
35
42
|
/**
|
|
36
43
|
* Execute a batch query against the API
|
|
37
44
|
*/
|
|
@@ -98,17 +105,15 @@ interface RequestContext {
|
|
|
98
105
|
*/
|
|
99
106
|
declare function getCurrentContext(): RequestContext | undefined;
|
|
100
107
|
/**
|
|
101
|
-
*
|
|
108
|
+
* Brain context available in request handler
|
|
102
109
|
*/
|
|
103
110
|
interface FetchBrainContext {
|
|
104
|
-
/** Whether
|
|
111
|
+
/** Whether the brain knows this URL */
|
|
105
112
|
known: boolean;
|
|
106
|
-
/**
|
|
113
|
+
/** Brain data if known */
|
|
107
114
|
data?: Record<string, unknown>;
|
|
108
|
-
/**
|
|
109
|
-
|
|
110
|
-
/** Use AI data and skip scraping (call in handler to early return) */
|
|
111
|
-
useAIData: () => Promise<void>;
|
|
115
|
+
/** Use brain data and skip scraping (call in handler to early return) */
|
|
116
|
+
use: () => Promise<void>;
|
|
112
117
|
}
|
|
113
118
|
/**
|
|
114
119
|
* FetchBrain main class
|
|
@@ -121,15 +126,14 @@ declare class FetchBrain {
|
|
|
121
126
|
private logger;
|
|
122
127
|
constructor(config: FetchBrainConfig);
|
|
123
128
|
/**
|
|
124
|
-
*
|
|
129
|
+
* Recall whether FetchBrain "knows" a URL
|
|
125
130
|
*/
|
|
126
|
-
|
|
131
|
+
recall(options: {
|
|
127
132
|
url: string;
|
|
128
|
-
|
|
133
|
+
memory?: string;
|
|
129
134
|
}): Promise<{
|
|
130
135
|
known: boolean;
|
|
131
136
|
data: Record<string, unknown> | undefined;
|
|
132
|
-
confidence: number | undefined;
|
|
133
137
|
}>;
|
|
134
138
|
/**
|
|
135
139
|
* "Teach" FetchBrain new data
|
|
@@ -146,8 +150,8 @@ declare class FetchBrain {
|
|
|
146
150
|
* Enhance a Crawlee crawler with FetchBrain optimization
|
|
147
151
|
*
|
|
148
152
|
* This wraps the crawler's request handler to:
|
|
149
|
-
* 1.
|
|
150
|
-
* 2. Teach
|
|
153
|
+
* 1. Recall the brain before making requests (brain knows = skip request)
|
|
154
|
+
* 2. Teach the brain after successful requests (learning)
|
|
151
155
|
*
|
|
152
156
|
* @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
|
|
153
157
|
* @param config - FetchBrain configuration
|
|
@@ -241,7 +245,7 @@ declare class CircuitBreaker {
|
|
|
241
245
|
type BatchExecutor = (items: {
|
|
242
246
|
ref: string;
|
|
243
247
|
request: RawRequest;
|
|
244
|
-
}[]) => Promise<Map<string,
|
|
248
|
+
}[]) => Promise<Map<string, RecallResult>>;
|
|
245
249
|
/**
|
|
246
250
|
* Request Batcher
|
|
247
251
|
*
|
|
@@ -259,7 +263,7 @@ declare class RequestBatcher {
|
|
|
259
263
|
/**
|
|
260
264
|
* Add a request to the batch queue
|
|
261
265
|
*/
|
|
262
|
-
query(request: RawRequest): Promise<
|
|
266
|
+
query(request: RawRequest): Promise<RecallResult>;
|
|
263
267
|
/**
|
|
264
268
|
* Flush the current batch
|
|
265
269
|
*/
|
|
@@ -365,4 +369,4 @@ declare class TelemetryBuffer {
|
|
|
365
369
|
stop(): Promise<void>;
|
|
366
370
|
}
|
|
367
371
|
|
|
368
|
-
export {
|
|
372
|
+
export { AskResponse, BatchConfig, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
|