@howells/fieldwork-sdk 0.3.1 → 0.4.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.
@@ -1,6 +1,75 @@
1
1
  import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
2
  import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { S as requireKey, b as createRawClient, c as num, h as requireId, i as compact, l as parseJson, m as refuseTogether, n as citation, o as list, p as record, s as meta, t as callSettings, v as text, x as poll, y as uniqueCitations } from "./util-YaZYZDSk.js";
3
+ import { C as createRawClient, D as citationOf, E as callSettings, I as refuseTogether, L as requireJobId, M as parseJson, R as uniqueCitations, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as meta, k as compact, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, w as poll, y as sourceShape } from "./parse-CxOri73y.js";
4
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-teOy7Od-.js";
5
+ import * as z from "zod/mini";
6
+ // src/adapters/perplexity/response.ts
7
+ /** `/search`. */
8
+ const SearchResponse = looseObject({
9
+ id: optionalScalar,
10
+ results: arrayOf(looseObject({
11
+ date: optionalString,
12
+ last_updated: optionalString,
13
+ snippet: optionalString,
14
+ title: optionalString,
15
+ url: optionalString
16
+ }))
17
+ });
18
+ /** An annotation on message text. Its `type` is kept as it arrived, since only an absent one or `url_citation` counts as a citation. */
19
+ const Annotation = looseObject({
20
+ ...sourceShape,
21
+ type: anything
22
+ });
23
+ const MessagePart = looseObject({
24
+ annotations: arrayOf(Annotation),
25
+ text: optionalString
26
+ });
27
+ const OutputEntry = looseObject({
28
+ content: arrayOf(MessagePart),
29
+ contents: arrayOf(Source),
30
+ results: arrayOf(Source),
31
+ type: optionalString
32
+ });
33
+ /** 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). */
34
+ const Agent = looseObject({
35
+ error: looseObject({
36
+ message: optionalString,
37
+ type: optionalString
38
+ }),
39
+ id: both(optionalString, optionalScalar),
40
+ output: arrayOf(OutputEntry),
41
+ status: optionalString,
42
+ usage: looseObject({
43
+ cost: looseObject({ total_cost: optionalNumber }),
44
+ input_tokens: optionalNumber,
45
+ input_tokens_details: looseObject({
46
+ cache_creation_input_tokens: optionalNumber,
47
+ cache_read_input_tokens: optionalNumber
48
+ }),
49
+ output_tokens: optionalNumber,
50
+ output_tokens_details: looseObject({ reasoning_tokens: optionalNumber }),
51
+ total_tokens: optionalNumber
52
+ })
53
+ });
54
+ /** An Agent API response beside the response as it arrived. */
55
+ const AgentRun = withOriginal(Agent);
56
+ /** The reply to starting a run: its id as a string, and as it arrived. */
57
+ const AgentStart = looseObject({ id: withOriginal(optionalId) });
58
+ const DecisionAnswer = looseObject({
59
+ choice: optionalString,
60
+ confidence: optionalNumber,
61
+ noul: optionalNumber,
62
+ probabilities: recordOf(optionalNumber),
63
+ type: optionalString
64
+ });
65
+ /** `/v1/decisions`. */
66
+ const DecisionsResponse = looseObject({
67
+ answers: recordOf(DecisionAnswer),
68
+ usage: looseObject({
69
+ input_tokens: optionalNumber,
70
+ output_tokens: optionalNumber
71
+ })
72
+ });
4
73
  // src/adapters/perplexity.ts
5
74
  const provider = "perplexity";
6
75
  const MAX_QUERIES = 5;
@@ -35,7 +104,7 @@ const webSearchTool = (o) => {
35
104
  const tool = compact({
36
105
  filters: Object.keys(filters).length > 0 ? filters : void 0,
37
106
  type: "web_search",
38
- user_location: o.country ? { country: o.country } : void 0
107
+ user_location: o.country === void 0 || o.country === "" ? void 0 : { country: o.country }
39
108
  });
40
109
  return Object.keys(tool).length > 1 ? tool : void 0;
41
110
  };
