> ## Documentation Index
> Fetch the complete documentation index at: https://docs.landing.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript Library

> Parse, extract, classify, and split documents with the ADE TypeScript library, and choose the Parse model version.

The [ade-typescript](https://github.com/landing-ai/ade-typescript) library wraps the Agentic Document Extraction APIs so you can parse, extract, classify, and split documents from TypeScript and JavaScript. The library is published as the `landingai-ade` package and generated from the API specification.

The Gen2 APIs live under the `client.v2` sub-client. It exposes both processing modes: async jobs through `client.v2.parseJobs` and `client.v2.extractJobs`, and synchronous calls through `client.v2.parse` and `client.v2.extract`. Jobs accept larger documents, default to the lower-consumption `standard` service tier, and suit automated pipelines and background work. See [Sync vs Async Processing](https://docs.landing.ai/dpt3/sync-async.md).

The Classify and Split APIs are on the top-level client: `client.classify` and `client.split`.

## Install the Library

```bash theme={null}
npm install landingai-ade
```

## Set Your API Key

The library reads your API key from the `VISION_AGENT_API_KEY` environment variable. [Generate an API key](https://docs.landing.ai/dpt3/agentic-api-key.md) first, then set it using any of the methods below. Do not hard-code your API key in source files.

### Method 1: Set the API Key as an Environment Variable

1. Set the environment variable. To persist the key across sessions on macOS or Linux, add the `export` command to your shell profile (`.zshrc` or `.bashrc`), then run `source ~/.zshrc`.

   ```bash macOS/Linux theme={null}
   export VISION_AGENT_API_KEY="<your-api-key>"
   ```

   ```cmd Windows (Command Prompt) theme={null}
   set "VISION_AGENT_API_KEY=<your-api-key>"
   ```

   ```powershell Windows (PowerShell) theme={null}
   $env:VISION_AGENT_API_KEY="<your-api-key>"
   ```
2. Initialize the client. It reads the `VISION_AGENT_API_KEY` environment variable automatically:
   ```typescript theme={null}
   import LandingAIADE from "landingai-ade";

   const client = new LandingAIADE();
   ```

### Method 2: Store the API Key in a .env File

Store your API key in a `.env` file. The library reads the key from the environment; it does not load `.env` files on its own, so use the `dotenv` package to load the file.

1. Install the `dotenv` package:
   ```bash theme={null}
   npm install dotenv
   ```
2. Create a `.env` file in your project root and add your API key:
   ```bash theme={null}
   VISION_AGENT_API_KEY=<your-api-key>
   ```
3. Load the `.env` file before you initialize the client:
   ```typescript theme={null}
   import "dotenv/config"; // Loads .env into process.env.
   import LandingAIADE from "landingai-ade";

   const client = new LandingAIADE();
   ```

> [!TIP]
>
> In Node.js 20.6 or later, you can skip the `dotenv` package and run your script with `node --env-file=.env your-script.js`.

### API Key Precedence

If the API key is set in more than one place, the library resolves it in this order (the first match wins):

1. The `apikey` passed to the client constructor.
2. The `VISION_AGENT_API_KEY` environment variable, whether you set it directly or loaded it from a `.env` file. A value already set in your environment is not overridden by a `.env` file.

For help with missing-key errors, keys that fail to load, or keys that resolve to the wrong account, see [Troubleshoot API Key Issues](https://docs.landing.ai/dpt3/agentic-api-key.md#troubleshoot-api-key-issues).

## Initialize the Client

Create a client. It reads `VISION_AGENT_API_KEY` from the environment automatically.

```typescript theme={null}
import LandingAIADE from "landingai-ade";

const client = new LandingAIADE();
```

By default, the library uses the US endpoints. If your API key is from the EU region, set the `environment` option to `eu`. API keys are region-specific: an EU key works only with the EU environment.

```typescript theme={null}
import LandingAIADE from "landingai-ade";

const client = new LandingAIADE({ environment: "eu" });
```

For more about using Agentic Document Extraction in the EU, see [European Union (EU)](https://docs.landing.ai/dpt3/eu.md).

## Parse a Document

Use `client.v2.parseJobs` to convert a document into Markdown, a structure tree, and per-element grounding. The sub-client exposes `create`, `get`, `list`, and `wait`. The `wait` method polls until the job reaches a terminal state and returns the finished job.

Pass a local file as a read stream with the `document` parameter, or a remote file with `document_url`. Setting `service_tier` to `standard` runs the job in the lane that consumes half the credits of `priority`.

A finished job carries the parse output in `result`, a `V2ParseResponse` with `markdown`, `structure`, and `metadata`. For the full workflow and parameters, see [Parse Asynchronously](https://docs.landing.ai/dpt3/parse-async.md).

```typescript theme={null}
import fs from "fs";
import LandingAIADE from "landingai-ade";

const client = new LandingAIADE();

const job = await client.v2.parseJobs.create({
  document: fs.createReadStream("document.pdf"),
  model: "dpt-3-pro-latest",
  service_tier: "standard",
});
const done = await client.v2.parseJobs.wait(job.job_id);
console.log((done.result as LandingAIADE.V2ParseResponse).markdown);
```

## Extract Data

Use `client.v2.extractJobs` to pull structured fields from parsed Markdown. Provide the Markdown as a string with `markdown` (or a remote URL with `markdown_url`) and a schema. The `schema` parameter accepts a JSON Schema object or a JSON string.

A finished job carries the extraction in `result`, a `V2ExtractResult` with `extraction`, `extraction_metadata`, `markdown`, and `metadata`. For the full workflow and parameters, see [Asynchronous Extraction](https://docs.landing.ai/dpt3/extract-async.md).

```typescript theme={null}
import fs from "fs";
import LandingAIADE from "landingai-ade";

const client = new LandingAIADE();

// Parse first to get Markdown, then extract.
const parseJob = await client.v2.parseJobs.create({
  document: fs.createReadStream("document.pdf"),
  model: "dpt-3-pro-latest",
  service_tier: "standard",
});
const parsed = await client.v2.parseJobs.wait(parseJob.job_id);

const extractJob = await client.v2.extractJobs.create({
  markdown: (parsed.result as LandingAIADE.V2ParseResponse).markdown,
  schema: {
    type: "object",
    properties: {
      revenue: { type: "string", description: "Q1 2024 revenue" },
    },
  },
  service_tier: "standard",
});
const extracted = await client.v2.extractJobs.wait(extractJob.job_id);
console.log((extracted.result as LandingAIADE.V2ExtractResult).extraction);
```

> [!TIP]
>
> To define a typed schema, use [Zod](https://zod.dev) (v4 or later) and pass `z.toJSONSchema(YourSchema)` as the `schema`.

## Classify Pages

Use `client.classify` to assign one of your classes to each page of a document. The method is on the top-level client, not under `client.v2`, and calls the [Classify API](https://docs.landing.ai/dpt3/classify.md) as a synchronous request. Pass a local file as a read stream with `document`, or a remote file with `document_url`. Each class has a `class` name and an optional `description`.

Pass the classes as a JSON string. The library's types declare an array, but the API reads this form field as JSON, so cast the string.

The method returns a `ClassifyResponse` with one `classification` entry per page. Each entry has `class`, `page` (0-indexed), `reason`, and `suggested_class`. See [JSON Response for Classification](https://docs.landing.ai/dpt3/classify-response.md).

```typescript theme={null}
import fs from "fs";
import LandingAIADE from "landingai-ade";

const client = new LandingAIADE();

const classes = [
  { class: "invoice", description: "A commercial bill with line items, totals, and payment terms" },
  { class: "bank_statement", description: "A monthly summary of account transactions" },
  { class: "pay_stub" },
];

const response = await client.classify({
  classes: JSON.stringify(classes) as any,
  document: fs.createReadStream("document.pdf"),
});

for (const result of response.classification) {
  console.log(`Page ${result.page}: ${result.class}`);
}
```

## Split a Document

Use `client.split` to separate a parsed document into classified sub-documents. The method is on the top-level client, not under `client.v2`, and calls the [Split API](https://docs.landing.ai/dpt3/split.md) as a synchronous request. Pass the `markdown` from a parse result with the `markdown` parameter, or a remote Markdown file with `markdown_url`. Each of your [Split Rules](https://docs.landing.ai/dpt3/split.md#split-rules) has a `name` and an optional `description` and `identifier`. Pass the rules as a JSON string and cast it, as with `classes` in [Classify Pages](#classify-pages).

The method returns a `SplitResponse`. Each entry in `splits` has `classification`, `identifier`, `pages` (0-indexed), and `markdowns` (one Markdown string per page). See [JSON Response for Splitting](https://docs.landing.ai/dpt3/split-response.md).

```typescript theme={null}
import fs from "fs";
import LandingAIADE from "landingai-ade";

const client = new LandingAIADE();

// Parse first to get Markdown, then split.
const parseJob = await client.v2.parseJobs.create({
  document: fs.createReadStream("document.pdf"),
  service_tier: "standard",
});
const parsed = await client.v2.parseJobs.wait(parseJob.job_id);

const splitClass = [
  {
    name: "Bank Statement",
    description: "Document from a bank that summarizes all account activity over a period of time.",
  },
  {
    name: "Pay Stub",
    description: "Document that details an employee's earnings, deductions, and net pay for a specific pay period.",
    identifier: "Pay Stub Date",
  },
];

const response = await client.split({
  split_class: JSON.stringify(splitClass) as any,
  markdown: (parsed.result as LandingAIADE.V2ParseResponse).markdown,
});

for (const split of response.splits) {
  console.log(`${split.classification} (${split.identifier}): pages ${split.pages}`);
}
```

## Set the Parse Model Version

For Parse, the `model` parameter is optional. When you omit it, the API uses the latest DPT-3 Pro model. To select a family or pin a version, pass a model string such as `dpt-3-verity`, or a dated snapshot. See [Parsing Models](https://docs.landing.ai/dpt3/parse-models.md).

Responses parsed with `dpt-3-verity` include a `confidence` score on each word-level `atomic_grounding` entry. See [Word Confidence Scores](https://docs.landing.ai/dpt3/parse-response.md#word-confidence-scores-dpt-3-verity).

```typescript theme={null}
import fs from "fs";

const job = await client.v2.parseJobs.create({
  document: fs.createReadStream("document.pdf"),
  model: "dpt-3-pro-latest",
  service_tier: "standard",
});
```

## Save Output to a File

The job `create` methods do not accept `saveTo`. To keep a job's output, write `result` to a file yourself, or pass `output_save_url` on `create` to have Agentic Document Extraction deliver the result straight to your own storage. See [Save Parsed Output to a URL](https://docs.landing.ai/dpt3/parse-async.md#save-parsed-output-to-a-url).

The synchronous `parse` and `extract` methods take an optional `saveTo` parameter instead, which writes the full response to a JSON file. Pass it a directory to use an auto-generated file name, or a path ending in `.json` to choose the exact file.

```typescript theme={null}
import fs from "fs";
import LandingAIADE from "landingai-ade";

const client = new LandingAIADE();

const job = await client.v2.parseJobs.create({
  document: fs.createReadStream("document.pdf"),
  service_tier: "standard",
});
const done = await client.v2.parseJobs.wait(job.job_id);

fs.writeFileSync("parse-output.json", JSON.stringify(done.result as LandingAIADE.V2ParseResponse, null, 2));
```

## Handle Errors

The synchronous `parse` and `extract` methods throw `V2SyncTimeoutError` if the request exceeds the server's synchronous time limit (HTTP 504). For large documents, use the async jobs interface instead.

When a parse partially succeeds (some pages fail), the API returns the full response with an HTTP 206 status, and the failed pages are listed in `metadata`. See [Troubleshoot Parsing](https://docs.landing.ai/dpt3/parse-troubleshoot.md).

The job `wait` method returns the finished job regardless of outcome, so check `job.status`. To throw instead when a job fails, pass `raiseOnFailure: true`, which throws `JobFailedError`. If a job does not finish within the `timeout`, `wait` throws `JobWaitTimeoutError`. These v2 helper errors do not extend `APIError`, so catch them by name.

```typescript theme={null}
import fs from "fs";
import LandingAIADE, { JobFailedError, JobWaitTimeoutError } from "landingai-ade";

const client = new LandingAIADE();

const job = await client.v2.parseJobs.create({
  document: fs.createReadStream("document.pdf"),
  service_tier: "standard",
});
try {
  const done = await client.v2.parseJobs.wait(job.job_id, { timeout: 600000, raiseOnFailure: true });
  console.log((done.result as LandingAIADE.V2ParseResponse).markdown);
} catch (error) {
  if (error instanceof JobFailedError) {
    console.error(`Job failed: ${error.message}`);
  } else if (error instanceof JobWaitTimeoutError) {
    console.error("Job did not finish in time; poll again with parseJobs.get().");
  } else {
    throw error;
  }
}
```

## Additional Resources

* [TypeScript library on GitHub](https://github.com/landing-ai/ade-typescript). The README covers client configuration not documented here, including retries, timeouts, logging, raw response access, and customizing the fetch client.
* [API reference](https://docs.landing.ai/api-reference/parse/ade-parse.md)
* [Parse Documents](https://docs.landing.ai/dpt3/parse.md) and [Extract Data](https://docs.landing.ai/dpt3/extract.md)
* [Classify](https://docs.landing.ai/dpt3/classify.md) and [Split](https://docs.landing.ai/dpt3/split.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.