@howells/fieldwork-sdk 0.5.0 → 0.5.2
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/dist/{adapter-BgdfLBs-.d.ts → adapter-BhTK51Yj.d.ts} +19 -5
- package/dist/brave.d.ts +22 -4
- package/dist/brave.js +69 -2
- package/dist/browserbase.d.ts +23 -3
- package/dist/browserbase.js +5 -2
- package/dist/{document-Dpj01mGx.js → document-CjMeBtV5.js} +1 -1
- package/dist/{errors-Yvk42oZH.js → errors-DROZyb9T.js} +13 -0
- package/dist/exa.d.ts +49 -7
- package/dist/exa.js +84 -24
- package/dist/{fieldwork-CXNIcqSN.d.ts → fieldwork-CseCD_-H.d.ts} +20 -4
- package/dist/firecrawl.d.ts +64 -4
- package/dist/firecrawl.js +231 -110
- package/dist/index.d.ts +3 -3
- package/dist/index.js +25 -1
- package/dist/job-DVsmQMKP.js +47 -0
- package/dist/llamaparse.d.ts +7 -2
- package/dist/llamaparse.js +39 -38
- package/dist/parallel.d.ts +79 -7
- package/dist/parallel.js +176 -69
- package/dist/{parse-D4SMt-Ip.js → parse-BY3R0oWO.js} +56 -43
- package/dist/perplexity.d.ts +37 -5
- package/dist/perplexity.js +121 -30
- package/dist/reducto.d.ts +16 -2
- package/dist/reducto.js +50 -47
- package/dist/{schema-DbSIABP0.js → schema-BYcXgfuZ.js} +8 -4
- package/dist/{schema-Cupy7-7q.d.ts → schema-CNd51xdD.d.ts} +1 -1
- package/dist/serpapi.d.ts +25 -5
- package/dist/serpapi.js +99 -2
- package/dist/tavily.d.ts +44 -4
- package/dist/tavily.js +80 -53
- package/dist/tools.d.ts +16 -18
- package/dist/tools.js +129 -14
- package/package.json +1 -1
package/dist/perplexity.d.ts
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
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-
|
|
2
|
-
import { t as OutputSchema } from "./schema-
|
|
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-BhTK51Yj.js";
|
|
2
|
+
import { t as OutputSchema } from "./schema-CNd51xdD.js";
|
|
3
|
+
/** Settings for `perplexity()`. */
|
|
3
4
|
interface PerplexityConfig {
|
|
4
5
|
/** Defaults to the PERPLEXITY_API_KEY environment variable. */
|
|
5
6
|
apiKey?: string;
|
|
7
|
+
/** Defaults to https://api.perplexity.ai. */
|
|
6
8
|
baseUrl?: string;
|
|
9
|
+
/** Used in place of the global `fetch`. */
|
|
7
10
|
fetch?: typeof fetch;
|
|
8
11
|
/** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
|
|
9
12
|
retries?: number;
|
|
10
13
|
}
|
|
11
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* The filters Perplexity applies to web search, on `/search` and inside the
|
|
16
|
+
* Agent API's `web_search` tool. Dates are given as YYYY-MM-DD and sent as
|
|
17
|
+
* MM/DD/YYYY, which Perplexity requires. Perplexity has one domain list, so
|
|
18
|
+
* `excludeDomains` entries are sent with a leading `-`.
|
|
19
|
+
*/
|
|
12
20
|
interface PerplexityFilters {
|
|
13
21
|
/** Plain domains such as `nature.com`; Perplexity also accepts a path (`nature.com/articles`) or a top-level domain (`.gov`). At most 20. Not with `excludeDomains`. */
|
|
14
22
|
includeDomains?: string[];
|
|
@@ -24,6 +32,11 @@ interface PerplexityFilters {
|
|
|
24
32
|
lastUpdatedBefore?: string;
|
|
25
33
|
recency?: Recency;
|
|
26
34
|
}
|
|
35
|
+
/**
|
|
36
|
+
* Options for `search` (`POST /search`). Refused before sending: both domain lists,
|
|
37
|
+
* more than five queries in all, a `limit` over 20 (50 with `searchType: "people"`),
|
|
38
|
+
* and a date that is not YYYY-MM-DD.
|
|
39
|
+
*/
|
|
27
40
|
interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
|
|
28
41
|
/** Results to return: up to 20, or up to 50 with `searchType: "people"`. */
|
|
29
42
|
limit?: number;
|
|
@@ -36,7 +49,7 @@ interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
|
|
|
36
49
|
searchType?: "web" | "fast" | "people";
|
|
37
50
|
/** ISO 3166-1 alpha-2 code such as "GB". */
|
|
38
51
|
country?: string;
|
|
39
|
-
/** ISO 639-1 codes, at most 20. Several codes match any of them. */
|
|
52
|
+
/** ISO 639-1 codes, at most 20, lower-cased before sending. Several codes match any of them. */
|
|
40
53
|
language?: string | string[];
|
|
41
54
|
/** Page-content tokens across all results. */
|
|
42
55
|
maxTokens?: number;
|
|
@@ -45,9 +58,11 @@ interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
|
|
|
45
58
|
}
|
|
46
59
|
/** An effort level, or a name pinned to a version such as `fast@2026-10-16.0`. */
|
|
47
60
|
type Pinned<Name extends string> = Name | `${Name}@${string}`;
|
|
61
|
+
/** Options for `answer`: a synchronous Agent API call. It takes no search filters. */
|
|
48
62
|
interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
|
|
49
63
|
/** Defaults to "fast". Answers are synchronous, so only the quicker levels are offered. */
|
|
50
64
|
effort?: Pinned<"fast" | "low" | "medium">;
|
|
65
|
+
/** System instructions for the answer. */
|
|
51
66
|
instructions?: string;
|
|
52
67
|
/** A JSON Schema, or a Zod, Valibot or ArkType schema that types and checks `output`. */
|
|
53
68
|
schema?: OutputSchema<T>;
|
|
@@ -59,6 +74,12 @@ interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
|
|
|
59
74
|
* `ultra-preview` and version pins (`high@2026-10-28.0`) are accepted too.
|
|
60
75
|
*/
|
|
61
76
|
type PerplexityEffort = "fast" | "low" | "medium" | "high" | "xhigh" | "ultra-preview" | (string & {});
|
|
77
|
+
/**
|
|
78
|
+
* Options for `research`: a background Agent API run, polled until it ends. The
|
|
79
|
+
* search filters go on the run's `web_search` tool, and both domain lists are
|
|
80
|
+
* refused together. A run that ends `incomplete` or `cancelled` with output returns
|
|
81
|
+
* `status: "partial"`.
|
|
82
|
+
*/
|
|
62
83
|
interface PerplexityResearchOptions<T = unknown> extends CallOptions, PerplexityFilters {
|
|
63
84
|
schema?: OutputSchema<T>;
|
|
64
85
|
/**
|
|
@@ -69,7 +90,11 @@ interface PerplexityResearchOptions<T = unknown> extends CallOptions, Perplexity
|
|
|
69
90
|
effort?: PerplexityEffort;
|
|
70
91
|
/** A model in `provider/model` form, such as `openai/gpt-6-luna`. Overrides the effort's model. */
|
|
71
92
|
model?: string;
|
|
72
|
-
/**
|
|
93
|
+
/**
|
|
94
|
+
* Models to try in order, one to five (more is refused); the first that works
|
|
95
|
+
* answers. Takes precedence over `model`. With `model` or `models` and no
|
|
96
|
+
* `effort`, the run gets the `web_search` and `fetch_url` tools.
|
|
97
|
+
*/
|
|
73
98
|
models?: string[];
|
|
74
99
|
/**
|
|
75
100
|
* Caps steps of the research loop (1 to 500), not money. With `model` or
|
|
@@ -78,6 +103,7 @@ interface PerplexityResearchOptions<T = unknown> extends CallOptions, Perplexity
|
|
|
78
103
|
*/
|
|
79
104
|
maxSteps?: number;
|
|
80
105
|
maxOutputTokens?: number;
|
|
106
|
+
/** System instructions for the run. */
|
|
81
107
|
instructions?: string;
|
|
82
108
|
/** ISO 639-1 code for the language of the report. */
|
|
83
109
|
languagePreference?: string;
|
|
@@ -90,11 +116,17 @@ interface PerplexityResearchOptions<T = unknown> extends CallOptions, Perplexity
|
|
|
90
116
|
/** Milliseconds between checks. Defaults to 2000. */
|
|
91
117
|
interval?: number;
|
|
92
118
|
}
|
|
119
|
+
/** Perplexity's decider models. The type is open so newer names are accepted. */
|
|
93
120
|
type PerplexityDeciderModel = "pplx-decider-v1.2" | "pplx-decider-flash-v1.2" | "pplx-decider-latest" | "pplx-decider-flash-latest" | (string & {});
|
|
121
|
+
/** Options for `decide` (`POST /v1/decisions`). The result never has citations. */
|
|
94
122
|
interface PerplexityDecideOptions extends CallOptions {
|
|
95
123
|
/** Defaults to "pplx-decider-latest". The flash models are smaller and cheaper. */
|
|
96
124
|
model?: PerplexityDeciderModel;
|
|
97
125
|
}
|
|
126
|
+
/**
|
|
127
|
+
* What Perplexity offers: search, answer, research and decide. `research` runs as a
|
|
128
|
+
* job and accepts `resume`.
|
|
129
|
+
*/
|
|
98
130
|
interface PerplexityOperations {
|
|
99
131
|
search: (query: string, options?: PerplexitySearchOptions) => Promise<SearchResponse>;
|
|
100
132
|
answer: <T = unknown>(question: string, options?: PerplexityAnswerOptions<T>) => Promise<Answer<T>>;
|
package/dist/perplexity.js
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import { t as defineAdapter } from "./adapter-DWYJys20.js";
|
|
2
|
-
import {
|
|
3
|
-
import { B as
|
|
4
|
-
import {
|
|
2
|
+
import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
|
|
3
|
+
import { A as citationOf, B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, P as meta, S as withOriginal, T as requireKey, V as uniqueCitations, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, y as sourceShape, z as refuseTogether } from "./parse-BY3R0oWO.js";
|
|
4
|
+
import { t as runJob } from "./job-DVsmQMKP.js";
|
|
5
|
+
import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
|
|
5
6
|
import * as z from "zod/mini";
|
|
6
7
|
// src/adapters/perplexity/parse.ts
|
|
8
|
+
/** The name this adapter reports in errors and results. */
|
|
7
9
|
const provider = "perplexity";
|
|
10
|
+
/** The Agent run statuses after which a run no longer changes. */
|
|
8
11
|
const TERMINAL = /* @__PURE__ */ new Set([
|
|
9
12
|
"completed",
|
|
10
13
|
"failed",
|
|
11
14
|
"incomplete",
|
|
12
15
|
"cancelled"
|
|
13
16
|
]);
|
|
17
|
+
/** Perplexity's MM/DD/YYYY form of a YYYY-MM-DD date. Refuses any other format. */
|
|
14
18
|
const usDate = (name, date) => {
|
|
15
19
|
if (date === void 0) return date;
|
|
16
20
|
const match = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u.exec(date);
|
|
@@ -18,6 +22,10 @@ const usDate = (name, date) => {
|
|
|
18
22
|
const { year, month, day } = match.groups;
|
|
19
23
|
return `${month}/${day}/${year}`;
|
|
20
24
|
};
|
|
25
|
+
/**
|
|
26
|
+
* The filter fields `/search` and the `web_search` tool share. Refuses both domain
|
|
27
|
+
* lists together, since Perplexity has one list and marks exclusions with `-`.
|
|
28
|
+
*/
|
|
21
29
|
const filterFields = (o) => {
|
|
22
30
|
refuseTogether(provider, { ...o }, "includeDomains", "excludeDomains");
|
|
23
31
|
const domains = o.includeDomains ?? o.excludeDomains?.map((d) => `-${d}`);
|
|
@@ -30,6 +38,10 @@ const filterFields = (o) => {
|
|
|
30
38
|
search_recency_filter: o.recency
|
|
31
39
|
});
|
|
32
40
|
};
|
|
41
|
+
/**
|
|
42
|
+
* The `web_search` tool with the filters and `country` (as the user's location), or
|
|
43
|
+
* undefined when none is set, so the effort's own tool applies.
|
|
44
|
+
*/
|
|
33
45
|
const webSearchTool = (o) => {
|
|
34
46
|
const filters = filterFields(o);
|
|
35
47
|
const tool = compact({
|
|
@@ -39,14 +51,23 @@ const webSearchTool = (o) => {
|
|
|
39
51
|
});
|
|
40
52
|
return Object.keys(tool).length > 1 ? tool : void 0;
|
|
41
53
|
};
|
|
54
|
+
/** Lower-cased language codes as a list, or undefined when there are none. */
|
|
42
55
|
const languageCodes = (language) => {
|
|
43
56
|
const codes = [language ?? []].flat().map((code) => code.toLowerCase());
|
|
44
57
|
return codes.length > 0 ? codes : void 0;
|
|
45
58
|
};
|
|
59
|
+
/**
|
|
60
|
+
* `JobFailed` once the run has an id, else `RateLimited` for a rate-limit error,
|
|
61
|
+
* else `ProviderError`.
|
|
62
|
+
*/
|
|
46
63
|
const errorCode = (jobId, rateLimited) => {
|
|
47
64
|
if (jobId !== void 0 && jobId !== "") return "JobFailed";
|
|
48
65
|
return rateLimited ? "RateLimited" : "ProviderError";
|
|
49
66
|
};
|
|
67
|
+
/**
|
|
68
|
+
* The error for an Agent response that failed, was cancelled or has no text. It
|
|
69
|
+
* carries `jobId` when given and is retryable for rate-limit and overloaded errors.
|
|
70
|
+
*/
|
|
50
71
|
const responseError = (run, jobId) => {
|
|
51
72
|
const { error, status } = run.value;
|
|
52
73
|
const { type } = error;
|
|
@@ -59,7 +80,16 @@ const responseError = (run, jobId) => {
|
|
|
59
80
|
retryable: rateLimited || type === "overloaded"
|
|
60
81
|
});
|
|
61
82
|
};
|
|
83
|
+
/**
|
|
84
|
+
* The citations in message annotations. Only `url_citation` annotations, or ones
|
|
85
|
+
* with no type, count.
|
|
86
|
+
*/
|
|
62
87
|
const annotated = (annotations) => annotations.filter((found) => found.type === void 0 || found.type === "url_citation").map((found) => citationOf(found)).filter((source) => source !== void 0);
|
|
88
|
+
/**
|
|
89
|
+
* Reads an Agent response. `text` joins every message part. `cited` is the unique
|
|
90
|
+
* sources annotating that text. `retrieved` is the unique pages the run's
|
|
91
|
+
* `search_results` and `fetch_url_results` returned, as title and URL only.
|
|
92
|
+
*/
|
|
63
93
|
const readResponse = (body) => {
|
|
64
94
|
const parts = [];
|
|
65
95
|
const cited = [];
|
|
@@ -86,6 +116,10 @@ const readResponse = (body) => {
|
|
|
86
116
|
text: parts.join("")
|
|
87
117
|
};
|
|
88
118
|
};
|
|
119
|
+
/**
|
|
120
|
+
* Meta from an Agent response: cost in USD, token units and the id as `requestId`.
|
|
121
|
+
* `warnings` is one message.
|
|
122
|
+
*/
|
|
89
123
|
const responseMeta = (body, warnings) => {
|
|
90
124
|
const { usage } = body;
|
|
91
125
|
const input = usage.input_tokens_details;
|
|
@@ -103,6 +137,7 @@ const responseMeta = (body, warnings) => {
|
|
|
103
137
|
warnings
|
|
104
138
|
});
|
|
105
139
|
};
|
|
140
|
+
/** The Agent `response_format` for a schema, named "output", or undefined. */
|
|
106
141
|
const responseFormat = (schema) => schema ? {
|
|
107
142
|
json_schema: {
|
|
108
143
|
name: "output",
|
|
@@ -110,11 +145,21 @@ const responseFormat = (schema) => schema ? {
|
|
|
110
145
|
},
|
|
111
146
|
type: "json_schema"
|
|
112
147
|
} : void 0;
|
|
148
|
+
/**
|
|
149
|
+
* The decision `state`. A string, object or array goes through as it is; a number
|
|
150
|
+
* or boolean is sent as text; anything else is refused.
|
|
151
|
+
*/
|
|
113
152
|
const decisionState = (context) => {
|
|
114
153
|
if (typeof context === "string" || typeof context === "object" && context) return context;
|
|
115
154
|
if (typeof context === "number" || typeof context === "boolean") return String(context);
|
|
116
155
|
throw invalidRequest(provider, "decide needs a context: a string, object or array");
|
|
117
156
|
};
|
|
157
|
+
/**
|
|
158
|
+
* The effort, model, step and tool fields of a research run. Refuses `models`
|
|
159
|
+
* outside one to five. With `model` or `models` and no `effort`, the run is built
|
|
160
|
+
* directly: `maxSteps` or 10 steps, with `web_search` and `fetch_url` tools.
|
|
161
|
+
* Otherwise the effort defaults to "high" and a tool is sent only to carry filters.
|
|
162
|
+
*/
|
|
118
163
|
const researchSetup = (o) => {
|
|
119
164
|
if (o.models && (o.models.length < 1 || o.models.length > 5)) throw invalidRequest(provider, "models takes one to five models");
|
|
120
165
|
const searchTool = webSearchTool(o);
|
|
@@ -132,20 +177,29 @@ const researchSetup = (o) => {
|
|
|
132
177
|
tools: searchTool ? [searchTool] : void 0
|
|
133
178
|
};
|
|
134
179
|
};
|
|
135
|
-
|
|
180
|
+
/**
|
|
181
|
+
* A research run's output: the reply text, or its parsed JSON when a schema is set.
|
|
182
|
+
* Invalid JSON from a completed run throws the parse error; from a run cut short it
|
|
183
|
+
* throws `JobFailed`.
|
|
184
|
+
*/
|
|
185
|
+
const researchOutput = (run, reply, schema) => {
|
|
136
186
|
if (!schema) return reply;
|
|
137
187
|
const { status } = run.value;
|
|
138
188
|
try {
|
|
139
189
|
return parseJson(provider, reply);
|
|
140
190
|
} catch (error) {
|
|
141
|
-
if (status === "completed") throw
|
|
191
|
+
if (status === "completed") throw error;
|
|
142
192
|
throw new FieldworkError("JobFailed", `perplexity research ended ${status} with output that is not valid JSON`, {
|
|
143
193
|
cause: run.original,
|
|
144
|
-
jobId: id,
|
|
145
194
|
provider
|
|
146
195
|
});
|
|
147
196
|
}
|
|
148
197
|
};
|
|
198
|
+
/**
|
|
199
|
+
* Perplexity's form of a normalized decision question: `yesno` is `noul`, `choice`
|
|
200
|
+
* takes its choices as criteria with no descriptions, and `score` takes the scale's
|
|
201
|
+
* labels, in order, as criteria.
|
|
202
|
+
*/
|
|
149
203
|
const decisionQuestion = (question) => {
|
|
150
204
|
if (question.type === "yesno") return {
|
|
151
205
|
instructions: question.question,
|
|
@@ -162,6 +216,11 @@ const decisionQuestion = (question) => {
|
|
|
162
216
|
type: "score"
|
|
163
217
|
};
|
|
164
218
|
};
|
|
219
|
+
/**
|
|
220
|
+
* One decision answer. `noul` gives a `probability`. Otherwise the probabilities
|
|
221
|
+
* without undefined entries; for a score, Perplexity's level indexes are renamed to
|
|
222
|
+
* the scale's keys (`scores`). `choice` is Perplexity's, else the most likely.
|
|
223
|
+
*/
|
|
165
224
|
const decisionAnswer = (found, scores) => {
|
|
166
225
|
if (found.type === "noul") return compact({ probability: found.noul });
|
|
167
226
|
let probabilities = Object.fromEntries(Object.entries(found.probabilities).filter((entry) => entry[1] !== void 0));
|
|
@@ -190,10 +249,15 @@ const Annotation = looseObject({
|
|
|
190
249
|
...sourceShape,
|
|
191
250
|
type: anything
|
|
192
251
|
});
|
|
252
|
+
/** One part of a message's content. */
|
|
193
253
|
const MessagePart = looseObject({
|
|
194
254
|
annotations: arrayOf(Annotation),
|
|
195
255
|
text: optionalString
|
|
196
256
|
});
|
|
257
|
+
/**
|
|
258
|
+
* One item of an Agent response's `output`: a `message` with `content`, or a list
|
|
259
|
+
* of pages in `results` (`search_results`) or `contents` (`fetch_url_results`).
|
|
260
|
+
*/
|
|
197
261
|
const OutputEntry = looseObject({
|
|
198
262
|
content: arrayOf(MessagePart),
|
|
199
263
|
contents: arrayOf(Source),
|
|
@@ -225,6 +289,10 @@ const Agent = looseObject({
|
|
|
225
289
|
const AgentRun = withOriginal(Agent);
|
|
226
290
|
/** The reply to starting a run: its id as a string, and as it arrived. */
|
|
227
291
|
const AgentStart = looseObject({ id: withOriginal(optionalId) });
|
|
292
|
+
/**
|
|
293
|
+
* One decision answer. `noul` is a yes/no probability; `probabilities` is keyed by
|
|
294
|
+
* choice, or by zero-based score level.
|
|
295
|
+
*/
|
|
228
296
|
const DecisionAnswer = looseObject({
|
|
229
297
|
choice: optionalString,
|
|
230
298
|
confidence: optionalNumber,
|
|
@@ -241,11 +309,17 @@ const DecisionsResponse = looseObject({
|
|
|
241
309
|
})
|
|
242
310
|
});
|
|
243
311
|
// src/adapters/perplexity.ts
|
|
312
|
+
/**
|
|
313
|
+
* `/search`. The query and any `queries` go in one request and come back as one
|
|
314
|
+
* flat list. Refuses more than five queries in all, and a `limit` over 20, or
|
|
315
|
+
* over 50 when `searchType` is "people".
|
|
316
|
+
*/
|
|
244
317
|
const search = async (raw, query, options) => {
|
|
245
318
|
const { call, rest: o } = callSettings(options);
|
|
246
319
|
const queries = [query, ...o.queries ?? []];
|
|
247
320
|
if (queries.length > 5) throw invalidRequest(provider, `search takes at most 5 queries in one request, got ${queries.length}`);
|
|
248
|
-
|
|
321
|
+
const maxResults = o.searchType === "people" ? 50 : 20;
|
|
322
|
+
if (o.limit !== void 0 && o.limit > maxResults) throw invalidRequest(provider, "search returns at most 20 results, or 50 when searchType is \"people\"");
|
|
249
323
|
const response = await raw.request("POST", "/search", {
|
|
250
324
|
...call,
|
|
251
325
|
body: compact({
|
|
@@ -272,6 +346,11 @@ const search = async (raw, query, options) => {
|
|
|
272
346
|
}))
|
|
273
347
|
};
|
|
274
348
|
};
|
|
349
|
+
/**
|
|
350
|
+
* A synchronous Agent API call at the "fast" effort unless `effort` says
|
|
351
|
+
* otherwise. An `incomplete` response returns its text with a warning; a failed or
|
|
352
|
+
* cancelled one, or one with no text, throws.
|
|
353
|
+
*/
|
|
275
354
|
const answer = async (raw, question, options) => {
|
|
276
355
|
const { call, rest: o } = callSettings(options);
|
|
277
356
|
const run = z.parse(AgentRun, await raw.request("POST", "/v1/agent", {
|
|
@@ -296,8 +375,8 @@ const answer = async (raw, question, options) => {
|
|
|
296
375
|
raw: run.original
|
|
297
376
|
});
|
|
298
377
|
};
|
|
378
|
+
/** Starts a background Agent API run and returns its id. */
|
|
299
379
|
const startResearch = async (raw, question, o, call) => {
|
|
300
|
-
if (o.resume !== void 0) return o.resume;
|
|
301
380
|
const created = z.parse(AgentStart, await raw.request("POST", "/v1/agent", {
|
|
302
381
|
creates: true,
|
|
303
382
|
...call,
|
|
@@ -314,34 +393,46 @@ const startResearch = async (raw, question, o, call) => {
|
|
|
314
393
|
}));
|
|
315
394
|
return requireJobId(provider, created.id);
|
|
316
395
|
};
|
|
396
|
+
/**
|
|
397
|
+
* Polls a research run until it reaches a terminal status. A `completed` run
|
|
398
|
+
* returns `completed`. An `incomplete` or `cancelled` one that left text returns
|
|
399
|
+
* `partial` with that status as `stopReason`. A `failed` run, or one with no text,
|
|
400
|
+
* throws `JobFailed`. The run's id is also its `continuationId`.
|
|
401
|
+
*/
|
|
317
402
|
const research = async (raw, question, options) => {
|
|
318
403
|
const { call, rest: o } = callSettings(options);
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
404
|
+
return await runJob(provider, {
|
|
405
|
+
check: async (id, request) => {
|
|
406
|
+
const found = z.parse(AgentRun, await raw.request("GET", `/v1/agent/${segment(id)}`, request));
|
|
407
|
+
return TERMINAL.has(found.value.status ?? "") ? found : void 0;
|
|
408
|
+
},
|
|
409
|
+
finish: async (run, id) => {
|
|
410
|
+
const { status } = run.value;
|
|
411
|
+
const read = readResponse(run.value);
|
|
412
|
+
if (status === "failed" || !read.text) throw responseError(run, id);
|
|
413
|
+
return compact({
|
|
414
|
+
continuationId: id,
|
|
415
|
+
id,
|
|
416
|
+
meta: responseMeta(run.value),
|
|
417
|
+
output: await checkOutput(o.schema, researchOutput(run, read.text, o.schema), { provider }),
|
|
418
|
+
raw: run.original,
|
|
419
|
+
retrieved: read.retrieved.length > 0 ? read.retrieved : void 0,
|
|
420
|
+
sources: read.cited,
|
|
421
|
+
status: status === "completed" ? "completed" : "partial",
|
|
422
|
+
stopReason: status === "completed" ? void 0 : status
|
|
423
|
+
});
|
|
424
|
+
},
|
|
425
|
+
start: async () => await startResearch(raw, question, o, call)
|
|
323
426
|
}, {
|
|
324
427
|
...call,
|
|
325
|
-
interval: o.interval
|
|
326
|
-
|
|
327
|
-
const { status } = run.value;
|
|
328
|
-
const read = readResponse(run.value);
|
|
329
|
-
if (status === "failed" || !read.text) throw responseError(run, id);
|
|
330
|
-
return compact({
|
|
331
|
-
continuationId: id,
|
|
332
|
-
id,
|
|
333
|
-
meta: responseMeta(run.value),
|
|
334
|
-
output: await checkOutput(o.schema, researchOutput(run, read.text, o.schema, id), {
|
|
335
|
-
jobId: id,
|
|
336
|
-
provider
|
|
337
|
-
}),
|
|
338
|
-
raw: run.original,
|
|
339
|
-
retrieved: read.retrieved.length > 0 ? read.retrieved : void 0,
|
|
340
|
-
sources: read.cited,
|
|
341
|
-
status: status === "completed" ? "completed" : "partial",
|
|
342
|
-
stopReason: status === "completed" ? void 0 : status
|
|
428
|
+
interval: o.interval,
|
|
429
|
+
resume: o.resume
|
|
343
430
|
});
|
|
344
431
|
};
|
|
432
|
+
/**
|
|
433
|
+
* `/v1/decisions`. Perplexity returns no citations, so `citations` is always empty.
|
|
434
|
+
* Score answers are keyed by the caller's scale keys.
|
|
435
|
+
*/
|
|
345
436
|
const decide = async (raw, context, questions, options) => {
|
|
346
437
|
const { call, rest: o } = callSettings(options);
|
|
347
438
|
const response = await raw.request("POST", "/v1/decisions", {
|
package/dist/reducto.d.ts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-
|
|
1
|
+
import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-BhTK51Yj.js";
|
|
2
|
+
/** Settings for `reducto()`. */
|
|
2
3
|
export interface ReductoConfig {
|
|
3
4
|
/** Defaults to the REDUCTO_API_KEY environment variable. */
|
|
4
5
|
apiKey?: string;
|
|
6
|
+
/** Defaults to https://platform.reducto.ai. */
|
|
5
7
|
baseUrl?: string;
|
|
8
|
+
/** Defaults to the global `fetch`. It also downloads a large result from the URL Reducto stores it at. A test passes a fake. */
|
|
6
9
|
fetch?: typeof fetch;
|
|
7
10
|
/** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
|
|
8
11
|
retries?: number;
|
|
9
12
|
}
|
|
13
|
+
/** Options for `parse`. */
|
|
10
14
|
export interface ReductoParseOptions extends CallOptions {
|
|
11
15
|
/** Return layout blocks with positions. */
|
|
12
16
|
blocks?: boolean;
|
|
@@ -20,8 +24,18 @@ export interface ReductoParseOptions extends CallOptions {
|
|
|
20
24
|
/** Milliseconds between checks. Defaults to 2000. */
|
|
21
25
|
interval?: number;
|
|
22
26
|
}
|
|
27
|
+
/** Options for collecting an earlier parse by its id, without the file. */
|
|
28
|
+
export type ReductoResumeOptions = Omit<ReductoParseOptions, "resume"> & {
|
|
29
|
+
resume: string;
|
|
30
|
+
};
|
|
31
|
+
/** What the Reducto adapter offers. */
|
|
23
32
|
export interface ReductoOperations {
|
|
24
|
-
parse:
|
|
33
|
+
parse: {
|
|
34
|
+
/** Uploads the file, starts the parse and waits for it. An error after the parse starts carries `jobId`. */
|
|
35
|
+
(document: DocumentInput, options?: ReductoParseOptions): Promise<ParsedDocument>;
|
|
36
|
+
/** Collects an earlier parse by its id, without sending the file again. */
|
|
37
|
+
(options: ReductoResumeOptions): Promise<ParsedDocument>;
|
|
38
|
+
};
|
|
25
39
|
}
|
|
26
40
|
/**
|
|
27
41
|
* An adapter for Reducto: parse. Pass it to `new Fieldwork({ adapter })`.
|
package/dist/reducto.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { t as defineAdapter } from "./adapter-DWYJys20.js";
|
|
2
|
-
import { a as refuseLarger, n as documentPart } from "./document-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { a as refuseLarger, n as documentPart } from "./document-CjMeBtV5.js";
|
|
3
|
+
import { t as FieldworkError } from "./errors-DROZyb9T.js";
|
|
4
|
+
import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-BY3R0oWO.js";
|
|
5
|
+
import { t as runJob } from "./job-DVsmQMKP.js";
|
|
5
6
|
import * as z from "zod/mini";
|
|
6
7
|
// src/adapters/reducto/response.ts
|
|
7
8
|
/** A box in fractions of the page, from its top-left corner. `page` counts the pages parsed; `original_page` the file's. */
|
|
@@ -13,6 +14,7 @@ const FractionBox = looseObject({
|
|
|
13
14
|
top: optionalNumber,
|
|
14
15
|
width: optionalNumber
|
|
15
16
|
});
|
|
17
|
+
/** A layout block. `extra` holds the word and cell citations, which the `return_citations` setting asks for. */
|
|
16
18
|
const Block = looseObject({
|
|
17
19
|
bbox: FractionBox,
|
|
18
20
|
content: optionalAnyString,
|
|
@@ -105,8 +107,8 @@ const documentBlocks = (output) => output.chunks.flatMap((chunk) => chunk.blocks
|
|
|
105
107
|
const provider = "reducto";
|
|
106
108
|
/** The largest file `/upload` takes, in megabytes. */
|
|
107
109
|
const MAX_UPLOAD_MB = 100;
|
|
110
|
+
/** Uploads the file, then starts the parse, and returns the job id. Refuses a file over the size limit before sending. */
|
|
108
111
|
const startParse = async (raw, document, o, call) => {
|
|
109
|
-
if (o.resume !== void 0) return o.resume;
|
|
110
112
|
refuseLarger(provider, document, MAX_UPLOAD_MB);
|
|
111
113
|
const form = new FormData();
|
|
112
114
|
form.set("file", documentPart(document), document.name);
|
|
@@ -125,20 +127,20 @@ const startParse = async (raw, document, o, call) => {
|
|
|
125
127
|
}));
|
|
126
128
|
return requireJobId(provider, started.job_id);
|
|
127
129
|
};
|
|
128
|
-
|
|
130
|
+
/** The result once the job has completed, undefined while it runs; throws `JobFailed` when Reducto reports a failure. */
|
|
131
|
+
const finished = (found) => {
|
|
129
132
|
const { error, reason, status } = found.value;
|
|
130
133
|
if (status === "Failed") {
|
|
131
134
|
const why = reason ?? error.message;
|
|
132
135
|
throw new FieldworkError("JobFailed", `reducto job failed${why === void 0 ? "" : `: ${why}`}`, {
|
|
133
136
|
cause: found.original,
|
|
134
|
-
jobId: id,
|
|
135
137
|
provider
|
|
136
138
|
});
|
|
137
139
|
}
|
|
138
140
|
return status === "Completed" ? found : void 0;
|
|
139
141
|
};
|
|
140
142
|
/** The parse output, fetched from where Reducto put it when it was too large to return. */
|
|
141
|
-
const outputOf = async (found,
|
|
143
|
+
const outputOf = async (found, options) => {
|
|
142
144
|
const output = found.value.result.result;
|
|
143
145
|
if (output.type === "full") return {
|
|
144
146
|
output,
|
|
@@ -146,54 +148,55 @@ const outputOf = async (found, id, options) => {
|
|
|
146
148
|
};
|
|
147
149
|
if (output.type !== "url") throw new FieldworkError("ProviderError", `reducto returned a result of type ${output.type ?? "(none)"}; Fieldwork reads "full" and "url"`, {
|
|
148
150
|
cause: found.original,
|
|
149
|
-
jobId: id,
|
|
150
151
|
provider
|
|
151
152
|
});
|
|
152
153
|
if (output.url === void 0) throw new FieldworkError("ProviderError", "reducto stored the result without saying where", {
|
|
153
154
|
cause: found.original,
|
|
154
|
-
jobId: id,
|
|
155
155
|
provider
|
|
156
156
|
});
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
};
|
|
163
|
-
} catch (error) {
|
|
164
|
-
throw withJob(error, id);
|
|
165
|
-
}
|
|
157
|
+
const stored = parseJson(provider, await readSigned(provider, output.url, options));
|
|
158
|
+
return {
|
|
159
|
+
output: z.parse(ParseOutput, stored),
|
|
160
|
+
stored
|
|
161
|
+
};
|
|
166
162
|
};
|
|
167
163
|
const parse = async (raw, document, options, fetchImpl) => {
|
|
168
164
|
const { call, rest: o } = callSettings(options);
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
165
|
+
return await runJob(provider, {
|
|
166
|
+
check: async (id, request) => finished(z.parse(JobResponse, await raw.request("GET", `/job/${segment(id)}`, request))),
|
|
167
|
+
finish: async (found, id) => {
|
|
168
|
+
const { output, stored } = await outputOf(found, {
|
|
169
|
+
fetch: fetchImpl,
|
|
170
|
+
signal: call.signal
|
|
171
|
+
});
|
|
172
|
+
if (output.chunks.length === 0) throw new FieldworkError("ProviderError", `reducto finished job ${id} without any chunks of output`, {
|
|
173
|
+
cause: stored ?? found.original,
|
|
174
|
+
provider
|
|
175
|
+
});
|
|
176
|
+
const { usage } = found.value.result;
|
|
177
|
+
return compact({
|
|
178
|
+
blocks: o.blocks === true || o.wordBoxes === true ? documentBlocks(output) : void 0,
|
|
179
|
+
id,
|
|
180
|
+
markdown: output.chunks.map((chunk) => chunk.content ?? "").join("\n\n"),
|
|
181
|
+
meta: meta({
|
|
182
|
+
credits: usage.credits,
|
|
183
|
+
units: { pages: usage.num_pages }
|
|
184
|
+
}),
|
|
185
|
+
pageCount: usage.num_pages,
|
|
186
|
+
raw: stored === void 0 ? found.original : {
|
|
187
|
+
job: found.original,
|
|
188
|
+
stored
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
},
|
|
192
|
+
start: async () => {
|
|
193
|
+
if (document === void 0) throw new FieldworkError("InvalidRequest", "parse needs a document, or resume with the id of an earlier parse", { provider });
|
|
194
|
+
return await startParse(raw, document, o, call);
|
|
196
195
|
}
|
|
196
|
+
}, {
|
|
197
|
+
...call,
|
|
198
|
+
interval: o.interval,
|
|
199
|
+
resume: o.resume
|
|
197
200
|
});
|
|
198
201
|
};
|
|
199
202
|
/**
|
|
@@ -211,8 +214,8 @@ const reducto = (config = {}) => {
|
|
|
211
214
|
});
|
|
212
215
|
return defineAdapter({
|
|
213
216
|
name: provider,
|
|
214
|
-
operations: { async parse(
|
|
215
|
-
return await parse(raw,
|
|
217
|
+
operations: { async parse(first, options) {
|
|
218
|
+
return "resume" in first ? await parse(raw, void 0, first, config.fetch) : await parse(raw, first, options, config.fetch);
|
|
216
219
|
} },
|
|
217
220
|
raw
|
|
218
221
|
});
|
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import { t as FieldworkError } from "./errors-
|
|
1
|
+
import { t as FieldworkError } from "./errors-DROZyb9T.js";
|
|
2
2
|
// src/schema.ts
|
|
3
3
|
const isStandard = (schema) => "~standard" in schema;
|
|
4
4
|
/**
|
|
5
5
|
* The JSON Schema to send to a provider. A plain JSON Schema passes through as
|
|
6
6
|
* given; a Standard Schema is converted to `target`, without its `$schema` key,
|
|
7
7
|
* because the provider's docs, not the library, say which dialect it reads.
|
|
8
|
+
*
|
|
9
|
+
* Throws `InvalidRequest`, with the library's error as `cause`, when the
|
|
10
|
+
* library cannot write the schema as `target`.
|
|
8
11
|
*/
|
|
9
12
|
const jsonSchemaOf = (schema, target = "draft-2020-12") => {
|
|
10
13
|
if (!isStandard(schema)) return schema;
|
|
@@ -27,9 +30,10 @@ const describeIssues = (issues) => {
|
|
|
27
30
|
};
|
|
28
31
|
/**
|
|
29
32
|
* The provider's structured output as the caller's type. A Standard Schema
|
|
30
|
-
* checks it and throws `ProviderError` listing the first issues with
|
|
31
|
-
* paths
|
|
32
|
-
*
|
|
33
|
+
* checks it and throws `ProviderError` listing the first three issues with
|
|
34
|
+
* their paths, not `retryable` and carrying the context's `jobId`; the value
|
|
35
|
+
* returned is the schema's own output, so transforms and defaults apply. A
|
|
36
|
+
* plain JSON Schema, or no schema, leaves it unchecked.
|
|
33
37
|
*/
|
|
34
38
|
const checkOutput = async (schema, value, context) => {
|
|
35
39
|
if (schema === void 0 || !isStandard(schema)) return value;
|