@howells/fieldwork-sdk 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -31
- package/dist/{adapter-CDY8qczv.d.ts → adapter-BgdfLBs-.d.ts} +85 -3
- package/dist/adapter-DWYJys20.js +8 -0
- package/dist/brave.d.ts +6 -1
- package/dist/brave.js +34 -14
- package/dist/browserbase.d.ts +8 -4
- package/dist/browserbase.js +16 -14
- package/dist/document-Dpj01mGx.js +51 -0
- package/dist/{errors-BiIBG9zN.js → errors-Yvk42oZH.js} +3 -1
- package/dist/exa.d.ts +7 -2
- package/dist/exa.js +31 -24
- package/dist/{fieldwork-DTNVIOzp.d.ts → fieldwork-CXNIcqSN.d.ts} +7 -1
- package/dist/firecrawl.d.ts +7 -2
- package/dist/firecrawl.js +114 -74
- package/dist/index.d.ts +5 -4
- package/dist/index.js +10 -4
- package/dist/llamaparse.d.ts +58 -0
- package/dist/llamaparse.js +286 -0
- package/dist/parallel.d.ts +7 -2
- package/dist/parallel.js +46 -40
- package/dist/{parse-CxOri73y.js → parse-D4SMt-Ip.js} +99 -30
- package/dist/perplexity.d.ts +16 -11
- package/dist/perplexity.js +145 -142
- package/dist/reducto.d.ts +31 -0
- package/dist/reducto.js +220 -0
- package/dist/{schema-EZlBkY5B.d.ts → schema-Cupy7-7q.d.ts} +1 -1
- package/dist/{schema-teOy7Od-.js → schema-DbSIABP0.js} +1 -1
- package/dist/serpapi.d.ts +6 -1
- package/dist/serpapi.js +17 -13
- package/dist/tavily.d.ts +7 -2
- package/dist/tavily.js +28 -24
- package/dist/tools.d.ts +5 -2
- package/dist/tools.js +62 -12
- package/package.json +14 -2
- package/dist/adapter-CEAQuT7F.js +0 -3
package/dist/parallel.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import { t as defineAdapter } from "./adapter-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { n as jsonSchemaOf, t as checkOutput } from "./schema-
|
|
1
|
+
import { t as defineAdapter } from "./adapter-DWYJys20.js";
|
|
2
|
+
import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
|
|
3
|
+
import { A as citationsOf, B as uniqueCitations, C as createRawClient, D as segment, E as requireKey, N as meta, O as callSettings, P as parseJson, R as refuseTogether, S as withOriginal, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as compact, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, v as recordOf, w as poll, x as warnings, y as sourceShape, z as requireJobId } from "./parse-D4SMt-Ip.js";
|
|
4
|
+
import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
|
|
5
5
|
import * as z from "zod/mini";
|
|
6
6
|
// src/adapters/parallel/parse.ts
|
|
7
7
|
const provider = "parallel";
|
|
8
|
-
const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
|
|
9
8
|
const nonEmpty = (value) => {
|
|
10
9
|
const result = compact(value);
|
|
11
10
|
return Object.keys(result).length > 0 ? result : void 0;
|
|
@@ -186,7 +185,7 @@ const sourcePolicy = (o) => {
|
|
|
186
185
|
});
|
|
187
186
|
};
|
|
188
187
|
const fetchPolicy = (maxAge) => {
|
|
189
|
-
if (maxAge !== void 0 && maxAge < 600) throw
|
|
188
|
+
if (maxAge !== void 0 && maxAge < 600) throw invalidRequest(provider, `cannot use a cached copy younger than 600 seconds (maxAge was ${maxAge}); it has no setting that always fetches fresh`);
|
|
190
189
|
return maxAge === void 0 ? void 0 : { max_age_seconds: Math.ceil(maxAge) };
|
|
191
190
|
};
|
|
192
191
|
const jsonOutput = (schema) => ({
|
|
@@ -200,7 +199,7 @@ const decisionQuestion = (name, question) => {
|
|
|
200
199
|
};
|
|
201
200
|
if (question.type === "choice") {
|
|
202
201
|
const choices = [...new Set(question.choices)];
|
|
203
|
-
if (choices.length < 2 || choices.length > 255) throw
|
|
202
|
+
if (choices.length < 2 || choices.length > 255) throw invalidRequest(provider, `decisions take 2 to 255 distinct choices; question "${name}" has ${choices.length}`);
|
|
204
203
|
return {
|
|
205
204
|
criteria: Object.fromEntries(choices.map((choice) => [choice, choice])),
|
|
206
205
|
instructions: question.question,
|
|
@@ -209,14 +208,14 @@ const decisionQuestion = (name, question) => {
|
|
|
209
208
|
}
|
|
210
209
|
if (question.type === "score") {
|
|
211
210
|
const levels = Object.values(question.scale);
|
|
212
|
-
if (levels.length < 2 || levels.length > 10) throw
|
|
211
|
+
if (levels.length < 2 || levels.length > 10) throw invalidRequest(provider, `decisions take a score scale of 2 to 10 levels; question "${name}" has ${levels.length}`);
|
|
213
212
|
return {
|
|
214
213
|
criteria: levels,
|
|
215
214
|
instructions: question.question,
|
|
216
215
|
type: "score"
|
|
217
216
|
};
|
|
218
217
|
}
|
|
219
|
-
throw
|
|
218
|
+
throw invalidRequest(provider, `does not know the question type "${String(question.type)}" for "${name}"`);
|
|
220
219
|
};
|
|
221
220
|
const NAMED_FREQUENCY = {
|
|
222
221
|
day: "1d",
|
|
@@ -224,13 +223,13 @@ const NAMED_FREQUENCY = {
|
|
|
224
223
|
week: "1w"
|
|
225
224
|
};
|
|
226
225
|
const frequency = (schedule) => {
|
|
227
|
-
if ("cron" in schedule) throw
|
|
226
|
+
if ("cron" in schedule) throw invalidRequest(provider, "monitors run at a fixed interval from 1 hour to 30 days and cannot follow a cron expression; pass { every: ... }");
|
|
228
227
|
const named = Object.entries(NAMED_FREQUENCY).find(([name]) => name === schedule.every)?.[1];
|
|
229
228
|
if (named) return named;
|
|
230
229
|
const match = /^(?<count>\d+)(?<unit>[hd])$/u.exec(schedule.every);
|
|
231
230
|
const count = Number(match?.groups?.count);
|
|
232
231
|
const limit = match?.groups?.unit === "h" ? 720 : 30;
|
|
233
|
-
if (!match || count < 1 || count > limit) throw
|
|
232
|
+
if (!match || count < 1 || count > limit) throw invalidRequest(provider, `monitors run every 1 hour to 30 days; "${schedule.every}" is outside that`);
|
|
234
233
|
return schedule.every;
|
|
235
234
|
};
|
|
236
235
|
const extractBody = (urls, o) => compact({
|
|
@@ -447,12 +446,12 @@ const stoppedRun = (id, entry) => {
|
|
|
447
446
|
provider
|
|
448
447
|
});
|
|
449
448
|
};
|
|
450
|
-
const taskResult = async (raw, id,
|
|
449
|
+
const taskResult = async (raw, id, request) => {
|
|
451
450
|
try {
|
|
452
|
-
return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${id}/result`,
|
|
451
|
+
return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${segment(id)}/result`, request));
|
|
453
452
|
} catch (error) {
|
|
454
453
|
if (error instanceof FieldworkError && error.code === "NotFound") {
|
|
455
|
-
const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${id}`,
|
|
454
|
+
const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
|
|
456
455
|
if (run.value.status === "failed" || run.value.status === "cancelled") throw stoppedRun(id, run);
|
|
457
456
|
}
|
|
458
457
|
throw error;
|
|
@@ -461,18 +460,17 @@ const taskResult = async (raw, id, signal) => {
|
|
|
461
460
|
const runTask = async (raw, body, settings) => {
|
|
462
461
|
const { resume, ...wait } = settings;
|
|
463
462
|
const id = resume ?? requireJobId(raw.provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
|
|
463
|
+
...wait,
|
|
464
464
|
body,
|
|
465
|
-
creates: true
|
|
466
|
-
signal: wait.signal,
|
|
467
|
-
timeout: wait.timeout
|
|
465
|
+
creates: true
|
|
468
466
|
})).run_id);
|
|
469
467
|
return {
|
|
470
468
|
id,
|
|
471
|
-
result: await poll(raw.provider, id, async () => {
|
|
472
|
-
const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${id}`,
|
|
469
|
+
result: await poll(raw.provider, id, async (request) => {
|
|
470
|
+
const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
|
|
473
471
|
const { status } = run.value;
|
|
474
472
|
if (status === "failed" || status === "cancelled" || status === "action_required") throw stoppedRun(id, run);
|
|
475
|
-
return status === "completed" ? await taskResult(raw, id,
|
|
473
|
+
return status === "completed" ? await taskResult(raw, id, request) : void 0;
|
|
476
474
|
}, wait)
|
|
477
475
|
};
|
|
478
476
|
};
|
|
@@ -495,13 +493,13 @@ const startFindAll = async (raw, objective, o, call) => {
|
|
|
495
493
|
}));
|
|
496
494
|
const id = requireJobId(provider, created.findall_id);
|
|
497
495
|
if (o.schema) try {
|
|
498
|
-
await raw.request("POST", `/v1beta/findall/runs/${id}/enrich`, {
|
|
496
|
+
await raw.request("POST", `/v1beta/findall/runs/${segment(id)}/enrich`, {
|
|
497
|
+
...call,
|
|
499
498
|
body: compact({
|
|
500
499
|
output_schema: jsonOutput(o.schema),
|
|
501
500
|
processor: o.processor
|
|
502
501
|
}),
|
|
503
|
-
creates: true
|
|
504
|
-
signal: call.signal
|
|
502
|
+
creates: true
|
|
505
503
|
});
|
|
506
504
|
} catch (error) {
|
|
507
505
|
throw withJob(error, id);
|
|
@@ -509,17 +507,22 @@ const startFindAll = async (raw, objective, o, call) => {
|
|
|
509
507
|
return id;
|
|
510
508
|
};
|
|
511
509
|
/** The result of a FindAll run once it has stopped, or undefined while it runs. */
|
|
512
|
-
const findAllResult = async (raw, id,
|
|
513
|
-
const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${id}`,
|
|
510
|
+
const findAllResult = async (raw, id, request) => {
|
|
511
|
+
const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}`, request));
|
|
514
512
|
const { status } = run.value.status;
|
|
515
513
|
if (status === "action_required") throw new FieldworkError("JobFailed", `parallel FindAll run ${id} stopped with status action_required: it is waiting for an action Fieldwork cannot take, so it will not finish on its own. Open the run in the Parallel console to see what it needs`, {
|
|
516
514
|
cause: run.original,
|
|
517
515
|
jobId: id,
|
|
518
516
|
provider
|
|
519
517
|
});
|
|
520
|
-
return status === "completed" || status === "failed" || status === "cancelled" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${id}/result`,
|
|
518
|
+
return status === "completed" || status === "failed" || status === "cancelled" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
|
|
521
519
|
};
|
|
522
520
|
// src/adapters/parallel.ts
|
|
521
|
+
/**
|
|
522
|
+
* An adapter for Parallel: search, images, read, readMany, extract, answer, research, discover, decide and monitor. Pass it to `new Fieldwork({ adapter })`.
|
|
523
|
+
*
|
|
524
|
+
* Throws `Unauthorized` when neither `apiKey` nor `PARALLEL_API_KEY` is set.
|
|
525
|
+
*/
|
|
523
526
|
const parallel = (config = {}) => {
|
|
524
527
|
const raw = createRawClient({
|
|
525
528
|
baseUrl: config.baseUrl ?? "https://api.parallel.ai",
|
|
@@ -593,9 +596,9 @@ const parallel = (config = {}) => {
|
|
|
593
596
|
const { call, rest: o } = callSettings(options);
|
|
594
597
|
const entries = Object.entries(questions);
|
|
595
598
|
const names = entries.map(([name]) => name);
|
|
596
|
-
if (names.length < 1 || names.length > 100) throw
|
|
599
|
+
if (names.length < 1 || names.length > 100) throw invalidRequest(provider, `decisions take 1 to 100 questions; got ${names.length}`);
|
|
597
600
|
const badName = names.find((name) => !QUESTION_NAME.test(name));
|
|
598
|
-
if (badName !== void 0) throw
|
|
601
|
+
if (badName !== void 0) throw invalidRequest(provider, `question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
|
|
599
602
|
const response = await raw.request("POST", "/v1/decisions", {
|
|
600
603
|
...call,
|
|
601
604
|
body: compact({
|
|
@@ -626,7 +629,7 @@ const parallel = (config = {}) => {
|
|
|
626
629
|
async discover(objective, options) {
|
|
627
630
|
const { call, rest: o } = callSettings(options);
|
|
628
631
|
const id = o.resume ?? await startFindAll(raw, objective, o, call);
|
|
629
|
-
const result = await poll(provider, id, async () => await findAllResult(raw, id,
|
|
632
|
+
const result = await poll(provider, id, async (request) => await findAllResult(raw, id, request), {
|
|
630
633
|
...call,
|
|
631
634
|
interval: o.interval
|
|
632
635
|
});
|
|
@@ -710,8 +713,8 @@ const parallel = (config = {}) => {
|
|
|
710
713
|
monitor: {
|
|
711
714
|
async create(options) {
|
|
712
715
|
const { call, rest: o } = callSettings(options);
|
|
713
|
-
if (Object.entries(o).some(([name, value]) => name === "urls" && value !== void 0)) throw
|
|
714
|
-
if (o.taskRunId === void 0 && o.query === void 0) throw
|
|
716
|
+
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");
|
|
717
|
+
if (o.taskRunId === void 0 && o.query === void 0) throw invalidRequest(provider, "a parallel monitor needs a query or a taskRunId");
|
|
715
718
|
if (o.taskRunId !== void 0) for (const name of [
|
|
716
719
|
"query",
|
|
717
720
|
"schema",
|
|
@@ -721,7 +724,7 @@ const parallel = (config = {}) => {
|
|
|
721
724
|
"excludeDomains",
|
|
722
725
|
"publishedAfter"
|
|
723
726
|
]) refuseTogether(provider, o, "taskRunId", name);
|
|
724
|
-
if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw
|
|
727
|
+
if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw invalidRequest(provider, "webhookEvents needs a webhookUrl");
|
|
725
728
|
const response = await raw.request("POST", "/v1/monitors", {
|
|
726
729
|
creates: true,
|
|
727
730
|
...call,
|
|
@@ -748,11 +751,11 @@ const parallel = (config = {}) => {
|
|
|
748
751
|
return monitorInfo(z.parse(MonitorEntry, response));
|
|
749
752
|
},
|
|
750
753
|
async delete(id, options) {
|
|
751
|
-
await raw.request("POST", `/v1/monitors/${
|
|
754
|
+
await raw.request("POST", `/v1/monitors/${segment(id)}/cancel`, options);
|
|
752
755
|
},
|
|
753
756
|
async events(id, options) {
|
|
754
757
|
const { call, rest: o } = callSettings(options);
|
|
755
|
-
const response = await raw.request("GET", `/v1/monitors/${
|
|
758
|
+
const response = await raw.request("GET", `/v1/monitors/${segment(id)}/events`, {
|
|
756
759
|
...call,
|
|
757
760
|
query: {
|
|
758
761
|
cursor: o.cursor,
|
|
@@ -769,14 +772,16 @@ const parallel = (config = {}) => {
|
|
|
769
772
|
});
|
|
770
773
|
},
|
|
771
774
|
async get(id, options) {
|
|
772
|
-
return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${
|
|
775
|
+
return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${segment(id)}`, options)));
|
|
773
776
|
},
|
|
774
777
|
async list(options) {
|
|
778
|
+
const { call } = callSettings(options);
|
|
775
779
|
const monitors = [];
|
|
780
|
+
const seen = /* @__PURE__ */ new Set();
|
|
776
781
|
let cursor;
|
|
777
|
-
|
|
782
|
+
for (;;) {
|
|
778
783
|
const page = z.parse(MonitorsPage, await raw.request("GET", "/v1/monitors", {
|
|
779
|
-
...
|
|
784
|
+
...call,
|
|
780
785
|
query: {
|
|
781
786
|
cursor,
|
|
782
787
|
limit: 100
|
|
@@ -784,8 +789,9 @@ const parallel = (config = {}) => {
|
|
|
784
789
|
}));
|
|
785
790
|
monitors.push(...page.monitors.map((entry) => monitorInfo(entry)));
|
|
786
791
|
cursor = page.next_cursor;
|
|
787
|
-
|
|
788
|
-
|
|
792
|
+
if (cursor === void 0 || seen.has(cursor)) return monitors;
|
|
793
|
+
seen.add(cursor);
|
|
794
|
+
}
|
|
789
795
|
}
|
|
790
796
|
},
|
|
791
797
|
async read(url, options) {
|
|
@@ -810,7 +816,7 @@ const parallel = (config = {}) => {
|
|
|
810
816
|
},
|
|
811
817
|
async readMany(urls, options) {
|
|
812
818
|
const { call, rest: o } = callSettings(options);
|
|
813
|
-
if (urls.length > 20) throw
|
|
819
|
+
if (urls.length > 20) throw invalidRequest(provider, `reads up to 20 URLs in one call; got ${urls.length}`);
|
|
814
820
|
const response = await raw.request("POST", "/v1/extract", {
|
|
815
821
|
...call,
|
|
816
822
|
body: extractBody(urls, o)
|
|
@@ -1,15 +1,26 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as withJob, n as codeForStatus, t as FieldworkError } from "./errors-Yvk42oZH.js";
|
|
2
2
|
import * as z from "zod/mini";
|
|
3
3
|
// src/util.ts
|
|
4
4
|
const isJson = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
5
|
const record = (value) => isJson(value) ? value : {};
|
|
6
6
|
const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Splits an operation's options into the provider's own and the call's
|
|
9
|
+
* settings. The call's `signal` also carries its `timeout` as a deadline, set
|
|
10
|
+
* now, so every request the operation makes (a start, each poll, a result
|
|
11
|
+
* download) shares one budget instead of restarting it. An empty `resume`
|
|
12
|
+
* names no job, so it is refused here, once for every adapter.
|
|
13
|
+
*
|
|
14
|
+
* `grace` extends the deadline past `timeout` for an operation that sends the
|
|
15
|
+
* timeout to the provider and needs a moment more to hear its report.
|
|
16
|
+
*/
|
|
17
|
+
const callSettings = (options, grace = 0) => {
|
|
8
18
|
const { retries, signal, timeout, ...rest } = options ?? {};
|
|
19
|
+
if ("resume" in rest && rest.resume === "") throw new FieldworkError("InvalidRequest", "resume is empty: pass the jobId an earlier call returned, or leave resume out to start a job");
|
|
9
20
|
return {
|
|
10
21
|
call: {
|
|
11
22
|
retries,
|
|
12
|
-
signal,
|
|
23
|
+
signal: timeout === void 0 ? signal : AbortSignal.any([...signal === void 0 ? [] : [signal], AbortSignal.timeout(timeout + grace)]),
|
|
13
24
|
timeout
|
|
14
25
|
},
|
|
15
26
|
rest
|
|
@@ -107,7 +118,7 @@ const FIRST_RETRY_WAIT = 500;
|
|
|
107
118
|
* timed out, the failure would recur, or the request created something.
|
|
108
119
|
*/
|
|
109
120
|
const retryDelay = (error, state) => {
|
|
110
|
-
if (state.count >= state.retries || state.signal?.aborted === true || !error.retryable || error.code === "Timeout" || state.creates && error.code !== "RateLimited") return;
|
|
121
|
+
if (state.count >= state.retries || state.signal?.aborted === true || !error.retryable || error.code === "Timeout" && error.status === void 0 || state.creates && error.code !== "RateLimited") return;
|
|
111
122
|
if (error.retryAfter !== void 0) {
|
|
112
123
|
const asked = error.retryAfter * 1e3;
|
|
113
124
|
return asked > MAX_RETRY_WAIT ? void 0 : asked;
|
|
@@ -115,6 +126,37 @@ const retryDelay = (error, state) => {
|
|
|
115
126
|
const ceiling = Math.min(MAX_RETRY_WAIT, FIRST_RETRY_WAIT * 2 ** state.count);
|
|
116
127
|
return ceiling / 2 + Math.random() * (ceiling / 2);
|
|
117
128
|
};
|
|
129
|
+
/** Whether a stopped signal's deadline ran out, rather than its caller cancelling. */
|
|
130
|
+
const timedOut = (signal) => signal.reason instanceof DOMException && signal.reason.name === "TimeoutError";
|
|
131
|
+
/**
|
|
132
|
+
* The error for a call its signal stopped: `Timeout` when the signal's
|
|
133
|
+
* deadline ran out (a call's `timeout` is a deadline signal across all its
|
|
134
|
+
* requests), `Aborted` when the caller cancelled.
|
|
135
|
+
*/
|
|
136
|
+
const stopped = (signal, message, options) => new FieldworkError(timedOut(signal) ? "Timeout" : "Aborted", message, options);
|
|
137
|
+
const transportError = (provider, error, signal) => {
|
|
138
|
+
if (signal?.aborted === true) return stopped(signal, `${provider} request stopped: ${timedOut(signal) ? "timed out" : "cancelled"}`, {
|
|
139
|
+
cause: error,
|
|
140
|
+
provider
|
|
141
|
+
});
|
|
142
|
+
if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
|
|
143
|
+
cause: error,
|
|
144
|
+
provider
|
|
145
|
+
});
|
|
146
|
+
return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
|
|
147
|
+
cause: error,
|
|
148
|
+
provider,
|
|
149
|
+
retryable: true
|
|
150
|
+
});
|
|
151
|
+
};
|
|
152
|
+
/** A response's body; a connection lost while it streams is a transport error like any other. */
|
|
153
|
+
const readText = async (provider, response, signal) => {
|
|
154
|
+
try {
|
|
155
|
+
return await response.text();
|
|
156
|
+
} catch (error) {
|
|
157
|
+
throw transportError(provider, error, signal);
|
|
158
|
+
}
|
|
159
|
+
};
|
|
118
160
|
const createRawClient = (config) => {
|
|
119
161
|
const doFetch = config.fetch ?? globalThis.fetch;
|
|
120
162
|
return {
|
|
@@ -153,9 +195,17 @@ const createRawClient = (config) => {
|
|
|
153
195
|
method,
|
|
154
196
|
url
|
|
155
197
|
});
|
|
156
|
-
const text = await response
|
|
157
|
-
const
|
|
158
|
-
|
|
198
|
+
const text = await readText(config.provider, response, signal);
|
|
199
|
+
const json = jsonOf(text);
|
|
200
|
+
const parsed = json === void 0 ? text : json.value;
|
|
201
|
+
if (response.ok) {
|
|
202
|
+
if (options.text !== true && json === void 0) throw new FieldworkError("ProviderError", `${config.provider} ${method} ${path} returned ${response.status} with a body that is not JSON: ${text.slice(0, 300)}`, {
|
|
203
|
+
cause: text,
|
|
204
|
+
provider: config.provider,
|
|
205
|
+
status: response.status
|
|
206
|
+
});
|
|
207
|
+
return options.text === true ? text : parsed;
|
|
208
|
+
}
|
|
159
209
|
throw new FieldworkError(codeForStatus(response.status), `${config.provider} ${method} ${path} returned ${response.status}: ${describe(parsed, text)}`, {
|
|
160
210
|
cause: parsed,
|
|
161
211
|
provider: config.provider,
|
|
@@ -178,7 +228,7 @@ const createRawClient = (config) => {
|
|
|
178
228
|
});
|
|
179
229
|
if (wait === void 0 || deadline !== void 0 && Date.now() + wait >= deadline) throw error;
|
|
180
230
|
await sleep(wait, signal);
|
|
181
|
-
if (options.signal?.aborted === true) throw
|
|
231
|
+
if (options.signal?.aborted === true) throw stopped(options.signal, `${config.provider} request stopped while waiting to retry`, {
|
|
182
232
|
cause: error,
|
|
183
233
|
provider: config.provider
|
|
184
234
|
});
|
|
@@ -229,27 +279,13 @@ const combineSignals = (signal, timeout) => {
|
|
|
229
279
|
const signals = [signal, timeout === void 0 ? void 0 : AbortSignal.timeout(timeout)].filter((value) => value !== void 0);
|
|
230
280
|
return signals.length <= 1 ? signals[0] : AbortSignal.any(signals);
|
|
231
281
|
};
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
provider
|
|
236
|
-
});
|
|
237
|
-
if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
|
|
238
|
-
cause: error,
|
|
239
|
-
provider
|
|
240
|
-
});
|
|
241
|
-
return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
|
|
242
|
-
cause: error,
|
|
243
|
-
provider,
|
|
244
|
-
retryable: true
|
|
245
|
-
});
|
|
246
|
-
};
|
|
247
|
-
const parseBody = (text) => {
|
|
248
|
-
if (text === "") return;
|
|
282
|
+
/** The body's JSON, or undefined when the body is not JSON. An empty body is JSON with no value. */
|
|
283
|
+
const jsonOf = (text) => {
|
|
284
|
+
if (text === "") return { value: void 0 };
|
|
249
285
|
try {
|
|
250
|
-
return JSON.parse(text);
|
|
286
|
+
return { value: JSON.parse(text) };
|
|
251
287
|
} catch {
|
|
252
|
-
return
|
|
288
|
+
return;
|
|
253
289
|
}
|
|
254
290
|
};
|
|
255
291
|
const describe = (parsed, text) => {
|
|
@@ -272,17 +308,27 @@ const retryAfterSeconds = (header, now = Date.now()) => {
|
|
|
272
308
|
const date = Date.parse(header);
|
|
273
309
|
return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
|
|
274
310
|
};
|
|
311
|
+
/**
|
|
312
|
+
* Checks a job until `check` returns its result. Each check is given the
|
|
313
|
+
* settings for its request: the call's signal, which carries the call's whole
|
|
314
|
+
* deadline, and its retries. A check that throws, a cancellation and a
|
|
315
|
+
* timeout all surface with `jobId`, so the caller can resume the job.
|
|
316
|
+
*/
|
|
275
317
|
const poll = async (provider, jobId, check, options = {}) => {
|
|
276
318
|
const interval = options.interval ?? 2e3;
|
|
277
319
|
const deadline = Date.now() + (options.timeout ?? 6e5);
|
|
320
|
+
const request = {
|
|
321
|
+
retries: options.retries,
|
|
322
|
+
signal: options.signal
|
|
323
|
+
};
|
|
278
324
|
for (;;) {
|
|
279
|
-
if (options.signal?.aborted === true) throw
|
|
325
|
+
if (options.signal?.aborted === true) throw stopped(options.signal, `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
|
|
280
326
|
jobId,
|
|
281
327
|
provider
|
|
282
328
|
});
|
|
283
329
|
let value;
|
|
284
330
|
try {
|
|
285
|
-
value = await check();
|
|
331
|
+
value = await check(request);
|
|
286
332
|
} catch (error) {
|
|
287
333
|
throw withJob(error, jobId);
|
|
288
334
|
}
|
|
@@ -294,11 +340,34 @@ const poll = async (provider, jobId, check, options = {}) => {
|
|
|
294
340
|
await sleep(interval, options.signal);
|
|
295
341
|
}
|
|
296
342
|
};
|
|
343
|
+
/** An id as one path segment, so a caller's `resume` cannot reach another endpoint. */
|
|
344
|
+
const segment = (id) => encodeURIComponent(id);
|
|
297
345
|
const requireKey = (provider, given, envName) => {
|
|
298
346
|
const key = given ?? process.env[envName];
|
|
299
347
|
if (key === void 0 || key === "") throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
|
|
300
348
|
return key;
|
|
301
349
|
};
|
|
350
|
+
/**
|
|
351
|
+
* Fetches a presigned URL a provider returned, such as a large result on
|
|
352
|
+
* storage, and returns its body as text. Nothing of the provider's client is
|
|
353
|
+
* sent with it: the URL carries its own authorization, and the key must not
|
|
354
|
+
* reach another host.
|
|
355
|
+
*/
|
|
356
|
+
const readSigned = async (provider, url, options) => {
|
|
357
|
+
const doFetch = options.fetch ?? globalThis.fetch;
|
|
358
|
+
let response;
|
|
359
|
+
try {
|
|
360
|
+
response = await doFetch(url, { signal: options.signal });
|
|
361
|
+
} catch (error) {
|
|
362
|
+
throw transportError(provider, error, options.signal);
|
|
363
|
+
}
|
|
364
|
+
const text = await readText(provider, response, options.signal);
|
|
365
|
+
if (!response.ok) throw new FieldworkError(codeForStatus(response.status), `${provider} result at ${new URL(url).origin} returned ${response.status}: ${text.slice(0, 300)}`, {
|
|
366
|
+
provider,
|
|
367
|
+
status: response.status
|
|
368
|
+
});
|
|
369
|
+
return text;
|
|
370
|
+
};
|
|
302
371
|
// src/parse.ts
|
|
303
372
|
/**
|
|
304
373
|
* Building blocks for the schemas that parse a provider's response at the
|
|
@@ -438,4 +507,4 @@ const optionalArrayOf = (item) => z.optional(z.union([z.pipe(z.array(z.unknown()
|
|
|
438
507
|
const parsed = z.safeParse(item, entry);
|
|
439
508
|
return parsed.success ? [parsed.data] : [];
|
|
440
509
|
}))), absent]));
|
|
441
|
-
export {
|
|
510
|
+
export { citationsOf as A, uniqueCitations as B, createRawClient as C, segment as D, requireKey as E, presentPage as F, presentPages as I, record as L, hours as M, meta as N, callSettings as O, parseJson as P, refuseTogether as R, withOriginal as S, readSigned as T, optionalStructure as _, looseObject as a, warningEntry as b, optionalArrayOf as c, optionalId as d, optionalNumber as f, optionalStringOrNumber as g, optionalString as h, both as i, compact as j, citationOf as k, optionalBoolean as l, optionalScalar as m, anything as n, nonEmptyString as o, optionalObject as p, arrayOf as r, optionalAnyString as s, Source as t, optionalFirstString as u, recordOf as v, poll as w, warnings as x, sourceShape as y, requireJobId as z };
|
package/dist/perplexity.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as OutputSchema } from "./schema-
|
|
3
|
-
|
|
1
|
+
import { K as Recency, Y as SearchResponse, a as RawClient, b as Decisions, l as Answer, p as CallOptions, q as Research, t as Adapter, y as DecisionQuestion } from "./adapter-BgdfLBs-.js";
|
|
2
|
+
import { t as OutputSchema } from "./schema-Cupy7-7q.js";
|
|
3
|
+
interface PerplexityConfig {
|
|
4
4
|
/** Defaults to the PERPLEXITY_API_KEY environment variable. */
|
|
5
5
|
apiKey?: string;
|
|
6
6
|
baseUrl?: string;
|
|
@@ -24,7 +24,7 @@ interface PerplexityFilters {
|
|
|
24
24
|
lastUpdatedBefore?: string;
|
|
25
25
|
recency?: Recency;
|
|
26
26
|
}
|
|
27
|
-
|
|
27
|
+
interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
|
|
28
28
|
/** Results to return: up to 20, or up to 50 with `searchType: "people"`. */
|
|
29
29
|
limit?: number;
|
|
30
30
|
/**
|
|
@@ -45,7 +45,7 @@ export interface PerplexitySearchOptions extends CallOptions, PerplexityFilters
|
|
|
45
45
|
}
|
|
46
46
|
/** An effort level, or a name pinned to a version such as `fast@2026-10-16.0`. */
|
|
47
47
|
type Pinned<Name extends string> = Name | `${Name}@${string}`;
|
|
48
|
-
|
|
48
|
+
interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
|
|
49
49
|
/** Defaults to "fast". Answers are synchronous, so only the quicker levels are offered. */
|
|
50
50
|
effort?: Pinned<"fast" | "low" | "medium">;
|
|
51
51
|
instructions?: string;
|
|
@@ -58,8 +58,8 @@ export interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
|
|
|
58
58
|
* Perplexity's effort levels. The names change slowly, so the type is open:
|
|
59
59
|
* `ultra-preview` and version pins (`high@2026-10-28.0`) are accepted too.
|
|
60
60
|
*/
|
|
61
|
-
|
|
62
|
-
|
|
61
|
+
type PerplexityEffort = "fast" | "low" | "medium" | "high" | "xhigh" | "ultra-preview" | (string & {});
|
|
62
|
+
interface PerplexityResearchOptions<T = unknown> extends CallOptions, PerplexityFilters {
|
|
63
63
|
schema?: OutputSchema<T>;
|
|
64
64
|
/**
|
|
65
65
|
* The configuration to run: a model, tools, system prompt and step budget in
|
|
@@ -90,16 +90,21 @@ export interface PerplexityResearchOptions<T = unknown> extends CallOptions, Per
|
|
|
90
90
|
/** Milliseconds between checks. Defaults to 2000. */
|
|
91
91
|
interval?: number;
|
|
92
92
|
}
|
|
93
|
-
|
|
94
|
-
|
|
93
|
+
type PerplexityDeciderModel = "pplx-decider-v1.2" | "pplx-decider-flash-v1.2" | "pplx-decider-latest" | "pplx-decider-flash-latest" | (string & {});
|
|
94
|
+
interface PerplexityDecideOptions extends CallOptions {
|
|
95
95
|
/** Defaults to "pplx-decider-latest". The flash models are smaller and cheaper. */
|
|
96
96
|
model?: PerplexityDeciderModel;
|
|
97
97
|
}
|
|
98
|
-
|
|
98
|
+
interface PerplexityOperations {
|
|
99
99
|
search: (query: string, options?: PerplexitySearchOptions) => Promise<SearchResponse>;
|
|
100
100
|
answer: <T = unknown>(question: string, options?: PerplexityAnswerOptions<T>) => Promise<Answer<T>>;
|
|
101
101
|
research: <T = unknown>(question: string, options?: PerplexityResearchOptions<T>) => Promise<Research<T>>;
|
|
102
102
|
decide: (context: unknown, questions: Record<string, DecisionQuestion>, options?: PerplexityDecideOptions) => Promise<Decisions>;
|
|
103
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* An adapter for Perplexity: search, answer, research and decide. Pass it to `new Fieldwork({ adapter })`.
|
|
106
|
+
*
|
|
107
|
+
* Throws `Unauthorized` when neither `apiKey` nor `PERPLEXITY_API_KEY` is set.
|
|
108
|
+
*/
|
|
104
109
|
export declare const perplexity: (config?: PerplexityConfig) => Adapter<"perplexity", PerplexityOperations, RawClient>;
|
|
105
|
-
export {};
|
|
110
|
+
export type { PerplexityAnswerOptions, PerplexityConfig, PerplexityDecideOptions, PerplexityDeciderModel, PerplexityEffort, PerplexityOperations, PerplexityResearchOptions, PerplexitySearchOptions };
|