### Add and Run an Example Source: https://github.com/reductoai/reducto-node-sdk/blob/main/CONTRIBUTING.md Demonstrates how to add a new TypeScript example to the 'examples/' directory and run it. Ensure the file is executable before running. ```ts // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T … ``` ```sh $ chmod +x examples/.ts # run the example against your api $ yarn tsn -T examples/.ts ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/reductoai/reducto-node-sdk/blob/main/CONTRIBUTING.md Installs all required dependencies and builds the project output files. Use this command after cloning the repository. ```sh $ yarn $ yarn build ``` -------------------------------- ### Install Reducto Node SDK Source: https://github.com/reductoai/reducto-node-sdk/blob/main/README.md Install the Reducto Node.js SDK using npm. ```sh npm install reductoai ``` -------------------------------- ### Install SDK via Git Source: https://github.com/reductoai/reducto-node-sdk/blob/main/CONTRIBUTING.md Installs the Reducto Node SDK directly from its GitHub repository using SSH. This is an alternative to installing from npm. ```sh $ npm install git+ssh://git@github.com:reductoai/reducto-node-sdk.git ``` -------------------------------- ### File Upload and Processing Example Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Demonstrates how to upload a file using the SDK and then process it using the `client.parse.run()` method, referencing the uploaded file by its ID. ```APIDOC ## File Upload and Processing ### Description This example shows the common pattern of uploading a file to Reducto and then using its identifier to perform operations like parsing. ### Usage ```typescript import fs from 'fs'; // Upload a file const upload = await client.upload({ file: fs.createReadStream('document.pdf') }); // Use in processing const result = await client.parse.run({ input: `reducto://${upload.file_id}` }); ``` ``` -------------------------------- ### client.pipeline.runJob Source: https://github.com/reductoai/reducto-node-sdk/blob/main/api.md Starts an asynchronous pipeline processing job. ```APIDOC ## POST /pipeline_async ### Description Initiates an asynchronous data pipeline processing job. ### Method POST ### Endpoint /pipeline_async ### Parameters #### Request Body - **params** (PipelineSettings) - Required - Settings for the pipeline. ### Response #### Success Response (200) - **AsyncPipelineResponse** - The response indicating the asynchronous pipeline job has started. ``` -------------------------------- ### Run Project Tests Source: https://github.com/reductoai/reducto-node-sdk/blob/main/CONTRIBUTING.md Executes all tests defined within the Reducto Node SDK project. Ensure all dependencies are installed before running. ```sh $ yarn run test ``` -------------------------------- ### Extraction with Custom Schema Example Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Shows how to use the `client.extract.run()` method with a custom JSON schema to extract structured data from a document. ```APIDOC ## Extraction with Custom Schema ### Description This example demonstrates how to define a specific JSON schema and use it with the `client.extract.run()` method to extract structured data from a document according to that schema. ### Usage ```typescript const result = await client.extract.run({ input: 'invoice.pdf', instructions: { schema: { type: 'object', properties: { vendor: { type: 'string' }, date: { type: 'string', format: 'date' }, items: { type: 'array', items: { type: 'object', properties: { description: { type: 'string' }, quantity: { type: 'number' }, unit_price: { type: 'number' } } } }, total: { type: 'number' } }, required: ['vendor', 'items', 'total'] } } }); console.log(result.result); // Structured data matching schema ``` ``` -------------------------------- ### Explicit Asynchronous Extraction Job with Webhook Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/extract.md Shows how to explicitly start an asynchronous extraction job using `runJob`, configuring a direct webhook for receiving completion notifications. Includes an example of polling for job completion. ```typescript const asyncResponse = await client.extract.runJob({ input: 'https://pdfobject.com/pdf/form.pdf', async: { webhook: { mode: 'direct', url: 'https://your-app.com/webhook' } }, instructions: { schema: { /* your schema */ } } }); // Poll for completion const job = await client.job.get(asyncResponse.job_id); if (job.status === 'Completed' && job.result) { console.log(job.result.result); } ``` -------------------------------- ### Async Processing with Polling Example Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Illustrates how to initiate an asynchronous processing job and then poll the job status until completion or failure, handling both success and error outcomes. ```APIDOC ## Async Processing with Polling ### Description This example demonstrates how to start an asynchronous job and then periodically check its status using `client.job.get()` until the job is finished. ### Usage ```typescript // Start async job const job = await client.parse.runJob({ input: 'https://example.com/doc.pdf', async: { webhook: { mode: 'disabled' } } }); // Poll for completion let status = 'Pending'; while (status === 'Pending') { const result = await client.job.get(job.job_id); status = result.status; if (status === 'Completed') { console.log(result.result); } else if (status === 'Failed') { console.error(result.reason); } else { await new Promise(r => setTimeout(r, 2000)); } } ``` ``` -------------------------------- ### List Jobs with Pagination Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/job.md Retrieve a list of all jobs, supporting filtering and pagination. Examples demonstrate fetching the first page, subsequent pages using a cursor, and iterating through all jobs. ```typescript // Get first page of jobs const response = await client.job.getAll({ limit: 50, exclude_configs: true }); console.log(response.jobs); // Array of jobs console.log(response.next_cursor); // For pagination // Get next page if (response.next_cursor) { const nextPage = await client.job.getAll({ cursor: response.next_cursor, limit: 50 }); } // Iterate through all jobs let cursor = undefined; let allJobs = []; while (true) { const page = await client.job.getAll({ cursor, limit: 100 }); allJobs = allJobs.concat(page.jobs); if (!page.next_cursor) break; cursor = page.next_cursor; } console.log(`Total jobs: ${allJobs.length}`); ``` -------------------------------- ### client.apiVersion() Source: https://github.com/reductoai/reducto-node-sdk/blob/main/api.md Retrieves the current API version. This is a simple GET request to the /version endpoint. ```APIDOC ## GET /version ### Description Retrieves the current API version. ### Method GET ### Endpoint /version ### Response #### Success Response (200) - **version** (string) - The current API version. ``` -------------------------------- ### Classify a Document Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/classify.md Use the `run` method to classify a document by providing its URL, a schema of categories and criteria, and optionally metadata and page ranges. This example demonstrates classifying a PDF into 'Invoice', 'Receipt', or 'Purchase Order'. ```typescript import Reducto from 'reductoai'; const client = new Reducto(); // Classify a document const response = await client.classify.run({ input: 'https://example.com/document.pdf', classification_schema: [ { category: 'Invoice', criteria: [ 'contains invoice number', 'has itemized charges', 'shows total amount due', 'includes vendor information' ] }, { category: 'Receipt', criteria: [ 'shows payment confirmation', 'includes date and amount', 'contains payment method', 'indicates customer name' ] }, { category: 'Purchase Order', criteria: [ 'contains PO number', 'lists items and quantities', 'includes delivery address', 'shows terms and conditions' ] } ], document_metadata: 'This document is from our accounting department', page_range: { start: 1, end: 3 } }); console.log(response.result.category); // 'Invoice' console.log(response.response_confidence); // Confidence scores for all categories // Access confidence details if (response.response_confidence) { response.response_confidence.categories.forEach(cat => { console.log(`${cat.category}: ${cat.confidence}`); cat.criteria_confidence.forEach(crit => { console.log(` - ${crit.criterion}: ${crit.confidence}`); }); }); } ``` -------------------------------- ### Handle API Errors with Reducto SDK Source: https://github.com/reductoai/reducto-node-sdk/blob/main/README.md Catch and handle API errors thrown by the Reducto SDK. This example shows how to check for specific APIError subclasses and access error details like status, name, and headers. ```ts const response = await client.parse .run({ input: 'https://pdfobject.com/pdf/sample.pdf' }) .catch(async (err) => { if (err instanceof Reducto.APIError) { console.log(err.status); // 400 console.log(err.name); // BadRequestError console.log(err.headers); // {server: 'nginx', ...} } else { throw err; } }); ``` -------------------------------- ### Initialize Reducto Client and Perform Operations Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Demonstrates how to initialize the Reducto client with an API key and environment, followed by synchronous parsing, structured data extraction, and asynchronous job processing with webhook configuration. ```typescript import Reducto from 'reductoai'; // Create client const client = new Reducto({ apiKey: process.env.REDUCTO_API_KEY, environment: 'production' }); // Synchronous parsing const parseResponse = await client.parse.run({ input: 'https://example.com/document.pdf' }); // Structured data extraction const extractResponse = await client.extract.run({ input: 'https://example.com/invoice.pdf', instructions: { schema: { type: 'object', properties: { invoice_number: { type: 'string' }, total: { type: 'number' } } } } }); // Async processing with webhooks const asyncResponse = await client.parse.runJob({ input: 'https://example.com/large-document.pdf', async: { webhook: { mode: 'svix', channels: ['production'] } } }); // Poll for job completion const job = await client.job.get(asyncResponse.job_id); ``` -------------------------------- ### Reducto Node SDK Client Initialization Options Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Configuration options for initializing the Reducto Node.js SDK client. These include API key, environment, base URL, timeouts, retries, and custom agents or fetch implementations. ```bash REDUCTO_API_KEY=your-api-key # API key (required) REDUCTO_BASE_URL=https://custom.url # Override base URL (optional) DEBUG=true # Enable request logging (optional) ``` -------------------------------- ### Webhook.run() Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/webhook.md Opens the Reducto webhook portal to configure delivery settings. Returns a URL to the Reducto Studio webhook configuration interface. ```APIDOC ## Webhook.run() ### Description Opens the Reducto webhook portal to configure webhook delivery settings. This returns a URL to the Reducto Studio webhook configuration interface. ### Method `run(options?: Core.RequestOptions): Core.APIPromise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import Reducto from 'reductoai'; const client = new Reducto(); // Get webhook portal URL const portalUrl = await client.webhook.run(); console.log(portalUrl); // Opens: https://studio.reducto.ai/webhooks/configure?token=... // Typically used in a web context to redirect user window.location.href = portalUrl; ``` ### Response #### Success Response (200) `Core.APIPromise` - URL to webhook configuration portal #### Response Example ```json "https://studio.reducto.ai/webhooks/configure?token=..." ``` ### Error Handling - `AuthenticationError` (401) - Invalid API key - `PermissionDeniedError` (403) - Insufficient permissions - `InternalServerError` (>=500) - Server error ``` -------------------------------- ### Handling InternalServerError in TypeScript Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/errors.md Example of catching an InternalServerError and logging the specific status and message. The SDK automatically retries this error. ```typescript try { await client.parse.run({ input: 'document.pdf' }); } catch (error) { if (error instanceof Reducto.InternalServerError) { console.error(`Server error (${error.status}): ${error.message}`); // Retry with exponential backoff } } ``` -------------------------------- ### Initialize Reducto Client (JavaScript) Source: https://github.com/reductoai/reducto-node-sdk/blob/main/README.md Initialize the Reducto client with an API key and environment. The API key defaults to the environment variable RECTO_API_KEY, and the environment defaults to 'production'. ```js import Reducto from 'reductoai'; const client = new Reducto({ apiKey: process.env['REDUCTO_API_KEY'], // This is the default and can be omitted environment: 'eu', // or 'production' | 'au'; defaults to 'production' }); const response = await client.parse.run({ input: 'https://pdfobject.com/pdf/sample.pdf' }); ``` -------------------------------- ### Client Initialization and Top-Level Methods Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md The main Reducto client class is used for initialization and provides top-level methods such as `apiVersion` and `upload`. It requires an API key and environment for configuration. ```APIDOC ## Client ### Description The main Reducto client class for SDK initialization and access to core functionalities. ### Initialization ```typescript import Reducto from 'reductoai'; const client = new Reducto({ apiKey: process.env.REDUCTO_API_KEY, environment: 'production' }); ``` ### Methods - **`apiVersion()`**: Retrieves the current API version. - **`upload(file: File | Buffer | string)`**: Uploads a document for processing. Returns an upload ID. ### Configuration Options - **`apiKey`** (string): Your Reducto API key. Required. - **`environment`** (string): The target environment ('production', 'staging', etc.). Required. - **`timeout`** (number): Request timeout in milliseconds. Default is 60000. - **`baseUrl`** (string): Custom base URL for the API. Default is `https://api.reducto.ai`. ``` -------------------------------- ### Handling RateLimitError in TypeScript Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/errors.md Example of catching a RateLimitError and implementing a manual retry mechanism with a delay. This is useful when the default SDK retries are insufficient. ```typescript try { await client.parse.run({ input: 'document.pdf' }); } catch (error) { if (error instanceof Reducto.RateLimitError) { console.error('Rate limited. Waiting before retry...'); await new Promise(r => setTimeout(r, 60000)); // Wait 1 minute // Retry the operation } } ``` -------------------------------- ### Client Initialization Options Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Details on the configuration options available when initializing the Reducto Node.js SDK client. These options allow customization of API key, environment, base URL, timeouts, and more. ```APIDOC ## Client Initialization ### Description Configure the Reducto client with various options to tailor its behavior for your specific needs, including authentication, regional deployment, and network settings. ### Options | Option | Default | Description | |---|---|---| | `apiKey` | `process.env.REDUCTO_API_KEY` | API key for authentication | | `environment` | `'production'` | Regional deployment: `'production'`, `'eu'`, `'au'` | | `baseURL` | Region-based | Override base URL | | `timeout` | `3600000 ms` | Request timeout (1 hour) | | `maxRetries` | `2` | Automatic retry count | | `httpAgent` | `Auto` | Custom HTTP agent for proxies | | `fetch` | `node-fetch or global` | Custom fetch implementation | | `defaultHeaders` | `—` | Headers for all requests | | `defaultQuery` | `—` | Query params for all requests | See [Configuration](configuration.md) for detailed options. ``` -------------------------------- ### Initialize Reducto Client Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/client.md Instantiate the Reducto client with an API key and environment. Alternatively, the client can use the REDUCTO_API_KEY environment variable if no key is explicitly provided. ```typescript import Reducto from 'reductoai'; const client = new Reducto({ apiKey: 'your-api-key', environment: 'production' }); // Or use environment variable const client = new Reducto(); ``` -------------------------------- ### Get API Version Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/client.md Retrieve the current API version string. This method is useful for verifying connectivity and understanding the API's current state. ```typescript const version = await client.apiVersion(); console.log(version); // e.g. "v1.0.0" ``` -------------------------------- ### client.webhook.run Source: https://github.com/reductoai/reducto-node-sdk/blob/main/api.md Configures a webhook endpoint. This operation does not take parameters and returns a confirmation string. ```APIDOC ## POST /configure_webhook ### Description Configures a webhook endpoint. ### Method POST ### Endpoint /configure_webhook ### Response #### Success Response (200) - **string** - A confirmation message indicating the webhook has been configured. ``` -------------------------------- ### File Uploads with Reducto SDK Source: https://github.com/reductoai/reducto-node-sdk/blob/main/README.md Demonstrates various methods for uploading files using the Reducto SDK, including Node.js streams, web File API, fetch Responses, and a utility helper function. ```ts import fs from 'fs'; import fetch from 'node-fetch'; import Reducto, { toFile } from 'reductoai'; const client = new Reducto(); // If you have access to Node `fs` we recommend using `fs.createReadStream()`: await client.upload({ file: fs.createReadStream('/path/to/file') }); // Or if you have the web `File` API you can pass a `File` instance: await client.upload({ file: new File(['my bytes'], 'file') }); // You can also pass a `fetch` `Response`: await client.upload({ file: await fetch('https://somesite/file') }); // Finally, if none of the above are convenient, you can use our `toFile` helper: await client.upload({ file: await toFile(Buffer.from('my bytes'), 'file') }); await client.upload({ file: await toFile(new Uint8Array([0, 1, 2]), 'file') }); ``` -------------------------------- ### Get Job Status Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/job.md Retrieve the status and result of an asynchronous job by its ID. This method is useful for checking the progress of a job or obtaining its final output once completed. ```APIDOC ## GET /job/{jobId} ### Description Retrieve the status and result of an async job by ID. ### Method GET ### Endpoint `/job/{jobId}` ### Parameters #### Path Parameters - **jobId** (string) - Yes - The job ID returned from an async operation #### Query Parameters - **options** (Core.RequestOptions) - No - Request options ### Response #### Success Response (200) - **status** (string) - Job status ('Pending', 'Completed', 'Failed', or 'Idle') - **progress** (number) - 0-100 percentage - **reason** (string) - Error message if failed - **result** (any) - Job result (if completed) #### Error Response - **AuthenticationError** (401) - Invalid API key - **PermissionDeniedError** (403) - Insufficient permissions - **NotFoundError** (404) - Job not found - **InternalServerError** (>=500) - Server error ``` -------------------------------- ### Reducto Constructor Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/client.md Initializes a new Reducto API client with optional configuration. It supports API key, environment selection, base URL override, timeouts, and custom fetch implementations. ```APIDOC ## `new Reducto(opts?: ClientOptions)` ### Description Initialize a new Reducto API client. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Parameters - **opts** (ClientOptions) - Optional - Client configuration options. - **opts.apiKey** (string) - Optional - API key for authentication. Defaults to `process.env['REDUCTO_API_KEY']`. - **opts.environment** ('production' | 'eu' | 'au') - Optional - Environment to use. Defaults to 'production'. - **opts.baseURL** (string) - Optional - Override the default base URL. Cannot be used with `environment`. - **opts.timeout** (number) - Optional - Request timeout in milliseconds. Defaults to 3600000. - **opts.httpAgent** (Agent) - Optional - HTTP agent for managing connections. - **opts.fetch** (Core.Fetch) - Optional - Custom fetch function implementation. - **opts.maxRetries** (number) - Optional - Maximum number of retries for temporary failures. Defaults to 2. - **opts.defaultHeaders** (Core.Headers) - Optional - Default headers to include with every request. - **opts.defaultQuery** (Core.DefaultQuery) - Optional - Default query parameters to include with every request. ### Throws - `ReductoError`: If `apiKey` is not provided and `REDUCTO_API_KEY` environment variable is not set, or if both `baseURL` and `environment` options are provided simultaneously. ### Example ```typescript import Reducto from 'reductoai'; const client = new Reducto({ apiKey: 'your-api-key', environment: 'production' }); // Or use environment variable const client = new Reducto(); ``` ``` -------------------------------- ### Get Job Status and Result Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/job.md Retrieve the status and result of an asynchronous job by its ID. This snippet also shows how to poll for job completion and handle the result. ```typescript import Reducto from 'reductoai'; const client = new Reducto(); // Get job status const job = await client.job.get('job_abc123'); console.log(job.status); // 'Pending', 'Completed', 'Failed', or 'Idle' console.log(job.progress); // 0-100 percentage console.log(job.reason); // Error message if failed // Poll until completion let job = await client.job.get(jobId); while (job.status === 'Pending' || job.status === 'Idle') { await new Promise(r => setTimeout(r, 2000)); // Wait 2 seconds job = await client.job.get(jobId); } if (job.status === 'Completed' && job.result) { console.log(job.result); // Parse/Extract/Split/Edit response } ``` -------------------------------- ### Webhook Payload Structure Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/webhook.md Example structure of the webhook payload sent by Reducto upon job completion. Includes status, job ID, metadata, result, and other relevant details. ```typescript { status: 'Completed' | 'Failed', job_id: string, metadata?: unknown, // Your provided metadata result?: ParseResponse | ExtractResponse | SplitResponse | EditResponse | PipelineResponse | V3Extract | ClassifyResponse, reason?: string, // Error message if failed duration?: number, // Duration in seconds created_at?: string, // ISO timestamp type?: 'Parse' | 'Extract' | 'Split' | 'Edit' | 'Pipeline' | 'Classify' } ``` -------------------------------- ### Configure Client to Use Global Web Fetch Source: https://github.com/reductoai/reducto-node-sdk/blob/main/README.md Instruct the SDK to use the global web `fetch` API instead of `node-fetch`, even in Node.js environments. This is useful for compatibility with environments like Next.js or when using experimental Node.js fetch flags. ```typescript // Tell TypeScript and the package to use the global web fetch instead of node-fetch. // Note, despite the name, this does not add any polyfills, but expects them to be provided if needed. import 'reductoai/shims/web'; import Reducto from 'reductoai'; ``` -------------------------------- ### client.pipeline.run Source: https://github.com/reductoai/reducto-node-sdk/blob/main/api.md Processes a data pipeline synchronously with the specified settings. ```APIDOC ## POST /pipeline ### Description Runs a data pipeline synchronously. ### Method POST ### Endpoint /pipeline ### Parameters #### Request Body - **params** (PipelineSettings) - Required - Settings for the pipeline. ### Response #### Success Response (200) - **PipelineResponse** - The result of the pipeline execution. ``` -------------------------------- ### Resource Modules Overview Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md An overview of the available resource modules within the Reducto Node.js SDK, detailing their purpose and the methods they expose for interacting with Reducto services. ```APIDOC ## Resource Modules ### Description Access various functionalities of the Reducto API through dedicated client modules. Each module groups related operations for document processing, data extraction, job management, and more. ### Modules | Module | Purpose | Methods | |---|---|---| | `client.parse` | Document parsing | `run()`, `runJob()` | | `client.extract` | Data extraction | `run()`, `runJob()` | | `client.split` | Document splitting | `run()`, `runJob()` | | `client.edit` | Document editing | `run()`, `runJob()` | | `client.classify` | Document classification | `run()` | | `client.pipeline` | Custom pipelines | `run()`, `runJob()` | | `client.job` | Job management | `get()`, `getAll()`, `cancel()` | | `client.webhook` | Webhook configuration | `run()` | ### Top-level Methods | Method | Purpose | |---|---| | `client.apiVersion()` | Get API version | | `client.upload()` | Upload file for processing | ``` -------------------------------- ### Synchronous and Asynchronous Parsing with `run` Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/parse.md Demonstrates how to parse a document synchronously by omitting the `async` configuration and asynchronously by providing it. Use this method for flexible parsing needs. ```typescript import Reducto from 'reductoai'; const client = new Reducto(); // Synchronous parsing const response = await client.parse.run({ input: 'https://pdfobject.com/pdf/sample.pdf', settings: { extraction_mode: 'hybrid' } }); console.log(response.job_id); console.log(response.duration); if (response.result.type === 'full') { response.result.chunks.forEach(chunk => { console.log(chunk.content); }); } // Asynchronous parsing with webhook const asyncResponse = await client.parse.run({ input: 'https://pdfobject.com/pdf/sample.pdf', async: { webhook: { mode: 'svix', channels: ['my-channel'] } } }); console.log(asyncResponse.job_id); // Poll this job or wait for webhook ``` -------------------------------- ### Table Summary Configuration Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/types.md Configuration for summarizing table content. Enable table summarization and provide a custom prompt if needed. ```typescript interface TableSummaryConfig { enabled?: boolean; prompt?: string; } ``` -------------------------------- ### Pipeline.run Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/pipeline.md Execute a custom pipeline synchronously. Pipelines are created in Reducto Studio and combine parse, extract, split, and edit operations. ```APIDOC ## Pipeline.run ### Description Execute a custom pipeline synchronously. Pipelines are created in Reducto Studio and combine parse, extract, split, and edit operations. ### Method POST ### Endpoint /pipeline/run ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (string | Array | Shared.Upload) - Required - Document URL or uploaded file ID - **pipeline_id** (string) - Required - ID of the pipeline to execute (from Reducto Studio) - **settings** (PipelineSettings) - Optional - Settings to override pipeline defaults ### Request Example ```json { "input": "https://example.com/document.pdf", "pipeline_id": "pipe_abc123def456" } ``` ### Response #### Success Response (200) - **job_id** (string) - ID of the asynchronous job - **result** (object) - Pipeline result containing parse, extract, split, and/or edit outputs - **result.parse** (any) - Parse output if configured - **result.extract** (any) - Extract output if configured - **result.split** (any) - Split output if configured - **result.edit** (any) - Edit output if configured #### Response Example ```json { "job_id": "job_12345", "result": { "parse": {}, "extract": {}, "split": {}, "edit": {} } } ``` ### Error Handling - **BadRequestError** (400) - Invalid pipeline ID or input - **AuthenticationError** (401) - Invalid API key - **PermissionDeniedError** (403) - Insufficient permissions - **NotFoundError** (404) - Pipeline not found - **RateLimitError** (429) - Rate limit exceeded - **InternalServerError** (>=500) - Server error ``` -------------------------------- ### AsyncConfigV3 Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/parse.md Configuration for asynchronous job processing, allowing for metadata, priority, and webhook settings. ```APIDOC ## AsyncConfigV3 Configuration for asynchronous job processing. ### Fields - **metadata** (unknown) - Optional - JSON metadata included in webhook request body. - **priority** (boolean) - Optional - If true, process with priority if budget available. Default: false - **webhook** (SvixWebhookConfig | DirectWebhookConfig | null) - Optional - Webhook configuration for delivery. null = no webhook. ``` -------------------------------- ### File Upload and Processing with Reducto SDK Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Demonstrates how to upload a file using the Reducto Node.js SDK and then use the uploaded file's ID for document processing tasks. ```typescript import fs from 'fs'; // Upload a file const upload = await client.upload({ file: fs.createReadStream('document.pdf') }); // Use in processing const result = await client.parse.run({ input: `reducto://${upload.file_id}` }); ``` -------------------------------- ### Synchronous and Asynchronous Extraction with JSON Schema Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/extract.md Demonstrates how to perform synchronous extraction using a JSON schema and system prompt, and how to initiate an asynchronous extraction job with webhook configuration. ```typescript import Reducto from 'reductoai'; const client = new Reducto(); // Synchronous extraction with JSON schema const response = await client.extract.run({ input: 'https://pdfobject.com/pdf/invoice.pdf', instructions: { schema: { type: 'object', properties: { invoice_number: { type: 'string' }, total_amount: { type: 'number' }, vendor: { type: 'string' }, line_items: { type: 'array', items: { type: 'object', properties: { description: { type: 'string' }, quantity: { type: 'number' }, price: { type: 'number' } } } } } }, system_prompt: 'Extract invoice data carefully' }, settings: { deep_extract: true, citations: { enabled: true } } }); console.log(response.result); console.log(response.usage.num_fields); ``` ```typescript // Asynchronous extraction const asyncResponse = await client.extract.run({ input: 'https://pdfobject.com/pdf/invoice.pdf', instructions: { /* schema */ }, async: { webhook: { mode: 'svix', metadata: { job_type: 'invoice' } } } }); console.log(asyncResponse.job_id); ``` -------------------------------- ### Asynchronous Processing and Polling with Reducto SDK Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Shows how to initiate an asynchronous job with the Reducto Node.js SDK and then poll for its completion status, handling both success and failure scenarios. ```typescript // Start async job const job = await client.parse.runJob({ input: 'https://example.com/doc.pdf', async: { webhook: { mode: 'disabled' } } }); // Poll for completion let status = 'Pending'; while (status === 'Pending') { const result = await client.job.get(job.job_id); status = result.status; if (status === 'Completed') { console.log(result.result); } else if (status === 'Failed') { console.error(result.reason); } else { await new Promise(r => setTimeout(r, 2000)); } } ``` -------------------------------- ### Provide Custom Fetch Client for Logging Source: https://github.com/reductoai/reducto-node-sdk/blob/main/README.md Instantiate the Reducto client with a custom `fetch` function to intercept and log requests and responses. This is valuable for debugging and understanding request/response lifecycles. ```typescript import { fetch } from 'undici'; // as one example import Reducto from 'reductoai'; const client = new Reducto({ fetch: async (url: RequestInfo, init?: RequestInit): Promise => { console.log('About to make a request', url, init); const response = await fetch(url, init); console.log('Got response', response); return response; }, }); ``` -------------------------------- ### client.split.runJob({ ...params }) Source: https://github.com/reductoai/reducto-node-sdk/blob/main/api.md Initiates an asynchronous splitting job. This is a POST request to the /split_async endpoint. ```APIDOC ## POST /split_async ### Description Initiates an asynchronous splitting job. ### Method POST ### Endpoint /split_async ### Parameters #### Request Body - **params** (object) - Required - Parameters for the asynchronous splitting job. The exact structure depends on the `AsyncSplitResponse` type definition. ``` -------------------------------- ### client.split.run({ ...params }) Source: https://github.com/reductoai/reducto-node-sdk/blob/main/api.md Runs a splitting job with the specified parameters. This is a POST request to the /split endpoint. ```APIDOC ## POST /split ### Description Runs a splitting job with the specified parameters. ### Method POST ### Endpoint /split ### Parameters #### Request Body - **params** (object) - Required - Parameters for the splitting job. The exact structure depends on the `SplitResponse` type definition. ``` -------------------------------- ### Figure Summary Configuration Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/types.md Configuration for summarizing figures and charts. Allows enabling summarization, using an advanced agent, overriding the default prompt, or providing a custom prompt. ```typescript interface FigureSummaryConfig { advanced_chart_agent?: boolean; enabled?: boolean; override?: boolean; prompt?: string; } ``` -------------------------------- ### ClientOptions Interface Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/configuration.md Defines the configuration object passed to the Reducto client constructor. Options include API key, environment, base URL, timeouts, and custom fetch implementations. ```typescript interface ClientOptions { apiKey?: string | undefined; environment?: 'production' | 'eu' | 'au' | undefined; baseURL?: string | null | undefined; timeout?: number | undefined; httpAgent?: Agent | undefined; fetch?: Core.Fetch | undefined; maxRetries?: number | undefined; defaultHeaders?: Core.Headers | undefined; defaultQuery?: Core.DefaultQuery | undefined; } ``` -------------------------------- ### Open Reducto Webhook Portal Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/webhook.md Use this method to open the Reducto webhook portal for configuring delivery settings. It returns a URL that can be used to redirect users to the configuration interface. ```typescript import Reducto from 'reductoai'; const client = new Reducto(); // Get webhook portal URL const portalUrl = await client.webhook.run(); console.log(portalUrl); // Opens: https://studio.reducto.ai/webhooks/configure?token=... // Typically used in a web context to redirect user window.location.href = portalUrl; ``` -------------------------------- ### Environment Type and Constants Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/types.md Defines supported deployment environments and their corresponding API endpoint URLs. Used for configuring the SDK's target environment. ```typescript type Environment = 'production' | 'eu' | 'au'; const environments = { production: 'https://platform.reducto.ai', eu: 'https://eu.platform.reducto.ai', au: 'https://au.platform.reducto.ai' }; ``` -------------------------------- ### Document Input Methods Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Details the various ways documents can be provided as input to SDK methods, including URLs, S3 URLs, upload IDs, job IDs, and arrays of URLs. ```APIDOC ## Core Concepts: Document Input ### Description This section outlines the different formats and sources accepted for document input across various SDK methods. ### Supported Input Types - **Public URL**: A direct web link to the document. `'https://example.com/document.pdf'` - **Presigned S3 URL**: A temporary, secure URL for accessing documents in S3. `'https://bucket.s3.amazonaws.com/...?X-Amz-Signature=...'` - **Upload ID**: An identifier obtained from a previous `client.upload()` call. `'reducto://file_id'` - **Job ID**: An identifier from a previous asynchronous operation (e.g., `parse.runJob()`). `'jobid://job_id'` - **Array of URLs/IDs**: Multiple document sources can be provided as an array for batch processing. `['url1', 'url2', 'reducto://file_id_3']` ``` -------------------------------- ### Synchronous vs Asynchronous Operations Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Explains the difference between synchronous and asynchronous operations, highlighting how to use `.run()` for immediate results and `.runJob()` or `.run()` with `async` config for background processing. ```APIDOC ## Core Concepts: Synchronous vs Asynchronous ### Description This section clarifies the distinction between synchronous and asynchronous API calls within the SDK. ### Synchronous Operations - **Usage**: Call methods like `.run()` without any `async` configuration. - **Behavior**: The SDK waits for the operation to complete and returns the result directly. - **Limitation**: Subject to a default timeout (1 hour). ```typescript // Sync (waits for result) const result = await client.parse.run({ input: 'doc.pdf' }); ``` ### Asynchronous Operations - **Usage**: Call methods like `.runJob()` or `.run()` with an `async` configuration object. - **Behavior**: The SDK initiates the operation in the background and immediately returns a job ID. The result can be retrieved later via polling or webhooks. - **Configuration**: Requires specifying `async` options, such as webhook details. ```typescript // Async (returns immediately with job_id) const job = await client.parse.runJob({ input: 'doc.pdf', async: { webhook: { mode: 'svix' } } }); ``` ``` -------------------------------- ### Handling Reducto Configuration Errors Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/errors.md Catch and log errors related to missing or invalid SDK configuration. Ensure the API key is provided. ```typescript import Reducto from 'reductoai'; try { const client = new Reducto({ apiKey: undefined }); } catch (error) { if (error instanceof Reducto.ReductoError) { console.error('Configuration error:', error.message); } } ``` -------------------------------- ### Configure Webhooks Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Allows configuration of webhooks for receiving asynchronous job completion notifications. ```APIDOC ## Webhook ### Description Configures webhook settings for receiving notifications about asynchronous job completion. ### Methods - **`run(params: WebhookRunParams)`**: Configures webhook settings for a job. This is typically used within the `async` configuration of other methods like `parse.runJob()`. ### Parameters for `run` (within `async` config) - **`mode`** (string): Webhook mode ('svix', 'http'). - **`channels`** (string[]): List of channels for webhook delivery. - **`callbackUrl`** (string): Custom URL for webhook delivery. ``` -------------------------------- ### ExperimentalProcessingOptions Interface Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/types.md Enables experimental and advanced processing features for specialized document handling, such as layout analysis models and native office conversion. Use with caution for cutting-edge capabilities. ```typescript interface ExperimentalProcessingOptions { chunk_table_blocks?: boolean; danger_filter_wide_boxes?: boolean; detect_signatures?: boolean; disable_office_external_links?: boolean; embed_text_metadata_pdf?: boolean; enable_checkboxes?: boolean; enable_equations?: boolean; enable_scripts?: boolean; enrich?: EnrichConfig; latency_sensitive?: boolean; layout_enrichment?: boolean; layout_model?: 'default' | 'beta' | 'rfdetr' | 'rfdetr0302' | 'rfdetr0303' | 'rfdetrbase0218' | 'rfdetr0304' | 'qwen35_27b_0317'; native_office_conversion?: boolean; promptable_agentic_text_on_regular_blocks?: boolean; return_figure_images?: boolean; return_page_images?: boolean; return_table_images?: boolean; rotate_figures?: boolean; rotate_pages?: boolean; user_specified_timeout_seconds?: number | null; } ``` -------------------------------- ### Link Local Repository with PNPM Source: https://github.com/reductoai/reducto-node-sdk/blob/main/CONTRIBUTING.md Links a local clone of the Reducto Node SDK repository to another package using PNPM. This is an alternative to using Yarn for local linking. ```sh # With pnpm $ pnpm link --global $ cd ../my-package $ pnpm link --global reductoai ``` -------------------------------- ### Synchronous Document Splitting Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/split.md Use the `run` method for synchronous document splitting. Provide the document input, a description of the desired sections, and optional rules for splitting. This method is suitable for smaller documents where immediate results are needed. ```typescript import Reducto from 'reductoai'; const client = new Reducto(); const response = await client.split.run({ input: 'https://pdfobject.com/pdf/sample.pdf', split_description: [ { name: 'Cover Page', description: 'The first page with title and author' }, { name: 'Table of Contents', description: 'List of chapters and page numbers' }, { name: 'Chapters', description: 'Main content chapters', partition_key: 'chapter_number' } ], split_rules: 'Identify major sections and chapters based on headers' }); console.log(response.result.splits); ``` -------------------------------- ### Execute Pipeline Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Executes custom pipelines defined in Reducto Studio. Supports synchronous (`.run()`) and asynchronous (`.runJob()`) operations. ```APIDOC ## Pipeline ### Description Executes custom processing pipelines defined in Reducto Studio. Supports synchronous and asynchronous operations. ### Methods - **`run(params: PipelineRunParams)`**: Synchronously executes a pipeline. Returns the pipeline output. - **`runJob(params: PipelineRunJobParams)`**: Asynchronously executes a pipeline. Returns a job ID. ### Parameters for `run` and `runJob` - **`pipelineId`** (string): The ID of the pipeline to execute. - **`input`** (string | string[]): Document source. Can be a public URL, presigned S3 URL, upload ID (`reducto://file_id`), job ID (`jobid://job_id`), or an array of these. - **`async`** (object): Configuration for asynchronous processing. If provided, `.runJob()` is implicitly called. - **`webhook`** (object): Webhook configuration for job completion. - **`mode`** (string): Webhook mode ('svix', 'http'). - **`channels`** (string[]): List of channels for webhook delivery. - **`callbackUrl`** (string): Custom URL for webhook delivery. ### Request Example (Synchronous) ```typescript const pipelineResponse = await client.pipeline.run({ pipelineId: 'your-pipeline-id', input: 'https://example.com/document.pdf' }); ``` ### Response (Synchronous) - **`output`** (any): The result of the pipeline execution. ``` -------------------------------- ### Data Extraction with Custom Schema using Reducto SDK Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/README.md Illustrates how to use the Reducto Node.js SDK's `extract.run` method to extract data from a document based on a user-defined JSON schema. ```typescript const result = await client.extract.run({ input: 'invoice.pdf', instructions: { schema: { type: 'object', properties: { vendor: { type: 'string' }, date: { type: 'string', format: 'date' }, items: { type: 'array', items: { type: 'object', properties: { description: { type: 'string' }, quantity: { type: 'number' }, unit_price: { type: 'number' } } } }, total: { type: 'number' } }, required: ['vendor', 'items', 'total'] } } }); console.log(result.result); // Structured data matching schema ``` -------------------------------- ### Pipeline.runJob Source: https://github.com/reductoai/reducto-node-sdk/blob/main/_autodocs/api-reference/pipeline.md Execute a pipeline asynchronously with webhook delivery. ```APIDOC ## Pipeline.runJob ### Description Execute a pipeline asynchronously with webhook delivery. ### Method POST ### Endpoint /pipeline/runJob ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (string | Array | Shared.Upload) - Required - Document URL or uploaded file ID - **pipeline_id** (string) - Required - Pipeline ID - **async** (AsyncConfigV3) - Required - Async configuration with webhook - **settings** (PipelineSettings) - Optional - Pipeline settings overrides ### Request Example ```json { "input": "https://example.com/document.pdf", "pipeline_id": "pipe_abc123def456", "async": { "webhook": { "mode": "svix", "channels": ["production"], "metadata": { "user_id": "user_123", "batch_id": "batch_456" } } } } ``` ### Response #### Success Response (200) - **job_id** (string) - Response with job_id #### Response Example ```json { "job_id": "job_abcdef12345" } ``` ### Error Handling - **BadRequestError** (400) - Invalid pipeline ID or input - **AuthenticationError** (401) - Invalid API key - **PermissionDeniedError** (403) - Insufficient permissions - **NotFoundError** (404) - Pipeline not found - **RateLimitError** (429) - Rate limit exceeded - **InternalServerError** (>=500) - Server error ```