@howells/fieldwork-sdk 0.2.0 → 0.3.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 +104 -38
- package/dist/adapter-CEAQuT7F.js +3 -0
- package/dist/adapter-DGehHCMo.d.ts +470 -0
- package/dist/brave.d.ts +164 -0
- package/dist/brave.js +399 -0
- package/dist/browserbase.d.ts +128 -0
- package/dist/browserbase.js +180 -0
- package/dist/{errors-pzPMh82H.js → errors-BiIBG9zN.js} +14 -18
- package/dist/exa.d.ts +150 -24
- package/dist/exa.js +427 -119
- package/dist/{fieldwork-nPzWEelg.d.ts → fieldwork-B3x3cxDJ.d.ts} +5 -5
- package/dist/firecrawl.d.ts +220 -28
- package/dist/firecrawl.js +850 -233
- package/dist/index.d.ts +11 -5
- package/dist/index.js +53 -35
- package/dist/parallel.d.ts +188 -19
- package/dist/parallel.js +644 -113
- package/dist/perplexity.d.ts +78 -22
- package/dist/perplexity.js +318 -92
- package/dist/serpapi.d.ts +172 -0
- package/dist/serpapi.js +517 -0
- package/dist/tavily.d.ts +104 -31
- package/dist/tavily.js +347 -102
- package/dist/tools.d.ts +42 -14
- package/dist/tools.js +1274 -484
- package/dist/types-CnomnF-6.js +27 -0
- package/dist/util-CYenIQQT.js +265 -0
- package/package.json +19 -3
- package/dist/adapter-C_kRm6TT.d.ts +0 -178
- package/dist/adapter-D-6-GFhJ.js +0 -5
- package/dist/util-D0PLE6Rl.d.ts +0 -2
- package/dist/util-DgcIZI2K.js +0 -214
package/dist/parallel.js
CHANGED
|
@@ -1,165 +1,696 @@
|
|
|
1
|
-
import { t as defineAdapter } from "./adapter-
|
|
2
|
-
import { r as withJob, t as FieldworkError } from "./errors-
|
|
3
|
-
import {
|
|
4
|
-
// src/adapters/parallel.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
|
|
2
|
+
import { r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
|
|
3
|
+
import { _ as uniqueCitations, b as requireKey, c as num, d as record, f as refuseTogether, g as text, h as strings, i as compact, l as parseJson, o as list, p as requireId, r as citations, s as meta, t as callSettings, v as createRawClient, y as poll } from "./util-CYenIQQT.js";
|
|
4
|
+
// src/adapters/parallel/parse.ts
|
|
5
|
+
const provider = "parallel";
|
|
6
|
+
const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
|
|
7
|
+
const nonEmpty = (value) => {
|
|
8
|
+
const result = compact(value);
|
|
9
|
+
return Object.keys(result).length > 0 ? result : void 0;
|
|
10
|
+
};
|
|
11
|
+
const usageUnits = (value) => {
|
|
12
|
+
const units = /* @__PURE__ */ new Map();
|
|
13
|
+
for (const item of list(value)) {
|
|
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
|
+
}
|
|
19
|
+
return Object.fromEntries(units);
|
|
20
|
+
};
|
|
21
|
+
const basis = (entries) => list(entries).map((item) => {
|
|
22
|
+
const entry = record(item);
|
|
23
|
+
return compact({
|
|
24
|
+
citations: citations(entry.citations),
|
|
25
|
+
confidence: text(entry.confidence),
|
|
26
|
+
field: text(entry.field) ?? "",
|
|
27
|
+
reasoning: text(entry.reasoning)
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
const citedBy = (fields) => uniqueCitations(fields.flatMap((field) => field.citations));
|
|
31
|
+
const taskMeta = (result) => {
|
|
32
|
+
const run = record(result.run);
|
|
33
|
+
return meta({
|
|
34
|
+
requestId: run.run_id,
|
|
35
|
+
warnings: run.warnings
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
const responseMessages = (response) => {
|
|
39
|
+
const messages = list(response.output).map((item) => record(item)).filter((item) => item.type === "message");
|
|
40
|
+
const final = messages.filter((item) => item.phase === "final_answer");
|
|
41
|
+
return final.length > 0 ? final : messages;
|
|
42
|
+
};
|
|
43
|
+
const probabilities = (value) => {
|
|
44
|
+
const entries = Object.entries(record(value)).filter((entry) => num(entry[1]) !== void 0);
|
|
45
|
+
return entries.length > 0 ? Object.fromEntries(entries) : void 0;
|
|
46
|
+
};
|
|
47
|
+
const mostLikely = (chances) => {
|
|
48
|
+
let best;
|
|
49
|
+
for (const [key, chance] of Object.entries(chances ?? {})) if (best === void 0 || chance > (chances?.[best] ?? 0)) best = key;
|
|
50
|
+
return best;
|
|
51
|
+
};
|
|
52
|
+
const decisionAnswer = (question, value) => {
|
|
53
|
+
const answer = record(value);
|
|
54
|
+
if (answer.type === "refusal") return { refusal: "Parallel declined to answer this question" };
|
|
55
|
+
const confidence = num(answer.confidence);
|
|
56
|
+
if (question.type === "yesno") return compact({ probability: num(answer.noul) });
|
|
57
|
+
if (question.type === "choice") return compact({
|
|
58
|
+
choice: text(answer.choice),
|
|
59
|
+
confidence,
|
|
60
|
+
probabilities: probabilities(answer.probabilities)
|
|
61
|
+
});
|
|
62
|
+
const keys = Object.keys(question.scale);
|
|
63
|
+
const byLevel = probabilities(answer.probabilities);
|
|
64
|
+
const byKey = byLevel && Object.fromEntries(Object.entries(byLevel).map(([level, chance]) => [keys[Number(level)] ?? level, chance]));
|
|
65
|
+
return compact({
|
|
66
|
+
choice: mostLikely(byKey),
|
|
67
|
+
confidence,
|
|
68
|
+
probabilities: byKey
|
|
69
|
+
});
|
|
70
|
+
};
|
|
71
|
+
/** Termination reasons that mean the run found everything it could. */
|
|
72
|
+
const FINISHED = /* @__PURE__ */ new Set(["match_limit_met", "candidates_exhausted"]);
|
|
73
|
+
const candidate = (value) => {
|
|
74
|
+
const item = record(value);
|
|
75
|
+
const status = text(item.match_status);
|
|
76
|
+
if (status === "discarded") return;
|
|
77
|
+
const data = {};
|
|
78
|
+
for (const [key, output] of Object.entries(record(item.output))) {
|
|
79
|
+
const entry = record(output);
|
|
80
|
+
if (entry.type === "enrichment") data[key] = entry.value;
|
|
81
|
+
}
|
|
82
|
+
const fields = basis(item.basis);
|
|
83
|
+
const sources = citedBy(fields);
|
|
84
|
+
let matched;
|
|
85
|
+
if (status === "matched") matched = true;
|
|
86
|
+
else if (status === "unmatched") matched = false;
|
|
87
|
+
return compact({
|
|
88
|
+
citations: sources.length > 0 ? sources : void 0,
|
|
89
|
+
data: nonEmpty(data),
|
|
90
|
+
description: text(item.description),
|
|
91
|
+
fields: fields.length > 0 ? fields : void 0,
|
|
92
|
+
matched,
|
|
93
|
+
name: text(item.name) ?? "",
|
|
94
|
+
url: text(item.url)
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
const monitorInfo = (value) => {
|
|
98
|
+
const monitor = record(value);
|
|
99
|
+
return compact({
|
|
100
|
+
createdAt: text(monitor.created_at),
|
|
101
|
+
id: requireId(provider, monitor.monitor_id),
|
|
102
|
+
raw: monitor,
|
|
103
|
+
schedule: text(monitor.frequency),
|
|
104
|
+
status: text(monitor.status),
|
|
105
|
+
watch: text(record(monitor.settings).query),
|
|
106
|
+
webhookUrl: text(record(monitor.webhook).url)
|
|
107
|
+
});
|
|
108
|
+
};
|
|
109
|
+
const monitorEvent = (value) => {
|
|
110
|
+
const event = record(value);
|
|
111
|
+
const type = text(event.event_type);
|
|
112
|
+
if (type === "completion") return {
|
|
113
|
+
at: text(event.timestamp),
|
|
114
|
+
raw: event,
|
|
115
|
+
summary: "Run finished with no material change."
|
|
116
|
+
};
|
|
117
|
+
if (type === "error") return compact({
|
|
118
|
+
at: text(event.timestamp),
|
|
119
|
+
raw: event,
|
|
120
|
+
summary: text(event.error_message)
|
|
121
|
+
});
|
|
122
|
+
const output = record(type === "snapshot" ? event.changed_output : event.output);
|
|
123
|
+
const { content } = output;
|
|
124
|
+
const sources = citedBy(basis(output.basis));
|
|
125
|
+
return compact({
|
|
126
|
+
at: text(event.event_date),
|
|
127
|
+
citations: sources.length > 0 ? sources : void 0,
|
|
128
|
+
id: text(event.event_id),
|
|
129
|
+
output: content && typeof content === "object" ? content : void 0,
|
|
130
|
+
raw: event,
|
|
131
|
+
summary: typeof content === "string" ? content : void 0
|
|
132
|
+
});
|
|
133
|
+
};
|
|
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
|
+
const extractFailure = (error) => {
|
|
144
|
+
const status = num(error.http_status_code);
|
|
145
|
+
const detail = text(error.content);
|
|
146
|
+
return [
|
|
147
|
+
text(error.error_type) ?? "error",
|
|
148
|
+
status === void 0 ? void 0 : `HTTP ${status}`,
|
|
149
|
+
detail
|
|
150
|
+
].filter((part) => part !== void 0).join(": ");
|
|
151
|
+
};
|
|
152
|
+
const extractMeta = (response) => meta({
|
|
153
|
+
requestId: response.extract_id,
|
|
154
|
+
units: usageUnits(response.usage),
|
|
155
|
+
warnings: response.warnings
|
|
156
|
+
});
|
|
157
|
+
const discovery = (id, result) => {
|
|
158
|
+
const run = record(record(result.run).status);
|
|
159
|
+
const metrics = record(run.metrics);
|
|
160
|
+
const reason = text(run.termination_reason);
|
|
161
|
+
const state = text(run.status) ?? "unknown";
|
|
162
|
+
const entities = list(result.candidates).map((item) => candidate(item)).filter((item) => item !== void 0);
|
|
163
|
+
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})` : ""} without a match`, {
|
|
165
|
+
cause: result,
|
|
166
|
+
jobId: id,
|
|
167
|
+
provider
|
|
168
|
+
});
|
|
169
|
+
const stopReason = reason ?? state;
|
|
170
|
+
return compact({
|
|
171
|
+
entities,
|
|
172
|
+
id,
|
|
173
|
+
meta: meta({
|
|
174
|
+
requestId: id,
|
|
175
|
+
units: {
|
|
176
|
+
generated_candidates: metrics.generated_candidates_count,
|
|
177
|
+
matched_candidates: metrics.matched_candidates_count
|
|
178
|
+
},
|
|
179
|
+
warnings: stoppedEarly ? [`the run stopped before it finished: ${stopReason}`] : void 0
|
|
180
|
+
}),
|
|
181
|
+
raw: result,
|
|
182
|
+
status: stoppedEarly ? "partial" : "completed",
|
|
183
|
+
stopReason: stoppedEarly ? stopReason : void 0
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
const QUESTION_NAME = /^[A-Za-z0-9_-]+$/u;
|
|
187
|
+
const sourcePolicy = (o) => {
|
|
188
|
+
refuseTogether(provider, o, "includeDomains", "excludeDomains");
|
|
189
|
+
return nonEmpty({
|
|
190
|
+
after_date: o.publishedAfter,
|
|
8
191
|
exclude_domains: o.excludeDomains,
|
|
9
|
-
|
|
192
|
+
include_domains: o.includeDomains
|
|
10
193
|
});
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
return
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
194
|
+
};
|
|
195
|
+
const fetchPolicy = (maxAge) => {
|
|
196
|
+
if (maxAge !== void 0 && maxAge < 600) throw invalid(`parallel cannot use a cached copy younger than 600 seconds (maxAge was ${maxAge}); it has no setting that always fetches fresh`);
|
|
197
|
+
return maxAge === void 0 ? void 0 : { max_age_seconds: Math.ceil(maxAge) };
|
|
198
|
+
};
|
|
199
|
+
const jsonOutput = (schema) => ({
|
|
200
|
+
json_schema: schema,
|
|
201
|
+
type: "json"
|
|
202
|
+
});
|
|
203
|
+
const decisionQuestion = (name, question) => {
|
|
204
|
+
if (question.type === "yesno") return {
|
|
205
|
+
instructions: question.question,
|
|
206
|
+
type: "noul"
|
|
207
|
+
};
|
|
208
|
+
if (question.type === "choice") {
|
|
209
|
+
const choices = [...new Set(question.choices)];
|
|
210
|
+
if (choices.length < 2 || choices.length > 255) throw invalid(`parallel decisions take 2 to 255 distinct choices; question "${name}" has ${choices.length}`);
|
|
211
|
+
return {
|
|
212
|
+
criteria: Object.fromEntries(choices.map((choice) => [choice, choice])),
|
|
213
|
+
instructions: question.question,
|
|
214
|
+
type: "choice"
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
if (question.type === "score") {
|
|
218
|
+
const levels = Object.values(question.scale);
|
|
219
|
+
if (levels.length < 2 || levels.length > 10) throw invalid(`parallel decisions take a score scale of 2 to 10 levels; question "${name}" has ${levels.length}`);
|
|
220
|
+
return {
|
|
221
|
+
criteria: levels,
|
|
222
|
+
instructions: question.question,
|
|
223
|
+
type: "score"
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
throw invalid(`parallel does not know the question type "${String(question.type)}" for "${name}"`);
|
|
227
|
+
};
|
|
228
|
+
const NAMED_FREQUENCY = {
|
|
229
|
+
day: "1d",
|
|
230
|
+
hour: "1h",
|
|
231
|
+
week: "1w"
|
|
232
|
+
};
|
|
233
|
+
const frequency = (schedule) => {
|
|
234
|
+
if ("cron" in schedule) throw invalid("parallel monitors run at a fixed interval from 1 hour to 30 days and cannot follow a cron expression; pass { every: ... }");
|
|
235
|
+
const named = NAMED_FREQUENCY[schedule.every];
|
|
236
|
+
if (named) return named;
|
|
237
|
+
const match = /^(?<count>\d+)(?<unit>[hd])$/u.exec(schedule.every);
|
|
238
|
+
const count = Number(match?.groups?.count);
|
|
239
|
+
const limit = match?.groups?.unit === "h" ? 720 : 30;
|
|
240
|
+
if (!match || count < 1 || count > limit) throw invalid(`parallel monitors run every 1 hour to 30 days; "${schedule.every}" is outside that`);
|
|
241
|
+
return schedule.every;
|
|
242
|
+
};
|
|
243
|
+
const extractBody = (urls, o) => compact({
|
|
244
|
+
advanced_settings: compact({
|
|
245
|
+
excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
|
|
246
|
+
fetch_policy: fetchPolicy(o.maxAge),
|
|
247
|
+
full_content: o.maxContentChars ? { max_chars_per_result: o.maxContentChars } : true
|
|
248
|
+
}),
|
|
249
|
+
max_chars_total: o.maxCharsTotal,
|
|
250
|
+
objective: o.query,
|
|
251
|
+
search_queries: o.queries,
|
|
252
|
+
session_id: o.sessionId,
|
|
253
|
+
urls
|
|
254
|
+
});
|
|
255
|
+
// src/adapters/parallel/jobs.ts
|
|
256
|
+
const stoppedRun = (id, run) => {
|
|
257
|
+
const status = text(run.status) ?? "unknown";
|
|
258
|
+
const reason = text(record(run.error).message);
|
|
259
|
+
const warnings = list(run.warnings).map((item) => text(record(item).message)).filter((item) => item !== void 0);
|
|
260
|
+
let message;
|
|
261
|
+
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
|
+
else if (status === "cancelled") message = `parallel task run ${id} was cancelled`;
|
|
263
|
+
else message = `parallel task run ${id} failed: ${reason ?? "no reason given"}`;
|
|
264
|
+
if (warnings.length > 0) message += ` (${warnings.join("; ")})`;
|
|
265
|
+
return new FieldworkError("JobFailed", message, {
|
|
266
|
+
cause: run,
|
|
267
|
+
jobId: id,
|
|
268
|
+
provider
|
|
269
|
+
});
|
|
270
|
+
};
|
|
271
|
+
const taskResult = async (raw, id, signal) => {
|
|
272
|
+
try {
|
|
273
|
+
return record(await raw.request("GET", `/v1/tasks/runs/${id}/result`, { signal }));
|
|
274
|
+
} catch (error) {
|
|
275
|
+
if (error instanceof FieldworkError && error.code === "NotFound") {
|
|
276
|
+
const run = record(await raw.request("GET", `/v1/tasks/runs/${id}`, { signal }));
|
|
277
|
+
if (text(run.status) === "failed" || text(run.status) === "cancelled") throw stoppedRun(id, run);
|
|
38
278
|
}
|
|
279
|
+
throw error;
|
|
39
280
|
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
281
|
+
};
|
|
282
|
+
const runTask = async (raw, body, settings) => {
|
|
283
|
+
const { resume, ...wait } = settings;
|
|
284
|
+
const id = resume ?? requireId(raw.provider, record(await raw.request("POST", "/v1/tasks/runs", {
|
|
285
|
+
body,
|
|
286
|
+
signal: wait.signal,
|
|
287
|
+
timeout: wait.timeout
|
|
288
|
+
})).run_id);
|
|
289
|
+
return {
|
|
290
|
+
id,
|
|
291
|
+
result: await poll(raw.provider, id, async () => {
|
|
292
|
+
const run = record(await raw.request("GET", `/v1/tasks/runs/${id}`, { signal: wait.signal }));
|
|
293
|
+
const status = text(run.status);
|
|
294
|
+
if (status === "failed" || status === "cancelled" || status === "action_required") throw stoppedRun(id, run);
|
|
295
|
+
return status === "completed" ? await taskResult(raw, id, wait.signal) : void 0;
|
|
296
|
+
}, wait)
|
|
297
|
+
};
|
|
298
|
+
};
|
|
299
|
+
const startFindAll = async (raw, objective, o, call) => {
|
|
300
|
+
const created = record(await raw.request("POST", "/v1beta/findall/runs", {
|
|
301
|
+
...call,
|
|
302
|
+
body: compact({
|
|
303
|
+
entity_type: o.entityType,
|
|
304
|
+
exclude_list: o.exclude,
|
|
305
|
+
generator: o.generator ?? "base",
|
|
306
|
+
match_conditions: o.conditions.map((condition) => ({
|
|
307
|
+
description: condition.description,
|
|
308
|
+
name: condition.name
|
|
309
|
+
})),
|
|
310
|
+
match_limit: o.limit ?? 10,
|
|
311
|
+
metadata: o.metadata,
|
|
312
|
+
objective
|
|
313
|
+
})
|
|
314
|
+
}));
|
|
315
|
+
const id = requireId(provider, created.findall_id);
|
|
316
|
+
if (o.schema) try {
|
|
317
|
+
await raw.request("POST", `/v1beta/findall/runs/${id}/enrich`, {
|
|
318
|
+
body: compact({
|
|
319
|
+
output_schema: jsonOutput(o.schema),
|
|
320
|
+
processor: o.processor
|
|
321
|
+
}),
|
|
322
|
+
signal: call.signal
|
|
49
323
|
});
|
|
324
|
+
} catch (error) {
|
|
325
|
+
throw withJob(error, id);
|
|
326
|
+
}
|
|
327
|
+
return id;
|
|
328
|
+
};
|
|
329
|
+
const findAllResult = async (raw, id, signal) => {
|
|
330
|
+
const run = record(await raw.request("GET", `/v1beta/findall/runs/${id}`, { signal }));
|
|
331
|
+
const status = text(record(run.status).status);
|
|
332
|
+
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,
|
|
334
|
+
jobId: id,
|
|
335
|
+
provider
|
|
50
336
|
});
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
|
|
337
|
+
return status === "completed" || status === "failed" || status === "cancelled" ? record(await raw.request("GET", `/v1beta/findall/runs/${id}/result`, { signal })) : void 0;
|
|
338
|
+
};
|
|
339
|
+
// src/adapters/parallel.ts
|
|
340
|
+
const parallel = (config = {}) => {
|
|
54
341
|
const raw = createRawClient({
|
|
55
|
-
provider,
|
|
56
342
|
baseUrl: config.baseUrl ?? "https://api.parallel.ai",
|
|
343
|
+
fetch: config.fetch,
|
|
57
344
|
headers: { "x-api-key": requireKey(provider, config.apiKey, "PARALLEL_API_KEY") },
|
|
58
|
-
|
|
345
|
+
provider
|
|
59
346
|
});
|
|
60
347
|
return defineAdapter({
|
|
61
348
|
name: provider,
|
|
62
349
|
operations: {
|
|
63
|
-
async
|
|
350
|
+
async answer(question, options) {
|
|
64
351
|
const { call, rest: o } = callSettings(options);
|
|
65
|
-
|
|
352
|
+
refuseTogether(provider, o, "includeDomains", "excludeDomains");
|
|
353
|
+
const filters = nonEmpty({
|
|
354
|
+
allowed_domains: o.includeDomains,
|
|
355
|
+
blocked_domains: o.excludeDomains
|
|
356
|
+
});
|
|
357
|
+
const response = record(await raw.request("POST", "/v1/responses", {
|
|
66
358
|
...call,
|
|
67
359
|
body: compact({
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
360
|
+
input: question,
|
|
361
|
+
instructions: o.instructions,
|
|
362
|
+
metadata: o.metadata,
|
|
363
|
+
model: "parallel",
|
|
364
|
+
previous_response_id: o.continueFrom,
|
|
365
|
+
reasoning: o.effort ? { effort: o.effort } : void 0,
|
|
366
|
+
text: o.schema ? { format: {
|
|
367
|
+
name: "answer",
|
|
368
|
+
schema: o.schema,
|
|
369
|
+
type: "json_schema"
|
|
370
|
+
} } : void 0,
|
|
371
|
+
tools: filters ? [{
|
|
372
|
+
filters,
|
|
373
|
+
type: "web_search"
|
|
374
|
+
}] : void 0
|
|
76
375
|
})
|
|
77
376
|
}));
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
377
|
+
const failure = record(response.error);
|
|
378
|
+
if (response.status === "failed" || text(failure.message)) throw new FieldworkError("ProviderError", `parallel could not answer: ${text(failure.message) ?? "the response failed"}`, {
|
|
379
|
+
cause: response,
|
|
380
|
+
provider
|
|
381
|
+
});
|
|
382
|
+
const parts = responseMessages(response).flatMap((message) => list(message.content).map((part) => record(part)).filter((part) => part.type === "output_text"));
|
|
383
|
+
const answer = parts.map((part) => text(part.text)).filter((part) => part !== void 0).join("\n\n");
|
|
384
|
+
if (answer === "") throw new FieldworkError("ProviderError", `parallel returned no answer text (status ${text(response.status) ?? "unknown"})`, {
|
|
385
|
+
cause: response,
|
|
386
|
+
provider
|
|
387
|
+
});
|
|
388
|
+
const usage = record(response.usage);
|
|
389
|
+
const incomplete = text(record(response.incomplete_details).reason);
|
|
390
|
+
return compact({
|
|
391
|
+
answer,
|
|
392
|
+
citations: uniqueCitations(citations(parts.flatMap((part) => list(part.annotations)).filter((item) => record(item).type === "url_citation"))),
|
|
393
|
+
continuationId: text(response.id),
|
|
394
|
+
meta: meta({
|
|
395
|
+
requestId: response.id,
|
|
396
|
+
units: {
|
|
397
|
+
input_tokens: usage.input_tokens,
|
|
398
|
+
output_tokens: usage.output_tokens,
|
|
399
|
+
total_tokens: usage.total_tokens
|
|
400
|
+
},
|
|
401
|
+
warnings: incomplete ? [`the answer is incomplete: ${incomplete}`] : void 0
|
|
87
402
|
}),
|
|
403
|
+
output: o.schema ? parseJson(provider, answer) : void 0,
|
|
88
404
|
raw: response
|
|
89
|
-
};
|
|
405
|
+
});
|
|
90
406
|
},
|
|
91
|
-
async
|
|
407
|
+
async decide(context, questions, options) {
|
|
92
408
|
const { call, rest: o } = callSettings(options);
|
|
93
|
-
const
|
|
409
|
+
const entries = Object.entries(questions);
|
|
410
|
+
const names = entries.map(([name]) => name);
|
|
411
|
+
if (names.length < 1 || names.length > 100) throw invalid(`parallel decisions take 1 to 100 questions; got ${names.length}`);
|
|
412
|
+
const badName = names.find((name) => !QUESTION_NAME.test(name));
|
|
413
|
+
if (badName !== void 0) throw invalid(`parallel question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
|
|
414
|
+
const response = record(await raw.request("POST", "/v1/decisions", {
|
|
94
415
|
...call,
|
|
95
416
|
body: compact({
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
})
|
|
417
|
+
advanced_settings: nonEmpty({
|
|
418
|
+
include_excerpts: o.includeExcerpts,
|
|
419
|
+
location: o.country
|
|
420
|
+
}),
|
|
421
|
+
questions: Object.fromEntries(entries.map(([name, question]) => [name, decisionQuestion(name, question)])),
|
|
422
|
+
state: context ?? null
|
|
103
423
|
})
|
|
104
424
|
}));
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
throw new FieldworkError("ProviderError", `parallel could not read ${url}: ${text(failure.content) ?? text(failure.error_type) ?? "no content returned"}`, {
|
|
109
|
-
provider,
|
|
110
|
-
cause: response
|
|
111
|
-
});
|
|
112
|
-
}
|
|
425
|
+
const answers = record(response.answers);
|
|
426
|
+
const result = {};
|
|
427
|
+
for (const [name, question] of entries) if (answers[name] !== void 0) result[name] = decisionAnswer(question, answers[name]);
|
|
113
428
|
return compact({
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
429
|
+
answers: result,
|
|
430
|
+
citations: citations(response.citations),
|
|
431
|
+
meta: meta({
|
|
432
|
+
requestId: response.decision_id,
|
|
433
|
+
units: { input_tokens: record(response.usage).input_tokens }
|
|
434
|
+
}),
|
|
118
435
|
raw: response
|
|
119
436
|
});
|
|
120
437
|
},
|
|
438
|
+
async discover(objective, options) {
|
|
439
|
+
const { call, rest: o } = callSettings(options);
|
|
440
|
+
const id = o.resume ?? await startFindAll(raw, objective, o, call);
|
|
441
|
+
const result = await poll(provider, id, async () => await findAllResult(raw, id, call.signal), {
|
|
442
|
+
...call,
|
|
443
|
+
interval: o.interval
|
|
444
|
+
});
|
|
445
|
+
return discovery(id, result);
|
|
446
|
+
},
|
|
121
447
|
async extract(url, options) {
|
|
122
448
|
const { call, rest: o } = callSettings(options);
|
|
123
449
|
const target = new URL(url);
|
|
124
|
-
const {
|
|
125
|
-
|
|
450
|
+
const { result } = await runTask(raw, compact({
|
|
451
|
+
advanced_settings: nonEmpty({ location: o.country }),
|
|
126
452
|
input: {
|
|
127
|
-
|
|
128
|
-
|
|
453
|
+
instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
|
|
454
|
+
url
|
|
129
455
|
},
|
|
456
|
+
metadata: o.metadata,
|
|
457
|
+
processor: o.processor ?? "base",
|
|
130
458
|
source_policy: { include_domains: [`${target.hostname}${target.pathname}`.replace(/\/$/u, "")] },
|
|
131
|
-
task_spec: { output_schema:
|
|
132
|
-
},
|
|
459
|
+
task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "auto" } }
|
|
460
|
+
}), {
|
|
461
|
+
...call,
|
|
462
|
+
interval: o.interval,
|
|
463
|
+
resume: o.resume
|
|
464
|
+
});
|
|
133
465
|
const output = record(result.output);
|
|
134
|
-
return {
|
|
466
|
+
return compact({
|
|
135
467
|
data: output.content,
|
|
136
|
-
fields: basis(output),
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
468
|
+
fields: basis(output.basis),
|
|
469
|
+
meta: taskMeta(result),
|
|
470
|
+
raw: result
|
|
471
|
+
});
|
|
472
|
+
},
|
|
473
|
+
async images(query, options) {
|
|
474
|
+
const { call, rest: o } = callSettings(options);
|
|
475
|
+
const response = record(await raw.request("POST", "/v1/images/search", {
|
|
476
|
+
...call,
|
|
477
|
+
body: compact({
|
|
478
|
+
advanced_settings: nonEmpty({
|
|
479
|
+
location: o.country,
|
|
480
|
+
max_results: o.limit
|
|
481
|
+
}),
|
|
482
|
+
mode: o.mode,
|
|
483
|
+
objective: o.objective ?? query,
|
|
484
|
+
search_queries: o.queries ?? [query],
|
|
485
|
+
session_id: o.sessionId
|
|
486
|
+
})
|
|
487
|
+
}));
|
|
488
|
+
return compact({
|
|
489
|
+
meta: meta({
|
|
490
|
+
requestId: response.search_id,
|
|
491
|
+
units: usageUnits(response.usage),
|
|
492
|
+
warnings: response.warnings
|
|
493
|
+
}),
|
|
494
|
+
raw: response,
|
|
495
|
+
results: list(response.results).map((item) => {
|
|
496
|
+
const image = record(item);
|
|
497
|
+
return compact({
|
|
498
|
+
height: num(image.height),
|
|
499
|
+
sourceUrl: text(image.source_page_url),
|
|
500
|
+
title: text(image.title),
|
|
501
|
+
url: text(image.image_url) ?? "",
|
|
502
|
+
width: num(image.width)
|
|
503
|
+
});
|
|
504
|
+
})
|
|
505
|
+
});
|
|
506
|
+
},
|
|
507
|
+
monitor: {
|
|
508
|
+
async create(options) {
|
|
509
|
+
const { call, rest: o } = callSettings(options);
|
|
510
|
+
const { urls } = o;
|
|
511
|
+
if (urls !== void 0) throw invalid("parallel monitors search the web for a query and cannot watch a list of URLs; restrict a query with includeDomains, which accepts domain/path prefixes");
|
|
512
|
+
if (o.taskRunId === void 0 && o.query === void 0) throw invalid("a parallel monitor needs a query or a taskRunId");
|
|
513
|
+
if (o.taskRunId !== void 0) for (const name of [
|
|
514
|
+
"query",
|
|
515
|
+
"schema",
|
|
516
|
+
"includeBackfill",
|
|
517
|
+
"country",
|
|
518
|
+
"includeDomains",
|
|
519
|
+
"excludeDomains",
|
|
520
|
+
"publishedAfter"
|
|
521
|
+
]) refuseTogether(provider, o, "taskRunId", name);
|
|
522
|
+
if (o.webhookEvents && !o.webhookUrl) throw invalid("webhookEvents needs a webhookUrl");
|
|
523
|
+
const response = await raw.request("POST", "/v1/monitors", {
|
|
524
|
+
...call,
|
|
525
|
+
body: compact({
|
|
526
|
+
frequency: frequency(o.schedule),
|
|
527
|
+
metadata: o.metadata,
|
|
528
|
+
processor: o.processor,
|
|
529
|
+
settings: o.taskRunId === void 0 ? compact({
|
|
530
|
+
advanced_settings: nonEmpty({
|
|
531
|
+
source_policy: sourcePolicy(o),
|
|
532
|
+
location: o.country
|
|
533
|
+
}),
|
|
534
|
+
include_backfill: o.includeBackfill,
|
|
535
|
+
output_schema: o.schema ? jsonOutput(o.schema) : void 0,
|
|
536
|
+
query: o.query
|
|
537
|
+
}) : { task_run_id: o.taskRunId },
|
|
538
|
+
type: o.taskRunId === void 0 ? "event_stream" : "snapshot",
|
|
539
|
+
webhook: o.webhookUrl ? compact({
|
|
540
|
+
event_types: o.webhookEvents,
|
|
541
|
+
url: o.webhookUrl
|
|
542
|
+
}) : void 0
|
|
543
|
+
})
|
|
544
|
+
});
|
|
545
|
+
return monitorInfo(response);
|
|
546
|
+
},
|
|
547
|
+
async delete(id, options) {
|
|
548
|
+
await raw.request("POST", `/v1/monitors/${encodeURIComponent(id)}/cancel`, options);
|
|
549
|
+
},
|
|
550
|
+
async events(id, options) {
|
|
551
|
+
const { call, rest: o } = callSettings(options);
|
|
552
|
+
const response = record(await raw.request("GET", `/v1/monitors/${encodeURIComponent(id)}/events`, {
|
|
553
|
+
...call,
|
|
554
|
+
query: {
|
|
555
|
+
cursor: o.cursor,
|
|
556
|
+
event_group_id: o.eventGroupId,
|
|
557
|
+
include_completions: o.includeCompletions,
|
|
558
|
+
limit: o.limit
|
|
559
|
+
}
|
|
560
|
+
}));
|
|
561
|
+
return compact({
|
|
562
|
+
events: list(response.events).map((item) => monitorEvent(item)),
|
|
563
|
+
next: text(response.next_cursor),
|
|
564
|
+
raw: response
|
|
565
|
+
});
|
|
566
|
+
},
|
|
567
|
+
async get(id, options) {
|
|
568
|
+
return monitorInfo(await raw.request("GET", `/v1/monitors/${encodeURIComponent(id)}`, options));
|
|
569
|
+
},
|
|
570
|
+
async list(options) {
|
|
571
|
+
const monitors = [];
|
|
572
|
+
let cursor;
|
|
573
|
+
do {
|
|
574
|
+
const page = record(await raw.request("GET", "/v1/monitors", {
|
|
575
|
+
...options,
|
|
576
|
+
query: {
|
|
577
|
+
cursor,
|
|
578
|
+
limit: 100
|
|
579
|
+
}
|
|
580
|
+
}));
|
|
581
|
+
monitors.push(...list(page.monitors).map((item) => monitorInfo(item)));
|
|
582
|
+
cursor = text(page.next_cursor);
|
|
583
|
+
} while (cursor !== void 0);
|
|
584
|
+
return monitors;
|
|
585
|
+
}
|
|
586
|
+
},
|
|
587
|
+
async read(url, options) {
|
|
588
|
+
const { call, rest: o } = callSettings(options);
|
|
589
|
+
const response = record(await raw.request("POST", "/v1/extract", {
|
|
590
|
+
...call,
|
|
591
|
+
body: extractBody([url], o)
|
|
592
|
+
}));
|
|
593
|
+
const result = record(list(response.results)[0]);
|
|
594
|
+
if (!result.url) {
|
|
595
|
+
const failure = record(list(response.errors)[0]);
|
|
596
|
+
throw new FieldworkError("ProviderError", `parallel could not read ${url}: ${Object.keys(failure).length > 0 ? extractFailure(failure) : "no content returned"}`, {
|
|
597
|
+
cause: response,
|
|
598
|
+
provider
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
return pageFrom(result, {
|
|
602
|
+
meta: extractMeta(response),
|
|
603
|
+
raw: response
|
|
604
|
+
});
|
|
605
|
+
},
|
|
606
|
+
async readMany(urls, options) {
|
|
607
|
+
const { call, rest: o } = callSettings(options);
|
|
608
|
+
if (urls.length > 20) throw invalid(`parallel reads up to 20 URLs in one call; got ${urls.length}`);
|
|
609
|
+
const response = record(await raw.request("POST", "/v1/extract", {
|
|
610
|
+
...call,
|
|
611
|
+
body: extractBody(urls, o)
|
|
612
|
+
}));
|
|
613
|
+
return compact({
|
|
614
|
+
failed: list(response.errors).map((item) => {
|
|
615
|
+
const failure = record(item);
|
|
616
|
+
return {
|
|
617
|
+
error: extractFailure(failure),
|
|
618
|
+
url: text(failure.url) ?? ""
|
|
619
|
+
};
|
|
620
|
+
}),
|
|
621
|
+
id: text(response.extract_id),
|
|
622
|
+
meta: extractMeta(response),
|
|
623
|
+
pages: list(response.results).map((item) => pageFrom(record(item))),
|
|
624
|
+
raw: response
|
|
625
|
+
});
|
|
142
626
|
},
|
|
143
627
|
async research(question, options) {
|
|
144
628
|
const { call, rest: o } = callSettings(options);
|
|
145
629
|
const { id, result } = await runTask(raw, compact({
|
|
146
|
-
|
|
630
|
+
advanced_settings: nonEmpty({ location: o.country }),
|
|
147
631
|
input: question,
|
|
632
|
+
metadata: o.metadata,
|
|
633
|
+
previous_interaction_id: o.continueFrom,
|
|
634
|
+
processor: o.processor ?? "base",
|
|
148
635
|
source_policy: sourcePolicy(o),
|
|
149
|
-
task_spec: { output_schema:
|
|
150
|
-
}),
|
|
636
|
+
task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "text" } }
|
|
637
|
+
}), {
|
|
638
|
+
...call,
|
|
639
|
+
interval: o.interval,
|
|
640
|
+
resume: o.resume
|
|
641
|
+
});
|
|
151
642
|
const output = record(result.output);
|
|
152
|
-
const fields = basis(output);
|
|
153
|
-
return {
|
|
643
|
+
const fields = basis(output.basis);
|
|
644
|
+
return compact({
|
|
645
|
+
continuationId: text(record(result.run).interaction_id),
|
|
646
|
+
fields,
|
|
154
647
|
id,
|
|
648
|
+
meta: taskMeta(result),
|
|
155
649
|
output: output.content,
|
|
156
|
-
|
|
157
|
-
fields,
|
|
158
|
-
|
|
159
|
-
};
|
|
650
|
+
raw: result,
|
|
651
|
+
sources: citedBy(fields),
|
|
652
|
+
status: "completed"
|
|
653
|
+
});
|
|
654
|
+
},
|
|
655
|
+
async search(query, options) {
|
|
656
|
+
const { call, rest: o } = callSettings(options);
|
|
657
|
+
const response = record(await raw.request("POST", "/v1/search", {
|
|
658
|
+
...call,
|
|
659
|
+
body: compact({
|
|
660
|
+
advanced_settings: nonEmpty({
|
|
661
|
+
excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
|
|
662
|
+
fetch_policy: fetchPolicy(o.maxAge),
|
|
663
|
+
location: o.country,
|
|
664
|
+
max_results: o.limit,
|
|
665
|
+
source_policy: sourcePolicy(o)
|
|
666
|
+
}),
|
|
667
|
+
max_chars_total: o.maxCharsTotal,
|
|
668
|
+
mode: o.mode,
|
|
669
|
+
objective: o.objective ?? query,
|
|
670
|
+
search_queries: o.queries ?? [query],
|
|
671
|
+
session_id: o.sessionId
|
|
672
|
+
})
|
|
673
|
+
}));
|
|
674
|
+
return compact({
|
|
675
|
+
meta: meta({
|
|
676
|
+
requestId: response.search_id,
|
|
677
|
+
units: usageUnits(response.usage),
|
|
678
|
+
warnings: response.warnings
|
|
679
|
+
}),
|
|
680
|
+
raw: response,
|
|
681
|
+
results: list(response.results).map((item) => {
|
|
682
|
+
const result = record(item);
|
|
683
|
+
return compact({
|
|
684
|
+
publishedAt: text(result.publish_date),
|
|
685
|
+
snippet: strings(result.excerpts)?.join(" … "),
|
|
686
|
+
title: text(result.title),
|
|
687
|
+
url: text(result.url) ?? ""
|
|
688
|
+
});
|
|
689
|
+
})
|
|
690
|
+
});
|
|
160
691
|
}
|
|
161
692
|
},
|
|
162
693
|
raw
|
|
163
694
|
});
|
|
164
|
-
}
|
|
695
|
+
};
|
|
165
696
|
export { parallel };
|