@howells/fieldwork-sdk 0.10.2 → 0.12.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.
Files changed (48) hide show
  1. package/README.md +104 -16
  2. package/dist/{adapter-DWYJys20.js → adapter-CBSAfErv.js} +1 -1
  3. package/dist/adapter-J2yatZJ0.d.ts +73 -0
  4. package/dist/best-CO9liYDa.js +1436 -0
  5. package/dist/brave.d.ts +7 -6
  6. package/dist/brave.js +180 -173
  7. package/dist/browserbase.d.ts +4 -3
  8. package/dist/browserbase.js +185 -170
  9. package/dist/{document-DMIUCoDA.js → document-BSCwJgBM.js} +4 -4
  10. package/dist/{download-CP8noBdX.js → download-kuTqNnuZ.js} +1 -1
  11. package/dist/{adapter-DQrBP1tj.d.ts → errors-gMtejKHc.d.ts} +111 -70
  12. package/dist/exa.d.ts +18 -11
  13. package/dist/exa.js +306 -275
  14. package/dist/fieldwork-D7npPoUf.d.ts +35 -0
  15. package/dist/firecrawl.d.ts +4 -3
  16. package/dist/firecrawl.js +450 -417
  17. package/dist/{parse-Q7H4mrnO.js → http-CJcvTPnE.js} +223 -225
  18. package/dist/image.d.ts +253 -0
  19. package/dist/image.js +1 -0
  20. package/dist/index.d.ts +6 -7
  21. package/dist/index.js +67 -82
  22. package/dist/{job-DnavRq_s.js → job-JLEpszjr.js} +9 -9
  23. package/dist/kernel.d.ts +20 -2
  24. package/dist/kernel.js +65 -19
  25. package/dist/llamaparse.d.ts +3 -2
  26. package/dist/llamaparse.js +16 -16
  27. package/dist/parallel.d.ts +9 -9
  28. package/dist/parallel.js +423 -389
  29. package/dist/path-DO2llIdp.js +10 -0
  30. package/dist/perplexity.d.ts +6 -5
  31. package/dist/perplexity.js +21 -21
  32. package/dist/reducto.d.ts +3 -2
  33. package/dist/reducto.js +14 -14
  34. package/dist/{schema-BFjS6CSz.d.ts → schema-C9xzRkKJ.d.ts} +17 -6
  35. package/dist/{schema--iU4AXSM.js → schema-CJXFAZ-x.js} +12 -3
  36. package/dist/serpapi.d.ts +63 -5
  37. package/dist/serpapi.js +374 -144
  38. package/dist/tavily.d.ts +4 -3
  39. package/dist/tavily.js +247 -234
  40. package/dist/tools.d.ts +76 -15
  41. package/dist/tools.js +522 -154
  42. package/dist/{types-rc8bl8Em.js → types-mq6d6YOK.js} +1 -0
  43. package/dist/{util-DFUXQX6v.js → util-LvME_uOj.js} +35 -11
  44. package/package.json +7 -2
  45. package/dist/fieldwork-JCfyw58T.d.ts +0 -113
  46. package/dist/path-DL5P8XH2.js +0 -17
  47. package/dist/util-DhYr1OS3.d.ts +0 -1
  48. package/dist/{errors-DkFJysIM.js → errors-gpxg6Tnh.js} +5 -5
package/dist/brave.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { $ as SearchResponse, P as ImageSearch, X as Recency, a as RawClient, l as Answer, p as CallOptions, t as Adapter } from "./adapter-DQrBP1tj.js";
1
+ import { a as RawClient, t as Adapter } from "./adapter-J2yatZJ0.js";
2
+ import { J as Recency, Q as SearchResponse, a as Answer, j as ImageSearch, l as CallOptions } from "./errors-gMtejKHc.js";
2
3
  /** Settings for `brave()`. */
