@howells/fieldwork-sdk 0.11.0 → 0.13.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 (47) hide show
  1. package/README.md +73 -15
  2. package/dist/{adapter-DWYJys20.js → adapter-CBSAfErv.js} +1 -1
  3. package/dist/adapter-J2yatZJ0.d.ts +73 -0
  4. package/dist/best-DiKYwLdC.js +1436 -0
  5. package/dist/brave.d.ts +7 -6
  6. package/dist/brave.js +175 -168
  7. package/dist/browserbase.d.ts +4 -3
  8. package/dist/browserbase.js +182 -167
  9. package/dist/{document-DMIUCoDA.js → document-x9fWsQ1W.js} +2 -2
  10. package/dist/{download-CP8noBdX.js → download-kuTqNnuZ.js} +1 -1
  11. package/dist/{adapter-B8kAAAgF.d.ts → errors-gMtejKHc.d.ts} +87 -69
  12. package/dist/exa.d.ts +18 -11
  13. package/dist/exa.js +301 -267
  14. package/dist/fieldwork-D7npPoUf.d.ts +35 -0
  15. package/dist/firecrawl.d.ts +4 -3
  16. package/dist/firecrawl.js +432 -399
  17. package/dist/{parse-Q7H4mrnO.js → http-Bg0h3D-t.js} +222 -224
  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 +66 -82
  22. package/dist/{job-DnavRq_s.js → job-BsrOrrO1.js} +7 -7
  23. package/dist/kernel.d.ts +20 -2
  24. package/dist/kernel.js +58 -12
  25. package/dist/llamaparse.d.ts +3 -2
  26. package/dist/llamaparse.js +8 -8
  27. package/dist/parallel.d.ts +10 -10
  28. package/dist/parallel.js +432 -391
  29. package/dist/path-tDCyAKK9.js +10 -0
  30. package/dist/perplexity.d.ts +6 -5
  31. package/dist/perplexity.js +16 -16
  32. package/dist/reducto.d.ts +3 -2
  33. package/dist/reducto.js +8 -8
  34. package/dist/{schema--iU4AXSM.js → schema-Bfd2E8u2.js} +12 -3
  35. package/dist/{schema-CAPSX7yQ.d.ts → schema-C9xzRkKJ.d.ts} +17 -6
  36. package/dist/serpapi.d.ts +3 -3
  37. package/dist/serpapi.js +170 -165
  38. package/dist/tavily.d.ts +4 -3
  39. package/dist/tavily.js +242 -229
  40. package/dist/tools.d.ts +79 -15
  41. package/dist/tools.js +431 -77
  42. package/dist/{util-DFUXQX6v.js → util-BOqd71Om.js} +44 -12
  43. package/package.json +11 -6
  44. package/dist/fieldwork-BrfoehvG.d.ts +0 -113
  45. package/dist/path-DL5P8XH2.js +0 -17
  46. package/dist/util-DhYr1OS3.d.ts +0 -1
  47. package/dist/{errors-DkFJysIM.js → errors-gpxg6Tnh.js} +5 -5
