@fetchbrain.com/sdk 0.2.0 → 0.3.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 +300 -120
- package/dist/index.d.mts +32 -22
- package/dist/index.d.ts +32 -22
- package/dist/index.js +138 -64
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +139 -64
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +20 -7
- package/dist/mock/index.d.ts +20 -7
- package/dist/mock/index.js +40 -15
- package/dist/mock/index.js.map +1 -1
- package/dist/mock/index.mjs +40 -15
- package/dist/mock/index.mjs.map +1 -1
- package/dist/{types-Ddu_K1Nn.d.mts → types-BOfLGSkb.d.mts} +44 -31
- package/dist/{types-Ddu_K1Nn.d.ts → types-BOfLGSkb.d.ts} +44 -31
- package/package.json +2 -2
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-BOfLGSkb.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-BOfLGSkb.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,19 @@ 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
|
+
* `model` picks the generation model for answer mode from the server's
|
|
39
|
+
* menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
|
|
40
|
+
* credits), or "byok" to answer with your own linked provider model.
|
|
41
|
+
* Omit it for the default model.
|
|
42
|
+
*/
|
|
43
|
+
ask(question: string, opts?: {
|
|
44
|
+
answer?: boolean;
|
|
45
|
+
limit?: number;
|
|
46
|
+
model?: string;
|
|
47
|
+
}): Promise<AskResponse>;
|
|
35
48
|
/**
|
|
36
49
|
* Execute a batch query against the API
|
|
37
50
|
*/
|
|
@@ -98,17 +111,15 @@ interface RequestContext {
|
|
|
98
111
|
*/
|
|
99
112
|
declare function getCurrentContext(): RequestContext | undefined;
|
|
100
113
|
/**
|
|
101
|
-
*
|
|
114
|
+
* Brain context available in request handler
|
|
102
115
|
*/
|
|
103
116
|
interface FetchBrainContext {
|
|
104
|
-
/** Whether
|
|
117
|
+
/** Whether the brain knows this URL */
|
|
105
118
|
known: boolean;
|
|
106
|
-
/**
|
|
119
|
+
/** Brain data if known */
|
|
107
120
|
data?: Record<string, unknown>;
|
|
108
|
-
/**
|
|
109
|
-
|
|
110
|
-
/** Use AI data and skip scraping (call in handler to early return) */
|
|
111
|
-
useAIData: () => Promise<void>;
|
|
121
|
+
/** Use brain data and skip scraping (call in handler to early return) */
|
|
122
|
+
use: () => Promise<void>;
|
|
112
123
|
}
|
|
113
124
|
/**
|
|
114
125
|
* FetchBrain main class
|
|
@@ -121,15 +132,14 @@ declare class FetchBrain {
|
|
|
121
132
|
private logger;
|
|
122
133
|
constructor(config: FetchBrainConfig);
|
|
123
134
|
/**
|
|
124
|
-
*
|
|
135
|
+
* Recall whether FetchBrain "knows" a URL
|
|
125
136
|
*/
|
|
126
|
-
|
|
137
|
+
recall(options: {
|
|
127
138
|
url: string;
|
|
128
|
-
|
|
139
|
+
memory?: string;
|
|
129
140
|
}): Promise<{
|
|
130
141
|
known: boolean;
|
|
131
142
|
data: Record<string, unknown> | undefined;
|
|
132
|
-
confidence: number | undefined;
|
|
133
143
|
}>;
|
|
134
144
|
/**
|
|
135
145
|
* "Teach" FetchBrain new data
|
|
@@ -146,8 +156,8 @@ declare class FetchBrain {
|
|
|
146
156
|
* Enhance a Crawlee crawler with FetchBrain optimization
|
|
147
157
|
*
|
|
148
158
|
* This wraps the crawler's request handler to:
|
|
149
|
-
* 1.
|
|
150
|
-
* 2. Teach
|
|
159
|
+
* 1. Recall the brain before making requests (brain knows = skip request)
|
|
160
|
+
* 2. Teach the brain after successful requests (learning)
|
|
151
161
|
*
|
|
152
162
|
* @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
|
|
153
163
|
* @param config - FetchBrain configuration
|
|
@@ -241,7 +251,7 @@ declare class CircuitBreaker {
|
|
|
241
251
|
type BatchExecutor = (items: {
|
|
242
252
|
ref: string;
|
|
243
253
|
request: RawRequest;
|
|
244
|
-
}[]) => Promise<Map<string,
|
|
254
|
+
}[]) => Promise<Map<string, RecallResult>>;
|
|
245
255
|
/**
|
|
246
256
|
* Request Batcher
|
|
247
257
|
*
|
|
@@ -259,7 +269,7 @@ declare class RequestBatcher {
|
|
|
259
269
|
/**
|
|
260
270
|
* Add a request to the batch queue
|
|
261
271
|
*/
|
|
262
|
-
query(request: RawRequest): Promise<
|
|
272
|
+
query(request: RawRequest): Promise<RecallResult>;
|
|
263
273
|
/**
|
|
264
274
|
* Flush the current batch
|
|
265
275
|
*/
|
|
@@ -365,4 +375,4 @@ declare class TelemetryBuffer {
|
|
|
365
375
|
stop(): Promise<void>;
|
|
366
376
|
}
|
|
367
377
|
|
|
368
|
-
export {
|
|
378
|
+
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 };
|
package/dist/index.d.ts
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-BOfLGSkb.js';
|
|
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-BOfLGSkb.js';
|
|
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,19 @@ 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
|
+
* `model` picks the generation model for answer mode from the server's
|
|
39
|
+
* menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
|
|
40
|
+
* credits), or "byok" to answer with your own linked provider model.
|
|
41
|
+
* Omit it for the default model.
|
|
42
|
+
*/
|
|
43
|
+
ask(question: string, opts?: {
|
|
44
|
+
answer?: boolean;
|
|
45
|
+
limit?: number;
|
|
46
|
+
model?: string;
|
|
47
|
+
}): Promise<AskResponse>;
|
|
35
48
|
/**
|
|
36
49
|
* Execute a batch query against the API
|
|
37
50
|
*/
|
|
@@ -98,17 +111,15 @@ interface RequestContext {
|
|
|
98
111
|
*/
|
|
99
112
|
declare function getCurrentContext(): RequestContext | undefined;
|
|
100
113
|
/**
|
|
101
|
-
*
|
|
114
|
+
* Brain context available in request handler
|
|
102
115
|
*/
|
|
103
116
|
interface FetchBrainContext {
|
|
104
|
-
/** Whether
|
|
117
|
+
/** Whether the brain knows this URL */
|
|
105
118
|
known: boolean;
|
|
106
|
-
/**
|
|
119
|
+
/** Brain data if known */
|
|
107
120
|
data?: Record<string, unknown>;
|
|
108
|
-
/**
|
|
109
|
-
|
|
110
|
-
/** Use AI data and skip scraping (call in handler to early return) */
|
|
111
|
-
useAIData: () => Promise<void>;
|
|
121
|
+
/** Use brain data and skip scraping (call in handler to early return) */
|
|
122
|
+
use: () => Promise<void>;
|
|
112
123
|
}
|
|
113
124
|
/**
|
|
114
125
|
* FetchBrain main class
|
|
@@ -121,15 +132,14 @@ declare class FetchBrain {
|
|
|
121
132
|
private logger;
|
|
122
133
|
constructor(config: FetchBrainConfig);
|
|
123
134
|
/**
|
|
124
|
-
*
|
|
135
|
+
* Recall whether FetchBrain "knows" a URL
|
|
125
136
|
*/
|
|
126
|
-
|
|
137
|
+
recall(options: {
|
|
127
138
|
url: string;
|
|
128
|
-
|
|
139
|
+
memory?: string;
|
|
129
140
|
}): Promise<{
|
|
130
141
|
known: boolean;
|
|
131
142
|
data: Record<string, unknown> | undefined;
|
|
132
|
-
confidence: number | undefined;
|
|
133
143
|
}>;
|
|
134
144
|
/**
|
|
135
145
|
* "Teach" FetchBrain new data
|
|
@@ -146,8 +156,8 @@ declare class FetchBrain {
|
|
|
146
156
|
* Enhance a Crawlee crawler with FetchBrain optimization
|
|
147
157
|
*
|
|
148
158
|
* This wraps the crawler's request handler to:
|
|
149
|
-
* 1.
|
|
150
|
-
* 2. Teach
|
|
159
|
+
* 1. Recall the brain before making requests (brain knows = skip request)
|
|
160
|
+
* 2. Teach the brain after successful requests (learning)
|
|
151
161
|
*
|
|
152
162
|
* @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
|
|
153
163
|
* @param config - FetchBrain configuration
|
|
@@ -241,7 +251,7 @@ declare class CircuitBreaker {
|
|
|
241
251
|
type BatchExecutor = (items: {
|
|
242
252
|
ref: string;
|
|
243
253
|
request: RawRequest;
|
|
244
|
-
}[]) => Promise<Map<string,
|
|
254
|
+
}[]) => Promise<Map<string, RecallResult>>;
|
|
245
255
|
/**
|
|
246
256
|
* Request Batcher
|
|
247
257
|
*
|
|
@@ -259,7 +269,7 @@ declare class RequestBatcher {
|
|
|
259
269
|
/**
|
|
260
270
|
* Add a request to the batch queue
|
|
261
271
|
*/
|
|
262
|
-
query(request: RawRequest): Promise<
|
|
272
|
+
query(request: RawRequest): Promise<RecallResult>;
|
|
263
273
|
/**
|
|
264
274
|
* Flush the current batch
|
|
265
275
|
*/
|
|
@@ -365,4 +375,4 @@ declare class TelemetryBuffer {
|
|
|
365
375
|
stop(): Promise<void>;
|
|
366
376
|
}
|
|
367
377
|
|
|
368
|
-
export {
|
|
378
|
+
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 };
|
package/dist/index.js
CHANGED
|
@@ -317,10 +317,44 @@ function createLogger(minLevel = "info", enabled = true) {
|
|
|
317
317
|
};
|
|
318
318
|
}
|
|
319
319
|
|
|
320
|
+
// src/native-context.ts
|
|
321
|
+
var ALLOWED_NAME = /_ID$|^(NODE_ENV|REGION|CI)$/;
|
|
322
|
+
var DENYLIST = /TOKEN|SECRET|PASSWORD|CREDENTIAL|KEY|AUTH|COOKIE/i;
|
|
323
|
+
var CREDENTIAL_VALUE = /^[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$|\/\/[^/\s@]+:[^/\s@]+@/;
|
|
324
|
+
var MAX_VALUE_LENGTH = 256;
|
|
325
|
+
var MAX_HEADER_LENGTH = 2048;
|
|
326
|
+
function buildNativeContext(env = process.env) {
|
|
327
|
+
const context = {};
|
|
328
|
+
const names = Object.keys(env).filter((name) => ALLOWED_NAME.test(name) && !DENYLIST.test(name)).sort();
|
|
329
|
+
for (const name of names) {
|
|
330
|
+
const value = env[name];
|
|
331
|
+
if (!value || value.length > MAX_VALUE_LENGTH) continue;
|
|
332
|
+
if (CREDENTIAL_VALUE.test(value)) continue;
|
|
333
|
+
const candidate = { ...context, [name]: value };
|
|
334
|
+
if (JSON.stringify(candidate).length > MAX_HEADER_LENGTH) break;
|
|
335
|
+
context[name] = value;
|
|
336
|
+
}
|
|
337
|
+
if (Object.keys(context).length === 0) return void 0;
|
|
338
|
+
return JSON.stringify(context);
|
|
339
|
+
}
|
|
340
|
+
function getPlatformBuildId(env = process.env) {
|
|
341
|
+
const key = Object.keys(env).find((name) => name.endsWith("BUILD_ID"));
|
|
342
|
+
return key ? env[key] || void 0 : void 0;
|
|
343
|
+
}
|
|
344
|
+
|
|
320
345
|
// src/client.ts
|
|
321
346
|
var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
|
|
322
347
|
var DEFAULT_TIMEOUT = 500;
|
|
323
348
|
var DEFAULT_LEARN_TIMEOUT = 5e3;
|
|
349
|
+
var ASK_TIMEOUT = 1e4;
|
|
350
|
+
var ApiError = class extends Error {
|
|
351
|
+
constructor(status, statusText, serverError) {
|
|
352
|
+
super(`API error: ${status} ${statusText}`);
|
|
353
|
+
this.status = status;
|
|
354
|
+
this.serverError = serverError;
|
|
355
|
+
this.name = "ApiError";
|
|
356
|
+
}
|
|
357
|
+
};
|
|
324
358
|
var currentContext = {};
|
|
325
359
|
function setScrapeContext(ctx) {
|
|
326
360
|
currentContext = ctx;
|
|
@@ -333,7 +367,7 @@ var FetchBrainClient = class {
|
|
|
333
367
|
this.config = {
|
|
334
368
|
apiKey: config.apiKey,
|
|
335
369
|
baseUrl: config.baseUrl || DEFAULT_BASE_URL,
|
|
336
|
-
|
|
370
|
+
memory: config.memory || "recent",
|
|
337
371
|
learning: config.learning ?? true,
|
|
338
372
|
alwaysRun: config.alwaysRun ?? false,
|
|
339
373
|
refreshOnRebuild: config.refreshOnRebuild ?? false,
|
|
@@ -341,7 +375,8 @@ var FetchBrainClient = class {
|
|
|
341
375
|
debug: config.debug || false,
|
|
342
376
|
extractForLearning: config.extractForLearning,
|
|
343
377
|
learnUrlField: config.learnUrlField,
|
|
344
|
-
telemetry: config.telemetry ?? { enabled:
|
|
378
|
+
telemetry: config.telemetry ?? { enabled: false },
|
|
379
|
+
// opt-in
|
|
345
380
|
batch: config.batch,
|
|
346
381
|
circuitBreaker: config.circuitBreaker
|
|
347
382
|
};
|
|
@@ -362,23 +397,23 @@ var FetchBrainClient = class {
|
|
|
362
397
|
);
|
|
363
398
|
}
|
|
364
399
|
/**
|
|
365
|
-
*
|
|
400
|
+
* Recall if FetchBrain "knows" a request
|
|
366
401
|
*/
|
|
367
|
-
async
|
|
402
|
+
async recall(request) {
|
|
368
403
|
if (this.circuitBreaker.isOpen()) {
|
|
369
404
|
return { known: false, fallback: true };
|
|
370
405
|
}
|
|
371
406
|
try {
|
|
372
407
|
return await this.batcher.query(request);
|
|
373
408
|
} catch (error) {
|
|
374
|
-
this.logger.debug("
|
|
409
|
+
this.logger.debug("Recall failed:", error);
|
|
375
410
|
return { known: false, fallback: true };
|
|
376
411
|
}
|
|
377
412
|
}
|
|
378
413
|
/**
|
|
379
|
-
*
|
|
414
|
+
* Recall multiple requests at once — returns ordered array matching input order
|
|
380
415
|
*/
|
|
381
|
-
async
|
|
416
|
+
async recallBulk(requests) {
|
|
382
417
|
if (this.circuitBreaker.isOpen()) {
|
|
383
418
|
return requests.map(() => ({ known: false, fallback: true }));
|
|
384
419
|
}
|
|
@@ -426,6 +461,53 @@ var FetchBrainClient = class {
|
|
|
426
461
|
return null;
|
|
427
462
|
}
|
|
428
463
|
}
|
|
464
|
+
/**
|
|
465
|
+
* Ask a natural-language question against learned knowledge
|
|
466
|
+
*
|
|
467
|
+
* `model` picks the generation model for answer mode from the server's
|
|
468
|
+
* menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
|
|
469
|
+
* credits), or "byok" to answer with your own linked provider model.
|
|
470
|
+
* Omit it for the default model.
|
|
471
|
+
*/
|
|
472
|
+
async ask(question, opts) {
|
|
473
|
+
if (this.circuitBreaker.isOpen()) {
|
|
474
|
+
return { sources: [], status: "unavailable" };
|
|
475
|
+
}
|
|
476
|
+
const askBody = {
|
|
477
|
+
query: question,
|
|
478
|
+
answer: opts?.answer,
|
|
479
|
+
limit: opts?.limit,
|
|
480
|
+
model: opts?.model
|
|
481
|
+
};
|
|
482
|
+
const platformBuildId = getPlatformBuildId();
|
|
483
|
+
if (this.config.refreshOnRebuild && platformBuildId) {
|
|
484
|
+
askBody.build = platformBuildId;
|
|
485
|
+
}
|
|
486
|
+
try {
|
|
487
|
+
const response = await this.makeRequest(
|
|
488
|
+
"/v1/ask",
|
|
489
|
+
{
|
|
490
|
+
method: "POST",
|
|
491
|
+
body: JSON.stringify(askBody)
|
|
492
|
+
},
|
|
493
|
+
ASK_TIMEOUT
|
|
494
|
+
);
|
|
495
|
+
this.circuitBreaker.recordSuccess();
|
|
496
|
+
return response;
|
|
497
|
+
} catch (error) {
|
|
498
|
+
if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
|
|
499
|
+
this.logger.debug("Ask rejected:", error);
|
|
500
|
+
return {
|
|
501
|
+
sources: [],
|
|
502
|
+
status: "rejected",
|
|
503
|
+
error: error.serverError ?? error.message
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
this.circuitBreaker.recordFailure();
|
|
507
|
+
this.logger.debug("Ask request failed:", error);
|
|
508
|
+
return { sources: [], status: "unavailable" };
|
|
509
|
+
}
|
|
510
|
+
}
|
|
429
511
|
/**
|
|
430
512
|
* Execute a batch query against the API
|
|
431
513
|
*/
|
|
@@ -433,19 +515,20 @@ var FetchBrainClient = class {
|
|
|
433
515
|
const results = /* @__PURE__ */ new Map();
|
|
434
516
|
const request = {
|
|
435
517
|
items,
|
|
436
|
-
|
|
518
|
+
memory: this.config.memory
|
|
437
519
|
};
|
|
438
|
-
|
|
439
|
-
|
|
520
|
+
const platformBuildId = getPlatformBuildId();
|
|
521
|
+
if (this.config.refreshOnRebuild && platformBuildId) {
|
|
522
|
+
request.build = platformBuildId;
|
|
440
523
|
}
|
|
441
524
|
try {
|
|
442
|
-
const response = await this.makeRequest("/v1/
|
|
525
|
+
const response = await this.makeRequest("/v1/recall", {
|
|
443
526
|
method: "POST",
|
|
444
527
|
body: JSON.stringify(request)
|
|
445
528
|
});
|
|
446
529
|
this.circuitBreaker.recordSuccess();
|
|
447
530
|
for (const item of response.known) {
|
|
448
|
-
results.set(item.ref, { known: true, data: item.data
|
|
531
|
+
results.set(item.ref, { known: true, data: item.data });
|
|
449
532
|
}
|
|
450
533
|
for (const ref of response.unknown) {
|
|
451
534
|
results.set(ref, { known: false });
|
|
@@ -464,12 +547,17 @@ var FetchBrainClient = class {
|
|
|
464
547
|
request: e.request,
|
|
465
548
|
data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
|
|
466
549
|
}));
|
|
550
|
+
const request = { entries: processed };
|
|
551
|
+
const platformBuildId = getPlatformBuildId();
|
|
552
|
+
if (this.config.refreshOnRebuild && platformBuildId) {
|
|
553
|
+
request.build = platformBuildId;
|
|
554
|
+
}
|
|
467
555
|
try {
|
|
468
556
|
const response = await this.makeRequest(
|
|
469
557
|
"/v1/learn",
|
|
470
558
|
{
|
|
471
559
|
method: "POST",
|
|
472
|
-
body: JSON.stringify(
|
|
560
|
+
body: JSON.stringify(request)
|
|
473
561
|
},
|
|
474
562
|
DEFAULT_LEARN_TIMEOUT
|
|
475
563
|
);
|
|
@@ -498,14 +586,9 @@ var FetchBrainClient = class {
|
|
|
498
586
|
if (process.env.NODE_ENV) {
|
|
499
587
|
contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
|
|
500
588
|
}
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
if (process.env.APIFY_ACTOR_BUILD_ID) {
|
|
505
|
-
contextHeaders["X-FB-Build"] = process.env.APIFY_ACTOR_BUILD_ID;
|
|
506
|
-
}
|
|
507
|
-
if (process.env.APIFY_ACTOR_RUN_ID) {
|
|
508
|
-
contextHeaders["X-FB-Apify-Run"] = process.env.APIFY_ACTOR_RUN_ID;
|
|
589
|
+
const nativeContext = buildNativeContext();
|
|
590
|
+
if (nativeContext) {
|
|
591
|
+
contextHeaders["X-FB-Context"] = nativeContext;
|
|
509
592
|
}
|
|
510
593
|
if (currentContext.crawler) {
|
|
511
594
|
contextHeaders["X-FB-Crawler"] = currentContext.crawler;
|
|
@@ -525,7 +608,13 @@ var FetchBrainClient = class {
|
|
|
525
608
|
signal: controller.signal
|
|
526
609
|
});
|
|
527
610
|
if (!response.ok) {
|
|
528
|
-
|
|
611
|
+
let serverError;
|
|
612
|
+
try {
|
|
613
|
+
const errBody = await response.json();
|
|
614
|
+
if (typeof errBody.error === "string") serverError = errBody.error;
|
|
615
|
+
} catch {
|
|
616
|
+
}
|
|
617
|
+
throw new ApiError(response.status, response.statusText, serverError);
|
|
529
618
|
}
|
|
530
619
|
return await response.json();
|
|
531
620
|
} finally {
|
|
@@ -738,7 +827,7 @@ var TelemetryBuffer = class {
|
|
|
738
827
|
|
|
739
828
|
// src/enhance.ts
|
|
740
829
|
var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
|
|
741
|
-
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["
|
|
830
|
+
var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
|
|
742
831
|
function buildRawRequest(request) {
|
|
743
832
|
const r = request;
|
|
744
833
|
let headers;
|
|
@@ -764,7 +853,7 @@ function warnDefaultUniqueKey(request, logger, warned) {
|
|
|
764
853
|
const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
|
|
765
854
|
if (method !== "GET" && isDefault && !warned.has(request.url)) {
|
|
766
855
|
warned.add(request.url);
|
|
767
|
-
logger.warn(`FetchBrain: ${method} ${request.url} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't
|
|
856
|
+
logger.warn(`FetchBrain: ${method} ${request.url} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't get their own memory.`);
|
|
768
857
|
}
|
|
769
858
|
}
|
|
770
859
|
var asyncContext = new async_hooks.AsyncLocalStorage();
|
|
@@ -788,14 +877,13 @@ var FetchBrain = class {
|
|
|
788
877
|
this.logger = createLogger(config.debug ? "debug" : "info", true);
|
|
789
878
|
}
|
|
790
879
|
/**
|
|
791
|
-
*
|
|
880
|
+
* Recall whether FetchBrain "knows" a URL
|
|
792
881
|
*/
|
|
793
|
-
async
|
|
794
|
-
const result = await this.client.
|
|
882
|
+
async recall(options) {
|
|
883
|
+
const result = await this.client.recall({ url: options.url });
|
|
795
884
|
return {
|
|
796
885
|
known: result.known,
|
|
797
|
-
data: result.data
|
|
798
|
-
confidence: result.confidence
|
|
886
|
+
data: result.data
|
|
799
887
|
};
|
|
800
888
|
}
|
|
801
889
|
/**
|
|
@@ -814,8 +902,8 @@ var FetchBrain = class {
|
|
|
814
902
|
* Enhance a Crawlee crawler with FetchBrain optimization
|
|
815
903
|
*
|
|
816
904
|
* This wraps the crawler's request handler to:
|
|
817
|
-
* 1.
|
|
818
|
-
* 2. Teach
|
|
905
|
+
* 1. Recall the brain before making requests (brain knows = skip request)
|
|
906
|
+
* 2. Teach the brain after successful requests (learning)
|
|
819
907
|
*
|
|
820
908
|
* @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
|
|
821
909
|
* @param config - FetchBrain configuration
|
|
@@ -824,11 +912,12 @@ var FetchBrain = class {
|
|
|
824
912
|
static enhance(crawler, config) {
|
|
825
913
|
const client = new FetchBrainClient(config);
|
|
826
914
|
const logger = createLogger(config.debug ? "debug" : "info", true);
|
|
915
|
+
const telemetryConfig = config.telemetry ?? { enabled: false };
|
|
827
916
|
const telemetryBuffer = new TelemetryBuffer({
|
|
828
917
|
maxSize: 50,
|
|
829
918
|
flushInterval: 3e4,
|
|
830
919
|
onFlush: async (entries) => {
|
|
831
|
-
if (
|
|
920
|
+
if (telemetryConfig.enabled) {
|
|
832
921
|
await client.sendTelemetry(entries);
|
|
833
922
|
logger.debug(`Telemetry: sent ${entries.length} entries`);
|
|
834
923
|
}
|
|
@@ -836,9 +925,9 @@ var FetchBrain = class {
|
|
|
836
925
|
});
|
|
837
926
|
const runStats = {
|
|
838
927
|
totalRequests: 0,
|
|
839
|
-
|
|
928
|
+
recalled: 0,
|
|
840
929
|
aiSkipped: 0,
|
|
841
|
-
//
|
|
930
|
+
// brain knew + skipped scraping
|
|
842
931
|
learned: 0,
|
|
843
932
|
scraped: 0,
|
|
844
933
|
// Actually ran handler
|
|
@@ -865,36 +954,31 @@ var FetchBrain = class {
|
|
|
865
954
|
const rawRequest = buildRawRequest(request);
|
|
866
955
|
warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
|
|
867
956
|
try {
|
|
868
|
-
const aiResult = await client.
|
|
957
|
+
const aiResult = await client.recall(rawRequest);
|
|
869
958
|
let usedAIData = false;
|
|
870
959
|
const originalPushData = context.pushData;
|
|
871
|
-
context.
|
|
960
|
+
context.brain = {
|
|
872
961
|
known: aiResult.known,
|
|
873
962
|
data: aiResult.data,
|
|
874
|
-
|
|
875
|
-
useAIData: async () => {
|
|
963
|
+
use: async () => {
|
|
876
964
|
if (aiResult.known && aiResult.data && originalPushData) {
|
|
877
965
|
usedAIData = true;
|
|
878
966
|
await originalPushData.call(context, aiResult.data);
|
|
879
|
-
logger.info(
|
|
880
|
-
`Used AI data: ${url} (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
|
|
881
|
-
);
|
|
967
|
+
logger.info(`Used brain data: ${url}`);
|
|
882
968
|
}
|
|
883
969
|
}
|
|
884
970
|
};
|
|
885
971
|
request.userData = {
|
|
886
972
|
...request.userData,
|
|
887
|
-
|
|
973
|
+
fetchBrainRecalled: aiResult.known,
|
|
888
974
|
fetchBrainData: aiResult.data
|
|
889
975
|
};
|
|
890
976
|
const handlerLabel = request.label;
|
|
891
977
|
const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
|
|
892
978
|
if (aiResult.known && aiResult.data && !runHandler) {
|
|
893
|
-
runStats.
|
|
979
|
+
runStats.recalled++;
|
|
894
980
|
runStats.aiSkipped++;
|
|
895
|
-
logger.info(
|
|
896
|
-
`AI known: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
|
|
897
|
-
);
|
|
981
|
+
logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
|
|
898
982
|
if (originalPushData) {
|
|
899
983
|
await originalPushData.call(context, aiResult.data);
|
|
900
984
|
}
|
|
@@ -902,9 +986,9 @@ var FetchBrain = class {
|
|
|
902
986
|
}
|
|
903
987
|
runStats.scraped++;
|
|
904
988
|
if (aiResult.known) {
|
|
905
|
-
runStats.
|
|
989
|
+
runStats.recalled++;
|
|
906
990
|
logger.info(
|
|
907
|
-
`Running handler [${handlerLabel || "default"}] with
|
|
991
|
+
`Running handler [${handlerLabel || "default"}] with recalled data available: ${url}`
|
|
908
992
|
);
|
|
909
993
|
} else {
|
|
910
994
|
logger.debug(`Learning: ${url}`);
|
|
@@ -928,7 +1012,7 @@ var FetchBrain = class {
|
|
|
928
1012
|
await asyncContext.run(requestContext, async () => {
|
|
929
1013
|
await originalHandler.call(crawler, context);
|
|
930
1014
|
});
|
|
931
|
-
if (
|
|
1015
|
+
if (telemetryConfig.enabled) {
|
|
932
1016
|
try {
|
|
933
1017
|
const telemetry = await collectTelemetry(
|
|
934
1018
|
{
|
|
@@ -960,7 +1044,7 @@ var FetchBrain = class {
|
|
|
960
1044
|
responseTime: Date.now() - startTime,
|
|
961
1045
|
contentSize: context.response?.body?.length
|
|
962
1046
|
},
|
|
963
|
-
|
|
1047
|
+
telemetryConfig
|
|
964
1048
|
);
|
|
965
1049
|
if (telemetry) {
|
|
966
1050
|
telemetryBuffer.add(telemetry);
|
|
@@ -970,7 +1054,7 @@ var FetchBrain = class {
|
|
|
970
1054
|
}
|
|
971
1055
|
}
|
|
972
1056
|
} catch (err) {
|
|
973
|
-
if (
|
|
1057
|
+
if (telemetryConfig.enabled) {
|
|
974
1058
|
try {
|
|
975
1059
|
const telemetry = await collectTelemetry(
|
|
976
1060
|
{
|
|
@@ -988,7 +1072,7 @@ var FetchBrain = class {
|
|
|
988
1072
|
endTime: Date.now(),
|
|
989
1073
|
responseTime: Date.now() - startTime
|
|
990
1074
|
},
|
|
991
|
-
|
|
1075
|
+
telemetryConfig,
|
|
992
1076
|
err instanceof Error ? err : new Error(String(err))
|
|
993
1077
|
);
|
|
994
1078
|
if (telemetry) {
|
|
@@ -1019,7 +1103,7 @@ var FetchBrain = class {
|
|
|
1019
1103
|
} finally {
|
|
1020
1104
|
logger.debug("Flushing pending learn requests on crawl complete");
|
|
1021
1105
|
await client.flushLearnBatch();
|
|
1022
|
-
if (
|
|
1106
|
+
if (telemetryConfig.enabled) {
|
|
1023
1107
|
logger.debug("Telemetry: flushing on crawl complete");
|
|
1024
1108
|
await telemetryBuffer.stop();
|
|
1025
1109
|
}
|
|
@@ -1028,7 +1112,7 @@ var FetchBrain = class {
|
|
|
1028
1112
|
);
|
|
1029
1113
|
const savingsPercent = runStats.totalRequests > 0 ? (runStats.aiSkipped / runStats.totalRequests * 100).toFixed(1) : "0";
|
|
1030
1114
|
logger.info(
|
|
1031
|
-
|
|
1115
|
+
`\u{1F9E0} Finished! recalled: ${runStats.recalled}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
|
|
1032
1116
|
);
|
|
1033
1117
|
}
|
|
1034
1118
|
};
|
|
@@ -1055,16 +1139,6 @@ async function pushData(data, dataset, datasetName) {
|
|
|
1055
1139
|
}
|
|
1056
1140
|
}
|
|
1057
1141
|
|
|
1058
|
-
// src/types.ts
|
|
1059
|
-
var AIMemoryDepth = /* @__PURE__ */ ((AIMemoryDepth2) => {
|
|
1060
|
-
AIMemoryDepth2[AIMemoryDepth2["REALTIME"] = 1] = "REALTIME";
|
|
1061
|
-
AIMemoryDepth2[AIMemoryDepth2["HIGH"] = 2] = "HIGH";
|
|
1062
|
-
AIMemoryDepth2[AIMemoryDepth2["STANDARD"] = 3] = "STANDARD";
|
|
1063
|
-
AIMemoryDepth2[AIMemoryDepth2["DEEP"] = 4] = "DEEP";
|
|
1064
|
-
return AIMemoryDepth2;
|
|
1065
|
-
})(AIMemoryDepth || {});
|
|
1066
|
-
|
|
1067
|
-
exports.AIMemoryDepth = AIMemoryDepth;
|
|
1068
1142
|
exports.CircuitBreaker = CircuitBreaker;
|
|
1069
1143
|
exports.FetchBrain = FetchBrain;
|
|
1070
1144
|
exports.FetchBrainClient = FetchBrainClient;
|