@fetchbrain.com/sdk 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +278 -0
- package/dist/index.d.mts +538 -0
- package/dist/index.d.ts +538 -0
- package/dist/index.js +903 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +891 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +77 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 FetchBrain
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
# @fetchbrain.com/sdk
|
|
2
|
+
|
|
3
|
+
> **The AI That Already Knows The Web** - AI-powered scraping optimization for Crawlee
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@fetchbrain.com/sdk)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
|
|
8
|
+
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.
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- 🚀 **Instant Results** - Skip redundant HTTP requests with pre-trained knowledge
|
|
13
|
+
- 🔄 **Auto-Learning** - AI automatically learns from scraped pages
|
|
14
|
+
- 🛡️ **Graceful Degradation** - Circuit breaker ensures your scraper never fails
|
|
15
|
+
- 📦 **Request Batching** - Optimized for high-concurrency scrapers
|
|
16
|
+
- 🔌 **Crawlee Compatible** - Works with CheerioCrawler, PlaywrightCrawler, and more
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install @fetchbrain.com/sdk
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Quick Start
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
import { FetchBrain } from "@fetchbrain.com/sdk";
|
|
28
|
+
import { CheerioCrawler } from "crawlee";
|
|
29
|
+
|
|
30
|
+
const crawler = FetchBrain.enhance(
|
|
31
|
+
new CheerioCrawler({
|
|
32
|
+
requestHandler: async ({ $, request, pushData }) => {
|
|
33
|
+
// This only runs when AI needs to "learn" (new page)
|
|
34
|
+
const data = {
|
|
35
|
+
title: $("h1").text(),
|
|
36
|
+
price: $(".price").text(),
|
|
37
|
+
};
|
|
38
|
+
await pushData(data);
|
|
39
|
+
},
|
|
40
|
+
}),
|
|
41
|
+
{
|
|
42
|
+
apiKey: process.env.FETCHBRAIN_API_KEY,
|
|
43
|
+
intelligence: "high", // High confidence AI responses
|
|
44
|
+
learning: true, // AI learns from scraped pages
|
|
45
|
+
}
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
await crawler.run(urls);
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## How It Works
|
|
52
|
+
|
|
53
|
+
1. **Before each request**, FetchBrain queries the AI if it "knows" the URL
|
|
54
|
+
2. **AI knows**: Return data instantly from neural inference, skip HTTP request
|
|
55
|
+
3. **AI learning**: Run your scraper normally, then teach the AI
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
Your Scraper → FetchBrain SDK → AI knows? → YES → Return AI knowledge (skip request)
|
|
59
|
+
→ NO → Run scraper → AI learns for next time
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Configuration
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
interface FetchBrainConfig {
|
|
66
|
+
// Required
|
|
67
|
+
apiKey: string;
|
|
68
|
+
|
|
69
|
+
// Optional
|
|
70
|
+
baseUrl?: string; // API URL (default: production)
|
|
71
|
+
intelligence?: IntelligenceLevel; // AI accuracy level
|
|
72
|
+
learning?: boolean; // Enable AI learning (default: true)
|
|
73
|
+
alwaysRun?: boolean | string | string[]; // Which handlers to run (default: false)
|
|
74
|
+
timeout?: number; // Request timeout in ms (default: 500)
|
|
75
|
+
debug?: boolean; // Enable debug logging
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Intelligence Levels
|
|
80
|
+
|
|
81
|
+
| Level | Description |
|
|
82
|
+
| ---------- | ----------------------------------- |
|
|
83
|
+
| `realtime` | Live AI inference, highest accuracy |
|
|
84
|
+
| `high` | High confidence responses |
|
|
85
|
+
| `standard` | Balanced accuracy and speed |
|
|
86
|
+
| `deep` | Deep knowledge, broader coverage |
|
|
87
|
+
|
|
88
|
+
### Always Run Mode
|
|
89
|
+
|
|
90
|
+
Control which handlers run when AI knows the page. Useful for routers with multiple handlers:
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
// Skip all handlers when AI knows (default)
|
|
94
|
+
FetchBrain.enhance(crawler, { alwaysRun: false });
|
|
95
|
+
|
|
96
|
+
// Always run all handlers
|
|
97
|
+
FetchBrain.enhance(crawler, { alwaysRun: true });
|
|
98
|
+
|
|
99
|
+
// Only run 'listing' handler (skip 'detail' when AI knows)
|
|
100
|
+
FetchBrain.enhance(crawler, { alwaysRun: "listing" });
|
|
101
|
+
|
|
102
|
+
// Run multiple specific handlers
|
|
103
|
+
FetchBrain.enhance(crawler, { alwaysRun: ["listing", "category"] });
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Value | Behavior |
|
|
107
|
+
| ------------------------- | ------------------------------------- |
|
|
108
|
+
| `false` (default) | Auto-skip all handlers when AI knows |
|
|
109
|
+
| `true` | Always run all handlers |
|
|
110
|
+
| `'listing'` | Only run handler with label 'listing' |
|
|
111
|
+
| `['listing', 'category']` | Run handlers with these labels |
|
|
112
|
+
|
|
113
|
+
## AI Context in Handler
|
|
114
|
+
|
|
115
|
+
Access AI data directly in your handler via `context.ai`:
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
const crawler = FetchBrain.enhance(
|
|
119
|
+
new CheerioCrawler({
|
|
120
|
+
requestHandler: async ({ $, request, ai, pushData }) => {
|
|
121
|
+
// Check if AI already knows this page
|
|
122
|
+
if (ai?.known && ai.confidence! > 0.9) {
|
|
123
|
+
console.log("AI knows this page with high confidence");
|
|
124
|
+
|
|
125
|
+
// Option 1: Use AI data directly (skip scraping)
|
|
126
|
+
await ai.useAIData();
|
|
127
|
+
return;
|
|
128
|
+
|
|
129
|
+
// Option 2: Compare AI data with scraped data
|
|
130
|
+
// const scraped = { title: $('h1').text() };
|
|
131
|
+
// console.log('AI:', ai.data, 'Scraped:', scraped);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Scrape normally if AI doesn't know
|
|
135
|
+
const data = { title: $("h1").text() };
|
|
136
|
+
await pushData(data);
|
|
137
|
+
},
|
|
138
|
+
}),
|
|
139
|
+
{ apiKey: "your-api-key", alwaysRun: true }
|
|
140
|
+
);
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### `context.ai` Properties
|
|
144
|
+
|
|
145
|
+
| Property | Type | Description |
|
|
146
|
+
| ------------- | -------- | ------------------------------ |
|
|
147
|
+
| `known` | boolean | Whether AI knows this URL |
|
|
148
|
+
| `data` | object | AI data (if known) |
|
|
149
|
+
| `confidence` | number | Confidence score 0-1 |
|
|
150
|
+
| `learnedAt` | string | When AI learned this |
|
|
151
|
+
| `useAIData()` | function | Push AI data and skip scraping |
|
|
152
|
+
|
|
153
|
+
## Using Dataset.pushData
|
|
154
|
+
|
|
155
|
+
If you use `Dataset.pushData()` instead of `context.pushData()`, use our wrapper for automatic AI learning:
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import { FetchBrain, pushData } from "@fetchbrain.com/sdk";
|
|
159
|
+
import { Dataset } from "crawlee";
|
|
160
|
+
|
|
161
|
+
const crawler = FetchBrain.enhance(
|
|
162
|
+
new CheerioCrawler({
|
|
163
|
+
requestHandler: async ({ $, request }) => {
|
|
164
|
+
const data = { title: $("h1").text() };
|
|
165
|
+
|
|
166
|
+
// Use pushData wrapper for AI learning
|
|
167
|
+
await pushData(data, Dataset);
|
|
168
|
+
|
|
169
|
+
// Or with named dataset
|
|
170
|
+
await pushData(data, Dataset, "products");
|
|
171
|
+
},
|
|
172
|
+
}),
|
|
173
|
+
{ apiKey: "your-api-key" }
|
|
174
|
+
);
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Manual API
|
|
178
|
+
|
|
179
|
+
For custom integrations without Crawlee:
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
import { FetchBrain } from "@fetchbrain.com/sdk";
|
|
183
|
+
|
|
184
|
+
const ai = new FetchBrain({
|
|
185
|
+
apiKey: "your-api-key",
|
|
186
|
+
intelligence: "high",
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
// Check if AI knows a URL
|
|
190
|
+
const result = await ai.query({ url: "https://example.com/product/123" });
|
|
191
|
+
|
|
192
|
+
if (result.known) {
|
|
193
|
+
console.log("AI knows:", result.data);
|
|
194
|
+
console.log("Confidence:", result.confidence);
|
|
195
|
+
} else {
|
|
196
|
+
// Fetch and teach
|
|
197
|
+
const data = await scrapeUrl("https://example.com/product/123");
|
|
198
|
+
await ai.learn({ url: "https://example.com/product/123", data });
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## Graceful Degradation
|
|
203
|
+
|
|
204
|
+
FetchBrain includes a circuit breaker that ensures your scraper continues even if the API is unavailable:
|
|
205
|
+
|
|
206
|
+
- **API healthy**: Normal operation with AI optimization
|
|
207
|
+
- **API slow (>500ms)**: Timeout, continue without AI
|
|
208
|
+
- **API down**: Circuit opens, scraper runs standalone
|
|
209
|
+
- **API recovers**: Circuit closes, AI optimization resumes
|
|
210
|
+
|
|
211
|
+
Your scraper will **never fail** due to FetchBrain issues.
|
|
212
|
+
|
|
213
|
+
## Local Development
|
|
214
|
+
|
|
215
|
+
### Mock Server
|
|
216
|
+
|
|
217
|
+
For local testing without the production API:
|
|
218
|
+
|
|
219
|
+
```bash
|
|
220
|
+
# Start mock server
|
|
221
|
+
npm run mock-server
|
|
222
|
+
|
|
223
|
+
# In your code, use localhost
|
|
224
|
+
const crawler = FetchBrain.enhance(crawler, {
|
|
225
|
+
apiKey: 'test_local_key',
|
|
226
|
+
baseUrl: 'http://localhost:3456',
|
|
227
|
+
});
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
### Mock Client for Testing
|
|
231
|
+
|
|
232
|
+
```typescript
|
|
233
|
+
import { MockFetchBrain } from "@fetchbrain.com/sdk/mock";
|
|
234
|
+
|
|
235
|
+
const mock = new MockFetchBrain({
|
|
236
|
+
initialKnowledge: new Map([
|
|
237
|
+
["https://example.com/product", { title: "Known Product" }],
|
|
238
|
+
]),
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
// Use in tests
|
|
242
|
+
const result = await mock.query("https://example.com/product");
|
|
243
|
+
expect(result.known).toBe(true);
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
## Examples
|
|
247
|
+
|
|
248
|
+
See the [examples](./examples) directory:
|
|
249
|
+
|
|
250
|
+
- **basic-cheerio** - CheerioCrawler with FetchBrain
|
|
251
|
+
- **manual-query** - Direct API usage without Crawlee
|
|
252
|
+
- **with-mock** - Unit testing with MockFetchBrain
|
|
253
|
+
|
|
254
|
+
## API Reference
|
|
255
|
+
|
|
256
|
+
### `FetchBrain.enhance(crawler, config)`
|
|
257
|
+
|
|
258
|
+
Wraps a Crawlee crawler with FetchBrain optimization.
|
|
259
|
+
|
|
260
|
+
### `FetchBrain.query({ url, intelligence? })`
|
|
261
|
+
|
|
262
|
+
Check if FetchBrain knows a URL.
|
|
263
|
+
|
|
264
|
+
### `FetchBrain.learn({ url, data })`
|
|
265
|
+
|
|
266
|
+
Teach FetchBrain new data.
|
|
267
|
+
|
|
268
|
+
### `FetchBrain.stats()`
|
|
269
|
+
|
|
270
|
+
Get usage statistics.
|
|
271
|
+
|
|
272
|
+
## License
|
|
273
|
+
|
|
274
|
+
MIT © FetchBrain
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
**Need help?** [Open an issue](https://github.com/fetchbrain-com/fetchbrain-sdk/issues) or check our [documentation](https://docs.fetchbrain.com).
|