package/dist/parallel.js CHANGED
@@ -1,10 +1,10 @@
1
- import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
- import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, v as recordOf, x as warnings, y as sourceShape } from "./parse-Q7H4mrnO.js";
4
- import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DnavRq_s.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema--iU4AXSM.js";
6
- import { a as compact, c as parseJson, f as refuseTogether, i as citationsOf, m as uniqueCitations, p as requireJobId, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
7
1
  import * as z from "zod/mini";
2
+ import { t as defineAdapter } from "./adapter-CBSAfErv.js";
3
+ import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-gpxg6Tnh.js";
4
+ import { C as optionalStructure, D as warnings, O as withOriginal, T as sourceShape, _ as optionalId, b as optionalScalar, c as anything, d as looseObject, i as segment, l as arrayOf, p as optionalAnyString, r as requireKey, s as Source, t as createRawClient, u as both, v as optionalNumber, w as recordOf, x as optionalString } from "./http-Bg0h3D-t.js";
5
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-BsrOrrO1.js";
6
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-Bfd2E8u2.js";
7
+ import { a as compact, c as parseJson, f as refuseTogether, i as citationsOf, l as positiveWhole, m as uniqueCitations, p as requireJobId, s as meta, t as callSettings } from "./util-BOqd71Om.js";
8
8
  // src/adapters/parallel/parse.ts
9
9
  /** The name this adapter reports in errors and results. */
10
10
  const provider = "parallel";
@@ -262,6 +262,8 @@ const jsonOutput = (schema) => ({
262
262
  json_schema: jsonSchemaOf(schema),
263
263
  type: "json"
264
264
  });
265
+ /** A question of a type the checks do not know: only its `type`, as it arrived. */
266
+ const UntypedQuestion = looseObject({ type: anything });
265
267
  /**
266
268
  * Parallel's form of a normalized decision question: `yesno` is `noul`, `choice`
267
269
  * keeps its type and `score` takes the scale's labels, in order, as criteria.
@@ -290,7 +292,8 @@ const decisionQuestion = (name, question) => {
290
292
  type: "score"
291
293
  };
292
294
  }
293
- throw invalidRequest(provider, `does not know the question type "${String(question.type)}" for "${name}"`);
295
+ const { type } = z.parse(UntypedQuestion, question);
296
+ throw invalidRequest(provider, `does not know the question type ${JSON.stringify(type)} for "${name}"`);
294
297
  };
295
298
  /** Parallel's short form of each named schedule. */
296
299
  const NAMED_FREQUENCY = {
@@ -314,20 +317,25 @@ const frequency = (schedule) => {
314
317
  };
315
318
  /**
316
319
  * The `/v1/extract` body that `read` and `readMany` share. It always asks for
317
- * `full_content`, capped only when `maxContentChars` is a non-zero number.
320
+ * `full_content`, capped when `maxContentChars` is set.
318
321
  */
319
- const extractBody = (urls, o) => compact({
320
- advanced_settings: compact({
321
- excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
322
- fetch_policy: fetchPolicy(o.maxAge),
323
- full_content: o.maxContentChars !== void 0 && o.maxContentChars !== 0 ? { max_chars_per_result: o.maxContentChars } : true
324
- }),
325
- max_chars_total: o.maxCharsTotal,
326
- objective: o.query,
327
- search_queries: o.queries,
328
- session_id: o.sessionId,
329
- urls
330
- });
322
+ const extractBody = (urls, o) => {
323
+ const maxContentChars = positiveWhole(provider, "maxContentChars", o.maxContentChars);
324
+ const maxCharsPerResult = positiveWhole(provider, "maxCharsPerResult", o.maxCharsPerResult);
325
+ const maxCharsTotal = positiveWhole(provider, "maxCharsTotal", o.maxCharsTotal);
326
+ return compact({
327
+ advanced_settings: compact({
328
+ excerpt_settings: nonEmpty({ max_chars_per_result: maxCharsPerResult }),
329
+ fetch_policy: fetchPolicy(o.maxAge),
330
+ full_content: maxContentChars === void 0 ? true : { max_chars_per_result: maxContentChars }
331
+ }),
332
+ max_chars_total: maxCharsTotal,
333
+ objective: o.query,
334
+ search_queries: o.queries,
335
+ session_id: o.sessionId,
336
+ urls
337
+ });
338
+ };
331
339
  // src/adapters/parallel/response.ts
332
340
  /** What a result says about the evidence for a field. */
333
341
  const Basis = looseObject({
@@ -667,9 +675,403 @@ const findAllResult = async (raw, id, request) => {
667
675
  });
668
676
  return state === "done" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
669
677
  };
678
+ // src/adapters/parallel/monitor.ts
679
+ /** Refuses a monitor Parallel cannot run, before anything is sent. */
680
+ const checkMonitor = (o) => {
681
+ if (Object.entries(o).some(([name, value]) => name === "urls" && value !== void 0)) throw invalidRequest(provider, "monitors search the web for a query and cannot watch a list of URLs; restrict a query with includeDomains, which accepts domain/path prefixes");
682
+ if (o.taskRunId === void 0 && o.query === void 0) throw invalidRequest(provider, "a parallel monitor needs a query or a taskRunId");
683
+ if (o.taskRunId !== void 0) for (const name of [
684
+ "query",
685
+ "schema",
686
+ "includeBackfill",
687
+ "country",
688
+ "includeDomains",
689
+ "excludeDomains",
690
+ "publishedAfter"
691
+ ]) refuseTogether(provider, o, "taskRunId", name);
692
+ if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw invalidRequest(provider, "webhookEvents needs a webhookUrl");
693
+ };
694
+ /** The body that creates a monitor: a query to search, or a Task run to repeat. */
695
+ const monitorBody = (o) => compact({
696
+ frequency: frequency(o.schedule),
697
+ metadata: o.metadata,
698
+ processor: o.processor,
699
+ settings: o.taskRunId === void 0 ? compact({
700
+ advanced_settings: nonEmpty({
701
+ location: o.country,
702
+ source_policy: sourcePolicy(o)
703
+ }),
704
+ include_backfill: o.includeBackfill,
705
+ output_schema: o.schema ? jsonOutput(o.schema) : void 0,
706
+ query: o.query
707
+ }) : { task_run_id: o.taskRunId },
708
+ type: o.taskRunId === void 0 ? "event_stream" : "snapshot",
709
+ webhook: o.webhookUrl === void 0 || o.webhookUrl === "" ? void 0 : compact({
710
+ event_types: o.webhookEvents,
711
+ url: o.webhookUrl
712
+ })
713
+ });
714
+ /**
715
+ * Every monitor from `cursor` on, one page after another: the next page is
716
+ * requested only once this one names its cursor. A cursor seen before would
717
+ * page forever, so it ends the listing.
718
+ */
719
+ const listMonitors = async (raw, call, cursor, seen) => {
720
+ const page = z.parse(MonitorsPage, await raw.request("GET", "/v1/monitors", {
721
+ ...call,
722
+ query: {
723
+ cursor,
724
+ limit: 100
725
+ }
726
+ }));
727
+ const monitors = page.monitors.map((entry) => monitorInfo(entry));
728
+ const next = page.next_cursor;
729
+ if (next === void 0 || seen.has(next)) return monitors;
730
+ return [...monitors, ...await listMonitors(raw, call, next, /* @__PURE__ */ new Set([...seen, next]))];
731
+ };
732
+ /** Parallel's monitor methods, calling through `raw`. */
733
+ const parallelMonitor = (raw) => ({
734
+ async create(options) {
735
+ const { call, rest: o } = callSettings(options);
736
+ checkMonitor(o);
737
+ const response = await raw.request("POST", "/v1/monitors", {
738
+ creates: true,
739
+ ...call,
740
+ body: monitorBody(o)
741
+ });
742
+ return monitorInfo(z.parse(MonitorEntry, response));
743
+ },
744
+ async delete(id, options) {
745
+ await raw.request("POST", `/v1/monitors/${segment(id)}/cancel`, options);
746
+ },
747
+ async events(id, options = {}) {
748
+ const { call, rest: o } = callSettings(options);
749
+ const response = await raw.request("GET", `/v1/monitors/${segment(id)}/events`, {
750
+ ...call,
751
+ query: {
752
+ cursor: o.cursor,
753
+ event_group_id: o.eventGroupId,
754
+ include_completions: o.includeCompletions,
755
+ limit: o.limit
756
+ }
757
+ });
758
+ const page = z.parse(EventsPage, response);
759
+ return compact({
760
+ events: page.events.map((entry) => monitorEvent(entry)),
761
+ next: page.next_cursor,
762
+ raw: response
763
+ });
764
+ },
765
+ async get(id, options) {
766
+ return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${segment(id)}`, options)));
767
+ },
768
+ async list(options = {}) {
769
+ const { call } = callSettings(options);
770
+ return await listMonitors(raw, call, void 0, /* @__PURE__ */ new Set());
771
+ }
772
+ });
670
773
  // src/adapters/parallel.ts
774
+ /** `answer`: one response from Parallel's model, with web search. */
775
+ const answering = (raw) => ({ async answer(question, options = {}) {
776
+ const { call, rest: o } = callSettings(options);
777
+ refuseTogether(provider, o, "includeDomains", "excludeDomains");
778
+ const filters = nonEmpty({
779
+ allowed_domains: o.includeDomains,
780
+ blocked_domains: o.excludeDomains
781
+ });
782
+ const response = await raw.request("POST", "/v1/responses", {
783
+ ...call,
784
+ body: compact({
785
+ input: question,
786
+ instructions: o.instructions,
787
+ metadata: o.metadata,
788
+ model: "parallel",
789
+ previous_response_id: o.continueFrom,
790
+ reasoning: o.effort ? { effort: o.effort } : void 0,
791
+ text: o.schema ? { format: {
792
+ name: "answer",
793
+ schema: jsonSchemaOf(o.schema),
794
+ type: "json_schema"
795
+ } } : void 0,
796
+ tools: filters ? [{
797
+ filters,
798
+ type: "web_search"
799
+ }] : void 0
800
+ })
801
+ });
802
+ const body = z.parse(AnswerResponse, response);
803
+ const failure = body.error.message;
804
+ if (body.status === "failed" || failure !== void 0) throw new FieldworkError("ProviderError", `parallel could not answer: ${failure ?? "the response failed"}`, {
805
+ cause: response,
806
+ provider
807
+ });
808
+ const parts = responseMessages(body).flatMap((message) => message.content.filter((part) => part.type === "output_text"));
809
+ const answer = parts.map((part) => part.text).filter((part) => part !== void 0).join("\n\n");
810
+ if (answer === "") throw new FieldworkError("ProviderError", `parallel returned no answer text (status ${body.status ?? "unknown"})`, {
811
+ cause: response,
812
+ provider
813
+ });
814
+ const { usage } = body;
815
+ const incomplete = body.incomplete_details.reason;
816
+ return compact({
817
+ answer,
818
+ citations: uniqueCitations(citationsOf(parts.flatMap((part) => part.annotations).filter((item) => item.type === "url_citation"))),
819
+ continuationId: body.id.text,
820
+ meta: meta({
821
+ requestId: body.id.request,
822
+ units: {
823
+ input_tokens: usage.input_tokens,
824
+ output_tokens: usage.output_tokens,
825
+ total_tokens: usage.total_tokens
826
+ },
827
+ warnings: incomplete === void 0 ? void 0 : [`the answer is incomplete: ${incomplete}`]
828
+ }),
829
+ output: o.schema ? await checkOutput(o.schema, parseJson(provider, answer), { provider }) : void 0,
830
+ raw: response
831
+ });
832
+ } });
833
+ /** `decide` and `discover`: questions answered about the web, and the entities a FindAll run turns up. */
834
+ const judging = (raw) => ({
835
+ async decide(context, questions, options = {}) {
836
+ const { call, rest: o } = callSettings(options);
837
+ const entries = Object.entries(questions);
838
+ const names = entries.map(([name]) => name);
839
+ if (names.length < 1 || names.length > 100) throw invalidRequest(provider, `decisions take 1 to 100 questions; got ${names.length}`);
840
+ const badName = names.find((name) => !QUESTION_NAME.test(name));
841
+ if (badName !== void 0) throw invalidRequest(provider, `question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
842
+ const response = await raw.request("POST", "/v1/decisions", {
843
+ ...call,
844
+ body: compact({
845
+ advanced_settings: nonEmpty({
846
+ include_excerpts: o.includeExcerpts,
847
+ location: o.country
848
+ }),
849
+ questions: Object.fromEntries(entries.map(([name, question]) => [name, decisionQuestion(name, question)])),
850
+ state: context ?? null
851
+ })
852
+ });
853
+ const body = z.parse(DecisionsResponse, response);
854
+ const result = {};
855
+ const unanswered = [];
856
+ for (const [name, question] of entries) {
857
+ const found = Object.hasOwn(body.answers, name) ? body.answers[name] : void 0;
858
+ const answer = found && decisionAnswer(question, found);
859
+ if (answer === void 0) unanswered.push(name);
860
+ else result[name] = answer;
861
+ }
862
+ if (unanswered.length > 0) throw new FieldworkError("ProviderError", `parallel returned no complete answer for ${unanswered.join(", ")}`, {
863
+ cause: response,
864
+ provider
865
+ });
866
+ return compact({
867
+ answers: result,
868
+ citations: citationsOf(body.citations),
869
+ meta: meta({
870
+ requestId: body.decision_id,
871
+ units: { input_tokens: body.usage.input_tokens }
872
+ }),
873
+ raw: response
874
+ });
875
+ },
876
+ async discover(objective, options) {
877
+ const { call, rest: o } = callSettings(options);
878
+ return await runJob(provider, {
879
+ check: async (id, request) => await findAllResult(raw, id, request),
880
+ finish: async (result, id) => {
881
+ const found = discovery(id, result);
882
+ const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => data === void 0 ? entity : {
883
+ ...entity,
884
+ data: await checkOutput(o.schema, data, { provider })
885
+ }));
886
+ return {
887
+ ...found,
888
+ entities
889
+ };
890
+ },
891
+ start: async () => await startFindAll(raw, objective, o, call)
892
+ }, {
893
+ ...call,
894
+ interval: o.interval,
895
+ resume: o.resume
896
+ });
897
+ }
898
+ });
899
+ /** `extract` and `research`: Task runs, polled to their result. */
900
+ const tasking = (raw) => ({
901
+ async extract(url, options = {}) {
902
+ const { call, rest: o } = callSettings(options);
903
+ if (!URL.canParse(url)) throw invalidRequest(provider, `cannot extract ${url}: it is not a URL`);
904
+ const target = new URL(url);
905
+ return await runTask(raw, compact({
906
+ advanced_settings: nonEmpty({ location: o.country }),
907
+ input: {
908
+ instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
909
+ url
910
+ },
911
+ metadata: o.metadata,
912
+ processor: o.processor ?? "base",
913
+ source_policy: { include_domains: [`${target.hostname}${target.pathname}`.replace(/\/$/u, "")] },
914
+ task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "auto" } }
915
+ }), {
916
+ ...call,
917
+ interval: o.interval,
918
+ resume: o.resume
919
+ }, async (result) => {
920
+ const { output } = result.value;
921
+ return compact({
922
+ data: await checkOutput(o.schema, output.content, { provider }),
923
+ fields: basis(output.basis),
924
+ meta: taskMeta(result),
925
+ raw: result.original
926
+ });
927
+ });
928
+ },
929
+ async research(question, options = {}) {
930
+ const { call, rest: o } = callSettings(options);
931
+ return await runTask(raw, compact({
932
+ advanced_settings: nonEmpty({ location: o.country }),
933
+ input: question,
934
+ metadata: o.metadata,
935
+ previous_interaction_id: o.continueFrom,
936
+ processor: o.processor ?? "base",
937
+ source_policy: sourcePolicy(o),
938
+ task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "text" } }
939
+ }), {
940
+ ...call,
941
+ interval: o.interval,
942
+ resume: o.resume
943
+ }, async (result, id) => {
944
+ const { output, run } = result.value;
945
+ const fields = basis(output.basis);
946
+ return compact({
947
+ continuationId: run.interaction_id,
948
+ fields,
949
+ id,
950
+ meta: taskMeta(result),
951
+ output: await checkOutput(o.schema, output.content, { provider }),
952
+ raw: result.original,
953
+ sources: citedBy(fields),
954
+ status: "completed"
955
+ });
956
+ });
957
+ }
958
+ });
959
+ /** `read` and `readMany`, through `/v1/extract`. */
960
+ const reading = (raw) => ({
961
+ async read(url, options = {}) {
962
+ const { call, rest: o } = callSettings(options);
963
+ const response = await raw.request("POST", "/v1/extract", {
964
+ ...call,
965
+ body: extractBody([url], o)
966
+ });
967
+ const body = z.parse(ExtractResponse, response);
968
+ const [result] = body.results;
969
+ if (result?.value.url === void 0) {
970
+ const [failure] = body.errors;
971
+ throw new FieldworkError("ProviderError", `parallel could not read ${url}: ${failure !== void 0 && Object.keys(failure).length > 0 ? extractFailure(failure) : "no content returned"}`, {
972
+ cause: response,
973
+ provider
974
+ });
975
+ }
976
+ return pageFrom(result, {
977
+ meta: extractMeta(body),
978
+ raw: response
979
+ });
980
+ },
981
+ async readMany(urls, options = {}) {
982
+ const { call, rest: o } = callSettings(options);
983
+ if (urls.length > 20) throw invalidRequest(provider, `reads up to 20 URLs in one call; got ${urls.length}`);
984
+ const response = await raw.request("POST", "/v1/extract", {
985
+ ...call,
986
+ body: extractBody(urls, o)
987
+ });
988
+ const body = z.parse(ExtractResponse, response);
989
+ return compact({
990
+ failed: body.errors.map((failure) => ({
991
+ error: extractFailure(failure),
992
+ url: failure.url ?? ""
993
+ })),
994
+ id: body.extract_id.text,
995
+ meta: extractMeta(body),
996
+ pages: body.results.map((entry) => pageFrom(entry)),
997
+ raw: response
998
+ });
999
+ }
1000
+ });
1001
+ /** `search` and `images`: one request each. */
1002
+ const searching = (raw) => ({
1003
+ async images(query, options = {}) {
1004
+ const { call, rest: o } = callSettings(options);
1005
+ const response = await raw.request("POST", "/v1/images/search", {
1006
+ ...call,
1007
+ body: compact({
1008
+ advanced_settings: nonEmpty({
1009
+ location: o.country,
1010
+ max_results: o.limit
1011
+ }),
1012
+ mode: o.mode,
1013
+ objective: o.objective ?? query,
1014
+ search_queries: o.queries ?? [query],
1015
+ session_id: o.sessionId
1016
+ })
1017
+ });
1018
+ const body = z.parse(ImagesResponse, response);
1019
+ return compact({
1020
+ meta: meta({
1021
+ requestId: body.search_id,
1022
+ units: usageUnits(body.usage),
1023
+ warnings: body.warnings
1024
+ }),
1025
+ raw: response,
1026
+ results: body.results.map((image) => compact({
1027
+ height: image.height,
1028
+ sourceUrl: image.source_page_url,
1029
+ title: image.title,
1030
+ url: image.image_url ?? "",
1031
+ width: image.width
1032
+ }))
1033
+ });
1034
+ },
1035
+ async search(query, options = {}) {
1036
+ const { call, rest: o } = callSettings(options);
1037
+ const maxCharsPerResult = positiveWhole(provider, "maxCharsPerResult", o.maxCharsPerResult);
1038
+ const maxCharsTotal = positiveWhole(provider, "maxCharsTotal", o.maxCharsTotal);
1039
+ const response = await raw.request("POST", "/v1/search", {
1040
+ ...call,
1041
+ body: compact({
1042
+ advanced_settings: nonEmpty({
1043
+ excerpt_settings: nonEmpty({ max_chars_per_result: maxCharsPerResult }),
1044
+ fetch_policy: fetchPolicy(o.maxAge),
1045
+ location: o.country,
1046
+ max_results: o.limit,
1047
+ source_policy: sourcePolicy(o)
1048
+ }),
1049
+ max_chars_total: maxCharsTotal,
1050
+ mode: o.mode,
1051
+ objective: o.objective ?? query,
1052
+ search_queries: o.queries ?? [query],
1053
+ session_id: o.sessionId
1054
+ })
1055
+ });
1056
+ const body = z.parse(SearchResponse, response);
1057
+ return compact({
1058
+ meta: meta({
1059
+ requestId: body.search_id,
1060
+ units: usageUnits(body.usage),
1061
+ warnings: body.warnings
1062
+ }),
1063
+ raw: response,
1064
+ results: body.results.map((result) => compact({
1065
+ publishedAt: result.publish_date,
1066
+ snippet: result.excerpts.length > 0 ? result.excerpts.join(" … ") : void 0,
1067
+ title: result.title,
1068
+ url: result.url ?? ""
1069
+ }))
1070
+ });
1071
+ }
1072
+ });
671
1073
  /**
672
- * An adapter for Parallel: search, images, read, readMany, extract, answer, research, discover, decide and monitor. Pass it to `new Fieldwork({ adapter })`.
1074
+ * An adapter for Parallel: search, images, read, readMany, extract, answer, research, discover, decide and monitor. Pass it to `fieldwork({ adapter })`.
673
1075
  *
674
1076
  * Throws `Unauthorized` when neither `apiKey` nor `PARALLEL_API_KEY` is set.
675
1077
  */
