@howells/fieldwork-sdk 0.0.0-stage → 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.
@@ -0,0 +1,101 @@
1
+ import { A as JsonSchema, G as Research, W as Recency, a as RawClient, f as CallOptions, l as Answer, q as SearchResponse, t as Adapter, v as DecisionQuestion, y as Decisions } from "./adapter-DGehHCMo.js";
2
+ export interface PerplexityConfig {
3
+ /** Defaults to the PERPLEXITY_API_KEY environment variable. */
4
+ apiKey?: string;
5
+ baseUrl?: string;
6
+ fetch?: typeof fetch;
7
+ }
8
+ /** The filters Perplexity applies to web search, on `/search` and inside the Agent API's `web_search` tool. */
9
+ interface PerplexityFilters {
10
+ /** 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`. */
11
+ includeDomains?: string[];
12
+ /** Same forms as `includeDomains`. At most 20. Not with `includeDomains`. */
13
+ excludeDomains?: string[];
14
+ /** YYYY-MM-DD; when the page was published. Inclusive. */
15
+ publishedAfter?: string;
16
+ /** YYYY-MM-DD; when the page was published. */
17
+ publishedBefore?: string;
18
+ /** YYYY-MM-DD; when the page last changed. */
19
+ lastUpdatedAfter?: string;
20
+ /** YYYY-MM-DD; when the page last changed. */
21
+ lastUpdatedBefore?: string;
22
+ recency?: Recency;
23
+ }
24
+ export interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
25
+ /** Results to return: up to 20, or up to 50 with `searchType: "people"`. */
26
+ limit?: number;
27
+ /**
28
+ * More queries, searched together with the first in one request. Perplexity
29
+ * allows five queries in all, and returns one flat list of results.
30
+ */
31
+ queries?: string[];
32
+ /** `web` (default), `fast` (lower latency and cost) or `people` (an index of professionals). */
33
+ searchType?: "web" | "fast" | "people";
34
+ /** ISO 3166-1 alpha-2 code such as "GB". */
35
+ country?: string;
36
+ /** ISO 639-1 codes, at most 20. Several codes match any of them. */
37
+ language?: string | string[];
38
+ /** Page-content tokens across all results. */
39
+ maxTokens?: number;
40
+ /** Page-content tokens for each result. */
41
+ maxTokensPerPage?: number;
42
+ }
43
+ /** An effort level, or a name pinned to a version such as `fast@2026-10-16.0`. */
44
+ type Pinned<Name extends string> = Name | `${Name}@${string}`;
45
+ export interface PerplexityAnswerOptions extends CallOptions {
46
+ /** Defaults to "fast". Answers are synchronous, so only the quicker levels are offered. */
47
+ effort?: Pinned<"fast" | "low" | "medium">;
48
+ instructions?: string;
49
+ schema?: JsonSchema;
50
+ /** The `continuationId` of an earlier answer or research result. */
51
+ continueFrom?: string;
52
+ }
53
+ /**
54
+ * Perplexity's effort levels. The names change slowly, so the type is open:
55
+ * `ultra-preview` and version pins (`high@2026-10-28.0`) are accepted too.
56
+ */
57
+ export type PerplexityEffort = "fast" | "low" | "medium" | "high" | "xhigh" | "ultra-preview" | (string & {});
58
+ export interface PerplexityResearchOptions extends CallOptions, PerplexityFilters {
59
+ schema?: JsonSchema;
60
+ /**
61
+ * The configuration to run: a model, tools, system prompt and step budget in
62
+ * one name. Defaults to "high" when neither `effort`, `model` nor `models` is
63
+ * given.
64
+ */
65
+ effort?: PerplexityEffort;
66
+ /** A model in `provider/model` form, such as `openai/gpt-6-luna`. Overrides the effort's model. */
67
+ model?: string;
68
+ /** Models to try in order, one to five; the first that works answers. Takes precedence over `model`. */
69
+ models?: string[];
70
+ /**
71
+ * Caps steps of the research loop (1 to 500), not money. With `model` or
72
+ * `models` and no `effort`, Perplexity defaults to 1 step, so this adapter
73
+ * sends 10 unless you set it.
74
+ */
75
+ maxSteps?: number;
76
+ maxOutputTokens?: number;
77
+ instructions?: string;
78
+ /** ISO 639-1 code for the language of the report. */
79
+ languagePreference?: string;
80
+ /** ISO 3166-1 alpha-2 code such as "GB", sent as the search location. */
81
+ country?: string;
82
+ /** The `continuationId` of an earlier answer or research result. */
83
+ continueFrom?: string;
84
+ /** The id of a run from an error's `jobId`; waits for it instead of starting another. */
85
+ resume?: string;
86
+ /** Milliseconds between checks. Defaults to 2000. */
87
+ interval?: number;
88
+ }
89
+ export type PerplexityDeciderModel = "pplx-decider-v1.2" | "pplx-decider-flash-v1.2" | "pplx-decider-latest" | "pplx-decider-flash-latest" | (string & {});
90
+ export interface PerplexityDecideOptions extends CallOptions {
91
+ /** Defaults to "pplx-decider-latest". The flash models are smaller and cheaper. */
92
+ model?: PerplexityDeciderModel;
93
+ }
94
+ export interface PerplexityOperations {
95
+ search(query: string, options?: PerplexitySearchOptions): Promise<SearchResponse>;
96
+ answer<T = unknown>(question: string, options?: PerplexityAnswerOptions): Promise<Answer<T>>;
97
+ research<T = unknown>(question: string, options?: PerplexityResearchOptions): Promise<Research<T>>;
98
+ decide(context: unknown, questions: Record<string, DecisionQuestion>, options?: PerplexityDecideOptions): Promise<Decisions>;
99
+ }
100
+ export declare const perplexity: (config?: PerplexityConfig) => Adapter<"perplexity", PerplexityOperations, RawClient>;
101
+ export {};
@@ -0,0 +1,333 @@
1
+ import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
+ import { 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, i as compact, l as parseJson, n as citation, o as list, p as requireId, s as meta, t as callSettings, v as createRawClient, y as poll } from "./util-CYenIQQT.js";
4
+ // src/adapters/perplexity.ts
5
+ const provider = "perplexity";
6
+ const MAX_QUERIES = 5;
7
+ const TERMINAL = /* @__PURE__ */ new Set([
8
+ "completed",
9
+ "failed",
10
+ "incomplete",
11
+ "cancelled"
12
+ ]);
13
+ const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
14
+ const usDate = (name, date) => {
15
+ if (date === void 0) return date;
16
+ const match = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u.exec(date);
17
+ if (!match?.groups) throw invalid(`${name} must be YYYY-MM-DD, got "${date}"`);
18
+ const { year, month, day } = match.groups;
19
+ return `${month}/${day}/${year}`;
20
+ };
21
+ const filterFields = (o) => {
22
+ refuseTogether(provider, { ...o }, "includeDomains", "excludeDomains");
23
+ const domains = o.includeDomains ?? o.excludeDomains?.map((d) => `-${d}`);
24
+ return compact({
25
+ last_updated_after_filter: usDate("lastUpdatedAfter", o.lastUpdatedAfter),
26
+ last_updated_before_filter: usDate("lastUpdatedBefore", o.lastUpdatedBefore),
27
+ search_after_date_filter: usDate("publishedAfter", o.publishedAfter),
28
+ search_before_date_filter: usDate("publishedBefore", o.publishedBefore),
29
+ search_domain_filter: domains && domains.length > 0 ? domains : void 0,
30
+ search_recency_filter: o.recency
31
+ });
32
+ };
33
+ const webSearchTool = (o) => {
34
+ const filters = filterFields(o);
35
+ const tool = compact({
36
+ filters: Object.keys(filters).length > 0 ? filters : void 0,
37
+ type: "web_search",
38
+ user_location: o.country ? { country: o.country } : void 0
39
+ });
40
+ return Object.keys(tool).length > 1 ? tool : void 0;
41
+ };
42
+ const languageCodes = (language) => {
43
+ const codes = [language ?? []].flat().map((code) => code.toLowerCase());
44
+ return codes.length > 0 ? codes : void 0;
45
+ };
46
+ const errorCode = (jobId, rateLimited) => {
47
+ if (jobId) return "JobFailed";
48
+ return rateLimited ? "RateLimited" : "ProviderError";
49
+ };
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);
54
+ const rateLimited = type === "request_rate_limit_exceeded" || type === "token_rate_limit_exceeded";
55
+ return new FieldworkError(errorCode(jobId, rateLimited), `perplexity ${message}`, {
56
+ cause: response,
57
+ jobId,
58
+ provider,
59
+ retryable: rateLimited || type === "overloaded"
60
+ });
61
+ };
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) => {
68
+ const parts = [];
69
+ const cited = [];
70
+ 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));
77
+ }
78
+ for (const found of retrievedBy(entry)) {
79
+ const source = citation(found);
80
+ if (source) retrieved.push(compact({
81
+ title: source.title,
82
+ url: source.url
83
+ }));
84
+ }
85
+ }
86
+ return {
87
+ cited: uniqueCitations(cited),
88
+ retrieved: uniqueCitations(retrieved),
89
+ text: parts.join("")
90
+ };
91
+ };
92
+ const responseMeta = (response, warnings) => {
93
+ const usage = record(response.usage);
94
+ const input = record(usage.input_tokens_details);
95
+ return meta({
96
+ costUsd: record(usage.cost).total_cost,
97
+ requestId: response.id,
98
+ units: {
99
+ cacheCreationInputTokens: input.cache_creation_input_tokens,
100
+ cacheReadInputTokens: input.cache_read_input_tokens,
101
+ inputTokens: usage.input_tokens,
102
+ outputTokens: usage.output_tokens,
103
+ reasoningTokens: record(usage.output_tokens_details).reasoning_tokens,
104
+ totalTokens: usage.total_tokens
105
+ },
106
+ warnings
107
+ });
108
+ };
109
+ const responseFormat = (schema) => schema ? {
110
+ json_schema: {
111
+ name: "output",
112
+ schema
113
+ },
114
+ type: "json_schema"
115
+ } : void 0;
116
+ const numbers = (value) => Object.fromEntries(Object.entries(record(value)).filter((entry) => num(entry[1]) !== void 0));
117
+ const decisionState = (context) => {
118
+ if (typeof context === "string" || typeof context === "object" && context) return context;
119
+ if (typeof context === "number" || typeof context === "boolean") return String(context);
120
+ throw invalid("perplexity decide needs a context: a string, object or array");
121
+ };
122
+ const search = async (raw, query, options) => {
123
+ const { call, rest: o } = callSettings(options);
124
+ const queries = [query, ...o.queries ?? []];
125
+ if (queries.length > MAX_QUERIES) throw invalid(`perplexity search takes at most ${MAX_QUERIES} queries in one request, got ${queries.length}`);
126
+ 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", {
128
+ ...call,
129
+ body: compact({
130
+ country: o.country,
131
+ max_results: o.limit,
132
+ max_tokens: o.maxTokens,
133
+ max_tokens_per_page: o.maxTokensPerPage,
134
+ query: queries.length > 1 ? queries : query,
135
+ search_language_filter: languageCodes(o.language),
136
+ search_type: o.searchType,
137
+ ...filterFields(o)
138
+ })
139
+ }));
140
+ return {
141
+ meta: meta({ requestId: response.id }),
142
+ 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
+ })
153
+ };
154
+ };
155
+ const answer = async (raw, question, options) => {
156
+ const { call, rest: o } = callSettings(options);
157
+ const response = record(await raw.request("POST", "/v1/agent", {
158
+ ...call,
159
+ body: compact({
160
+ effort: o.effort ?? "fast",
161
+ input: question,
162
+ instructions: o.instructions,
163
+ previous_response_id: o.continueFrom,
164
+ response_format: responseFormat(o.schema)
165
+ })
166
+ }));
167
+ const read = readResponse(response);
168
+ const status = text(response.status);
169
+ if (status === "failed" || status === "cancelled" || !read.text) throw responseError(response);
170
+ return compact({
171
+ answer: read.text,
172
+ 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
177
+ });
178
+ };
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
+ const startResearch = async (raw, question, o, call) => {
197
+ if (o.resume) return o.resume;
198
+ const created = record(await raw.request("POST", "/v1/agent", {
199
+ ...call,
200
+ body: compact({
201
+ ...researchSetup(o),
202
+ background: true,
203
+ input: question,
204
+ instructions: o.instructions,
205
+ language_preference: o.languagePreference,
206
+ max_output_tokens: o.maxOutputTokens,
207
+ previous_response_id: o.continueFrom,
208
+ response_format: responseFormat(o.schema)
209
+ })
210
+ }));
211
+ return requireId(provider, created.id);
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
+ }
226
+ };
227
+ const research = async (raw, question, options) => {
228
+ const { call, rest: o } = callSettings(options);
229
+ 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;
233
+ }, {
234
+ interval: o.interval,
235
+ signal: call.signal,
236
+ timeout: call.timeout
237
+ });
238
+ const status = text(response.status);
239
+ const read = readResponse(response);
240
+ if (status === "failed" || !read.text) throw responseError(response, id);
241
+ return compact({
242
+ continuationId: id,
243
+ id,
244
+ meta: responseMeta(response),
245
+ output: researchOutput(response, read.text, o.schema, id),
246
+ raw: response,
247
+ retrieved: read.retrieved.length > 0 ? read.retrieved : void 0,
248
+ sources: read.cited,
249
+ status: status === "completed" ? "completed" : "partial",
250
+ stopReason: status === "completed" ? void 0 : status
251
+ });
252
+ };
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
+ const decide = async (raw, context, questions, options) => {
282
+ const { call, rest: o } = callSettings(options);
283
+ const response = record(await raw.request("POST", "/v1/decisions", {
284
+ ...call,
285
+ body: {
286
+ model: o.model ?? "pplx-decider-latest",
287
+ questions: Object.fromEntries(Object.entries(questions).map(([name, question]) => [name, decisionQuestion(question)])),
288
+ state: decisionState(context)
289
+ }
290
+ }));
291
+ const answers = {};
292
+ for (const [name, value] of Object.entries(record(response.answers))) {
293
+ const question = questions[name];
294
+ answers[name] = decisionAnswer(value, question?.type === "score" ? Object.keys(question.scale) : void 0);
295
+ }
296
+ const usage = record(response.usage);
297
+ return {
298
+ answers,
299
+ citations: [],
300
+ meta: meta({ units: {
301
+ inputTokens: usage.input_tokens,
302
+ outputTokens: usage.output_tokens
303
+ } }),
304
+ raw: response
305
+ };
306
+ };
307
+ const perplexity = (config = {}) => {
308
+ const raw = createRawClient({
309
+ baseUrl: config.baseUrl ?? "https://api.perplexity.ai",
310
+ fetch: config.fetch,
311
+ headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "PERPLEXITY_API_KEY")}` },
312
+ provider
313
+ });
314
+ return defineAdapter({
315
+ name: provider,
316
+ operations: {
317
+ async answer(question, options) {
318
+ return await answer(raw, question, options);
319
+ },
320
+ async decide(context, questions, options) {
321
+ return await decide(raw, context, questions, options);
322
+ },
323
+ async research(question, options) {
324
+ return await research(raw, question, options);
325
+ },
326
+ async search(query, options) {
327
+ return await search(raw, query, options);
328
+ }
329
+ },
330
+ raw
331
+ });
332
+ };
333
+ export { perplexity };
@@ -0,0 +1,172 @@
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";
2
+ interface SerpApiConfig {
3
+ /** Defaults to the SERPAPI_API_KEY environment variable. */
4
+ apiKey?: string;
5
+ baseUrl?: string;
6
+ fetch?: typeof fetch;
7
+ }
8
+ type Device = "desktop" | "tablet" | "mobile";
9
+ interface SerpApiBaseOptions extends CallOptions {
10
+ /**
11
+ * Skip SerpApi's one-hour cache and fetch fresh results. Cached searches
12
+ * are free and do not count toward the monthly allowance.
13
+ */
14
+ noCache?: boolean;
15
+ }
16
+ /** Google web search: `GET /search?engine=google`, organic results and the answer box. */
17
+ interface SerpApiGoogleOptions extends SerpApiBaseOptions {
18
+ engine?: "google";
19
+ /** ISO 3166-1 alpha-2 code such as "GB"; sent as `gl` ("uk" for GB, as SerpApi documents). */
20
+ country?: string;
21
+ /** Sent as `hl`: a language code such as "en", or "en-gb". */
22
+ language?: string;
23
+ /** Where the search originates, as text: "Austin, Texas, United States". */
24
+ location?: string;
25
+ /** Sent as `tbs` `qdr`. Not allowed with `publishedAfter` or `publishedBefore`. */
26
+ recency?: Recency;
27
+ /** YYYY-MM-DD. Sent as `tbs` `cdr`. */
28
+ publishedAfter?: string;
29
+ /** YYYY-MM-DD. Sent as `tbs` `cdr`. */
30
+ publishedBefore?: string;
31
+ safe?: "active" | "off";
32
+ device?: Device;
33
+ /** Result offset: 0 is the first page, 10 the second. */
34
+ start?: number;
35
+ }
36
+ /** Google News: `engine=google_news`. SerpApi documents `q`, `gl` and `hl` for a news search. */
37
+ interface SerpApiNewsOptions extends SerpApiBaseOptions {
38
+ engine: "google_news";
39
+ country?: string;
40
+ language?: string;
41
+ }
42
+ /** Google Shopping: `engine=google_shopping`. */
43
+ interface SerpApiShoppingOptions extends SerpApiBaseOptions {
44
+ engine: "google_shopping";
45
+ country?: string;
46
+ language?: string;
47
+ location?: string;
48
+ safe?: "active" | "off";
49
+ device?: Device;
50
+ minPrice?: number;
51
+ maxPrice?: number;
52
+ /** 1 sorts by price, low to high; 2 by price, high to low. */
53
+ sortBy?: 1 | 2;
54
+ freeShipping?: boolean;
55
+ onSale?: boolean;
56
+ smallBusiness?: boolean;
57
+ }
58
+ /**
59
+ * Google Maps: `engine=google_maps`, `type=search`. Give the search origin as
60
+ * `latitude` and `longitude`, or as `location`, and always with `zoom`.
61
+ */
62
+ interface SerpApiMapsOptions extends SerpApiBaseOptions {
63
+ engine: "google_maps";
64
+ language?: string;
65
+ latitude?: number;
66
+ longitude?: number;
67
+ /** A place name for the search origin. Needs `zoom`. */
68
+ location?: string;
69
+ /** Map zoom, 3 (whole world) to 30. Sent as `z`. */
70
+ zoom?: number;
71
+ /** Result offset in steps of 20. */
72
+ start?: number;
73
+ }
74
+ /** Google Scholar: `engine=google_scholar`. */
75
+ interface SerpApiScholarOptions extends SerpApiBaseOptions {
76
+ engine: "google_scholar";
77
+ /** Results to return, 1 to 20. Sent as `num`. */
78
+ limit?: number;
79
+ language?: string;
80
+ safe?: "active" | "off";
81
+ /** Leaves out results before this year (`as_ylo`). Scholar filters by year only. */
82
+ yearFrom?: number;
83
+ /** Leaves out results after this year (`as_yhi`). */
84
+ yearTo?: number;
85
+ /** Result offset: 0 is the first page, 10 the second. */
86
+ start?: number;
87
+ }
88
+ /** Google Patents: `engine=google_patents`. */
89
+ interface SerpApiPatentsOptions extends SerpApiBaseOptions {
90
+ engine: "google_patents";
91
+ /** Results per page, 10 to 100. Sent as `num`. */
92
+ limit?: number;
93
+ /** Page number, starting at 1. */
94
+ page?: number;
95
+ /** "new" and "old" sort by filing date. The default is relevance. */
96
+ sort?: "new" | "old";
97
+ /** YYYY-MM-DD. Sent as `after=publication:YYYYMMDD`. */
98
+ publishedAfter?: string;
99
+ /** YYYY-MM-DD. Sent as `before=publication:YYYYMMDD`. */
100
+ publishedBefore?: string;
101
+ /** Inventor names, separated by commas. */
102
+ inventor?: string;
103
+ /** Assignee names, separated by commas. */
104
+ assignee?: string;
105
+ status?: "GRANT" | "APPLICATION";
106
+ }
107
+ /** Bing: `engine=bing`. */
108
+ interface SerpApiBingOptions extends SerpApiBaseOptions {
109
+ engine: "bing";
110
+ /** ISO 3166-1 alpha-2 code such as "GB"; sent as `cc`. Not allowed with `market`. */
111
+ country?: string;
112
+ /** Bing market code such as "en-US"; sent as `mkt`. Not allowed with `country`. */
113
+ market?: string;
114
+ location?: string;
115
+ /** Sent as `safeSearch`. */
116
+ safeSearch?: "Off" | "Moderate" | "Strict";
117
+ device?: Device;
118
+ /** Position of the first organic result to return, starting at 1. */
119
+ first?: number;
120
+ }
121
+ /** DuckDuckGo: `engine=duckduckgo`. */
122
+ interface SerpApiDuckDuckGoOptions extends SerpApiBaseOptions {
123
+ engine: "duckduckgo";
124
+ /** Results to return, 1 to 50. Sent as `m`. */
125
+ limit?: number;
126
+ /** DuckDuckGo region such as "us-en" or "fr-fr"; sent as `kl`. */
127
+ region?: string;
128
+ /** 1 is strict, -1 moderate (the default), -2 off. */
129
+ safe?: 1 | -1 | -2;
130
+ /** Sent as `df`. DuckDuckGo has no hour window. Not allowed with the date options. */
131
+ recency?: Exclude<Recency, "hour">;
132
+ /** YYYY-MM-DD. DuckDuckGo needs both dates for a range. */
133
+ publishedAfter?: string;
134
+ /** YYYY-MM-DD. DuckDuckGo needs both dates for a range. */
135
+ publishedBefore?: string;
136
+ start?: number;
137
+ }
138
+ type SerpApiSearchOptions = SerpApiGoogleOptions | SerpApiNewsOptions | SerpApiShoppingOptions | SerpApiMapsOptions | SerpApiScholarOptions | SerpApiPatentsOptions | SerpApiBingOptions | SerpApiDuckDuckGoOptions;
139
+ type SerpApiEngine = NonNullable<SerpApiSearchOptions["engine"]>;
140
+ /** Google Images: `engine=google_images`. */
141
+ interface SerpApiImagesOptions extends SerpApiBaseOptions {
142
+ country?: string;
143
+ language?: string;
144
+ location?: string;
145
+ /** Sent as `period_unit`. Not allowed with `publishedAfter` or `publishedBefore`. */
146
+ recency?: Recency;
147
+ /** YYYY-MM-DD. Sent as `start_date`. */
148
+ publishedAfter?: string;
149
+ /** YYYY-MM-DD. Sent as `end_date`. */
150
+ publishedBefore?: string;
151
+ safe?: "active" | "off";
152
+ device?: Device;
153
+ /** Page number, 0 to 99. Sent as `ijn`. */
154
+ page?: number;
155
+ /** s square, t tall, w wide, xw panoramic. Sent as `imgar`. */
156
+ aspectRatio?: "s" | "t" | "w" | "xw";
157
+ /** Sent as `imgsz`: l, m, i, or a minimum such as "qsvga" or "2mp". */
158
+ size?: "l" | "m" | "i" | "qsvga" | "vga" | "svga" | "xga" | "2mp" | "4mp" | "6mp" | "8mp" | "10mp" | "12mp" | "15mp" | "20mp" | "40mp" | "70mp";
159
+ /** Sent as `image_color`. */
160
+ color?: "bw" | "trans" | "red" | "orange" | "yellow" | "green" | "teal" | "blue" | "purple" | "pink" | "white" | "gray" | "black" | "brown";
161
+ /** Sent as `image_type`. */
162
+ imageType?: "face" | "photo" | "clipart" | "lineart" | "animated";
163
+ /** Sent as `licenses`: f, fc, fm, fmc, cl or ol. */
164
+ license?: "f" | "fc" | "fm" | "fmc" | "cl" | "ol";
165
+ }
166
+ 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
+ }
171
+ export declare const serpapi: (config?: SerpApiConfig) => Adapter<"serpapi", SerpApiOperations, RawClient>;
172
+ export type { SerpApiBingOptions, SerpApiConfig, SerpApiDuckDuckGoOptions, SerpApiEngine, SerpApiGoogleOptions, SerpApiImagesOptions, SerpApiMapsOptions, SerpApiNewsOptions, SerpApiOperations, SerpApiPatentsOptions, SerpApiScholarOptions, SerpApiSearchOptions, SerpApiShoppingOptions };