@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/perplexity.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import { t as defineAdapter } from "./adapter-
|
|
2
|
-
import { t as FieldworkError } from "./errors-
|
|
3
|
-
import {
|
|
4
|
-
|
|
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 { 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, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as compact, k as citationOf, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, w as poll, 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";
|
|
6
|
+
// src/adapters/perplexity/parse.ts
|
|
5
7
|
const provider = "perplexity";
|
|
6
|
-
const MAX_QUERIES = 5;
|
|
7
8
|
const TERMINAL = /* @__PURE__ */ new Set([
|
|
8
9
|
"completed",
|
|
9
10
|
"failed",
|
|
10
11
|
"incomplete",
|
|
11
12
|
"cancelled"
|
|
12
13
|
]);
|
|
13
|
-
const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
|
|
14
14
|
const usDate = (name, date) => {
|
|
15
15
|
if (date === void 0) return date;
|
|
16
16
|
const match = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u.exec(date);
|
|
17
|
-
if (!match?.groups) throw
|
|
17
|
+
if (!match?.groups) throw invalidRequest(provider, `${name} must be YYYY-MM-DD, got "${date}"`);
|
|
18
18
|
const { year, month, day } = match.groups;
|
|
19
19
|
return `${month}/${day}/${year}`;
|
|
20
20
|
};
|
|
@@ -35,7 +35,7 @@ const webSearchTool = (o) => {
|
|
|
35
35
|
const tool = compact({
|
|
36
36
|
filters: Object.keys(filters).length > 0 ? filters : void 0,
|
|
37
37
|
type: "web_search",
|
|
38
|
-
user_location: o.country ? { country: o.country }
|
|
38
|
+
user_location: o.country === void 0 || o.country === "" ? void 0 : { country: o.country }
|
|
39
39
|
});
|
|
40
40
|
return Object.keys(tool).length > 1 ? tool : void 0;
|
|
41
41
|
};
|
|
@@ -44,39 +44,36 @@ const languageCodes = (language) => {
|
|
|
44
44
|
return codes.length > 0 ? codes : void 0;
|
|
45
45
|
};
|
|
46
46
|
const errorCode = (jobId, rateLimited) => {
|
|
47
|
-
if (jobId) return "JobFailed";
|
|
47
|
+
if (jobId !== void 0 && jobId !== "") return "JobFailed";
|
|
48
48
|
return rateLimited ? "RateLimited" : "ProviderError";
|
|
49
49
|
};
|
|
50
|
-
const responseError = (
|
|
51
|
-
const error =
|
|
52
|
-
const
|
|
53
|
-
const
|
|
50
|
+
const responseError = (run, jobId) => {
|
|
51
|
+
const { error, status } = run.value;
|
|
52
|
+
const { type } = error;
|
|
53
|
+
const message = error.message ?? `ended ${status ?? "unknown"}`;
|
|
54
54
|
const rateLimited = type === "request_rate_limit_exceeded" || type === "token_rate_limit_exceeded";
|
|
55
55
|
return new FieldworkError(errorCode(jobId, rateLimited), `perplexity ${message}`, {
|
|
56
|
-
cause:
|
|
56
|
+
cause: run.original,
|
|
57
57
|
jobId,
|
|
58
58
|
provider,
|
|
59
59
|
retryable: rateLimited || type === "overloaded"
|
|
60
60
|
});
|
|
61
61
|
};
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
return entry.type === "fetch_url_results" ? list(entry.contents) : [];
|
|
65
|
-
};
|
|
66
|
-
const annotated = (part) => list(part.annotations).map((annotation) => record(annotation)).filter((found) => found.type === void 0 || found.type === "url_citation").map((found) => citation(found)).filter((source) => source !== void 0);
|
|
67
|
-
const readResponse = (response) => {
|
|
62
|
+
const annotated = (annotations) => annotations.filter((found) => found.type === void 0 || found.type === "url_citation").map((found) => citationOf(found)).filter((source) => source !== void 0);
|
|
63
|
+
const readResponse = (body) => {
|
|
68
64
|
const parts = [];
|
|
69
65
|
const cited = [];
|
|
70
66
|
const retrieved = [];
|
|
71
|
-
for (const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
parts.push(text(part.text) ?? "");
|
|
76
|
-
cited.push(...annotated(part));
|
|
67
|
+
for (const entry of body.output) {
|
|
68
|
+
if (entry.type === "message") for (const part of entry.content) {
|
|
69
|
+
parts.push(part.text ?? "");
|
|
70
|
+
cited.push(...annotated(part.annotations));
|
|
77
71
|
}
|
|
78
|
-
|
|
79
|
-
|
|
72
|
+
let found = entry.contents;
|
|
73
|
+
if (entry.type === "search_results") found = entry.results;
|
|
74
|
+
else if (entry.type !== "fetch_url_results") found = [];
|
|
75
|
+
for (const item of found) {
|
|
76
|
+
const source = citationOf(item);
|
|
80
77
|
if (source) retrieved.push(compact({
|
|
81
78
|
title: source.title,
|
|
82
79
|
url: source.url
|
|
@@ -89,18 +86,18 @@ const readResponse = (response) => {
|
|
|
89
86
|
text: parts.join("")
|
|
90
87
|
};
|
|
91
88
|
};
|
|
92
|
-
const responseMeta = (
|
|
93
|
-
const usage =
|
|
94
|
-
const input =
|
|
89
|
+
const responseMeta = (body, warnings) => {
|
|
90
|
+
const { usage } = body;
|
|
91
|
+
const input = usage.input_tokens_details;
|
|
95
92
|
return meta({
|
|
96
|
-
costUsd:
|
|
97
|
-
requestId:
|
|
93
|
+
costUsd: usage.cost.total_cost,
|
|
94
|
+
requestId: body.id.second,
|
|
98
95
|
units: {
|
|
99
96
|
cacheCreationInputTokens: input.cache_creation_input_tokens,
|
|
100
97
|
cacheReadInputTokens: input.cache_read_input_tokens,
|
|
101
98
|
inputTokens: usage.input_tokens,
|
|
102
99
|
outputTokens: usage.output_tokens,
|
|
103
|
-
reasoningTokens:
|
|
100
|
+
reasoningTokens: usage.output_tokens_details.reasoning_tokens,
|
|
104
101
|
totalTokens: usage.total_tokens
|
|
105
102
|
},
|
|
106
103
|
warnings
|
|
@@ -109,22 +106,147 @@ const responseMeta = (response, warnings) => {
|
|
|
109
106
|
const responseFormat = (schema) => schema ? {
|
|
110
107
|
json_schema: {
|
|
111
108
|
name: "output",
|
|
112
|
-
schema
|
|
109
|
+
schema: jsonSchemaOf(schema)
|
|
113
110
|
},
|
|
114
111
|
type: "json_schema"
|
|
115
112
|
} : void 0;
|
|
116
|
-
const numbers = (value) => Object.fromEntries(Object.entries(record(value)).filter((entry) => num(entry[1]) !== void 0));
|
|
117
113
|
const decisionState = (context) => {
|
|
118
114
|
if (typeof context === "string" || typeof context === "object" && context) return context;
|
|
119
115
|
if (typeof context === "number" || typeof context === "boolean") return String(context);
|
|
120
|
-
throw
|
|
116
|
+
throw invalidRequest(provider, "decide needs a context: a string, object or array");
|
|
117
|
+
};
|
|
118
|
+
const researchSetup = (o) => {
|
|
119
|
+
if (o.models && (o.models.length < 1 || o.models.length > 5)) throw invalidRequest(provider, "models takes one to five models");
|
|
120
|
+
const searchTool = webSearchTool(o);
|
|
121
|
+
if (o.effort === void 0 && (o.model !== void 0 || o.models !== void 0)) return {
|
|
122
|
+
max_steps: o.maxSteps ?? 10,
|
|
123
|
+
model: o.model,
|
|
124
|
+
models: o.models,
|
|
125
|
+
tools: [searchTool ?? { type: "web_search" }, { type: "fetch_url" }]
|
|
126
|
+
};
|
|
127
|
+
return {
|
|
128
|
+
effort: o.effort ?? "high",
|
|
129
|
+
max_steps: o.maxSteps,
|
|
130
|
+
model: o.model,
|
|
131
|
+
models: o.models,
|
|
132
|
+
tools: searchTool ? [searchTool] : void 0
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
const researchOutput = (run, reply, schema, id) => {
|
|
136
|
+
if (!schema) return reply;
|
|
137
|
+
const { status } = run.value;
|
|
138
|
+
try {
|
|
139
|
+
return parseJson(provider, reply);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (status === "completed") throw withJob(error, id);
|
|
142
|
+
throw new FieldworkError("JobFailed", `perplexity research ended ${status} with output that is not valid JSON`, {
|
|
143
|
+
cause: run.original,
|
|
144
|
+
jobId: id,
|
|
145
|
+
provider
|
|
146
|
+
});
|
|
147
|
+
}
|
|
121
148
|
};
|
|
149
|
+
const decisionQuestion = (question) => {
|
|
150
|
+
if (question.type === "yesno") return {
|
|
151
|
+
instructions: question.question,
|
|
152
|
+
type: "noul"
|
|
153
|
+
};
|
|
154
|
+
if (question.type === "choice") return {
|
|
155
|
+
criteria: Object.fromEntries(question.choices.map((choice) => [choice, null])),
|
|
156
|
+
instructions: question.question,
|
|
157
|
+
type: "choice"
|
|
158
|
+
};
|
|
159
|
+
return {
|
|
160
|
+
criteria: Object.values(question.scale),
|
|
161
|
+
instructions: question.question,
|
|
162
|
+
type: "score"
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
const decisionAnswer = (found, scores) => {
|
|
166
|
+
if (found.type === "noul") return compact({ probability: found.noul });
|
|
167
|
+
let probabilities = Object.fromEntries(Object.entries(found.probabilities).filter((entry) => entry[1] !== void 0));
|
|
168
|
+
if (found.type === "score") probabilities = Object.fromEntries(Object.entries(probabilities).map(([index, probability]) => [scores?.[Number(index)] ?? index, probability]));
|
|
169
|
+
const top = Object.entries(probabilities).toSorted((a, b) => b[1] - a[1])[0]?.[0];
|
|
170
|
+
return compact({
|
|
171
|
+
choice: found.choice ?? top,
|
|
172
|
+
confidence: found.confidence,
|
|
173
|
+
probabilities
|
|
174
|
+
});
|
|
175
|
+
};
|
|
176
|
+
// src/adapters/perplexity/response.ts
|
|
177
|
+
/** `/search`. */
|
|
178
|
+
const SearchResponse = looseObject({
|
|
179
|
+
id: optionalScalar,
|
|
180
|
+
results: arrayOf(looseObject({
|
|
181
|
+
date: optionalString,
|
|
182
|
+
last_updated: optionalString,
|
|
183
|
+
snippet: optionalString,
|
|
184
|
+
title: optionalString,
|
|
185
|
+
url: optionalString
|
|
186
|
+
}))
|
|
187
|
+
});
|
|
188
|
+
/** An annotation on message text. Its `type` is kept as it arrived, since only an absent one or `url_citation` counts as a citation. */
|
|
189
|
+
const Annotation = looseObject({
|
|
190
|
+
...sourceShape,
|
|
191
|
+
type: anything
|
|
192
|
+
});
|
|
193
|
+
const MessagePart = looseObject({
|
|
194
|
+
annotations: arrayOf(Annotation),
|
|
195
|
+
text: optionalString
|
|
196
|
+
});
|
|
197
|
+
const OutputEntry = looseObject({
|
|
198
|
+
content: arrayOf(MessagePart),
|
|
199
|
+
contents: arrayOf(Source),
|
|
200
|
+
results: arrayOf(Source),
|
|
201
|
+
type: optionalString
|
|
202
|
+
});
|
|
203
|
+
/** A response of the Agent API, whole. Its `id` is read as a continuation id (a non-empty string) and as a request id (a string, number or boolean). */
|
|
204
|
+
const Agent = looseObject({
|
|
205
|
+
error: looseObject({
|
|
206
|
+
message: optionalString,
|
|
207
|
+
type: optionalString
|
|
208
|
+
}),
|
|
209
|
+
id: both(optionalString, optionalScalar),
|
|
210
|
+
output: arrayOf(OutputEntry),
|
|
211
|
+
status: optionalString,
|
|
212
|
+
usage: looseObject({
|
|
213
|
+
cost: looseObject({ total_cost: optionalNumber }),
|
|
214
|
+
input_tokens: optionalNumber,
|
|
215
|
+
input_tokens_details: looseObject({
|
|
216
|
+
cache_creation_input_tokens: optionalNumber,
|
|
217
|
+
cache_read_input_tokens: optionalNumber
|
|
218
|
+
}),
|
|
219
|
+
output_tokens: optionalNumber,
|
|
220
|
+
output_tokens_details: looseObject({ reasoning_tokens: optionalNumber }),
|
|
221
|
+
total_tokens: optionalNumber
|
|
222
|
+
})
|
|
223
|
+
});
|
|
224
|
+
/** An Agent API response beside the response as it arrived. */
|
|
225
|
+
const AgentRun = withOriginal(Agent);
|
|
226
|
+
/** The reply to starting a run: its id as a string, and as it arrived. */
|
|
227
|
+
const AgentStart = looseObject({ id: withOriginal(optionalId) });
|
|
228
|
+
const DecisionAnswer = looseObject({
|
|
229
|
+
choice: optionalString,
|
|
230
|
+
confidence: optionalNumber,
|
|
231
|
+
noul: optionalNumber,
|
|
232
|
+
probabilities: recordOf(optionalNumber),
|
|
233
|
+
type: optionalString
|
|
234
|
+
});
|
|
235
|
+
/** `/v1/decisions`. */
|
|
236
|
+
const DecisionsResponse = looseObject({
|
|
237
|
+
answers: recordOf(DecisionAnswer),
|
|
238
|
+
usage: looseObject({
|
|
239
|
+
input_tokens: optionalNumber,
|
|
240
|
+
output_tokens: optionalNumber
|
|
241
|
+
})
|
|
242
|
+
});
|
|
243
|
+
// src/adapters/perplexity.ts
|
|
122
244
|
const search = async (raw, query, options) => {
|
|
123
245
|
const { call, rest: o } = callSettings(options);
|
|
124
246
|
const queries = [query, ...o.queries ?? []];
|
|
125
|
-
if (queries.length >
|
|
126
|
-
if (o.limit !== void 0 && o.limit > 20 && o.searchType !== "people") throw
|
|
127
|
-
const response =
|
|
247
|
+
if (queries.length > 5) throw invalidRequest(provider, `search takes at most 5 queries in one request, got ${queries.length}`);
|
|
248
|
+
if (o.limit !== void 0 && o.limit > 20 && o.searchType !== "people") throw invalidRequest(provider, "search returns at most 20 results unless searchType is \"people\"");
|
|
249
|
+
const response = await raw.request("POST", "/search", {
|
|
128
250
|
...call,
|
|
129
251
|
body: compact({
|
|
130
252
|
country: o.country,
|
|
@@ -136,25 +258,23 @@ const search = async (raw, query, options) => {
|
|
|
136
258
|
search_type: o.searchType,
|
|
137
259
|
...filterFields(o)
|
|
138
260
|
})
|
|
139
|
-
})
|
|
261
|
+
});
|
|
262
|
+
const body = z.parse(SearchResponse, response);
|
|
140
263
|
return {
|
|
141
|
-
meta: meta({ requestId:
|
|
264
|
+
meta: meta({ requestId: body.id }),
|
|
142
265
|
raw: response,
|
|
143
|
-
results:
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
url: text(result.url) ?? ""
|
|
151
|
-
});
|
|
152
|
-
})
|
|
266
|
+
results: body.results.map((result) => compact({
|
|
267
|
+
lastUpdatedAt: result.last_updated,
|
|
268
|
+
publishedAt: result.date,
|
|
269
|
+
snippet: result.snippet,
|
|
270
|
+
title: result.title,
|
|
271
|
+
url: result.url ?? ""
|
|
272
|
+
}))
|
|
153
273
|
};
|
|
154
274
|
};
|
|
155
275
|
const answer = async (raw, question, options) => {
|
|
156
276
|
const { call, rest: o } = callSettings(options);
|
|
157
|
-
const
|
|
277
|
+
const run = z.parse(AgentRun, await raw.request("POST", "/v1/agent", {
|
|
158
278
|
...call,
|
|
159
279
|
body: compact({
|
|
160
280
|
effort: o.effort ?? "fast",
|
|
@@ -164,38 +284,22 @@ const answer = async (raw, question, options) => {
|
|
|
164
284
|
response_format: responseFormat(o.schema)
|
|
165
285
|
})
|
|
166
286
|
}));
|
|
167
|
-
const read = readResponse(
|
|
168
|
-
const status =
|
|
169
|
-
if (status === "failed" || status === "cancelled" || !read.text) throw responseError(
|
|
287
|
+
const read = readResponse(run.value);
|
|
288
|
+
const { status } = run.value;
|
|
289
|
+
if (status === "failed" || status === "cancelled" || !read.text) throw responseError(run);
|
|
170
290
|
return compact({
|
|
171
291
|
answer: read.text,
|
|
172
292
|
citations: read.cited,
|
|
173
|
-
continuationId:
|
|
174
|
-
meta: responseMeta(
|
|
175
|
-
output: o.schema ? parseJson(provider, read.text) : void 0,
|
|
176
|
-
raw:
|
|
293
|
+
continuationId: run.value.id.first,
|
|
294
|
+
meta: responseMeta(run.value, status === "incomplete" ? "perplexity stopped before finishing the answer" : void 0),
|
|
295
|
+
output: o.schema ? await checkOutput(o.schema, parseJson(provider, read.text), { provider }) : void 0,
|
|
296
|
+
raw: run.original
|
|
177
297
|
});
|
|
178
298
|
};
|
|
179
|
-
const researchSetup = (o) => {
|
|
180
|
-
if (o.models && (o.models.length < 1 || o.models.length > 5)) throw invalid("perplexity models takes one to five models");
|
|
181
|
-
const searchTool = webSearchTool(o);
|
|
182
|
-
if (o.effort === void 0 && (o.model !== void 0 || o.models !== void 0)) return {
|
|
183
|
-
max_steps: o.maxSteps ?? 10,
|
|
184
|
-
model: o.model,
|
|
185
|
-
models: o.models,
|
|
186
|
-
tools: [searchTool ?? { type: "web_search" }, { type: "fetch_url" }]
|
|
187
|
-
};
|
|
188
|
-
return {
|
|
189
|
-
effort: o.effort ?? "high",
|
|
190
|
-
max_steps: o.maxSteps,
|
|
191
|
-
model: o.model,
|
|
192
|
-
models: o.models,
|
|
193
|
-
tools: searchTool ? [searchTool] : void 0
|
|
194
|
-
};
|
|
195
|
-
};
|
|
196
299
|
const startResearch = async (raw, question, o, call) => {
|
|
197
|
-
if (o.resume) return o.resume;
|
|
198
|
-
const created =
|
|
300
|
+
if (o.resume !== void 0) return o.resume;
|
|
301
|
+
const created = z.parse(AgentStart, await raw.request("POST", "/v1/agent", {
|
|
302
|
+
creates: true,
|
|
199
303
|
...call,
|
|
200
304
|
body: compact({
|
|
201
305
|
...researchSetup(o),
|
|
@@ -208,92 +312,53 @@ const startResearch = async (raw, question, o, call) => {
|
|
|
208
312
|
response_format: responseFormat(o.schema)
|
|
209
313
|
})
|
|
210
314
|
}));
|
|
211
|
-
return
|
|
212
|
-
};
|
|
213
|
-
const researchOutput = (response, reply, schema, id) => {
|
|
214
|
-
if (!schema) return reply;
|
|
215
|
-
const status = text(response.status);
|
|
216
|
-
try {
|
|
217
|
-
return parseJson(provider, reply);
|
|
218
|
-
} catch (error) {
|
|
219
|
-
if (status === "completed") throw error;
|
|
220
|
-
throw new FieldworkError("JobFailed", `perplexity research ended ${status} with output that is not valid JSON`, {
|
|
221
|
-
cause: response,
|
|
222
|
-
jobId: id,
|
|
223
|
-
provider
|
|
224
|
-
});
|
|
225
|
-
}
|
|
315
|
+
return requireJobId(provider, created.id);
|
|
226
316
|
};
|
|
227
317
|
const research = async (raw, question, options) => {
|
|
228
318
|
const { call, rest: o } = callSettings(options);
|
|
229
319
|
const id = await startResearch(raw, question, o, call);
|
|
230
|
-
const
|
|
231
|
-
const found =
|
|
232
|
-
return TERMINAL.has(
|
|
320
|
+
const run = await poll(provider, id, async (request) => {
|
|
321
|
+
const found = z.parse(AgentRun, await raw.request("GET", `/v1/agent/${segment(id)}`, request));
|
|
322
|
+
return TERMINAL.has(found.value.status ?? "") ? found : void 0;
|
|
233
323
|
}, {
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
timeout: call.timeout
|
|
324
|
+
...call,
|
|
325
|
+
interval: o.interval
|
|
237
326
|
});
|
|
238
|
-
const status =
|
|
239
|
-
const read = readResponse(
|
|
240
|
-
if (status === "failed" || !read.text) throw responseError(
|
|
327
|
+
const { status } = run.value;
|
|
328
|
+
const read = readResponse(run.value);
|
|
329
|
+
if (status === "failed" || !read.text) throw responseError(run, id);
|
|
241
330
|
return compact({
|
|
242
331
|
continuationId: id,
|
|
243
332
|
id,
|
|
244
|
-
meta: responseMeta(
|
|
245
|
-
output: researchOutput(
|
|
246
|
-
|
|
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,
|
|
247
339
|
retrieved: read.retrieved.length > 0 ? read.retrieved : void 0,
|
|
248
340
|
sources: read.cited,
|
|
249
341
|
status: status === "completed" ? "completed" : "partial",
|
|
250
342
|
stopReason: status === "completed" ? void 0 : status
|
|
251
343
|
});
|
|
252
344
|
};
|
|
253
|
-
const decisionQuestion = (question) => {
|
|
254
|
-
if (question.type === "yesno") return {
|
|
255
|
-
instructions: question.question,
|
|
256
|
-
type: "noul"
|
|
257
|
-
};
|
|
258
|
-
if (question.type === "choice") return {
|
|
259
|
-
criteria: Object.fromEntries(question.choices.map((choice) => [choice, null])),
|
|
260
|
-
instructions: question.question,
|
|
261
|
-
type: "choice"
|
|
262
|
-
};
|
|
263
|
-
return {
|
|
264
|
-
criteria: Object.values(question.scale),
|
|
265
|
-
instructions: question.question,
|
|
266
|
-
type: "score"
|
|
267
|
-
};
|
|
268
|
-
};
|
|
269
|
-
const decisionAnswer = (value, scores) => {
|
|
270
|
-
const found = record(value);
|
|
271
|
-
if (found.type === "noul") return compact({ probability: num(found.noul) });
|
|
272
|
-
let probabilities = numbers(found.probabilities);
|
|
273
|
-
if (found.type === "score") probabilities = Object.fromEntries(Object.entries(probabilities).map(([index, probability]) => [scores?.[Number(index)] ?? index, probability]));
|
|
274
|
-
const top = Object.entries(probabilities).toSorted((a, b) => b[1] - a[1])[0]?.[0];
|
|
275
|
-
return compact({
|
|
276
|
-
choice: text(found.choice) ?? top,
|
|
277
|
-
confidence: num(found.confidence),
|
|
278
|
-
probabilities
|
|
279
|
-
});
|
|
280
|
-
};
|
|
281
345
|
const decide = async (raw, context, questions, options) => {
|
|
282
346
|
const { call, rest: o } = callSettings(options);
|
|
283
|
-
const response =
|
|
347
|
+
const response = await raw.request("POST", "/v1/decisions", {
|
|
284
348
|
...call,
|
|
285
349
|
body: {
|
|
286
350
|
model: o.model ?? "pplx-decider-latest",
|
|
287
351
|
questions: Object.fromEntries(Object.entries(questions).map(([name, question]) => [name, decisionQuestion(question)])),
|
|
288
352
|
state: decisionState(context)
|
|
289
353
|
}
|
|
290
|
-
})
|
|
354
|
+
});
|
|
355
|
+
const body = z.parse(DecisionsResponse, response);
|
|
291
356
|
const answers = {};
|
|
292
|
-
for (const [name, value] of Object.entries(
|
|
357
|
+
for (const [name, value] of Object.entries(body.answers)) {
|
|
293
358
|
const question = questions[name];
|
|
294
359
|
answers[name] = decisionAnswer(value, question?.type === "score" ? Object.keys(question.scale) : void 0);
|
|
295
360
|
}
|
|
296
|
-
const usage =
|
|
361
|
+
const { usage } = body;
|
|
297
362
|
return {
|
|
298
363
|
answers,
|
|
299
364
|
citations: [],
|
|
@@ -304,12 +369,18 @@ const decide = async (raw, context, questions, options) => {
|
|
|
304
369
|
raw: response
|
|
305
370
|
};
|
|
306
371
|
};
|
|
372
|
+
/**
|
|
373
|
+
* An adapter for Perplexity: search, answer, research and decide. Pass it to `new Fieldwork({ adapter })`.
|
|
374
|
+
*
|
|
375
|
+
* Throws `Unauthorized` when neither `apiKey` nor `PERPLEXITY_API_KEY` is set.
|
|
376
|
+
*/
|
|
307
377
|
const perplexity = (config = {}) => {
|
|
308
378
|
const raw = createRawClient({
|
|
309
379
|
baseUrl: config.baseUrl ?? "https://api.perplexity.ai",
|
|
310
380
|
fetch: config.fetch,
|
|
311
381
|
headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "PERPLEXITY_API_KEY")}` },
|
|
312
|
-
provider
|
|
382
|
+
provider,
|
|
383
|
+
retries: config.retries
|
|
313
384
|
});
|
|
314
385
|
return defineAdapter({
|
|
315
386
|
name: provider,
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-BgdfLBs-.js";
|
|
2
|
+
export interface ReductoConfig {
|
|
3
|
+
/** Defaults to the REDUCTO_API_KEY environment variable. */
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
baseUrl?: string;
|
|
6
|
+
fetch?: typeof fetch;
|
|
7
|
+
/** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
|
|
8
|
+
retries?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface ReductoParseOptions extends CallOptions {
|
|
11
|
+
/** Return layout blocks with positions. */
|
|
12
|
+
blocks?: boolean;
|
|
13
|
+
/** Also return where each word and table cell sits in each block. Returns blocks too. */
|
|
14
|
+
wordBoxes?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* The id of a job from an error's `jobId`; waits for it instead of starting
|
|
17
|
+
* another. Reducto keeps a job's result for about 12 hours.
|
|
18
|
+
*/
|
|
19
|
+
resume?: string;
|
|
20
|
+
/** Milliseconds between checks. Defaults to 2000. */
|
|
21
|
+
interval?: number;
|
|
22
|
+
}
|
|
23
|
+
export interface ReductoOperations {
|
|
24
|
+
parse: (document: DocumentInput, options?: ReductoParseOptions) => Promise<ParsedDocument>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* An adapter for Reducto: parse. Pass it to `new Fieldwork({ adapter })`.
|
|
28
|
+
*
|
|
29
|
+
* Throws `Unauthorized` when neither `apiKey` nor `REDUCTO_API_KEY` is set.
|
|
30
|
+
*/
|
|
31
|
+
export declare const reducto: (config?: ReductoConfig) => Adapter<"reducto", ReductoOperations, RawClient>;
|