@@ -681,378 +1083,17 @@ const parallel = (config = {}) => {
681
1083
  provider,
682
1084
  retries: config.retries
683
1085
  });
1086
+ const operations = {
1087
+ ...answering(raw),
1088
+ ...judging(raw),
1089
+ ...reading(raw),
1090
+ ...searching(raw),
1091
+ ...tasking(raw),
1092
+ monitor: parallelMonitor(raw)
1093
+ };
684
1094
  return defineAdapter({
685
1095
  name: provider,
686
- operations: {
687
- async answer(question, options) {
688
- const { call, rest: o } = callSettings(options);
689
- refuseTogether(provider, o, "includeDomains", "excludeDomains");
690
- const filters = nonEmpty({
691
- allowed_domains: o.includeDomains,
692
- blocked_domains: o.excludeDomains
693
- });
694
- const response = await raw.request("POST", "/v1/responses", {
695
- ...call,
696
- body: compact({
697
- input: question,
698
- instructions: o.instructions,
699
- metadata: o.metadata,
700
- model: "parallel",
701
- previous_response_id: o.continueFrom,
702
- reasoning: o.effort ? { effort: o.effort } : void 0,
703
- text: o.schema ? { format: {
704
- name: "answer",
705
- schema: jsonSchemaOf(o.schema),
706
- type: "json_schema"
707
- } } : void 0,
708
- tools: filters ? [{
709
- filters,
710
- type: "web_search"
711
- }] : void 0
712
- })
713
- });
714
- const body = z.parse(AnswerResponse, response);
715
- const failure = body.error.message;
716
- if (body.status === "failed" || failure !== void 0) throw new FieldworkError("ProviderError", `parallel could not answer: ${failure ?? "the response failed"}`, {
717
- cause: response,
718
- provider
719
- });
720
- const parts = responseMessages(body).flatMap((message) => message.content.filter((part) => part.type === "output_text"));
721
- const answer = parts.map((part) => part.text).filter((part) => part !== void 0).join("\n\n");
722
- if (answer === "") throw new FieldworkError("ProviderError", `parallel returned no answer text (status ${body.status ?? "unknown"})`, {
723
- cause: response,
724
- provider
725
- });
726
- const { usage } = body;
727
- const incomplete = body.incomplete_details.reason;
728
- return compact({
729
- answer,
730
- citations: uniqueCitations(citationsOf(parts.flatMap((part) => part.annotations).filter((item) => item.type === "url_citation"))),
731
- continuationId: body.id.text,
732
- meta: meta({
733
- requestId: body.id.request,
734
- units: {
735
- input_tokens: usage.input_tokens,
736
- output_tokens: usage.output_tokens,
737
- total_tokens: usage.total_tokens
738
- },
739
- warnings: incomplete === void 0 ? void 0 : [`the answer is incomplete: ${incomplete}`]
740
- }),
741
- output: o.schema ? await checkOutput(o.schema, parseJson(provider, answer), { provider }) : void 0,
742
- raw: response
743
- });
744
- },
745
- async decide(context, questions, options) {
746
- const { call, rest: o } = callSettings(options);
747
- const entries = Object.entries(questions);
748
- const names = entries.map(([name]) => name);
749
- if (names.length < 1 || names.length > 100) throw invalidRequest(provider, `decisions take 1 to 100 questions; got ${names.length}`);
750
- const badName = names.find((name) => !QUESTION_NAME.test(name));
751
- if (badName !== void 0) throw invalidRequest(provider, `question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
752
- const response = await raw.request("POST", "/v1/decisions", {
753
- ...call,
754
- body: compact({
755
- advanced_settings: nonEmpty({
756
- include_excerpts: o.includeExcerpts,
757
- location: o.country
758
- }),
759
- questions: Object.fromEntries(entries.map(([name, question]) => [name, decisionQuestion(name, question)])),
760
- state: context ?? null
761
- })
762
- });
763
- const body = z.parse(DecisionsResponse, response);
764
- const result = {};
765
- const unanswered = [];
766
- for (const [name, question] of entries) {
767
- const found = Object.hasOwn(body.answers, name) ? body.answers[name] : void 0;
768
- const answer = found && decisionAnswer(question, found);
769
- if (answer === void 0) unanswered.push(name);
770
- else result[name] = answer;
771
- }
772
- if (unanswered.length > 0) throw new FieldworkError("ProviderError", `parallel returned no complete answer for ${unanswered.join(", ")}`, {
773
- cause: response,
774
- provider
775
- });
776
- return compact({
777
- answers: result,
778
- citations: citationsOf(body.citations),
779
- meta: meta({
780
- requestId: body.decision_id,
781
- units: { input_tokens: body.usage.input_tokens }
782
- }),
783
- raw: response
784
- });
785
- },
786
- async discover(objective, options) {
787
- const { call, rest: o } = callSettings(options);
788
- return await runJob(provider, {
789
- check: async (id, request) => await findAllResult(raw, id, request),
790
- finish: async (result, id) => {
791
- const found = discovery(id, result);
792
- const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => data === void 0 ? entity : {
793
- ...entity,
794
- data: await checkOutput(o.schema, data, { provider })
795
- }));
796
- return {
797
- ...found,
798
- entities
799
- };
800
- },
801
- start: async () => await startFindAll(raw, objective, o, call)
802
- }, {
803
- ...call,
804
- interval: o.interval,
805
- resume: o.resume
806
- });
807
- },
808
- async extract(url, options) {
809
- const { call, rest: o } = callSettings(options);
810
- if (!URL.canParse(url)) throw invalidRequest(provider, `cannot extract ${url}: it is not a URL`);
811
- const target = new URL(url);
812
- return await runTask(raw, compact({
813
- advanced_settings: nonEmpty({ location: o.country }),
814
- input: {
815
- instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
816
- url
817
- },
818
- metadata: o.metadata,
819
- processor: o.processor ?? "base",
820
- source_policy: { include_domains: [`${target.hostname}${target.pathname}`.replace(/\/$/u, "")] },
821
- task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "auto" } }
822
- }), {
823
- ...call,
824
- interval: o.interval,
825
- resume: o.resume
826
- }, async (result) => {
827
- const { output } = result.value;
828
- return compact({
829
- data: await checkOutput(o.schema, output.content, { provider }),
830
- fields: basis(output.basis),
831
- meta: taskMeta(result),
832
- raw: result.original
833
- });
834
- });
835
- },
836
- async images(query, options) {
837
- const { call, rest: o } = callSettings(options);
838
- const response = await raw.request("POST", "/v1/images/search", {
839
- ...call,
840
- body: compact({
841
- advanced_settings: nonEmpty({
842
- location: o.country,
843
- max_results: o.limit
844
- }),
845
- mode: o.mode,
846
- objective: o.objective ?? query,
847
- search_queries: o.queries ?? [query],
848
- session_id: o.sessionId
849
- })
850
- });
851
- const body = z.parse(ImagesResponse, response);
852
- return compact({
853
- meta: meta({
854
- requestId: body.search_id,
855
- units: usageUnits(body.usage),
856
- warnings: body.warnings
857
- }),
858
- raw: response,
859
- results: body.results.map((image) => compact({
860
- height: image.height,
861
- sourceUrl: image.source_page_url,
862
- title: image.title,
863
- url: image.image_url ?? "",
864
- width: image.width
865
- }))
866
- });
867
- },
868
- monitor: {
869
- async create(options) {
870
- const { call, rest: o } = callSettings(options);
871
- if (Object.entries(o).some(([name, value]) => name === "urls" && value !== void 0)) throw invalidRequest(provider, "monitors search the web for a query and cannot watch a list of URLs; restrict a query with includeDomains, which accepts domain/path prefixes");
872
- if (o.taskRunId === void 0 && o.query === void 0) throw invalidRequest(provider, "a parallel monitor needs a query or a taskRunId");
873
- if (o.taskRunId !== void 0) for (const name of [
874
- "query",
875
- "schema",
876
- "includeBackfill",
877
- "country",
878
- "includeDomains",
879
- "excludeDomains",
880
- "publishedAfter"
881
- ]) refuseTogether(provider, o, "taskRunId", name);
882
- if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw invalidRequest(provider, "webhookEvents needs a webhookUrl");
883
- const response = await raw.request("POST", "/v1/monitors", {
884
- creates: true,
885
- ...call,
886
- body: compact({
887
- frequency: frequency(o.schedule),
888
- metadata: o.metadata,
889
- processor: o.processor,
890
- settings: o.taskRunId === void 0 ? compact({
891
- advanced_settings: nonEmpty({
892
- location: o.country,
893
- source_policy: sourcePolicy(o)
894
- }),
895
- include_backfill: o.includeBackfill,
896
- output_schema: o.schema ? jsonOutput(o.schema) : void 0,
897
- query: o.query
898
- }) : { task_run_id: o.taskRunId },
899
- type: o.taskRunId === void 0 ? "event_stream" : "snapshot",
900
- webhook: o.webhookUrl === void 0 || o.webhookUrl === "" ? void 0 : compact({
901
- event_types: o.webhookEvents,
902
- url: o.webhookUrl
903
- })
904
- })
905
- });
906
- return monitorInfo(z.parse(MonitorEntry, response));
907
- },
908
- async delete(id, options) {
909
- await raw.request("POST", `/v1/monitors/${segment(id)}/cancel`, options);
910
- },
911
- async events(id, options) {
912
- const { call, rest: o } = callSettings(options);
913
- const response = await raw.request("GET", `/v1/monitors/${segment(id)}/events`, {
914
- ...call,
915
- query: {
916
- cursor: o.cursor,
917
- event_group_id: o.eventGroupId,
918
- include_completions: o.includeCompletions,
919
- limit: o.limit
920
- }
921
- });
922
- const page = z.parse(EventsPage, response);
923
- return compact({
924
- events: page.events.map((entry) => monitorEvent(entry)),
925
- next: page.next_cursor,
926
- raw: response
927
- });
928
- },
929
- async get(id, options) {
930
- return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${segment(id)}`, options)));
931
- },
932
- async list(options) {
933
- const { call } = callSettings(options);
934
- const monitors = [];
935
- const seen = /* @__PURE__ */ new Set();
936
- let cursor;
937
- for (;;) {
938
- const page = z.parse(MonitorsPage, await raw.request("GET", "/v1/monitors", {
939
- ...call,
940
- query: {
941
- cursor,
942
- limit: 100
943
- }
944
- }));
945
- monitors.push(...page.monitors.map((entry) => monitorInfo(entry)));
946
- cursor = page.next_cursor;
947
- if (cursor === void 0 || seen.has(cursor)) return monitors;
948
- seen.add(cursor);
949
- }
950
- }
951
- },
952
- async read(url, options) {
953
- const { call, rest: o } = callSettings(options);
954
- const response = await raw.request("POST", "/v1/extract", {
955
- ...call,
956
- body: extractBody([url], o)
957
- });
958
- const body = z.parse(ExtractResponse, response);
959
- const [result] = body.results;
960
- if (result?.value.url === void 0) {
961
- const [failure] = body.errors;
962
- throw new FieldworkError("ProviderError", `parallel could not read ${url}: ${failure !== void 0 && Object.keys(failure).length > 0 ? extractFailure(failure) : "no content returned"}`, {
963
- cause: response,
964
- provider
965
- });
966
- }
967
- return pageFrom(result, {
968
- meta: extractMeta(body),
969
- raw: response
970
- });
971
- },
972
- async readMany(urls, options) {
973
- const { call, rest: o } = callSettings(options);
974
- if (urls.length > 20) throw invalidRequest(provider, `reads up to 20 URLs in one call; got ${urls.length}`);
975
- const response = await raw.request("POST", "/v1/extract", {
976
- ...call,
977
- body: extractBody(urls, o)
978
- });
979
- const body = z.parse(ExtractResponse, response);
980
- return compact({
981
- failed: body.errors.map((failure) => ({
982
- error: extractFailure(failure),
983
- url: failure.url ?? ""
984
- })),
985
- id: body.extract_id.text,
986
- meta: extractMeta(body),
987
- pages: body.results.map((entry) => pageFrom(entry)),
988
- raw: response
989
- });
990
- },
991
- async research(question, options) {
992
- const { call, rest: o } = callSettings(options);
993
- return await runTask(raw, compact({
994
- advanced_settings: nonEmpty({ location: o.country }),
995
- input: question,
996
- metadata: o.metadata,
997
- previous_interaction_id: o.continueFrom,
998
- processor: o.processor ?? "base",
999
- source_policy: sourcePolicy(o),
1000
- task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "text" } }
1001
- }), {
1002
- ...call,
1003
- interval: o.interval,
1004
- resume: o.resume
1005
- }, async (result, id) => {
1006
- const { output, run } = result.value;
1007
- const fields = basis(output.basis);
1008
- return compact({
1009
- continuationId: run.interaction_id,
1010
- fields,
1011
- id,
1012
- meta: taskMeta(result),
1013
- output: await checkOutput(o.schema, output.content, { provider }),
1014
- raw: result.original,
1015
- sources: citedBy(fields),
1016
- status: "completed"
1017
- });
1018
- });
1019
- },
1020
- async search(query, options) {
1021
- const { call, rest: o } = callSettings(options);
1022
- const response = await raw.request("POST", "/v1/search", {
1023
- ...call,
1024
- body: compact({
1025
- advanced_settings: nonEmpty({
1026
- excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
1027
- fetch_policy: fetchPolicy(o.maxAge),
1028
- location: o.country,
1029
- max_results: o.limit,
1030
- source_policy: sourcePolicy(o)
1031
- }),
1032
- max_chars_total: o.maxCharsTotal,
1033
- mode: o.mode,
1034
- objective: o.objective ?? query,
1035
- search_queries: o.queries ?? [query],
1036
- session_id: o.sessionId
1037
- })
1038
- });
1039
- const body = z.parse(SearchResponse, response);
1040
- return compact({
1041
- meta: meta({
1042
- requestId: body.search_id,
1043
- units: usageUnits(body.usage),
1044
- warnings: body.warnings
1045
- }),
1046
- raw: response,
1047
- results: body.results.map((result) => compact({
1048
- publishedAt: result.publish_date,
1049
- snippet: result.excerpts.length > 0 ? result.excerpts.join(" … ") : void 0,
1050
- title: result.title,
1051
- url: result.url ?? ""
1052
- }))
1053
- });
1054
- }
1055
- },
1096
+ operations,
1056
1097
  raw
1057
1098
  });
1058
1099
  };