3
4
  interface BraveConfig {
4
5
  /** Defaults to the BRAVE_API_KEY environment variable. */
@@ -47,7 +48,7 @@ interface BraveWebSearchOptions extends BraveSearchBase {
47
48
  vertical?: "web";
48
49
  content?: false;
49
50
  maxTokens?: never;
50
- maxTokensPerUrl?: never;
51
+ maxTokensPerResult?: never;
51
52
  relevance?: never;
52
53
  sourceMetadata?: never;
53
54
  /**
@@ -82,7 +83,7 @@ interface BraveNewsSearchOptions extends BraveSearchBase {
82
83
  units?: never;
83
84
  textDecorations?: never;
84
85
  maxTokens?: never;
85
- maxTokensPerUrl?: never;
86
+ maxTokensPerResult?: never;
86
87
  relevance?: never;
87
88
  sourceMetadata?: never;
88
89
  offset?: number;
@@ -102,7 +103,7 @@ interface BraveVideoSearchOptions extends BraveSearchBase {
102
103
  textDecorations?: never;
103
104
  goggles?: never;
104
105
  maxTokens?: never;
105
- maxTokensPerUrl?: never;
106
+ maxTokensPerResult?: never;
106
107
  relevance?: never;
107
108
  sourceMetadata?: never;
108
109
  offset?: number;
@@ -128,7 +129,7 @@ interface BraveContentSearchOptions extends BraveSearchBase {
128
129
  /** Total token budget for all passages, 1024 to 32768 (Brave's default is 8192). */
129
130
  maxTokens?: number;
130
131
  /** Token cap for one page's passages, 512 to 8192 (default 4096). */
131
- maxTokensPerUrl?: number;
132
+ maxTokensPerResult?: number;
132
133
  /** How strictly passages must match the query. */
133
134
  relevance?: "strict" | "balanced" | "lenient" | "disabled";
134
135
  /** Return the site name, favicon, thumbnail and description of each source. */
@@ -181,7 +182,7 @@ interface BraveOperations {
181
182
  answer: (question: string, options?: BraveAnswerOptions) => Promise<Answer<unknown>>;
182
183
  }
183
184
  /**
184
- * An adapter for Brave: search, images and answer. Pass it to `new Fieldwork({ adapter })`.
185
+ * An adapter for Brave: search, images and answer. Pass it to `fieldwork({ adapter })`.
185
186
  *
186
187
  * Throws `Unauthorized` when neither `apiKey` nor `BRAVE_API_KEY` is set.
187
188
  */
package/dist/brave.js CHANGED
@@ -1,8 +1,8 @@
1
- import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
- import { C as createRawClient, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf } from "./parse-Q7H4mrnO.js";
4
- import { a as compact, c as parseJson, f as refuseTogether, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
5
- import * as z from "zod/mini";
1
+ import { t as defineAdapter } from "./adapter-CBSAfErv.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-gpxg6Tnh.js";
3
+ import { d as looseObject, f as nonEmptyString, h as optionalBoolean, l as arrayOf, r as requireKey, t as createRawClient, v as optionalNumber, w as recordOf, x as optionalString } from "./http-CJcvTPnE.js";
4
+ import { a as compact, c as parseJson, d as refuseTogether, s as meta, t as callSettings } from "./util-LvME_uOj.js";
5
+ import * as z$1 from "zod/mini";
6
6
  // src/adapters/brave/response.ts
7
7
  /** The `query` block every search response carries. */
8
8
  const Query = looseObject({
@@ -132,7 +132,7 @@ const ALLOWED = {
132
132
  ...SHARED,
133
133
  "content",
134
134
  "maxTokens",
135
- "maxTokensPerUrl",
135
+ "maxTokensPerResult",
136
136
  "relevance",
137
137
  "sourceMetadata",
138
138
  "operators",
@@ -328,7 +328,7 @@ const streamText = (stream) => {
328
328
  const payload = line.slice(5).trim();
329
329
  if (payload === "" || payload === "[DONE]") continue;
330
330
  try {
331
- const chunk = z.parse(Completion, JSON.parse(payload));
331
+ const chunk = z$1.parse(Completion, JSON.parse(payload));
332
332
  for (const choice of chunk.choices) content += choice.delta.content ?? "";
333
333
  } catch {}
334
334
  }
@@ -347,8 +347,8 @@ const USAGE_TAG = /<usage>(?<body>[\s\S]*?)<\/usage>/gu;
347
347
  const parseTag = (body, schema) => {
348
348
  try {
349
349
  const value = JSON.parse(body);
350
- const twice = z.safeParse(z.string(), value);
351
- return [z.parse(schema, twice.success ? JSON.parse(twice.data) : value)];
350
+ const twice = z$1.safeParse(z$1.string(), value);
351
+ return [z$1.parse(schema, twice.success ? JSON.parse(twice.data) : value)];
352
352
  } catch {
353
353
  return [];
354
354
  }
@@ -384,13 +384,176 @@ const replyContent = (reply) => {
384
384
  };
385
385
  const completion = parseJson(provider, reply);
386
386
  return {
387
- content: completionText(z.parse(Completion, completion)),
387
+ content: completionText(z$1.parse(Completion, completion)),
388
388
  response: completion
389
389
  };
390
390
  };
391
391
  // src/adapters/brave.ts
392
+ /** `answer`: a streamed reply from Brave's model, with its citations. */
393
+ const answering = (raw) => ({ async answer(question, options = {}) {
394
+ const { call, rest: o } = callSettings(options);
395
+ const location = compact({
396
+ city: o.userLocation?.city,
397
+ country: upper(o.userLocation?.country),
398
+ region: o.userLocation?.region,
399
+ timezone: o.userLocation?.timezone
400
+ });
401
+ const searchOptions = compact({
402
+ search_context_size: o.searchContextSize,
403
+ user_location: Object.keys(location).length > 0 ? {
404
+ approximate: location,
405
+ type: "approximate"
406
+ } : void 0
407
+ });
408
+ const reply = await raw.request("POST", "/chat/completions", {
409
+ ...call,
410
+ body: compact({
411
+ country: upper(o.country),
412
+ enable_citations: true,
413
+ language: lower(o.language),
414
+ max_completion_tokens: o.maxTokens,
415
+ messages: [{
416
+ content: question,
417
+ role: "user"
418
+ }],
419
+ model: o.model,
420
+ safesearch: o.safesearch,
421
+ stream: true,
422
+ web_search_options: Object.keys(searchOptions).length > 0 ? searchOptions : void 0
423
+ }),
424
+ text: true
425
+ });
426
+ const { content, response } = replyContent(z$1.parse(z$1.string(), reply));
427
+ const answer = content.replace(CITATION_TAG, "").replace(USAGE_TAG, "").trim();
428
+ if (answer === "") throw new FieldworkError("ProviderError", "brave returned no answer text", {
429
+ cause: response,
430
+ provider
431
+ });
432
+ const usage = tagBodies(content, USAGE_TAG, UsageTag).at(-1);
433
+ return compact({
434
+ answer,
435
+ citations: answerCitations(content),
436
+ meta: meta({
437
+ costUsd: usage?.["X-Request-Total-Cost"],
438
+ units: {
439
+ queries: usage?.["X-Request-Queries"],
440
+ requests: usage?.["X-Request-Requests"],
441
+ tokensIn: usage?.["X-Request-Tokens-In"],
442
+ tokensOut: usage?.["X-Request-Tokens-Out"]
443
+ }
444
+ }),
445
+ raw: response
446
+ });
447
+ } });
448
+ /** `images`: one image search. */
449
+ const imaging = (raw) => ({ async images(query, options = {}) {
450
+ const { call, rest: o } = callSettings(options);
451
+ const response = await raw.request("GET", withQuery("/images/search", {
452
+ count: o.limit,
453
+ country: upper(o.country),
454
+ q: query,
455
+ safesearch: o.safesearch,
456
+ search_lang: lower(o.language),
457
+ spellcheck: o.spellcheck
458
+ }), call);
459
+ const body = z$1.parse(ImageSearchResponse, response);
460
+ const results = [];
461
+ let withoutImage = 0;
462
+ for (const item of body.results) {
463
+ const { url } = item.properties;
464
+ if (url === void 0) {
465
+ withoutImage += 1;
466
+ continue;
467
+ }
468
+ results.push(compact({
469
+ height: item.properties.height,
470
+ sourceUrl: item.url,
471
+ thumbnailUrl: item.thumbnail.src,
472
+ title: item.title,
473
+ url,
474
+ width: item.properties.width
475
+ }));
476
+ }
477
+ const warnings = [...warningsOf(body.query), ...withoutImage > 0 ? [`${withoutImage} results had no image URL and were left out`] : []];
478
+ return compact({
479
+ meta: meta({ warnings }),
480
+ raw: response,
481
+ results
482
+ });
483
+ } });
484
+ /** `search`: the web, news, videos or LLM context, by the mode the options pick. */
485
+ const searching = (raw) => ({ async search(query, options = {}) {
486
+ const { call, rest } = callSettings(options);
487
+ const o = rest;
488
+ const mode = modeOf(o);
489
+ refuseUnsupported(mode, o);
490
+ const window = freshness(o);
491
+ const goggles = gogglesOf(o.goggles);
492
+ const shared = {
493
+ count: o.limit,
494
+ country: upper(o.country),
495
+ freshness: window,
496
+ goggles,
497
+ operators: o.operators,
498
+ q: query,
499
+ safesearch: o.safesearch,
500
+ search_lang: lower(o.language)
501
+ };
502
+ if (mode === "context") {
503
+ const response = await raw.request("GET", withQuery("/llm/context", {
504
+ ...shared,
505
+ context_threshold_mode: o.relevance,
506
+ enable_source_metadata: o.sourceMetadata,
507
+ maximum_number_of_tokens: o.maxTokens,
508
+ maximum_number_of_tokens_per_url: o.maxTokensPerResult,
509
+ maximum_number_of_urls: o.limit
510
+ }), call);
511
+ return compact({
512
+ raw: response,
513
+ results: parseContext(z$1.parse(ContextResponse, response))
514
+ });
515
+ }
516
+ if (mode === "news" || mode === "videos") {
517
+ const response = await raw.request("GET", withQuery(`/${mode}/search`, {
518
+ ...shared,
519
+ extra_snippets: mode === "news" ? o.extraSnippets : void 0,
520
+ offset: o.offset,
521
+ spellcheck: o.spellcheck,
522
+ ui_lang: o.uiLanguage
523
+ }), call);
524
+ const body = z$1.parse(VerticalSearchResponse, response);
525
+ const kind = mode === "news" ? "news" : "video";
526
+ return compact({
527
+ meta: meta({ warnings: warningsOf(body.query) }),
528
+ raw: response,
529
+ results: section(body.results, (item) => result(item, kind))
530
+ });
531
+ }
532
+ const response = await raw.request("GET", withQuery("/web/search", {
533
+ ...shared,
534
+ extra_snippets: o.extraSnippets,
535
+ offset: o.offset,
536
+ result_filter: o.resultTypes?.join(","),
537
+ spellcheck: o.spellcheck,
538
+ text_decorations: o.textDecorations ?? false,
539
+ ui_lang: o.uiLanguage,
540
+ units: o.units
541
+ }), call);
542
+ const body = z$1.parse(WebSearchResponse, response);
543
+ return compact({
544
+ meta: meta({ warnings: warningsOf(body.query) }),
545
+ raw: response,
546
+ results: [
547
+ ...section(body.web.results, (item) => result(item, "web")),
548
+ ...section(body.news.results, (item) => result(item, "news")),
549
+ ...section(body.discussions.results, (item) => result(item, "discussion")),
550
+ ...section(body.videos.results, (item) => result(item, "video")),
551
+ ...section(body.locations.results, placeResult)
552
+ ]
553
+ });
554
+ } });
392
555
  /**
393
- * An adapter for Brave: search, images and answer. Pass it to `new Fieldwork({ adapter })`.
556
+ * An adapter for Brave: search, images and answer. Pass it to `fieldwork({ adapter })`.
394
557
  *
395
558
  * Throws `Unauthorized` when neither `apiKey` nor `BRAVE_API_KEY` is set.
396
559
  */
@@ -402,170 +565,14 @@ const brave = (config = {}) => {
402
565
  provider,
403
566
  retries: config.retries
404
567
  });
568
+ const operations = {
569
+ ...answering(raw),
570
+ ...imaging(raw),
571
+ ...searching(raw)
572
+ };
405
573
  return defineAdapter({
406
574
  name: provider,
407
- operations: {
408
- async answer(question, options) {
409
- const { call, rest: o } = callSettings(options);
410
- const location = compact({
411
- city: o.userLocation?.city,
412
- country: upper(o.userLocation?.country),
413
- region: o.userLocation?.region,
414
- timezone: o.userLocation?.timezone
415
- });
416
- const searchOptions = compact({
417
- search_context_size: o.searchContextSize,
418
- user_location: Object.keys(location).length > 0 ? {
419
- approximate: location,
420
- type: "approximate"
421
- } : void 0
422
- });
423
- const reply = await raw.request("POST", "/chat/completions", {
424
- ...call,
425
- body: compact({
426
- country: upper(o.country),
427
- enable_citations: true,
428
- language: lower(o.language),
429
- max_completion_tokens: o.maxTokens,
430
- messages: [{
431
- content: question,
432
- role: "user"
433
- }],
434
- model: o.model,
435
- safesearch: o.safesearch,
436
- stream: true,
437
- web_search_options: Object.keys(searchOptions).length > 0 ? searchOptions : void 0
438
- }),
439
- text: true
440
- });
441
- const { content, response } = replyContent(reply);
442
- const answer = content.replace(CITATION_TAG, "").replace(USAGE_TAG, "").trim();
443
- if (answer === "") throw new FieldworkError("ProviderError", "brave returned no answer text", {
444
- cause: response,
445
- provider
446
- });
447
- const usage = tagBodies(content, USAGE_TAG, UsageTag).at(-1);
448
- return compact({
449
- answer,
450
- citations: answerCitations(content),
451
- meta: meta({
452
- costUsd: usage?.["X-Request-Total-Cost"],
453
- units: {
454
- queries: usage?.["X-Request-Queries"],
455
- requests: usage?.["X-Request-Requests"],
456
- tokensIn: usage?.["X-Request-Tokens-In"],
457
- tokensOut: usage?.["X-Request-Tokens-Out"]
458
- }
459
- }),
460
- raw: response
461
- });
462
- },
463
- async images(query, options) {
464
- const { call, rest: o } = callSettings(options);
465
- const response = await raw.request("GET", withQuery("/images/search", {
466
- count: o.limit,
467
- country: upper(o.country),
468
- q: query,
469
- safesearch: o.safesearch,
470
- search_lang: lower(o.language),
471
- spellcheck: o.spellcheck
472
- }), call);
473
- const body = z.parse(ImageSearchResponse, response);
474
- const results = [];
475
- let withoutImage = 0;
476
- for (const item of body.results) {
477
- const { url } = item.properties;
478
- if (url === void 0) {
479
- withoutImage += 1;
480
- continue;
481
- }
482
- results.push(compact({
483
- height: item.properties.height,
484
- sourceUrl: item.url,
485
- thumbnailUrl: item.thumbnail.src,
486
- title: item.title,
487
- url,
488
- width: item.properties.width
489
- }));
490
- }
491
- const warnings = [...warningsOf(body.query), ...withoutImage > 0 ? [`${withoutImage} results had no image URL and were left out`] : []];
492
- return compact({
493
- meta: meta({ warnings }),
494
- raw: response,
495
- results
496
- });
497
- },
498
- async search(query, options) {
499
- const { call, rest } = callSettings(options);
500
- const o = rest;
501
- const mode = modeOf(o);
502
- refuseUnsupported(mode, o);
503
- const window = freshness(o);
504
- const goggles = gogglesOf(o.goggles);
505
- const shared = {
506
- count: o.limit,
507
- country: upper(o.country),
508
- freshness: window,
509
- goggles,
510
- operators: o.operators,
511
- q: query,
512
- safesearch: o.safesearch,
513
- search_lang: lower(o.language)
514
- };
515
- if (mode === "context") {
516
- const response = await raw.request("GET", withQuery("/llm/context", {
517
- ...shared,
518
- context_threshold_mode: o.relevance,
519
- enable_source_metadata: o.sourceMetadata,
520
- maximum_number_of_tokens: o.maxTokens,
521
- maximum_number_of_tokens_per_url: o.maxTokensPerUrl,
522
- maximum_number_of_urls: o.limit
523
- }), call);
524
- return compact({
525
- raw: response,
526
- results: parseContext(z.parse(ContextResponse, response))
527
- });
528
- }
529
- if (mode === "news" || mode === "videos") {
530
- const response = await raw.request("GET", withQuery(`/${mode}/search`, {
531
- ...shared,
532
- extra_snippets: mode === "news" ? o.extraSnippets : void 0,
533
- offset: o.offset,
534
- spellcheck: o.spellcheck,
535
- ui_lang: o.uiLanguage
536
- }), call);
537
- const body = z.parse(VerticalSearchResponse, response);
538
- const kind = mode === "news" ? "news" : "video";
539
- return compact({
540
- meta: meta({ warnings: warningsOf(body.query) }),
541
- raw: response,
542
- results: section(body.results, (item) => result(item, kind))
543
- });
544
- }
545
- const response = await raw.request("GET", withQuery("/web/search", {
546
- ...shared,
547
- extra_snippets: o.extraSnippets,
548
- offset: o.offset,
549
- result_filter: o.resultTypes?.join(","),
550
- spellcheck: o.spellcheck,
551
- text_decorations: o.textDecorations ?? false,
552
- ui_lang: o.uiLanguage,
553
- units: o.units
554
- }), call);
555
- const body = z.parse(WebSearchResponse, response);
556
- return compact({
557
- meta: meta({ warnings: warningsOf(body.query) }),
558
- raw: response,
559
- results: [
560
- ...section(body.web.results, (item) => result(item, "web")),
561
- ...section(body.news.results, (item) => result(item, "news")),
562
- ...section(body.discussions.results, (item) => result(item, "discussion")),
563
- ...section(body.videos.results, (item) => result(item, "video")),
564
- ...section(body.locations.results, placeResult)
565
- ]
566
- });
567
- }
568
- },
575
+ operations,
569
576
  raw
570
577
  });
571
578
  };
@@ -1,4 +1,5 @@
1
- import { $ as SearchResponse, D as DownloadedFile, E as DownloadOptions, H as Page, a as RawClient, d as BrowserSession, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-DQrBP1tj.js";
1
+ import { a as RawClient, t as Adapter } from "./adapter-J2yatZJ0.js";
2
+ import { B as Page, C as DownloadedFile, Q as SearchResponse, S as DownloadOptions, at as JsonObject, l as CallOptions, r as AccountUsage, s as BrowserSession } from "./errors-gMtejKHc.js";
2
3
  /** Settings for `browserbase()`. */
3
4
  export interface BrowserbaseConfig {
4
5
  /** Defaults to the BROWSERBASE_API_KEY environment variable. */
@@ -149,7 +150,7 @@ export interface BrowserbaseOpenOptions extends CallOptions {
149
150
  /** A navigation policy of the project. */
150
151
  riskPolicyId?: string;
151
152
  /** Tags stored with the session, searchable in the dashboard. */
152
- userMetadata?: Record<string, unknown>;
153
+ userMetadata?: JsonObject;
153
154
  }
154
155
  /** What the Browserbase adapter offers. */
155
156
  export interface BrowserbaseOperations {
@@ -170,7 +171,7 @@ export interface BrowserbaseOperations {
170
171
  usage: (options?: CallOptions) => Promise<AccountUsage>;
171
172
  }
172
173
  /**
173
- * An adapter for Browserbase: search, read, download, browser and usage. Pass it to `new Fieldwork({ adapter })`.
174
+ * An adapter for Browserbase: search, read, download, browser and usage. Pass it to `fieldwork({ adapter })`.
174
175
  *
175
176
  * Throws `Unauthorized` when neither `apiKey` nor `BROWSERBASE_API_KEY` is set.
176
177
  */