@howells/fieldwork-sdk 0.3.1 → 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 +66 -33
- package/dist/{adapter-DGehHCMo.d.ts → adapter-BgdfLBs-.d.ts} +101 -5
- package/dist/adapter-DWYJys20.js +8 -0
- package/dist/brave.d.ts +11 -4
- package/dist/brave.js +230 -127
- package/dist/browserbase.d.ts +15 -9
- package/dist/browserbase.js +97 -49
- package/dist/document-Dpj01mGx.js +51 -0
- package/dist/{errors-BiIBG9zN.js → errors-Yvk42oZH.js} +3 -1
- package/dist/exa.d.ts +28 -19
- package/dist/exa.js +324 -177
- package/dist/{fieldwork-B3x3cxDJ.d.ts → fieldwork-CXNIcqSN.d.ts} +9 -3
- package/dist/firecrawl.d.ts +33 -25
- package/dist/firecrawl.js +688 -364
- package/dist/index.d.ts +5 -3
- package/dist/index.js +33 -13
- package/dist/llamaparse.d.ts +58 -0
- package/dist/llamaparse.js +286 -0
- package/dist/parallel.d.ts +36 -26
- package/dist/parallel.js +440 -230
- package/dist/parse-D4SMt-Ip.js +510 -0
- package/dist/perplexity.d.ts +25 -16
- package/dist/perplexity.js +210 -139
- package/dist/reducto.d.ts +31 -0
- package/dist/reducto.js +220 -0
- package/dist/schema-Cupy7-7q.d.ts +90 -0
- package/dist/schema-DbSIABP0.js +45 -0
- package/dist/serpapi.d.ts +12 -4
- package/dist/serpapi.js +280 -174
- package/dist/tavily.d.ts +20 -12
- package/dist/tavily.js +209 -131
- package/dist/tools.d.ts +5 -2
- package/dist/tools.js +62 -12
- package/dist/util-DhYr1OS3.d.ts +1 -0
- package/package.json +17 -2
- package/dist/adapter-CEAQuT7F.js +0 -3
- package/dist/util-YaZYZDSk.js +0 -287
package/dist/parallel.js
CHANGED
|
@@ -1,47 +1,41 @@
|
|
|
1
|
-
import { t as defineAdapter } from "./adapter-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
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
|
+
import * as z from "zod/mini";
|
|
4
6
|
// src/adapters/parallel/parse.ts
|
|
5
7
|
const provider = "parallel";
|
|
6
|
-
const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
|
|
7
8
|
const nonEmpty = (value) => {
|
|
8
9
|
const result = compact(value);
|
|
9
10
|
return Object.keys(result).length > 0 ? result : void 0;
|
|
10
11
|
};
|
|
11
|
-
const usageUnits = (
|
|
12
|
+
const usageUnits = (entries) => {
|
|
12
13
|
const units = /* @__PURE__ */ new Map();
|
|
13
|
-
for (const
|
|
14
|
-
const entry = record(item);
|
|
15
|
-
const name = text(entry.name);
|
|
16
|
-
const count = num(entry.count);
|
|
17
|
-
if (name && count !== void 0) units.set(name, (units.get(name) ?? 0) + count);
|
|
18
|
-
}
|
|
14
|
+
for (const { count, name } of entries) if (name !== void 0 && count !== void 0) units.set(name, (units.get(name) ?? 0) + count);
|
|
19
15
|
return Object.fromEntries(units);
|
|
20
16
|
};
|
|
21
|
-
const basis = (entries) =>
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
reasoning: text(entry.reasoning)
|
|
28
|
-
});
|
|
29
|
-
});
|
|
17
|
+
const basis = (entries) => entries.map((entry) => compact({
|
|
18
|
+
citations: citationsOf(entry.citations),
|
|
19
|
+
confidence: entry.confidence,
|
|
20
|
+
field: entry.field ?? "",
|
|
21
|
+
reasoning: entry.reasoning
|
|
22
|
+
}));
|
|
30
23
|
const citedBy = (fields) => uniqueCitations(fields.flatMap((field) => field.citations));
|
|
31
24
|
const taskMeta = (result) => {
|
|
32
|
-
const run =
|
|
25
|
+
const { run } = result.value;
|
|
33
26
|
return meta({
|
|
34
27
|
requestId: run.run_id,
|
|
35
28
|
warnings: run.warnings
|
|
36
29
|
});
|
|
37
30
|
};
|
|
38
|
-
|
|
39
|
-
|
|
31
|
+
/** The messages of a response; only the final answer's when it marks one. */
|
|
32
|
+
const responseMessages = (body) => {
|
|
33
|
+
const messages = body.output.filter((item) => item.type === "message");
|
|
40
34
|
const final = messages.filter((item) => item.phase === "final_answer");
|
|
41
35
|
return final.length > 0 ? final : messages;
|
|
42
36
|
};
|
|
43
|
-
const probabilities = (
|
|
44
|
-
const entries = Object.entries(
|
|
37
|
+
const probabilities = (chances) => {
|
|
38
|
+
const entries = Object.entries(chances).filter((entry) => entry[1] !== void 0);
|
|
45
39
|
return entries.length > 0 ? Object.fromEntries(entries) : void 0;
|
|
46
40
|
};
|
|
47
41
|
const mostLikely = (chances) => {
|
|
@@ -49,13 +43,12 @@ const mostLikely = (chances) => {
|
|
|
49
43
|
for (const [key, chance] of Object.entries(chances ?? {})) if (best === void 0 || chance > (chances?.[best] ?? 0)) best = key;
|
|
50
44
|
return best;
|
|
51
45
|
};
|
|
52
|
-
const decisionAnswer = (question,
|
|
53
|
-
const answer = record(value);
|
|
46
|
+
const decisionAnswer = (question, answer) => {
|
|
54
47
|
if (answer.type === "refusal") return { refusal: "Parallel declined to answer this question" };
|
|
55
|
-
const confidence =
|
|
56
|
-
if (question.type === "yesno") return compact({ probability:
|
|
48
|
+
const { confidence } = answer;
|
|
49
|
+
if (question.type === "yesno") return compact({ probability: answer.noul });
|
|
57
50
|
if (question.type === "choice") return compact({
|
|
58
|
-
choice:
|
|
51
|
+
choice: answer.choice,
|
|
59
52
|
confidence,
|
|
60
53
|
probabilities: probabilities(answer.probabilities)
|
|
61
54
|
});
|
|
@@ -70,15 +63,11 @@ const decisionAnswer = (question, value) => {
|
|
|
70
63
|
};
|
|
71
64
|
/** Termination reasons that mean the run found everything it could. */
|
|
72
65
|
const FINISHED = /* @__PURE__ */ new Set(["match_limit_met", "candidates_exhausted"]);
|
|
73
|
-
const candidate = (
|
|
74
|
-
const
|
|
75
|
-
const status = text(item.match_status);
|
|
66
|
+
const candidate = (item) => {
|
|
67
|
+
const status = item.match_status;
|
|
76
68
|
if (status === "discarded") return;
|
|
77
69
|
const data = {};
|
|
78
|
-
for (const [key, output] of Object.entries(
|
|
79
|
-
const entry = record(output);
|
|
80
|
-
if (entry.type === "enrichment") data[key] = entry.value;
|
|
81
|
-
}
|
|
70
|
+
for (const [key, output] of Object.entries(item.output)) if (output.type === "enrichment") data[key] = output.value;
|
|
82
71
|
const fields = basis(item.basis);
|
|
83
72
|
const sources = citedBy(fields);
|
|
84
73
|
let matched;
|
|
@@ -87,82 +76,85 @@ const candidate = (value) => {
|
|
|
87
76
|
return compact({
|
|
88
77
|
citations: sources.length > 0 ? sources : void 0,
|
|
89
78
|
data: nonEmpty(data),
|
|
90
|
-
description:
|
|
79
|
+
description: item.description,
|
|
91
80
|
fields: fields.length > 0 ? fields : void 0,
|
|
92
81
|
matched,
|
|
93
|
-
name:
|
|
94
|
-
url:
|
|
82
|
+
name: item.name ?? "",
|
|
83
|
+
url: item.url
|
|
95
84
|
});
|
|
96
85
|
};
|
|
97
|
-
const monitorInfo = (
|
|
98
|
-
const monitor =
|
|
86
|
+
const monitorInfo = (entry) => {
|
|
87
|
+
const monitor = entry.value;
|
|
99
88
|
return compact({
|
|
100
|
-
createdAt:
|
|
101
|
-
id:
|
|
102
|
-
raw:
|
|
103
|
-
schedule:
|
|
104
|
-
status:
|
|
105
|
-
watch:
|
|
106
|
-
webhookUrl:
|
|
89
|
+
createdAt: monitor.created_at,
|
|
90
|
+
id: requireJobId(provider, monitor.monitor_id),
|
|
91
|
+
raw: entry.original,
|
|
92
|
+
schedule: monitor.frequency,
|
|
93
|
+
status: monitor.status,
|
|
94
|
+
watch: monitor.settings.query,
|
|
95
|
+
webhookUrl: monitor.webhook.url
|
|
107
96
|
});
|
|
108
97
|
};
|
|
109
|
-
const monitorEvent = (
|
|
110
|
-
const event =
|
|
111
|
-
const type =
|
|
98
|
+
const monitorEvent = (entry) => {
|
|
99
|
+
const event = entry.value;
|
|
100
|
+
const type = event.event_type;
|
|
112
101
|
if (type === "completion") return {
|
|
113
|
-
at:
|
|
114
|
-
raw:
|
|
102
|
+
at: event.timestamp,
|
|
103
|
+
raw: entry.original,
|
|
115
104
|
summary: "Run finished with no material change."
|
|
116
105
|
};
|
|
117
106
|
if (type === "error") return compact({
|
|
118
|
-
at:
|
|
119
|
-
raw:
|
|
120
|
-
summary:
|
|
107
|
+
at: event.timestamp,
|
|
108
|
+
raw: entry.original,
|
|
109
|
+
summary: event.error_message
|
|
121
110
|
});
|
|
122
|
-
const output =
|
|
123
|
-
const {
|
|
111
|
+
const output = type === "snapshot" ? event.changed_output : event.output;
|
|
112
|
+
const { structure, text } = output.content;
|
|
124
113
|
const sources = citedBy(basis(output.basis));
|
|
125
114
|
return compact({
|
|
126
|
-
at:
|
|
115
|
+
at: event.event_date,
|
|
127
116
|
citations: sources.length > 0 ? sources : void 0,
|
|
128
|
-
id:
|
|
129
|
-
output:
|
|
130
|
-
raw:
|
|
131
|
-
summary:
|
|
117
|
+
id: event.event_id,
|
|
118
|
+
output: structure,
|
|
119
|
+
raw: entry.original,
|
|
120
|
+
summary: text
|
|
121
|
+
});
|
|
122
|
+
};
|
|
123
|
+
/** A page from an extracted result; `raw` is the entry as it arrived unless `extra` sets it. */
|
|
124
|
+
const pageFrom = (entry, extra = {}) => {
|
|
125
|
+
const result = entry.value;
|
|
126
|
+
return compact({
|
|
127
|
+
excerpts: result.excerpts.length > 0 ? result.excerpts : void 0,
|
|
128
|
+
markdown: result.full_content,
|
|
129
|
+
publishedAt: result.publish_date,
|
|
130
|
+
raw: entry.original,
|
|
131
|
+
title: result.title,
|
|
132
|
+
url: result.url ?? "",
|
|
133
|
+
...extra
|
|
132
134
|
});
|
|
133
135
|
};
|
|
134
|
-
const pageFrom = (result, extra = {}) => compact({
|
|
135
|
-
excerpts: strings(result.excerpts),
|
|
136
|
-
markdown: text(result.full_content),
|
|
137
|
-
publishedAt: text(result.publish_date),
|
|
138
|
-
raw: result,
|
|
139
|
-
title: text(result.title),
|
|
140
|
-
url: text(result.url) ?? "",
|
|
141
|
-
...extra
|
|
142
|
-
});
|
|
143
136
|
const extractFailure = (error) => {
|
|
144
|
-
const status =
|
|
145
|
-
const detail = text(error.content);
|
|
137
|
+
const status = error.http_status_code;
|
|
146
138
|
return [
|
|
147
|
-
|
|
139
|
+
error.error_type ?? "error",
|
|
148
140
|
status === void 0 ? void 0 : `HTTP ${status}`,
|
|
149
|
-
|
|
141
|
+
error.content
|
|
150
142
|
].filter((part) => part !== void 0).join(": ");
|
|
151
143
|
};
|
|
152
|
-
const extractMeta = (
|
|
153
|
-
requestId:
|
|
154
|
-
units: usageUnits(
|
|
155
|
-
warnings:
|
|
144
|
+
const extractMeta = (body) => meta({
|
|
145
|
+
requestId: body.extract_id.id,
|
|
146
|
+
units: usageUnits(body.usage),
|
|
147
|
+
warnings: body.warnings
|
|
156
148
|
});
|
|
157
|
-
const discovery = (id,
|
|
158
|
-
const run =
|
|
159
|
-
const metrics =
|
|
160
|
-
const reason =
|
|
161
|
-
const state =
|
|
162
|
-
const entities =
|
|
149
|
+
const discovery = (id, entry) => {
|
|
150
|
+
const run = entry.value.run.status;
|
|
151
|
+
const { metrics } = run;
|
|
152
|
+
const reason = run.termination_reason;
|
|
153
|
+
const state = run.status ?? "unknown";
|
|
154
|
+
const entities = entry.value.candidates.map((item) => candidate(item)).filter((item) => item !== void 0);
|
|
163
155
|
const stoppedEarly = state !== "completed" || reason !== void 0 && !FINISHED.has(reason);
|
|
164
|
-
if (stoppedEarly && !entities.some((entity) => entity.matched)) throw new FieldworkError("JobFailed", `parallel FindAll run ${id} ended as ${state}${reason ? ` (${reason})`
|
|
165
|
-
cause:
|
|
156
|
+
if (stoppedEarly && !entities.some((entity) => entity.matched === true)) throw new FieldworkError("JobFailed", `parallel FindAll run ${id} ended as ${state}${reason === void 0 ? "" : ` (${reason})`} without a match`, {
|
|
157
|
+
cause: entry.original,
|
|
166
158
|
jobId: id,
|
|
167
159
|
provider
|
|
168
160
|
});
|
|
@@ -178,7 +170,7 @@ const discovery = (id, result) => {
|
|
|
178
170
|
},
|
|
179
171
|
warnings: stoppedEarly ? [`the run stopped before it finished: ${stopReason}`] : void 0
|
|
180
172
|
}),
|
|
181
|
-
raw:
|
|
173
|
+
raw: entry.original,
|
|
182
174
|
status: stoppedEarly ? "partial" : "completed",
|
|
183
175
|
stopReason: stoppedEarly ? stopReason : void 0
|
|
184
176
|
});
|
|
@@ -193,11 +185,11 @@ const sourcePolicy = (o) => {
|
|
|
193
185
|
});
|
|
194
186
|
};
|
|
195
187
|
const fetchPolicy = (maxAge) => {
|
|
196
|
-
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`);
|
|
197
189
|
return maxAge === void 0 ? void 0 : { max_age_seconds: Math.ceil(maxAge) };
|
|
198
190
|
};
|
|
199
191
|
const jsonOutput = (schema) => ({
|
|
200
|
-
json_schema: schema,
|
|
192
|
+
json_schema: jsonSchemaOf(schema),
|
|
201
193
|
type: "json"
|
|
202
194
|
});
|
|
203
195
|
const decisionQuestion = (name, question) => {
|
|
@@ -207,7 +199,7 @@ const decisionQuestion = (name, question) => {
|
|
|
207
199
|
};
|
|
208
200
|
if (question.type === "choice") {
|
|
209
201
|
const choices = [...new Set(question.choices)];
|
|
210
|
-
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}`);
|
|
211
203
|
return {
|
|
212
204
|
criteria: Object.fromEntries(choices.map((choice) => [choice, choice])),
|
|
213
205
|
instructions: question.question,
|
|
@@ -216,14 +208,14 @@ const decisionQuestion = (name, question) => {
|
|
|
216
208
|
}
|
|
217
209
|
if (question.type === "score") {
|
|
218
210
|
const levels = Object.values(question.scale);
|
|
219
|
-
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}`);
|
|
220
212
|
return {
|
|
221
213
|
criteria: levels,
|
|
222
214
|
instructions: question.question,
|
|
223
215
|
type: "score"
|
|
224
216
|
};
|
|
225
217
|
}
|
|
226
|
-
throw
|
|
218
|
+
throw invalidRequest(provider, `does not know the question type "${String(question.type)}" for "${name}"`);
|
|
227
219
|
};
|
|
228
220
|
const NAMED_FREQUENCY = {
|
|
229
221
|
day: "1d",
|
|
@@ -231,20 +223,20 @@ const NAMED_FREQUENCY = {
|
|
|
231
223
|
week: "1w"
|
|
232
224
|
};
|
|
233
225
|
const frequency = (schedule) => {
|
|
234
|
-
if ("cron" in schedule) throw
|
|
235
|
-
const named = NAMED_FREQUENCY[schedule.every];
|
|
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: ... }");
|
|
227
|
+
const named = Object.entries(NAMED_FREQUENCY).find(([name]) => name === schedule.every)?.[1];
|
|
236
228
|
if (named) return named;
|
|
237
229
|
const match = /^(?<count>\d+)(?<unit>[hd])$/u.exec(schedule.every);
|
|
238
230
|
const count = Number(match?.groups?.count);
|
|
239
231
|
const limit = match?.groups?.unit === "h" ? 720 : 30;
|
|
240
|
-
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`);
|
|
241
233
|
return schedule.every;
|
|
242
234
|
};
|
|
243
235
|
const extractBody = (urls, o) => compact({
|
|
244
236
|
advanced_settings: compact({
|
|
245
237
|
excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
|
|
246
238
|
fetch_policy: fetchPolicy(o.maxAge),
|
|
247
|
-
full_content: o.maxContentChars ? { max_chars_per_result: o.maxContentChars } : true
|
|
239
|
+
full_content: o.maxContentChars !== void 0 && o.maxContentChars !== 0 ? { max_chars_per_result: o.maxContentChars } : true
|
|
248
240
|
}),
|
|
249
241
|
max_chars_total: o.maxCharsTotal,
|
|
250
242
|
objective: o.query,
|
|
@@ -252,52 +244,239 @@ const extractBody = (urls, o) => compact({
|
|
|
252
244
|
session_id: o.sessionId,
|
|
253
245
|
urls
|
|
254
246
|
});
|
|
247
|
+
// src/adapters/parallel/response.ts
|
|
248
|
+
/** What a result says about the evidence for a field. */
|
|
249
|
+
const Basis = looseObject({
|
|
250
|
+
citations: arrayOf(Source),
|
|
251
|
+
confidence: optionalString,
|
|
252
|
+
field: optionalString,
|
|
253
|
+
reasoning: optionalString
|
|
254
|
+
});
|
|
255
|
+
/** The units a call used, one entry per kind. */
|
|
256
|
+
const Usage = arrayOf(looseObject({
|
|
257
|
+
count: optionalNumber,
|
|
258
|
+
name: optionalString
|
|
259
|
+
}));
|
|
260
|
+
/** A string, an object or an array as it arrived, told apart. */
|
|
261
|
+
const Content = z.pipe(both(optionalAnyString, optionalStructure), z.transform(({ first, second }) => ({
|
|
262
|
+
structure: second,
|
|
263
|
+
text: first
|
|
264
|
+
})));
|
|
265
|
+
/** `/v1/search`. */
|
|
266
|
+
const SearchResponse = looseObject({
|
|
267
|
+
results: arrayOf(looseObject({
|
|
268
|
+
excerpts: arrayOf(z.string()),
|
|
269
|
+
publish_date: optionalString,
|
|
270
|
+
title: optionalString,
|
|
271
|
+
url: optionalString
|
|
272
|
+
})),
|
|
273
|
+
search_id: optionalScalar,
|
|
274
|
+
usage: Usage,
|
|
275
|
+
warnings
|
|
276
|
+
});
|
|
277
|
+
/** `/v1/images/search`. */
|
|
278
|
+
const ImagesResponse = looseObject({
|
|
279
|
+
results: arrayOf(looseObject({
|
|
280
|
+
height: optionalNumber,
|
|
281
|
+
image_url: optionalString,
|
|
282
|
+
source_page_url: optionalString,
|
|
283
|
+
title: optionalString,
|
|
284
|
+
width: optionalNumber
|
|
285
|
+
})),
|
|
286
|
+
search_id: optionalScalar,
|
|
287
|
+
usage: Usage,
|
|
288
|
+
warnings
|
|
289
|
+
});
|
|
290
|
+
const ExtractResult = looseObject({
|
|
291
|
+
excerpts: arrayOf(z.string()),
|
|
292
|
+
full_content: optionalString,
|
|
293
|
+
publish_date: optionalString,
|
|
294
|
+
title: optionalString,
|
|
295
|
+
url: optionalString
|
|
296
|
+
});
|
|
297
|
+
/** `/v1/extract`. Each result keeps its own entry as it arrived. */
|
|
298
|
+
const ExtractResponse = looseObject({
|
|
299
|
+
errors: arrayOf(looseObject({
|
|
300
|
+
content: optionalString,
|
|
301
|
+
error_type: optionalString,
|
|
302
|
+
http_status_code: optionalNumber,
|
|
303
|
+
url: optionalString
|
|
304
|
+
})),
|
|
305
|
+
extract_id: z.pipe(both(optionalString, optionalScalar), z.transform(({ first, second }) => ({
|
|
306
|
+
id: second,
|
|
307
|
+
text: first
|
|
308
|
+
}))),
|
|
309
|
+
results: arrayOf(withOriginal(ExtractResult)),
|
|
310
|
+
usage: Usage,
|
|
311
|
+
warnings
|
|
312
|
+
});
|
|
313
|
+
/** `/v1/responses`: the ids are read as text (a continuation id) and as a request id. */
|
|
314
|
+
const AnswerResponse = looseObject({
|
|
315
|
+
error: looseObject({ message: optionalString }),
|
|
316
|
+
id: z.pipe(both(optionalString, optionalScalar), z.transform(({ first, second }) => ({
|
|
317
|
+
request: second,
|
|
318
|
+
text: first
|
|
319
|
+
}))),
|
|
320
|
+
incomplete_details: looseObject({ reason: optionalString }),
|
|
321
|
+
output: arrayOf(looseObject({
|
|
322
|
+
content: arrayOf(looseObject({
|
|
323
|
+
annotations: arrayOf(looseObject({
|
|
324
|
+
...sourceShape,
|
|
325
|
+
type: optionalString
|
|
326
|
+
})),
|
|
327
|
+
text: optionalString,
|
|
328
|
+
type: optionalString
|
|
329
|
+
})),
|
|
330
|
+
phase: optionalString,
|
|
331
|
+
type: optionalString
|
|
332
|
+
})),
|
|
333
|
+
status: optionalString,
|
|
334
|
+
usage: looseObject({
|
|
335
|
+
input_tokens: optionalNumber,
|
|
336
|
+
output_tokens: optionalNumber,
|
|
337
|
+
total_tokens: optionalNumber
|
|
338
|
+
})
|
|
339
|
+
});
|
|
340
|
+
const Decision = looseObject({
|
|
341
|
+
choice: optionalString,
|
|
342
|
+
confidence: optionalNumber,
|
|
343
|
+
noul: optionalNumber,
|
|
344
|
+
probabilities: recordOf(optionalNumber),
|
|
345
|
+
type: optionalString
|
|
346
|
+
});
|
|
347
|
+
/** `/v1/decisions`. */
|
|
348
|
+
const DecisionsResponse = looseObject({
|
|
349
|
+
answers: recordOf(Decision),
|
|
350
|
+
citations: arrayOf(Source),
|
|
351
|
+
decision_id: optionalScalar,
|
|
352
|
+
usage: looseObject({ input_tokens: optionalNumber })
|
|
353
|
+
});
|
|
354
|
+
/** The reply to starting a task run. */
|
|
355
|
+
const TaskStart = looseObject({ run_id: withOriginal(optionalId) });
|
|
356
|
+
/** A task run while it is polled. */
|
|
357
|
+
const TaskRun = withOriginal(looseObject({
|
|
358
|
+
error: looseObject({ message: optionalString }),
|
|
359
|
+
status: optionalString,
|
|
360
|
+
warnings: arrayOf(looseObject({ message: optionalString }))
|
|
361
|
+
}));
|
|
362
|
+
/** A finished task run's result, beside the response as it arrived. */
|
|
363
|
+
const TaskResult = withOriginal(looseObject({
|
|
364
|
+
output: looseObject({
|
|
365
|
+
basis: arrayOf(Basis),
|
|
366
|
+
content: anything
|
|
367
|
+
}),
|
|
368
|
+
run: looseObject({
|
|
369
|
+
interaction_id: optionalString,
|
|
370
|
+
run_id: optionalScalar,
|
|
371
|
+
warnings
|
|
372
|
+
})
|
|
373
|
+
}));
|
|
374
|
+
/** The reply to starting a FindAll run. */
|
|
375
|
+
const FindAllStart = looseObject({ findall_id: withOriginal(optionalId) });
|
|
376
|
+
/** A FindAll run while it is polled. */
|
|
377
|
+
const FindAllRun = withOriginal(looseObject({ status: looseObject({ status: optionalString }) }));
|
|
378
|
+
const Candidate = looseObject({
|
|
379
|
+
basis: arrayOf(Basis),
|
|
380
|
+
description: optionalString,
|
|
381
|
+
match_status: optionalString,
|
|
382
|
+
name: optionalString,
|
|
383
|
+
output: recordOf(looseObject({
|
|
384
|
+
type: optionalString,
|
|
385
|
+
value: anything
|
|
386
|
+
})),
|
|
387
|
+
url: optionalString
|
|
388
|
+
});
|
|
389
|
+
/** A finished FindAll run's result, beside the response as it arrived. */
|
|
390
|
+
const FindAllResult = withOriginal(looseObject({
|
|
391
|
+
candidates: arrayOf(Candidate),
|
|
392
|
+
run: looseObject({ status: looseObject({
|
|
393
|
+
metrics: looseObject({
|
|
394
|
+
generated_candidates_count: optionalNumber,
|
|
395
|
+
matched_candidates_count: optionalNumber
|
|
396
|
+
}),
|
|
397
|
+
status: optionalString,
|
|
398
|
+
termination_reason: optionalString
|
|
399
|
+
}) })
|
|
400
|
+
}));
|
|
401
|
+
/** A monitor beside the entry as it arrived. */
|
|
402
|
+
const MonitorEntry = withOriginal(looseObject({
|
|
403
|
+
created_at: optionalString,
|
|
404
|
+
frequency: optionalString,
|
|
405
|
+
monitor_id: withOriginal(optionalId),
|
|
406
|
+
settings: looseObject({ query: optionalString }),
|
|
407
|
+
status: optionalString,
|
|
408
|
+
webhook: looseObject({ url: optionalString })
|
|
409
|
+
}));
|
|
410
|
+
/** One page of monitors. */
|
|
411
|
+
const MonitorsPage = looseObject({
|
|
412
|
+
monitors: arrayOf(MonitorEntry),
|
|
413
|
+
next_cursor: optionalString
|
|
414
|
+
});
|
|
415
|
+
const EventOutput = looseObject({
|
|
416
|
+
basis: arrayOf(Basis),
|
|
417
|
+
content: Content
|
|
418
|
+
});
|
|
419
|
+
/** One page of a monitor's events, each beside its entry as it arrived. */
|
|
420
|
+
const EventsPage = looseObject({
|
|
421
|
+
events: arrayOf(withOriginal(looseObject({
|
|
422
|
+
changed_output: EventOutput,
|
|
423
|
+
error_message: optionalString,
|
|
424
|
+
event_date: optionalString,
|
|
425
|
+
event_id: optionalString,
|
|
426
|
+
event_type: optionalString,
|
|
427
|
+
output: EventOutput,
|
|
428
|
+
timestamp: optionalString
|
|
429
|
+
}))),
|
|
430
|
+
next_cursor: optionalString
|
|
431
|
+
});
|
|
255
432
|
// src/adapters/parallel/jobs.ts
|
|
256
|
-
const stoppedRun = (id,
|
|
257
|
-
const
|
|
258
|
-
const
|
|
259
|
-
const
|
|
433
|
+
const stoppedRun = (id, entry) => {
|
|
434
|
+
const run = entry.value;
|
|
435
|
+
const status = run.status ?? "unknown";
|
|
436
|
+
const reason = run.error.message;
|
|
437
|
+
const warnings = run.warnings.map((item) => item.message).filter((item) => item !== void 0);
|
|
260
438
|
let message;
|
|
261
439
|
if (status === "action_required") message = `parallel task 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`;
|
|
262
440
|
else if (status === "cancelled") message = `parallel task run ${id} was cancelled`;
|
|
263
441
|
else message = `parallel task run ${id} failed: ${reason ?? "no reason given"}`;
|
|
264
442
|
if (warnings.length > 0) message += ` (${warnings.join("; ")})`;
|
|
265
443
|
return new FieldworkError("JobFailed", message, {
|
|
266
|
-
cause:
|
|
444
|
+
cause: entry.original,
|
|
267
445
|
jobId: id,
|
|
268
446
|
provider
|
|
269
447
|
});
|
|
270
448
|
};
|
|
271
|
-
const taskResult = async (raw, id,
|
|
449
|
+
const taskResult = async (raw, id, request) => {
|
|
272
450
|
try {
|
|
273
|
-
return
|
|
451
|
+
return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${segment(id)}/result`, request));
|
|
274
452
|
} catch (error) {
|
|
275
453
|
if (error instanceof FieldworkError && error.code === "NotFound") {
|
|
276
|
-
const run =
|
|
277
|
-
if (
|
|
454
|
+
const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
|
|
455
|
+
if (run.value.status === "failed" || run.value.status === "cancelled") throw stoppedRun(id, run);
|
|
278
456
|
}
|
|
279
457
|
throw error;
|
|
280
458
|
}
|
|
281
459
|
};
|
|
282
460
|
const runTask = async (raw, body, settings) => {
|
|
283
461
|
const { resume, ...wait } = settings;
|
|
284
|
-
const id = resume ??
|
|
462
|
+
const id = resume ?? requireJobId(raw.provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
|
|
463
|
+
...wait,
|
|
285
464
|
body,
|
|
286
|
-
|
|
287
|
-
timeout: wait.timeout
|
|
465
|
+
creates: true
|
|
288
466
|
})).run_id);
|
|
289
467
|
return {
|
|
290
468
|
id,
|
|
291
|
-
result: await poll(raw.provider, id, async () => {
|
|
292
|
-
const run =
|
|
293
|
-
const status =
|
|
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));
|
|
471
|
+
const { status } = run.value;
|
|
294
472
|
if (status === "failed" || status === "cancelled" || status === "action_required") throw stoppedRun(id, run);
|
|
295
|
-
return status === "completed" ? await taskResult(raw, id,
|
|
473
|
+
return status === "completed" ? await taskResult(raw, id, request) : void 0;
|
|
296
474
|
}, wait)
|
|
297
475
|
};
|
|
298
476
|
};
|
|
299
477
|
const startFindAll = async (raw, objective, o, call) => {
|
|
300
|
-
const created =
|
|
478
|
+
const created = z.parse(FindAllStart, await raw.request("POST", "/v1beta/findall/runs", {
|
|
479
|
+
creates: true,
|
|
301
480
|
...call,
|
|
302
481
|
body: compact({
|
|
303
482
|
entity_type: o.entityType,
|
|
@@ -312,37 +491,45 @@ const startFindAll = async (raw, objective, o, call) => {
|
|
|
312
491
|
objective
|
|
313
492
|
})
|
|
314
493
|
}));
|
|
315
|
-
const id =
|
|
494
|
+
const id = requireJobId(provider, created.findall_id);
|
|
316
495
|
if (o.schema) try {
|
|
317
|
-
await raw.request("POST", `/v1beta/findall/runs/${id}/enrich`, {
|
|
496
|
+
await raw.request("POST", `/v1beta/findall/runs/${segment(id)}/enrich`, {
|
|
497
|
+
...call,
|
|
318
498
|
body: compact({
|
|
319
499
|
output_schema: jsonOutput(o.schema),
|
|
320
500
|
processor: o.processor
|
|
321
501
|
}),
|
|
322
|
-
|
|
502
|
+
creates: true
|
|
323
503
|
});
|
|
324
504
|
} catch (error) {
|
|
325
505
|
throw withJob(error, id);
|
|
326
506
|
}
|
|
327
507
|
return id;
|
|
328
508
|
};
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
const
|
|
509
|
+
/** The result of a FindAll run once it has stopped, or undefined while it runs. */
|
|
510
|
+
const findAllResult = async (raw, id, request) => {
|
|
511
|
+
const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}`, request));
|
|
512
|
+
const { status } = run.value.status;
|
|
332
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`, {
|
|
333
|
-
cause: run,
|
|
514
|
+
cause: run.original,
|
|
334
515
|
jobId: id,
|
|
335
516
|
provider
|
|
336
517
|
});
|
|
337
|
-
return status === "completed" || status === "failed" || status === "cancelled" ?
|
|
518
|
+
return status === "completed" || status === "failed" || status === "cancelled" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
|
|
338
519
|
};
|
|
339
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
|
+
*/
|
|
340
526
|
const parallel = (config = {}) => {
|
|
341
527
|
const raw = createRawClient({
|
|
342
528
|
baseUrl: config.baseUrl ?? "https://api.parallel.ai",
|
|
343
529
|
fetch: config.fetch,
|
|
344
530
|
headers: { "x-api-key": requireKey(provider, config.apiKey, "PARALLEL_API_KEY") },
|
|
345
|
-
provider
|
|
531
|
+
provider,
|
|
532
|
+
retries: config.retries
|
|
346
533
|
});
|
|
347
534
|
return defineAdapter({
|
|
348
535
|
name: provider,
|
|
@@ -354,7 +541,7 @@ const parallel = (config = {}) => {
|
|
|
354
541
|
allowed_domains: o.includeDomains,
|
|
355
542
|
blocked_domains: o.excludeDomains
|
|
356
543
|
});
|
|
357
|
-
const response =
|
|
544
|
+
const response = await raw.request("POST", "/v1/responses", {
|
|
358
545
|
...call,
|
|
359
546
|
body: compact({
|
|
360
547
|
input: question,
|
|
@@ -365,7 +552,7 @@ const parallel = (config = {}) => {
|
|
|
365
552
|
reasoning: o.effort ? { effort: o.effort } : void 0,
|
|
366
553
|
text: o.schema ? { format: {
|
|
367
554
|
name: "answer",
|
|
368
|
-
schema: o.schema,
|
|
555
|
+
schema: jsonSchemaOf(o.schema),
|
|
369
556
|
type: "json_schema"
|
|
370
557
|
} } : void 0,
|
|
371
558
|
tools: filters ? [{
|
|
@@ -373,34 +560,35 @@ const parallel = (config = {}) => {
|
|
|
373
560
|
type: "web_search"
|
|
374
561
|
}] : void 0
|
|
375
562
|
})
|
|
376
|
-
})
|
|
377
|
-
const
|
|
378
|
-
|
|
563
|
+
});
|
|
564
|
+
const body = z.parse(AnswerResponse, response);
|
|
565
|
+
const failure = body.error.message;
|
|
566
|
+
if (body.status === "failed" || failure !== void 0) throw new FieldworkError("ProviderError", `parallel could not answer: ${failure ?? "the response failed"}`, {
|
|
379
567
|
cause: response,
|
|
380
568
|
provider
|
|
381
569
|
});
|
|
382
|
-
const parts = responseMessages(
|
|
383
|
-
const answer = parts.map((part) =>
|
|
384
|
-
if (answer === "") throw new FieldworkError("ProviderError", `parallel returned no answer text (status ${
|
|
570
|
+
const parts = responseMessages(body).flatMap((message) => message.content.filter((part) => part.type === "output_text"));
|
|
571
|
+
const answer = parts.map((part) => part.text).filter((part) => part !== void 0).join("\n\n");
|
|
572
|
+
if (answer === "") throw new FieldworkError("ProviderError", `parallel returned no answer text (status ${body.status ?? "unknown"})`, {
|
|
385
573
|
cause: response,
|
|
386
574
|
provider
|
|
387
575
|
});
|
|
388
|
-
const usage =
|
|
389
|
-
const incomplete =
|
|
576
|
+
const { usage } = body;
|
|
577
|
+
const incomplete = body.incomplete_details.reason;
|
|
390
578
|
return compact({
|
|
391
579
|
answer,
|
|
392
|
-
citations: uniqueCitations(
|
|
393
|
-
continuationId:
|
|
580
|
+
citations: uniqueCitations(citationsOf(parts.flatMap((part) => part.annotations).filter((item) => item.type === "url_citation"))),
|
|
581
|
+
continuationId: body.id.text,
|
|
394
582
|
meta: meta({
|
|
395
|
-
requestId:
|
|
583
|
+
requestId: body.id.request,
|
|
396
584
|
units: {
|
|
397
585
|
input_tokens: usage.input_tokens,
|
|
398
586
|
output_tokens: usage.output_tokens,
|
|
399
587
|
total_tokens: usage.total_tokens
|
|
400
588
|
},
|
|
401
|
-
warnings: incomplete ? [`the answer is incomplete: ${incomplete}`]
|
|
589
|
+
warnings: incomplete === void 0 ? void 0 : [`the answer is incomplete: ${incomplete}`]
|
|
402
590
|
}),
|
|
403
|
-
output: o.schema ? parseJson(provider, answer) : void 0,
|
|
591
|
+
output: o.schema ? await checkOutput(o.schema, parseJson(provider, answer), { provider }) : void 0,
|
|
404
592
|
raw: response
|
|
405
593
|
});
|
|
406
594
|
},
|
|
@@ -408,10 +596,10 @@ const parallel = (config = {}) => {
|
|
|
408
596
|
const { call, rest: o } = callSettings(options);
|
|
409
597
|
const entries = Object.entries(questions);
|
|
410
598
|
const names = entries.map(([name]) => name);
|
|
411
|
-
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}`);
|
|
412
600
|
const badName = names.find((name) => !QUESTION_NAME.test(name));
|
|
413
|
-
if (badName !== void 0) throw
|
|
414
|
-
const response =
|
|
601
|
+
if (badName !== void 0) throw invalidRequest(provider, `question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
|
|
602
|
+
const response = await raw.request("POST", "/v1/decisions", {
|
|
415
603
|
...call,
|
|
416
604
|
body: compact({
|
|
417
605
|
advanced_settings: nonEmpty({
|
|
@@ -421,16 +609,19 @@ const parallel = (config = {}) => {
|
|
|
421
609
|
questions: Object.fromEntries(entries.map(([name, question]) => [name, decisionQuestion(name, question)])),
|
|
422
610
|
state: context ?? null
|
|
423
611
|
})
|
|
424
|
-
})
|
|
425
|
-
const
|
|
612
|
+
});
|
|
613
|
+
const body = z.parse(DecisionsResponse, response);
|
|
426
614
|
const result = {};
|
|
427
|
-
for (const [name, question] of entries)
|
|
615
|
+
for (const [name, question] of entries) {
|
|
616
|
+
const answer = body.answers[name];
|
|
617
|
+
if (answer !== void 0) result[name] = decisionAnswer(question, answer);
|
|
618
|
+
}
|
|
428
619
|
return compact({
|
|
429
620
|
answers: result,
|
|
430
|
-
citations:
|
|
621
|
+
citations: citationsOf(body.citations),
|
|
431
622
|
meta: meta({
|
|
432
|
-
requestId:
|
|
433
|
-
units: { input_tokens:
|
|
623
|
+
requestId: body.decision_id,
|
|
624
|
+
units: { input_tokens: body.usage.input_tokens }
|
|
434
625
|
}),
|
|
435
626
|
raw: response
|
|
436
627
|
});
|
|
@@ -438,16 +629,30 @@ const parallel = (config = {}) => {
|
|
|
438
629
|
async discover(objective, options) {
|
|
439
630
|
const { call, rest: o } = callSettings(options);
|
|
440
631
|
const id = o.resume ?? await startFindAll(raw, objective, o, call);
|
|
441
|
-
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), {
|
|
442
633
|
...call,
|
|
443
634
|
interval: o.interval
|
|
444
635
|
});
|
|
445
|
-
|
|
636
|
+
const found = discovery(id, result);
|
|
637
|
+
const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => {
|
|
638
|
+
if (data === void 0) return entity;
|
|
639
|
+
return {
|
|
640
|
+
...entity,
|
|
641
|
+
data: await checkOutput(o.schema, data, {
|
|
642
|
+
jobId: id,
|
|
643
|
+
provider
|
|
644
|
+
})
|
|
645
|
+
};
|
|
646
|
+
}));
|
|
647
|
+
return {
|
|
648
|
+
...found,
|
|
649
|
+
entities
|
|
650
|
+
};
|
|
446
651
|
},
|
|
447
652
|
async extract(url, options) {
|
|
448
653
|
const { call, rest: o } = callSettings(options);
|
|
449
654
|
const target = new URL(url);
|
|
450
|
-
const { result } = await runTask(raw, compact({
|
|
655
|
+
const { id, result } = await runTask(raw, compact({
|
|
451
656
|
advanced_settings: nonEmpty({ location: o.country }),
|
|
452
657
|
input: {
|
|
453
658
|
instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
|
|
@@ -462,17 +667,20 @@ const parallel = (config = {}) => {
|
|
|
462
667
|
interval: o.interval,
|
|
463
668
|
resume: o.resume
|
|
464
669
|
});
|
|
465
|
-
const output =
|
|
670
|
+
const { output } = result.value;
|
|
466
671
|
return compact({
|
|
467
|
-
data: output.content,
|
|
672
|
+
data: await checkOutput(o.schema, output.content, {
|
|
673
|
+
jobId: id,
|
|
674
|
+
provider
|
|
675
|
+
}),
|
|
468
676
|
fields: basis(output.basis),
|
|
469
677
|
meta: taskMeta(result),
|
|
470
|
-
raw: result
|
|
678
|
+
raw: result.original
|
|
471
679
|
});
|
|
472
680
|
},
|
|
473
681
|
async images(query, options) {
|
|
474
682
|
const { call, rest: o } = callSettings(options);
|
|
475
|
-
const response =
|
|
683
|
+
const response = await raw.request("POST", "/v1/images/search", {
|
|
476
684
|
...call,
|
|
477
685
|
body: compact({
|
|
478
686
|
advanced_settings: nonEmpty({
|
|
@@ -484,32 +692,29 @@ const parallel = (config = {}) => {
|
|
|
484
692
|
search_queries: o.queries ?? [query],
|
|
485
693
|
session_id: o.sessionId
|
|
486
694
|
})
|
|
487
|
-
})
|
|
695
|
+
});
|
|
696
|
+
const body = z.parse(ImagesResponse, response);
|
|
488
697
|
return compact({
|
|
489
698
|
meta: meta({
|
|
490
|
-
requestId:
|
|
491
|
-
units: usageUnits(
|
|
492
|
-
warnings:
|
|
699
|
+
requestId: body.search_id,
|
|
700
|
+
units: usageUnits(body.usage),
|
|
701
|
+
warnings: body.warnings
|
|
493
702
|
}),
|
|
494
703
|
raw: response,
|
|
495
|
-
results:
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
width: num(image.width)
|
|
503
|
-
});
|
|
504
|
-
})
|
|
704
|
+
results: body.results.map((image) => compact({
|
|
705
|
+
height: image.height,
|
|
706
|
+
sourceUrl: image.source_page_url,
|
|
707
|
+
title: image.title,
|
|
708
|
+
url: image.image_url ?? "",
|
|
709
|
+
width: image.width
|
|
710
|
+
}))
|
|
505
711
|
});
|
|
506
712
|
},
|
|
507
713
|
monitor: {
|
|
508
714
|
async create(options) {
|
|
509
715
|
const { call, rest: o } = callSettings(options);
|
|
510
|
-
|
|
511
|
-
if (
|
|
512
|
-
if (o.taskRunId === void 0 && o.query === void 0) throw invalid("a parallel monitor needs a query or a taskRunId");
|
|
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");
|
|
513
718
|
if (o.taskRunId !== void 0) for (const name of [
|
|
514
719
|
"query",
|
|
515
720
|
"schema",
|
|
@@ -519,8 +724,9 @@ const parallel = (config = {}) => {
|
|
|
519
724
|
"excludeDomains",
|
|
520
725
|
"publishedAfter"
|
|
521
726
|
]) refuseTogether(provider, o, "taskRunId", name);
|
|
522
|
-
if (o.webhookEvents &&
|
|
727
|
+
if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw invalidRequest(provider, "webhookEvents needs a webhookUrl");
|
|
523
728
|
const response = await raw.request("POST", "/v1/monitors", {
|
|
729
|
+
creates: true,
|
|
524
730
|
...call,
|
|
525
731
|
body: compact({
|
|
526
732
|
frequency: frequency(o.schedule),
|
|
@@ -528,28 +734,28 @@ const parallel = (config = {}) => {
|
|
|
528
734
|
processor: o.processor,
|
|
529
735
|
settings: o.taskRunId === void 0 ? compact({
|
|
530
736
|
advanced_settings: nonEmpty({
|
|
531
|
-
|
|
532
|
-
|
|
737
|
+
location: o.country,
|
|
738
|
+
source_policy: sourcePolicy(o)
|
|
533
739
|
}),
|
|
534
740
|
include_backfill: o.includeBackfill,
|
|
535
741
|
output_schema: o.schema ? jsonOutput(o.schema) : void 0,
|
|
536
742
|
query: o.query
|
|
537
743
|
}) : { task_run_id: o.taskRunId },
|
|
538
744
|
type: o.taskRunId === void 0 ? "event_stream" : "snapshot",
|
|
539
|
-
webhook: o.webhookUrl ? compact({
|
|
745
|
+
webhook: o.webhookUrl === void 0 || o.webhookUrl === "" ? void 0 : compact({
|
|
540
746
|
event_types: o.webhookEvents,
|
|
541
747
|
url: o.webhookUrl
|
|
542
|
-
})
|
|
748
|
+
})
|
|
543
749
|
})
|
|
544
750
|
});
|
|
545
|
-
return monitorInfo(response);
|
|
751
|
+
return monitorInfo(z.parse(MonitorEntry, response));
|
|
546
752
|
},
|
|
547
753
|
async delete(id, options) {
|
|
548
|
-
await raw.request("POST", `/v1/monitors/${
|
|
754
|
+
await raw.request("POST", `/v1/monitors/${segment(id)}/cancel`, options);
|
|
549
755
|
},
|
|
550
756
|
async events(id, options) {
|
|
551
757
|
const { call, rest: o } = callSettings(options);
|
|
552
|
-
const response =
|
|
758
|
+
const response = await raw.request("GET", `/v1/monitors/${segment(id)}/events`, {
|
|
553
759
|
...call,
|
|
554
760
|
query: {
|
|
555
761
|
cursor: o.cursor,
|
|
@@ -557,70 +763,73 @@ const parallel = (config = {}) => {
|
|
|
557
763
|
include_completions: o.includeCompletions,
|
|
558
764
|
limit: o.limit
|
|
559
765
|
}
|
|
560
|
-
})
|
|
766
|
+
});
|
|
767
|
+
const page = z.parse(EventsPage, response);
|
|
561
768
|
return compact({
|
|
562
|
-
events:
|
|
563
|
-
next:
|
|
769
|
+
events: page.events.map((entry) => monitorEvent(entry)),
|
|
770
|
+
next: page.next_cursor,
|
|
564
771
|
raw: response
|
|
565
772
|
});
|
|
566
773
|
},
|
|
567
774
|
async get(id, options) {
|
|
568
|
-
return monitorInfo(await raw.request("GET", `/v1/monitors/${
|
|
775
|
+
return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${segment(id)}`, options)));
|
|
569
776
|
},
|
|
570
777
|
async list(options) {
|
|
778
|
+
const { call } = callSettings(options);
|
|
571
779
|
const monitors = [];
|
|
780
|
+
const seen = /* @__PURE__ */ new Set();
|
|
572
781
|
let cursor;
|
|
573
|
-
|
|
574
|
-
const page =
|
|
575
|
-
...
|
|
782
|
+
for (;;) {
|
|
783
|
+
const page = z.parse(MonitorsPage, await raw.request("GET", "/v1/monitors", {
|
|
784
|
+
...call,
|
|
576
785
|
query: {
|
|
577
786
|
cursor,
|
|
578
787
|
limit: 100
|
|
579
788
|
}
|
|
580
789
|
}));
|
|
581
|
-
monitors.push(...
|
|
582
|
-
cursor =
|
|
583
|
-
|
|
584
|
-
|
|
790
|
+
monitors.push(...page.monitors.map((entry) => monitorInfo(entry)));
|
|
791
|
+
cursor = page.next_cursor;
|
|
792
|
+
if (cursor === void 0 || seen.has(cursor)) return monitors;
|
|
793
|
+
seen.add(cursor);
|
|
794
|
+
}
|
|
585
795
|
}
|
|
586
796
|
},
|
|
587
797
|
async read(url, options) {
|
|
588
798
|
const { call, rest: o } = callSettings(options);
|
|
589
|
-
const response =
|
|
799
|
+
const response = await raw.request("POST", "/v1/extract", {
|
|
590
800
|
...call,
|
|
591
801
|
body: extractBody([url], o)
|
|
592
|
-
})
|
|
593
|
-
const
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
802
|
+
});
|
|
803
|
+
const body = z.parse(ExtractResponse, response);
|
|
804
|
+
const [result] = body.results;
|
|
805
|
+
if (result?.value.url === void 0) {
|
|
806
|
+
const [failure] = body.errors;
|
|
807
|
+
throw new FieldworkError("ProviderError", `parallel could not read ${url}: ${failure !== void 0 && Object.keys(failure).length > 0 ? extractFailure(failure) : "no content returned"}`, {
|
|
597
808
|
cause: response,
|
|
598
809
|
provider
|
|
599
810
|
});
|
|
600
811
|
}
|
|
601
812
|
return pageFrom(result, {
|
|
602
|
-
meta: extractMeta(
|
|
813
|
+
meta: extractMeta(body),
|
|
603
814
|
raw: response
|
|
604
815
|
});
|
|
605
816
|
},
|
|
606
817
|
async readMany(urls, options) {
|
|
607
818
|
const { call, rest: o } = callSettings(options);
|
|
608
|
-
if (urls.length > 20) throw
|
|
609
|
-
const response =
|
|
819
|
+
if (urls.length > 20) throw invalidRequest(provider, `reads up to 20 URLs in one call; got ${urls.length}`);
|
|
820
|
+
const response = await raw.request("POST", "/v1/extract", {
|
|
610
821
|
...call,
|
|
611
822
|
body: extractBody(urls, o)
|
|
612
|
-
})
|
|
823
|
+
});
|
|
824
|
+
const body = z.parse(ExtractResponse, response);
|
|
613
825
|
return compact({
|
|
614
|
-
failed:
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
id: text(response.extract_id),
|
|
622
|
-
meta: extractMeta(response),
|
|
623
|
-
pages: list(response.results).map((item) => pageFrom(record(item))),
|
|
826
|
+
failed: body.errors.map((failure) => ({
|
|
827
|
+
error: extractFailure(failure),
|
|
828
|
+
url: failure.url ?? ""
|
|
829
|
+
})),
|
|
830
|
+
id: body.extract_id.text,
|
|
831
|
+
meta: extractMeta(body),
|
|
832
|
+
pages: body.results.map((entry) => pageFrom(entry)),
|
|
624
833
|
raw: response
|
|
625
834
|
});
|
|
626
835
|
},
|
|
@@ -639,22 +848,25 @@ const parallel = (config = {}) => {
|
|
|
639
848
|
interval: o.interval,
|
|
640
849
|
resume: o.resume
|
|
641
850
|
});
|
|
642
|
-
const output =
|
|
851
|
+
const { output, run } = result.value;
|
|
643
852
|
const fields = basis(output.basis);
|
|
644
853
|
return compact({
|
|
645
|
-
continuationId:
|
|
854
|
+
continuationId: run.interaction_id,
|
|
646
855
|
fields,
|
|
647
856
|
id,
|
|
648
857
|
meta: taskMeta(result),
|
|
649
|
-
output: output.content,
|
|
650
|
-
|
|
858
|
+
output: await checkOutput(o.schema, output.content, {
|
|
859
|
+
jobId: id,
|
|
860
|
+
provider
|
|
861
|
+
}),
|
|
862
|
+
raw: result.original,
|
|
651
863
|
sources: citedBy(fields),
|
|
652
864
|
status: "completed"
|
|
653
865
|
});
|
|
654
866
|
},
|
|
655
867
|
async search(query, options) {
|
|
656
868
|
const { call, rest: o } = callSettings(options);
|
|
657
|
-
const response =
|
|
869
|
+
const response = await raw.request("POST", "/v1/search", {
|
|
658
870
|
...call,
|
|
659
871
|
body: compact({
|
|
660
872
|
advanced_settings: nonEmpty({
|
|
@@ -670,23 +882,21 @@ const parallel = (config = {}) => {
|
|
|
670
882
|
search_queries: o.queries ?? [query],
|
|
671
883
|
session_id: o.sessionId
|
|
672
884
|
})
|
|
673
|
-
})
|
|
885
|
+
});
|
|
886
|
+
const body = z.parse(SearchResponse, response);
|
|
674
887
|
return compact({
|
|
675
888
|
meta: meta({
|
|
676
|
-
requestId:
|
|
677
|
-
units: usageUnits(
|
|
678
|
-
warnings:
|
|
889
|
+
requestId: body.search_id,
|
|
890
|
+
units: usageUnits(body.usage),
|
|
891
|
+
warnings: body.warnings
|
|
679
892
|
}),
|
|
680
893
|
raw: response,
|
|
681
|
-
results:
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
url: text(result.url) ?? ""
|
|
688
|
-
});
|
|
689
|
-
})
|
|
894
|
+
results: body.results.map((result) => compact({
|
|
895
|
+
publishedAt: result.publish_date,
|
|
896
|
+
snippet: result.excerpts.length > 0 ? result.excerpts.join(" … ") : void 0,
|
|
897
|
+
title: result.title,
|
|
898
|
+
url: result.url ?? ""
|
|
899
|
+
}))
|
|
690
900
|
});
|
|
691
901
|
}
|
|
692
902
|
},
|