@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/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { A as JsonSchema, B as Price, C as Entity, D as GROUP_CAPABILITIES, E as FieldSource, F as MonitorSchedule, G as Research, H as ProductImage, I as Page, J as SearchResult, K as RunStatus, L as PageBatch, M as MonitorEvent, N as MonitorEvents, O as ImageResult, P as MonitorInfo, R as ParsedDocument, S as DocumentPage, T as FailedUrl, U as ProductVariant, V as Product, W as Recency, X as SiteMap, Y as SiteLink, Z as Usage, _ as DecisionAnswer, a as RawClient, b as Discovery, c as ActResult, d as CAPABILITIES, f as CallOptions, g as Crawl, h as Condition, i as defineAdapter, j as Meta, k as ImageSearch, l as Answer, m as Citation, n as AnyAdapter, o as RequestOptions, p as Capability, q as SearchResponse, r as Operations, s as AccountUsage, t as Adapter, u as BrowserSession, v as DecisionQuestion, w as Extraction, x as DocumentInput, y as Decisions, z as Place } from "./adapter-DGehHCMo.js";
2
- import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-B3x3cxDJ.js";
1
+ import { $ as TableCell, A as ImageResult, B as ParsedDocument, C as DocumentInput, D as FailedUrl, E as Extraction, F as MonitorEvents, G as ProductVariant, H as Price, I as MonitorInfo, J as RunStatus, K as Recency, L as MonitorSchedule, M as JsonSchema, N as Meta, O as FieldSource, P as MonitorEvent, Q as SiteMap, R as Page, S as DocumentBlock, T as Entity, U as Product, V as Place, W as ProductImage, X as SearchResult, Y as SearchResponse, Z as SiteLink, _ as Crawl, a as RawClient, b as Decisions, c as ActResult, d as BrowserSession, et as Usage, f as CAPABILITIES, g as Condition, h as Citation, i as defineAdapter, j as ImageSearch, k as GROUP_CAPABILITIES, l as Answer, m as Capability, n as AnyAdapter, o as RequestOptions, p as CallOptions, q as Research, r as Operations, s as AccountUsage, t as Adapter, tt as WordBox, u as Box, v as DecisionAnswer, w as DocumentPage, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-BgdfLBs-.js";
2
+ import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-CXNIcqSN.js";
3
+ import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-Cupy7-7q.js";
4
+ /** Which adapter serves each capability, for `router`. */
3
5
  type Routes = Partial<Record<Capability, AnyAdapter>>;
4
6
  /** Each route must name an adapter whose provider offers that capability. */
5
7
  type ValidRoutes<R extends Routes> = { [C in keyof R]: C extends Capability ? R[C] extends {
@@ -21,4 +23,4 @@ export declare const router: <const R extends Routes>(routes: R & ValidRoutes<R>
21
23
  * `Unsupported` here instead of failing to compile.
22
24
  */
23
25
  export declare const runtimeRouter: (routes: Routes) => AnyAdapter;
24
- export { AccountUsage, ActResult, type Adapter, Answer, type AnyAdapter, BrowserSession, CAPABILITIES, CallOptions, Capability, Citation, Condition, Crawl, DecisionAnswer, DecisionQuestion, Decisions, Discovery, DocumentInput, DocumentPage, Entity, Extraction, FailedUrl, FieldSource, Fieldwork, FieldworkError, type FieldworkErrorCode, type FieldworkOptions, GROUP_CAPABILITIES, ImageResult, ImageSearch, JsonSchema, Meta, MonitorEvent, MonitorEvents, MonitorInfo, MonitorSchedule, type Operations, Page, PageBatch, ParsedDocument, Place, Price, Product, ProductImage, ProductVariant, type RawClient, Recency, type RequestOptions, Research, type Routes, RunStatus, SearchResponse, SearchResult, SiteLink, SiteMap, Usage, defineAdapter };
26
+ export { AccountUsage, ActResult, type Adapter, Answer, type AnyAdapter, Box, BrowserSession, CAPABILITIES, CallOptions, Capability, Citation, Condition, Crawl, DecisionAnswer, DecisionQuestion, Decisions, Discovery, DocumentBlock, DocumentInput, DocumentPage, Entity, Extraction, FailedUrl, FieldSource, Fieldwork, FieldworkError, type FieldworkErrorCode, type FieldworkOptions, GROUP_CAPABILITIES, ImageResult, ImageSearch, JsonSchema, Meta, MonitorEvent, MonitorEvents, MonitorInfo, MonitorSchedule, type Operations, type OutputSchema, Page, PageBatch, ParsedDocument, Place, Price, Product, ProductImage, ProductVariant, type RawClient, Recency, type RequestOptions, Research, type Routes, RunStatus, SearchResponse, SearchResult, SiteLink, SiteMap, type StandardSchemaWithJSON, TableCell, Usage, WordBox, defineAdapter };
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { t as FieldworkError } from "./errors-Yvk42oZH.js";
3
3
  import { n as GROUP_CAPABILITIES, t as CAPABILITIES } from "./types-CnomnF-6.js";
4
4
  // src/fieldwork.ts
5
5
  const bindOperation = (operations, capability) => {
6
6
  const all = operations;
7
7
  const operation = all[capability];
8
8
  if (typeof operation === "function") return operation.bind(all);
9
- if (GROUP_CAPABILITIES.includes(capability) && operation && typeof operation === "object") {
9
+ if (GROUP_CAPABILITIES.some((group) => group === capability) && typeof operation === "object" && operation !== null) {
10
10
  const group = operation;
11
11
  return Object.fromEntries(Object.entries(group).map(([name, method]) => [name, typeof method === "function" ? method.bind(group) : method]));
12
12
  }
@@ -28,14 +28,28 @@ var FieldworkClient = class {
28
28
  this.provider = adapter.name;
29
29
  this.raw = adapter.raw;
30
30
  this.#providers = adapter.providers ?? {};
31
- const capabilities = {};
32
- const self = this;
33
- for (const capability of CAPABILITIES) {
34
- const operation = bindOperation(adapter.operations, capability);
35
- capabilities[capability] = operation !== void 0;
36
- self[capability] = operation ?? unsupported(adapter.name, capability);
37
- }
38
- this.capabilities = Object.freeze(capabilities);
31
+ const bound = new Map(CAPABILITIES.map((capability) => [capability, bindOperation(adapter.operations, capability)]));
32
+ const has = (capability) => bound.get(capability) !== void 0;
33
+ this.capabilities = Object.freeze({
34
+ act: has("act"),
35
+ answer: has("answer"),
36
+ browser: has("browser"),
37
+ crawl: has("crawl"),
38
+ decide: has("decide"),
39
+ discover: has("discover"),
40
+ extract: has("extract"),
41
+ images: has("images"),
42
+ map: has("map"),
43
+ monitor: has("monitor"),
44
+ parse: has("parse"),
45
+ product: has("product"),
46
+ read: has("read"),
47
+ readMany: has("readMany"),
48
+ research: has("research"),
49
+ search: has("search"),
50
+ usage: has("usage")
51
+ });
52
+ Object.assign(this, Object.fromEntries(CAPABILITIES.map((capability) => [capability, bound.get(capability) ?? unsupported(adapter.name, capability)])));
39
53
  }
40
54
  supports(capability) {
41
55
  return this.capabilities[capability];
@@ -45,6 +59,11 @@ var FieldworkClient = class {
45
59
  return this.#providers[capability] ?? this.provider;
46
60
  }
47
61
  };
62
+ /**
63
+ * The client: `new Fieldwork({ adapter })` has exactly the methods its adapter offers.
64
+ *
65
+ * Check `supports` or `capabilities` before calling dynamically; a capability the provider lacks throws `Unsupported`.
66
+ */
48
67
  const Fieldwork = FieldworkClient;
49
68
  // src/router.ts
50
69
  const build = (routes) => {
@@ -52,11 +71,12 @@ const build = (routes) => {
52
71
  const raw = {};
53
72
  const providers = {};
54
73
  for (const [capability, adapter] of Object.entries(routes)) {
55
- if (!adapter) continue;
74
+ if (adapter === void 0) continue;
56
75
  const operation = bindOperation(adapter.operations, capability);
57
76
  if (operation === void 0) throw new FieldworkError("Unsupported", `${adapter.name} does not offer ${capability}`, { provider: adapter.name });
58
77
  operations[capability] = operation;
59
- providers[capability] = adapter.name;
78
+ const known = CAPABILITIES.find((name) => name === capability);
79
+ if (known !== void 0) providers[known] = adapter.name;
60
80
  raw[adapter.name] = adapter.raw;
61
81
  }
62
82
  return {
@@ -0,0 +1,58 @@
1
+ import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-BgdfLBs-.js";
2
+ export interface LlamaParseConfig {
3
+ /** Defaults to the LLAMA_CLOUD_API_KEY environment variable. */
4
+ apiKey?: string;
5
+ /** Defaults to https://api.cloud.llamaindex.ai; the EU region is https://api.cloud.eu.llamaindex.ai. */
6
+ baseUrl?: string;
7
+ fetch?: typeof fetch;
8
+ /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
+ retries?: number;
10
+ }
11
+ /**
12
+ * LlamaParse's tiers, cheapest first. `fast` reads the text layer only, with
13
+ * no AI model; `agentic` reads tables, scans and multi-column layouts.
14
+ */
15
+ export type LlamaParseTier = "fast" | "cost_effective" | "agentic" | "agentic_plus";
16
+ export interface LlamaParseParseOptions extends CallOptions {
17
+ /** Defaults to "agentic". */
18
+ tier?: LlamaParseTier;
19
+ /** The parser version: "latest" (the default) or a date such as "2026-09-28". */
20
+ version?: string;
21
+ /** Return layout blocks with positions. */
22
+ blocks?: boolean;
23
+ /**
24
+ * Also return where each word and table cell sits in each block, from a
25
+ * second download. Returns blocks too. LlamaParse does not charge for it.
26
+ */
27
+ wordBoxes?: boolean;
28
+ /** Leave out text a reader cannot see, such as white text on white. */
29
+ ignoreHiddenText?: boolean;
30
+ /**
31
+ * Also return a picture of each page as `pages[].image`, an address that
32
+ * expires after about an hour. Collect fresh addresses with
33
+ * `parse({ resume: id, pageImages: true })`; a parse started without
34
+ * `pageImages` saved no pictures, so resuming it with them throws.
35
+ */
36
+ pageImages?: boolean;
37
+ /** The id of a job from an error's `jobId`; waits for it instead of starting another. */
38
+ resume?: string;
39
+ /** Milliseconds between checks. Defaults to 2000. */
40
+ interval?: number;
41
+ }
42
+ /** Options for collecting an earlier parse by its id, without the file. */
43
+ export type LlamaParseResumeOptions = Omit<LlamaParseParseOptions, "resume"> & {
44
+ resume: string;
45
+ };
46
+ export interface LlamaParseOperations {
47
+ parse: {
48
+ (document: DocumentInput, options?: LlamaParseParseOptions): Promise<ParsedDocument>;
49
+ /** Collects an earlier parse by its id, without sending the file again. */
50
+ (options: LlamaParseResumeOptions): Promise<ParsedDocument>;
51
+ };
52
+ }
53
+ /**
54
+ * An adapter for LlamaParse: parse. Pass it to `new Fieldwork({ adapter })`.
55
+ *
56
+ * Throws `Unauthorized` when neither `apiKey` nor `LLAMA_CLOUD_API_KEY` is set.
57
+ */
58
+ export declare const llamaparse: (config?: LlamaParseConfig) => Adapter<"llamaparse", LlamaParseOperations, RawClient>;
@@ -0,0 +1,286 @@
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { a as refuseLarger, n as documentPart, r as enclosing } from "./document-Dpj01mGx.js";
3
+ import { i as withJob, t as FieldworkError } from "./errors-Yvk42oZH.js";
4
+ import { C as createRawClient, D as segment, E as requireKey, N as meta, O as callSettings, P as parseJson, S as withOriginal, T as readSigned, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, j as compact, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
5
+ import * as z from "zod/mini";
6
+ // src/adapters/llamaparse/response.ts
7
+ /** A box in page points, from the page's top-left corner. */
8
+ const PointBox = looseObject({
9
+ h: optionalNumber,
10
+ w: optionalNumber,
11
+ x: optionalNumber,
12
+ y: optionalNumber
13
+ });
14
+ /** A word: `span` is `[start, end)` in UTF-8 bytes of its item's text. */
15
+ const Word = looseObject({
16
+ bbox: PointBox,
17
+ span: arrayOf(z.number())
18
+ });
19
+ const Line = looseObject({ words: arrayOf(Word) });
20
+ const Cell = looseObject({
21
+ bbox: arrayOf(PointBox),
22
+ lines: arrayOf(Line)
23
+ });
24
+ /** An item of a page. Its own `items` (a header's, a list's) are read one level at a time. */
25
+ const Item = looseObject({
26
+ bbox: arrayOf(PointBox),
27
+ grounding: looseObject({
28
+ lines: arrayOf(Line),
29
+ rows: arrayOf(arrayOf(Cell))
30
+ }),
31
+ items: arrayOf(anything),
32
+ md: optionalAnyString,
33
+ /** A table's cells as text; a number reads as its digits. */
34
+ rows: arrayOf(arrayOf(optionalScalar)),
35
+ type: optionalString,
36
+ value: optionalAnyString
37
+ });
38
+ /** A page of items: in `items.pages` of a job, and a row of the grounded items. */
39
+ const ItemsPage = looseObject({
40
+ items: arrayOf(Item),
41
+ page_height: optionalNumber,
42
+ page_number: optionalNumber,
43
+ page_width: optionalNumber
44
+ });
45
+ /** `POST /api/v2/parse/upload`. */
46
+ const JobStart = looseObject({ id: withOriginal(optionalId) });
47
+ /** `GET /api/v2/parse/{id}`, as it arrived beside the value read from it. */
48
+ const JobResult = withOriginal(looseObject({
49
+ images_content_metadata: looseObject({ images: arrayOf(looseObject({
50
+ filename: optionalString,
51
+ presigned_url: optionalString
52
+ })) }),
53
+ items: looseObject({ pages: arrayOf(ItemsPage) }),
54
+ job: looseObject({
55
+ error_message: optionalString,
56
+ status: optionalString,
57
+ usage: looseObject({ credits: optionalNumber })
58
+ }),
59
+ markdown: looseObject({ pages: arrayOf(looseObject({
60
+ markdown: optionalAnyString,
61
+ page_number: optionalNumber
62
+ })) }),
63
+ result_content_metadata: looseObject({ grounded_items: looseObject({ presigned_url: optionalString }) })
64
+ }));
65
+ const encoder = new TextEncoder();
66
+ const decoder = new TextDecoder();
67
+ const fraction = (box, size) => {
68
+ const { h, w, x, y } = box;
69
+ if (x === void 0 || y === void 0 || w === void 0 || h === void 0) return;
70
+ return {
71
+ height: h / size.height,
72
+ left: x / size.width,
73
+ top: y / size.height,
74
+ width: w / size.width
75
+ };
76
+ };
77
+ const around = (boxes, size) => enclosing(boxes.map((box) => fraction(box, size)).filter((box) => box !== void 0));
78
+ const wordsOf = (lines, text, size) => {
79
+ const bytes = encoder.encode(text);
80
+ return lines.flatMap((line) => line.words.flatMap((word) => {
81
+ const box = fraction(word.bbox, size);
82
+ const [start, end] = word.span;
83
+ if (box === void 0 || start === void 0 || end === void 0) return [];
84
+ return [{
85
+ box,
86
+ text: decoder.decode(bytes.slice(start, end))
87
+ }];
88
+ }));
89
+ };
90
+ const tableOf = (item, size) => {
91
+ const cells = [];
92
+ const words = [];
93
+ for (const [row, grounded] of item.grounding.rows.entries()) for (const [column, cell] of grounded.entries()) {
94
+ const text = item.rows[row]?.[column];
95
+ if (text !== void 0) {
96
+ cells.push(compact({
97
+ box: around(cell.bbox, size),
98
+ column,
99
+ row,
100
+ text
101
+ }));
102
+ words.push(...wordsOf(cell.lines, text, size));
103
+ }
104
+ }
105
+ return {
106
+ cells,
107
+ words
108
+ };
109
+ };
110
+ const blocksOfItem = (item, page, size) => {
111
+ if (item.items.length > 0) return item.items.flatMap((child) => blocksOfItem(z.parse(Item, child), page, size));
112
+ const text = item.md ?? item.value ?? "";
113
+ if (size === void 0) return [{
114
+ page,
115
+ text,
116
+ type: item.type ?? "unknown"
117
+ }];
118
+ const table = tableOf(item, size);
119
+ const words = [...wordsOf(item.grounding.lines, text, size), ...table.words];
120
+ return [compact({
121
+ box: around(item.bbox, size),
122
+ cells: table.cells.length > 0 ? table.cells : void 0,
123
+ page,
124
+ text,
125
+ type: item.type ?? "unknown",
126
+ words: words.length > 0 ? words : void 0
127
+ })];
128
+ };
129
+ /** The blocks of each page, its boxes turned from points into fractions of the page. */
130
+ const documentBlocks = (pages) => pages.flatMap((entry) => {
131
+ const page = entry.page_number;
132
+ if (page === void 0) return [];
133
+ const size = entry.page_width !== void 0 && entry.page_height !== void 0 && entry.page_width > 0 && entry.page_height > 0 ? {
134
+ height: entry.page_height,
135
+ width: entry.page_width
136
+ } : void 0;
137
+ return entry.items.flatMap((item) => blocksOfItem(item, page, size));
138
+ });
139
+ // src/adapters/llamaparse.ts
140
+ const provider = "llamaparse";
141
+ /** LlamaParse names each page's screenshot `page_<n>.jpg`. */
142
+ const PAGE_IMAGE = /^page_(?<page>\d+)\.jpg$/u;
143
+ /** The largest file LlamaParse takes, in megabytes. */
144
+ const MAX_PARSE_MB = 512;
145
+ const configuration = (o) => compact({
146
+ output_options: o.wordBoxes === true || o.pageImages === true ? compact({
147
+ granular_bboxes: o.wordBoxes === true ? [
148
+ "word",
149
+ "line",
150
+ "cell"
151
+ ] : void 0,
152
+ images_to_save: o.pageImages === true ? ["screenshot"] : void 0
153
+ }) : void 0,
154
+ processing_options: o.ignoreHiddenText === true ? { ignore: { ignore_hidden_text: true } } : void 0,
155
+ tier: o.tier ?? "agentic",
156
+ version: o.version ?? "latest"
157
+ });
158
+ const startParse = async (raw, document, o, call) => {
159
+ if (o.resume !== void 0) return o.resume;
160
+ if (document === void 0) throw new FieldworkError("InvalidRequest", "parse needs a document, or resume with the id of an earlier parse", { provider });
161
+ refuseLarger(provider, document, MAX_PARSE_MB);
162
+ const form = new FormData();
163
+ form.set("configuration", JSON.stringify(configuration(o)));
164
+ form.set("file", documentPart(document), document.name);
165
+ const created = z.parse(JobStart, await raw.request("POST", "/api/v2/parse/upload", {
166
+ creates: true,
167
+ ...call,
168
+ form
169
+ }));
170
+ return requireJobId(provider, created.id);
171
+ };
172
+ const finished = (found, id) => {
173
+ const { error_message: message, status } = found.value.job;
174
+ if (status === "FAILED" || status === "CANCELLED") throw new FieldworkError("JobFailed", `llamaparse job ${status.toLowerCase()}${message === void 0 ? "" : `: ${message}`}`, {
175
+ cause: found.original,
176
+ jobId: id,
177
+ provider
178
+ });
179
+ return status === "COMPLETED" ? found : void 0;
180
+ };
181
+ /** The grounded items: one JSON line per page, each page's items with word and cell boxes. */
182
+ const groundedPages = async (found, id, options) => {
183
+ const url = found.value.result_content_metadata.grounded_items.presigned_url;
184
+ if (url === void 0) throw new FieldworkError("ProviderError", "llamaparse finished without the word boxes it was asked for", {
185
+ cause: found.original,
186
+ jobId: id,
187
+ provider
188
+ });
189
+ try {
190
+ return (await readSigned(provider, url, options)).split("\n").filter((line) => line.trim() !== "").map((line) => parseJson(provider, line));
191
+ } catch (error) {
192
+ throw withJob(error, id);
193
+ }
194
+ };
195
+ /** Each page's picture, keyed by page number, from the job's saved screenshots. */
196
+ const pageImageAddresses = (found, id) => {
197
+ const addresses = /* @__PURE__ */ new Map();
198
+ for (const image of found.value.images_content_metadata.images) {
199
+ const page = PAGE_IMAGE.exec(image.filename ?? "")?.groups?.page;
200
+ if (page !== void 0 && image.presigned_url !== void 0) addresses.set(Number(page), image.presigned_url);
201
+ }
202
+ if (addresses.size === 0) throw new FieldworkError("ProviderError", `llamaparse job ${id} has no page pictures; only a parse started with pageImages saves them`, {
203
+ cause: found.original,
204
+ jobId: id,
205
+ provider
206
+ });
207
+ return addresses;
208
+ };
209
+ const parse = async (raw, document, options, fetchImpl) => {
210
+ const { call, rest: o } = callSettings(options);
211
+ const id = await startParse(raw, document, o, call);
212
+ const blocks = o.blocks === true || o.wordBoxes === true;
213
+ const expand = [
214
+ "markdown",
215
+ "usage",
216
+ ...blocks ? ["items"] : [],
217
+ ...o.pageImages === true ? ["images_content_metadata"] : []
218
+ ].join(",");
219
+ const found = await poll(provider, id, async (request) => finished(z.parse(JobResult, await raw.request("GET", `/api/v2/parse/${segment(id)}`, {
220
+ ...request,
221
+ query: { expand }
222
+ })), id), {
223
+ ...call,
224
+ interval: o.interval
225
+ });
226
+ if (found.value.markdown.pages.length === 0) throw new FieldworkError("ProviderError", `llamaparse finished job ${id} without any pages of Markdown`, {
227
+ cause: found.original,
228
+ jobId: id,
229
+ provider
230
+ });
231
+ const grounded = o.wordBoxes === true ? await groundedPages(found, id, {
232
+ fetch: fetchImpl,
233
+ signal: call.signal
234
+ }) : void 0;
235
+ const images = o.pageImages === true ? pageImageAddresses(found, id) : void 0;
236
+ const pages = found.value.markdown.pages.flatMap((page) => {
237
+ if (page.page_number === void 0) return [];
238
+ const image = images?.get(page.page_number);
239
+ if (images !== void 0 && image === void 0) throw new FieldworkError("ProviderError", `llamaparse job ${id} has no picture of page ${page.page_number}`, {
240
+ cause: found.original,
241
+ jobId: id,
242
+ provider
243
+ });
244
+ return [compact({
245
+ image,
246
+ markdown: page.markdown ?? "",
247
+ pageNumber: page.page_number
248
+ })];
249
+ });
250
+ let laidOut;
251
+ if (grounded !== void 0) laidOut = documentBlocks(grounded.map((row) => z.parse(ItemsPage, row)));
252
+ else if (blocks) laidOut = documentBlocks(found.value.items.pages);
253
+ return compact({
254
+ blocks: laidOut,
255
+ id,
256
+ markdown: pages.map((page) => page.markdown).join("\n\n"),
257
+ meta: meta({ credits: found.value.job.usage.credits }),
258
+ pages,
259
+ raw: grounded === void 0 ? found.original : {
260
+ groundedItems: grounded,
261
+ job: found.original
262
+ }
263
+ });
264
+ };
265
+ /**
266
+ * An adapter for LlamaParse: parse. Pass it to `new Fieldwork({ adapter })`.
267
+ *
268
+ * Throws `Unauthorized` when neither `apiKey` nor `LLAMA_CLOUD_API_KEY` is set.
269
+ */
270
+ const llamaparse = (config = {}) => {
271
+ const raw = createRawClient({
272
+ baseUrl: config.baseUrl ?? "https://api.cloud.llamaindex.ai",
273
+ fetch: config.fetch,
274
+ headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "LLAMA_CLOUD_API_KEY")}` },
275
+ provider,
276
+ retries: config.retries
277
+ });
278
+ return defineAdapter({
279
+ name: provider,
280
+ operations: { async parse(first, options) {
281
+ return "resume" in first ? await parse(raw, void 0, first, config.fetch) : await parse(raw, first, options, config.fetch);
282
+ } },
283
+ raw
284
+ });
285
+ };
286
+ export { llamaparse };
@@ -1,9 +1,13 @@
1
- import { A as JsonSchema, F as MonitorSchedule, G as Research, I as Page, L as PageBatch, N as MonitorEvents, P as MonitorInfo, a as RawClient, b as Discovery, f as CallOptions, h as Condition, k as ImageSearch, l as Answer, q as SearchResponse, t as Adapter, v as DecisionQuestion, w as Extraction, y as Decisions } from "./adapter-DGehHCMo.js";
1
+ import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, b as Decisions, g as Condition, j as ImageSearch, l as Answer, p as CallOptions, q as Research, t as Adapter, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-BgdfLBs-.js";
2
+ import { t as OutputSchema } from "./schema-Cupy7-7q.js";
3
+ import "./util-DhYr1OS3.js";
2
4
  interface ParallelConfig {
3
5
  /** Defaults to the PARALLEL_API_KEY environment variable. */
4
6
  apiKey?: string;
5
7
  baseUrl?: string;
6
8
  fetch?: typeof fetch;
9
+ /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
10
+ retries?: number;
7
11
  }
8
12
  /**
9
13
  * A Task API processor. Parallel documents `processor` as a free string, so any
@@ -72,13 +76,14 @@ interface ParallelReadOptions extends CallOptions {
72
76
  sessionId?: string;
73
77
  }
74
78
  type ParallelReadManyOptions = ParallelReadOptions;
75
- interface ParallelExtractOptions extends CallOptions {
79
+ interface ParallelExtractOptions<T = unknown> extends CallOptions {
76
80
  /**
77
81
  * The values to extract. Without one, Parallel picks the fields itself (its
78
82
  * `auto` output schema, which gives deep-research style output on `pro` and
79
- * above).
83
+ * above). A JSON Schema, or a Zod, Valibot or ArkType schema that types and
84
+ * checks `data`.
80
85
  */
81
- schema?: JsonSchema;
86
+ schema?: OutputSchema<T>;
82
87
  prompt?: string;
83
88
  /** Defaults to "base". */
84
89
  processor?: ParallelProcessor;
@@ -93,9 +98,9 @@ interface ParallelExtractOptions extends CallOptions {
93
98
  */
94
99
  resume?: string;
95
100
  }
96
- interface ParallelAnswerOptions extends CallOptions {
101
+ interface ParallelAnswerOptions<T = unknown> extends CallOptions {
97
102
  /** The answer in the shape of this schema, in `output`. */
98
- schema?: JsonSchema;
103
+ schema?: OutputSchema<T>;
99
104
  /** System instructions for the answer. */
100
105
  instructions?: string;
101
106
  /** How much research the answer does: `low`, `medium` (the default), `high` or `auto`. */
@@ -108,9 +113,9 @@ interface ParallelAnswerOptions extends CallOptions {
108
113
  /** Up to 16 keys, keys up to 64 characters, values up to 512. */
109
114
  metadata?: Record<string, string>;
110
115
  }
111
- interface ParallelResearchOptions extends CallOptions, ParallelSources {
116
+ interface ParallelResearchOptions<T = unknown> extends CallOptions, ParallelSources {
112
117
  /** Structured output in the shape of this schema; without one the output is report text. */
113
- schema?: JsonSchema;
118
+ schema?: OutputSchema<T>;
114
119
  /** Defaults to "base". */
115
120
  processor?: ParallelProcessor;
116
121
  /** The `continuationId` of an earlier run. */
@@ -126,7 +131,7 @@ interface ParallelResearchOptions extends CallOptions, ParallelSources {
126
131
  */
127
132
  resume?: string;
128
133
  }
129
- interface ParallelDiscoverOptions extends CallOptions {
134
+ interface ParallelDiscoverOptions<T = unknown> extends CallOptions {
130
135
  /** What kind of entity to find, such as "companies" or "people". */
131
136
  entityType: string;
132
137
  /** Every discovered entity is tested against all of these. */
@@ -144,7 +149,7 @@ interface ParallelDiscoverOptions extends CallOptions {
144
149
  * Fills these fields for every match (Parallel's enrichment, run as a Task
145
150
  * after the run starts), returned in each entity's `data`.
146
151
  */
147
- schema?: JsonSchema;
152
+ schema?: OutputSchema<T>;
148
153
  /** The Task processor that fills `schema`. Parallel defaults to "core". */
149
154
  processor?: ParallelProcessor;
150
155
  metadata?: ParallelMetadata;
@@ -178,8 +183,8 @@ interface ParallelMonitorCreateOptions extends CallOptions, ParallelSources {
178
183
  taskRunId?: string;
179
184
  /** Parallel runs at a fixed interval from 1 hour to 30 days; cron is refused. */
180
185
  schedule: MonitorSchedule;
181
- /** Events come back in the shape of this schema. */
182
- schema?: JsonSchema;
186
+ /** Events come back in the shape of this schema. Events are not checked against a Standard Schema. */
187
+ schema?: OutputSchema<unknown>;
183
188
  /** The first run returns a sample of recent events (a preview, not exhaustive). */
184
189
  includeBackfill?: boolean;
185
190
  country?: string;
@@ -208,23 +213,28 @@ type ParallelDiscovery<T> = Discovery<T> & {
208
213
  stopReason?: string;
209
214
  };
210
215
  interface ParallelOperations {
211
- search(query: string, options?: ParallelSearchOptions): Promise<SearchResponse>;
212
- images(query: string, options?: ParallelImagesOptions): Promise<ImageSearch>;
213
- read(url: string, options?: ParallelReadOptions): Promise<Page>;
214
- readMany(urls: string[], options?: ParallelReadManyOptions): Promise<PageBatch>;
215
- extract<T = unknown>(url: string, options?: ParallelExtractOptions): Promise<Extraction<T>>;
216
- answer<T = unknown>(question: string, options?: ParallelAnswerOptions): Promise<Answer<T>>;
217
- research<T = unknown>(question: string, options?: ParallelResearchOptions): Promise<Research<T>>;
218
- discover<T = Record<string, unknown>>(objective: string, options: ParallelDiscoverOptions): Promise<ParallelDiscovery<T>>;
219
- decide(context: unknown, questions: Record<string, DecisionQuestion>, options?: ParallelDecideOptions): Promise<Decisions>;
216
+ search: (query: string, options?: ParallelSearchOptions) => Promise<SearchResponse>;
217
+ images: (query: string, options?: ParallelImagesOptions) => Promise<ImageSearch>;
218
+ read: (url: string, options?: ParallelReadOptions) => Promise<Page>;
219
+ readMany: (urls: string[], options?: ParallelReadManyOptions) => Promise<PageBatch>;
220
+ extract: <T = unknown>(url: string, options?: ParallelExtractOptions<T>) => Promise<Extraction<T>>;
221
+ answer: <T = unknown>(question: string, options?: ParallelAnswerOptions<T>) => Promise<Answer<T>>;
222
+ research: <T = unknown>(question: string, options?: ParallelResearchOptions<T>) => Promise<Research<T>>;
223
+ discover: <T = Record<string, unknown>>(objective: string, options: ParallelDiscoverOptions<T>) => Promise<ParallelDiscovery<T>>;
224
+ decide: (context: unknown, questions: Record<string, DecisionQuestion>, options?: ParallelDecideOptions) => Promise<Decisions>;
220
225
  monitor: {
221
- create(options: ParallelMonitorCreateOptions): Promise<MonitorInfo>;
222
- get(id: string, options?: CallOptions): Promise<MonitorInfo>;
223
- list(options?: CallOptions): Promise<MonitorInfo[]>;
226
+ create: (options: ParallelMonitorCreateOptions) => Promise<MonitorInfo>;
227
+ get: (id: string, options?: CallOptions) => Promise<MonitorInfo>;
228
+ list: (options?: CallOptions) => Promise<MonitorInfo[]>;
224
229
  /** Parallel cancels a monitor for good; it has no delete. */
225
- delete(id: string, options?: CallOptions): Promise<void>;
226
- events(id: string, options?: ParallelMonitorEventsOptions): Promise<MonitorEvents>;
230
+ delete: (id: string, options?: CallOptions) => Promise<void>;
231
+ events: (id: string, options?: ParallelMonitorEventsOptions) => Promise<MonitorEvents>;
227
232
  };
228
233
  }
234
+ /**
235
+ * An adapter for Parallel: search, images, read, readMany, extract, answer, research, discover, decide and monitor. Pass it to `new Fieldwork({ adapter })`.
236
+ *
237
+ * Throws `Unauthorized` when neither `apiKey` nor `PARALLEL_API_KEY` is set.
238
+ */
229
239
  export declare const parallel: (config?: ParallelConfig) => Adapter<"parallel", ParallelOperations, RawClient>;
230
240
  export type { ParallelAnswerOptions, ParallelConfig, ParallelDecideOptions, ParallelDiscoverOptions, ParallelDiscovery, ParallelExtractOptions, ParallelImagesOptions, ParallelMetadata, ParallelMonitorCreateOptions, ParallelMonitorEventsOptions, ParallelOperations, ParallelProcessor, ParallelReadManyOptions, ParallelReadOptions, ParallelResearchOptions, ParallelSearchOptions, ParallelSources, ParallelWebhookEvent };