@@ -44,39 +113,36 @@ const languageCodes = (language) => {
44
113
  return codes.length > 0 ? codes : void 0;
45
114
  };
46
115
  const errorCode = (jobId, rateLimited) => {
47
- if (jobId) return "JobFailed";
116
+ if (jobId !== void 0 && jobId !== "") return "JobFailed";
48
117
  return rateLimited ? "RateLimited" : "ProviderError";
49
118
  };
50
- const responseError = (response, jobId) => {
51
- const error = record(response.error);
52
- const message = text(error.message) ?? `ended ${text(response.status) ?? "unknown"}`;
53
- const type = text(error.type);
119
+ const responseError = (run, jobId) => {
120
+ const { error, status } = run.value;
121
+ const { type } = error;
122
+ const message = error.message ?? `ended ${status ?? "unknown"}`;
54
123
  const rateLimited = type === "request_rate_limit_exceeded" || type === "token_rate_limit_exceeded";
55
124
  return new FieldworkError(errorCode(jobId, rateLimited), `perplexity ${message}`, {
56
- cause: response,
125
+ cause: run.original,
57
126
  jobId,
58
127
  provider,
59
128
  retryable: rateLimited || type === "overloaded"
60
129
  });
61
130
  };
62
- const retrievedBy = (entry) => {
63
- if (entry.type === "search_results") return list(entry.results);
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) => {
131
+ const annotated = (annotations) => annotations.filter((found) => found.type === void 0 || found.type === "url_citation").map((found) => citationOf(found)).filter((source) => source !== void 0);
132
+ const readResponse = (body) => {
68
133
  const parts = [];
69
134
  const cited = [];
70
135
  const retrieved = [];
71
- for (const item of list(response.output)) {
72
- const entry = record(item);
73
- if (entry.type === "message") for (const content of list(entry.content)) {
74
- const part = record(content);
75
- parts.push(text(part.text) ?? "");
76
- cited.push(...annotated(part));
136
+ for (const entry of body.output) {
137
+ if (entry.type === "message") for (const part of entry.content) {
138
+ parts.push(part.text ?? "");
139
+ cited.push(...annotated(part.annotations));
77
140
  }
78
- for (const found of retrievedBy(entry)) {
79
- const source = citation(found);
141
+ let found = entry.contents;
142
+ if (entry.type === "search_results") found = entry.results;
143
+ else if (entry.type !== "fetch_url_results") found = [];
144
+ for (const item of found) {
145
+ const source = citationOf(item);
80
146
  if (source) retrieved.push(compact({
81
147
  title: source.title,
82
148
  url: source.url
@@ -89,18 +155,18 @@ const readResponse = (response) => {
89
155
  text: parts.join("")
90
156
  };
91
157
  };
92
- const responseMeta = (response, warnings) => {
93
- const usage = record(response.usage);
94
- const input = record(usage.input_tokens_details);
158
+ const responseMeta = (body, warnings) => {
159
+ const { usage } = body;
160
+ const input = usage.input_tokens_details;
95
161
  return meta({
96
- costUsd: record(usage.cost).total_cost,
97
- requestId: response.id,
162
+ costUsd: usage.cost.total_cost,
163
+ requestId: body.id.second,
98
164
  units: {
99
165
  cacheCreationInputTokens: input.cache_creation_input_tokens,
100
166
  cacheReadInputTokens: input.cache_read_input_tokens,
101
167
  inputTokens: usage.input_tokens,
102
168
  outputTokens: usage.output_tokens,
103
- reasoningTokens: record(usage.output_tokens_details).reasoning_tokens,
169
+ reasoningTokens: usage.output_tokens_details.reasoning_tokens,
104
170
  totalTokens: usage.total_tokens
105
171
  },
106
172
  warnings
@@ -109,11 +175,10 @@ const responseMeta = (response, warnings) => {
109
175
  const responseFormat = (schema) => schema ? {
110
176
  json_schema: {
111
177
  name: "output",
112
- schema
178
+ schema: jsonSchemaOf(schema)
113
179
  },
114
180
  type: "json_schema"
115
181
  } : void 0;
116
- const numbers = (value) => Object.fromEntries(Object.entries(record(value)).filter((entry) => num(entry[1]) !== void 0));
117
182
  const decisionState = (context) => {
118
183
  if (typeof context === "string" || typeof context === "object" && context) return context;
119
184
  if (typeof context === "number" || typeof context === "boolean") return String(context);
@@ -124,7 +189,7 @@ const search = async (raw, query, options) => {
124
189
  const queries = [query, ...o.queries ?? []];
125
190
  if (queries.length > MAX_QUERIES) throw invalid(`perplexity search takes at most ${MAX_QUERIES} queries in one request, got ${queries.length}`);
126
191
  if (o.limit !== void 0 && o.limit > 20 && o.searchType !== "people") throw invalid("perplexity search returns at most 20 results unless searchType is \"people\"");
127
- const response = record(await raw.request("POST", "/search", {
192
+ const response = await raw.request("POST", "/search", {
128
193
  ...call,
129
194
  body: compact({
130
195
  country: o.country,
@@ -136,25 +201,23 @@ const search = async (raw, query, options) => {
136
201
  search_type: o.searchType,
137
202
  ...filterFields(o)
138
203
  })
139
- }));
204
+ });
205
+ const body = z.parse(SearchResponse, response);
140
206
  return {
141
- meta: meta({ requestId: response.id }),
207
+ meta: meta({ requestId: body.id }),
142
208
  raw: response,
143
- results: list(response.results).map((item) => {
144
- const result = record(item);
145
- return compact({
146
- lastUpdatedAt: text(result.last_updated),
147
- publishedAt: text(result.date),
148
- snippet: text(result.snippet),
149
- title: text(result.title),
150
- url: text(result.url) ?? ""
151
- });
152
- })
209
+ results: body.results.map((result) => compact({
210
+ lastUpdatedAt: result.last_updated,
211
+ publishedAt: result.date,
212
+ snippet: result.snippet,
213
+ title: result.title,
214
+ url: result.url ?? ""
215
+ }))
153
216
  };
154
217
  };
155
218
  const answer = async (raw, question, options) => {
156
219
  const { call, rest: o } = callSettings(options);
157
- const response = record(await raw.request("POST", "/v1/agent", {
220
+ const run = z.parse(AgentRun, await raw.request("POST", "/v1/agent", {
158
221
  ...call,
159
222
  body: compact({
160
223
  effort: o.effort ?? "fast",
@@ -164,16 +227,16 @@ const answer = async (raw, question, options) => {
164
227
  response_format: responseFormat(o.schema)
165
228
  })
166
229
  }));
167
- const read = readResponse(response);
168
- const status = text(response.status);
169
- if (status === "failed" || status === "cancelled" || !read.text) throw responseError(response);
230
+ const read = readResponse(run.value);
231
+ const { status } = run.value;
232
+ if (status === "failed" || status === "cancelled" || !read.text) throw responseError(run);
170
233
  return compact({
171
234
  answer: read.text,
172
235
  citations: read.cited,
173
- continuationId: text(response.id),
174
- meta: responseMeta(response, status === "incomplete" ? "perplexity stopped before finishing the answer" : void 0),
175
- output: o.schema ? parseJson(provider, read.text) : void 0,
176
- raw: response
236
+ continuationId: run.value.id.first,
237
+ meta: responseMeta(run.value, status === "incomplete" ? "perplexity stopped before finishing the answer" : void 0),
238
+ output: o.schema ? await checkOutput(o.schema, parseJson(provider, read.text), { provider }) : void 0,
239
+ raw: run.original
177
240
  });
178
241
  };
179
242
  const researchSetup = (o) => {
@@ -194,8 +257,9 @@ const researchSetup = (o) => {
194
257
  };
195
258
  };
196
259
  const startResearch = async (raw, question, o, call) => {
197
- if (o.resume) return o.resume;
198
- const created = record(await raw.request("POST", "/v1/agent", {
260
+ if (o.resume !== void 0 && o.resume !== "") return o.resume;
261
+ const created = z.parse(AgentStart, await raw.request("POST", "/v1/agent", {
262
+ creates: true,
199
263
  ...call,
200
264
  body: compact({
201
265
  ...researchSetup(o),
@@ -208,17 +272,17 @@ const startResearch = async (raw, question, o, call) => {
208
272
  response_format: responseFormat(o.schema)
209
273
  })
210
274
  }));
211
- return requireId(provider, created.id);
275
+ return requireJobId(provider, created.id);
212
276
  };
213
- const researchOutput = (response, reply, schema, id) => {
277
+ const researchOutput = (run, reply, schema, id) => {
214
278
  if (!schema) return reply;
215
- const status = text(response.status);
279
+ const { status } = run.value;
216
280
  try {
217
281
  return parseJson(provider, reply);
218
282
  } catch (error) {
219
283
  if (status === "completed") throw error;
220
284
  throw new FieldworkError("JobFailed", `perplexity research ended ${status} with output that is not valid JSON`, {
221
- cause: response,
285
+ cause: run.original,
222
286
  jobId: id,
223
287
  provider
224
288
  });
@@ -227,23 +291,26 @@ const researchOutput = (response, reply, schema, id) => {
227
291
  const research = async (raw, question, options) => {
228
292
  const { call, rest: o } = callSettings(options);
229
293
  const id = await startResearch(raw, question, o, call);
230
- const response = await poll(provider, id, async () => {
231
- const found = record(await raw.request("GET", `/v1/agent/${encodeURIComponent(id)}`, { signal: call.signal }));
232
- return TERMINAL.has(text(found.status) ?? "") ? found : void 0;
294
+ const run = await poll(provider, id, async () => {
295
+ const found = z.parse(AgentRun, await raw.request("GET", `/v1/agent/${encodeURIComponent(id)}`, { signal: call.signal }));
296
+ return TERMINAL.has(found.value.status ?? "") ? found : void 0;
233
297
  }, {
234
298
  interval: o.interval,
235
299
  signal: call.signal,
236
300
  timeout: call.timeout
237
301
  });
238
- const status = text(response.status);
239
- const read = readResponse(response);
240
- if (status === "failed" || !read.text) throw responseError(response, id);
302
+ const { status } = run.value;
303
+ const read = readResponse(run.value);
304
+ if (status === "failed" || !read.text) throw responseError(run, id);
241
305
  return compact({
242
306
  continuationId: id,
243
307
  id,
244
- meta: responseMeta(response),
245
- output: researchOutput(response, read.text, o.schema, id),
246
- raw: response,
308
+ meta: responseMeta(run.value),
309
+ output: await checkOutput(o.schema, researchOutput(run, read.text, o.schema, id), {
310
+ jobId: id,
311
+ provider
312
+ }),
313
+ raw: run.original,
247
314
  retrieved: read.retrieved.length > 0 ? read.retrieved : void 0,
248
315
  sources: read.cited,
249
316
  status: status === "completed" ? "completed" : "partial",
@@ -266,34 +333,34 @@ const decisionQuestion = (question) => {
266
333
  type: "score"
267
334
  };
268
335
  };
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);
336
+ const decisionAnswer = (found, scores) => {
337
+ if (found.type === "noul") return compact({ probability: found.noul });
338
+ let probabilities = Object.fromEntries(Object.entries(found.probabilities).filter((entry) => entry[1] !== void 0));
273
339
  if (found.type === "score") probabilities = Object.fromEntries(Object.entries(probabilities).map(([index, probability]) => [scores?.[Number(index)] ?? index, probability]));
274
340
  const top = Object.entries(probabilities).toSorted((a, b) => b[1] - a[1])[0]?.[0];
275
341
  return compact({
276
- choice: text(found.choice) ?? top,
277
- confidence: num(found.confidence),
342
+ choice: found.choice ?? top,
343
+ confidence: found.confidence,
278
344
  probabilities
279
345
  });
280
346
  };
281
347
  const decide = async (raw, context, questions, options) => {
282
348
  const { call, rest: o } = callSettings(options);
283
- const response = record(await raw.request("POST", "/v1/decisions", {
349
+ const response = await raw.request("POST", "/v1/decisions", {
284
350
  ...call,
285
351
  body: {
286
352
  model: o.model ?? "pplx-decider-latest",
287
353
  questions: Object.fromEntries(Object.entries(questions).map(([name, question]) => [name, decisionQuestion(question)])),
288
354
  state: decisionState(context)
289
355
  }
290
- }));
356
+ });
357
+ const body = z.parse(DecisionsResponse, response);
291
358
  const answers = {};
292
- for (const [name, value] of Object.entries(record(response.answers))) {
359
+ for (const [name, value] of Object.entries(body.answers)) {
293
360
  const question = questions[name];
294
361
  answers[name] = decisionAnswer(value, question?.type === "score" ? Object.keys(question.scale) : void 0);
295
362
  }
296
- const usage = record(response.usage);
363
+ const { usage } = body;
297
364
  return {
298
365
  answers,
299
366
  citations: [],
@@ -309,7 +376,8 @@ const perplexity = (config = {}) => {
309
376
  baseUrl: config.baseUrl ?? "https://api.perplexity.ai",
310
377
  fetch: config.fetch,
311
378
  headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "PERPLEXITY_API_KEY")}` },
312
- provider
379
+ provider,
380
+ retries: config.retries
313
381
  });
314
382
  return defineAdapter({
315
383
  name: provider,
@@ -0,0 +1,90 @@
1
+ import { A as JsonSchema } from "./adapter-CDY8qczv.js";
2
+ /** Vendor-specific parameters a schema library may accept. */
3
+ type LibraryOptions = JsonSchema;
4
+ /** The path segment interface of an issue. */
5
+ interface StandardSchemaPathSegment {
6
+ /** The key representing a path segment. */
7
+ readonly key: PropertyKey;
8
+ }
9
+ /** The issue interface of a failed validation. */
10
+ interface StandardSchemaIssue {
11
+ /** The error message of the issue. */
12
+ readonly message: string;
13
+ /** The path of the issue, if any. */
14
+ readonly path?: readonly (PropertyKey | StandardSchemaPathSegment)[];
15
+ }
16
+ /** The result interface if validation succeeds. */
17
+ interface StandardSchemaSuccess<Output> {
18
+ /** The typed output value. */
19
+ readonly value: Output;
20
+ /** The absence of issues indicates success. */
21
+ readonly issues?: undefined;
22
+ }
23
+ /** The result interface if validation fails. */
24
+ interface StandardSchemaFailure {
25
+ /** The issues of failed validation. */
26
+ readonly issues: readonly StandardSchemaIssue[];
27
+ }
28
+ /** The result interface of the validate function. */
29
+ type StandardSchemaResult<Output> = StandardSchemaSuccess<Output> | StandardSchemaFailure;
30
+ /** The options of the validate function. */
31
+ interface StandardSchemaOptions {
32
+ /** Implicit support for additional vendor-specific parameters, if needed. */
33
+ readonly libraryOptions?: LibraryOptions;
34
+ }
35
+ /** The Standard types interface. */
36
+ interface StandardTypes<Input = unknown, Output = Input> {
37
+ /** The input type of the schema. */
38
+ readonly input: Input;
39
+ /** The output type of the schema. */
40
+ readonly output: Output;
41
+ }
42
+ /** The Standard properties shared by both interfaces. */
43
+ interface StandardTypedProps<Input = unknown, Output = Input> {
44
+ /** The version number of the standard. */
45
+ readonly version: 1;
46
+ /** The vendor name of the schema library. */
47
+ readonly vendor: string;
48
+ /** Inferred types associated with the schema. */
49
+ readonly types?: StandardTypes<Input, Output> | undefined;
50
+ }
51
+ /** The Standard Schema properties interface. */
52
+ interface StandardSchemaProps<Input = unknown, Output = Input> extends StandardTypedProps<Input, Output> {
53
+ /** Validates a value. `OutputSchema` fixes `Input` to `unknown`, as the spec has it. */
54
+ readonly validate: (value: Input, options?: StandardSchemaOptions) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
55
+ }
56
+ /**
57
+ * The target version of the generated JSON Schema. Libraries should support
58
+ * `"draft-2020-12"` and `"draft-07"`.
59
+ */
60
+ type StandardJSONSchemaTarget = "draft-2020-12" | "draft-07" | "openapi-3.0" | (string & {});
61
+ /** The options for the input/output methods. */
62
+ interface StandardJSONSchemaOptions {
63
+ /** The target version of the generated JSON Schema. */
64
+ readonly target: StandardJSONSchemaTarget;
65
+ /** Implicit support for additional vendor-specific parameters, if needed. */
66
+ readonly libraryOptions?: LibraryOptions;
67
+ }
68
+ /** The Standard JSON Schema converter interface. */
69
+ interface StandardJSONSchemaConverter {
70
+ /** Converts the input type to JSON Schema. May throw if conversion is not supported. */
71
+ readonly input: (options: StandardJSONSchemaOptions) => JsonSchema;
72
+ /** Converts the output type to JSON Schema. May throw if conversion is not supported. */
73
+ readonly output: (options: StandardJSONSchemaOptions) => JsonSchema;
74
+ }
75
+ /** The Standard JSON Schema properties interface. */
76
+ interface StandardJSONSchemaProps<Input = unknown, Output = Input> extends StandardTypedProps<Input, Output> {
77
+ /** Methods for generating the input/output JSON Schema. */
78
+ readonly jsonSchema: StandardJSONSchemaConverter;
79
+ }
80
+ /** A schema that both validates and describes itself: Zod, Valibot and ArkType. */
81
+ interface StandardSchemaWithJSON<Input = unknown, Output = Input> {
82
+ readonly "~standard": StandardSchemaProps<Input, Output> & StandardJSONSchemaProps<Input, Output>;
83
+ }
84
+ /**
85
+ * The shape of a structured output: a plain JSON Schema, or a Standard Schema
86
+ * with JSON Schema support. A Standard Schema gives the result its type and
87
+ * checks the provider's output against it; a plain JSON Schema does neither.
88
+ */
89
+ type OutputSchema<T> = JsonSchema | StandardSchemaWithJSON<unknown, T>;
90
+ export { StandardSchemaWithJSON as n, OutputSchema as t };
@@ -0,0 +1,45 @@
1
+ import { t as FieldworkError } from "./errors-BiIBG9zN.js";
2
+ // src/schema.ts
3
+ const isStandard = (schema) => "~standard" in schema;
4
+ /**
5
+ * The JSON Schema to send to a provider. A plain JSON Schema passes through as
6
+ * given; a Standard Schema is converted to `target`, without its `$schema` key,
7
+ * because the provider's docs, not the library, say which dialect it reads.
8
+ */
9
+ const jsonSchemaOf = (schema, target = "draft-2020-12") => {
10
+ if (!isStandard(schema)) return schema;
11
+ try {
12
+ const converted = schema["~standard"].jsonSchema.input({ target });
13
+ return Object.fromEntries(Object.entries(converted).filter(([key]) => key !== "$schema"));
14
+ } catch (error) {
15
+ throw new FieldworkError("InvalidRequest", `the ${schema["~standard"].vendor} schema cannot be written as ${target} JSON Schema: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
16
+ }
17
+ };
18
+ const MAX_ISSUES = 3;
19
+ const pathOf = (issue) => {
20
+ const segments = (issue.path ?? []).map((segment) => String(segment instanceof Object ? segment.key : segment));
21
+ return segments.length > 0 ? segments.join(".") : "(root)";
22
+ };
23
+ const describeIssues = (issues) => {
24
+ const shown = issues.slice(0, MAX_ISSUES).map((issue) => `${pathOf(issue)}: ${issue.message}`);
25
+ const more = issues.length - shown.length;
26
+ return `${shown.join("; ")}${more > 0 ? `; and ${more} more` : ""}`;
27
+ };
28
+ /**
29
+ * The provider's structured output as the caller's type. A Standard Schema
30
+ * checks it and throws `ProviderError` listing the first issues with their
31
+ * paths; the value returned is the schema's own output, so transforms and
32
+ * defaults apply. A plain JSON Schema, or no schema, leaves it unchecked.
33
+ */
34
+ const checkOutput = async (schema, value, context) => {
35
+ if (schema === void 0 || !isStandard(schema)) return value;
36
+ const result = await schema["~standard"].validate(value);
37
+ if (result.issues !== void 0) throw new FieldworkError("ProviderError", `${context.provider} returned output that does not match the schema: ${describeIssues(result.issues)}`, {
38
+ cause: result.issues,
39
+ jobId: context.jobId,
40
+ provider: context.provider,
41
+ retryable: false
42
+ });
43
+ return result.value;
44
+ };
45
+ export { jsonSchemaOf as n, checkOutput as t };
package/dist/serpapi.d.ts CHANGED
@@ -1,9 +1,12 @@
1
- import { W as Recency, a as RawClient, f as CallOptions, k as ImageSearch, q as SearchResponse, s as AccountUsage, t as Adapter } from "./adapter-DGehHCMo.js";
1
+ import { W as Recency, a as RawClient, f as CallOptions, k as ImageSearch, q as SearchResponse, s as AccountUsage, t as Adapter } from "./adapter-CDY8qczv.js";
2
+ import "./util-DhYr1OS3.js";
2
3
  interface SerpApiConfig {
3
4
  /** Defaults to the SERPAPI_API_KEY environment variable. */
4
5
  apiKey?: string;
5
6
  baseUrl?: string;
6
7
  fetch?: typeof fetch;
8
+ /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
+ retries?: number;
7
10
  }
8
11
  type Device = "desktop" | "tablet" | "mobile";
9
12
  interface SerpApiBaseOptions extends CallOptions {
@@ -164,9 +167,9 @@ interface SerpApiImagesOptions extends SerpApiBaseOptions {
164
167
  license?: "f" | "fc" | "fm" | "fmc" | "cl" | "ol";
165
168
  }
166
169
  interface SerpApiOperations {
167
- search(query: string, options?: SerpApiSearchOptions): Promise<SearchResponse>;
168
- images(query: string, options?: SerpApiImagesOptions): Promise<ImageSearch>;
169
- usage(options?: CallOptions): Promise<AccountUsage>;
170
+ search: (query: string, options?: SerpApiSearchOptions) => Promise<SearchResponse>;
171
+ images: (query: string, options?: SerpApiImagesOptions) => Promise<ImageSearch>;
172
+ usage: (options?: CallOptions) => Promise<AccountUsage>;
170
173
  }
171
174
  export declare const serpapi: (config?: SerpApiConfig) => Adapter<"serpapi", SerpApiOperations, RawClient>;
172
175
  export type { SerpApiBingOptions, SerpApiConfig, SerpApiDuckDuckGoOptions, SerpApiEngine, SerpApiGoogleOptions, SerpApiImagesOptions, SerpApiMapsOptions, SerpApiNewsOptions, SerpApiOperations, SerpApiPatentsOptions, SerpApiScholarOptions, SerpApiSearchOptions, SerpApiShoppingOptions };