> For the complete documentation index, see [llms.txt](https://docs.algenta.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.algenta.ai/sdks/typescript/overview.md).

# TypeScript client reference

The `algenta-sdk` package is the official TypeScript and JavaScript client for Algenta. It wraps the [HTTP API](/http-api/overview.md) in one typed `AlgentaClient`, works on Node.js 18+ and modern browsers, and uses `fetch` with no required dependencies. This page covers the essentials you need before any call: installing the package, constructing the client, how methods resolve, and how errors surface. The method surface itself is split across four reference pages linked at the end.

{% hint style="info" %}
Methods are `camelCase`, but request bodies and query parameters stay `snake_case`. You call `getDatasetSummary(...)` and `queryWithMetadata(...)`, and the payloads you pass and receive use fields like `dataset_id`, `source_name`, and `metric_column`. This mirrors the HTTP contract exactly.
{% endhint %}

## Install

{% tabs %}
{% tab title="npm" %}

```bash
npm install algenta-sdk
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add algenta-sdk
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add algenta-sdk
```

{% endtab %}
{% endtabs %}

## Construct the client

`new AlgentaClient(config)` takes an optional config object. If you omit `apiKey`, the client reads it from `ALGENTA_API_KEY`, then the legacy `DE_API_KEY`. If none is set, the constructor throws with guidance rather than failing silently.

```typescript
import { AlgentaClient } from "algenta-sdk";

const client = new AlgentaClient({
  apiKey: process.env.ALGENTA_API_KEY,          // falls back to DE_API_KEY, then throws
  baseUrl: "https://api.algenta.ai",            // or http://localhost:8000 for self-host
});

const models = await client.listModels();
console.log(models);
```

`new AlgentaClient(config)` accepts an `AlgentaClientConfig`:

| Option           | Type                     | Default                                       | Notes                                                                 |
| ---------------- | ------------------------ | --------------------------------------------- | --------------------------------------------------------------------- |
| `apiKey`         | `string`                 | `ALGENTA_API_KEY`, then `DE_API_KEY`          | Required. Read from the environment if not passed.                    |
| `baseUrl`        | `string`                 | `https://api.algenta.ai` (`DEFAULT_BASE_URL`) | Set an explicit origin for a self-hosted engine.                      |
| `timeout`        | `number`                 | `120000`                                      | Per-request timeout in milliseconds, enforced with `AbortController`. |
| `maxRetries`     | `number`                 | `3`                                           | Retries with exponential backoff; honors `Retry-After` on `429`.      |
| `defaultHeaders` | `Record<string, string>` | `{}`                                          | Merged into every request.                                            |

{% hint style="warning" %}
A self-hosted engine needs an explicit `baseUrl`. The client never silently falls back to Algenta cloud — pass `http://localhost:8000` (or your own origin) and the API key provisioned by that deployment.
{% endhint %}

## Calls return promises

Every method returns a `Promise`, so use `await` (or `.then`). Streaming methods — `streamChatCompletions` and `streamResponses` — return an `AsyncGenerator`, so iterate them with `for await`.

```typescript
// Awaitable request/response.
const summary = await client.getDatasetSummary("ds_nps_scores");
console.log(summary.dataset_id, summary.name);

// Streaming method: iterate the async generator.
for await (const chunk of client.streamChatCompletions({
  messages: [{ role: "user", content: "Summarize Q3 in one line." }],
})) {
  process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
}
```

## Errors

All client errors extend `DecisionEngineError` and carry a normalized `errorCode`, a `statusCode`, the raw `responseBody`, and a `details` accessor (with `validationErrors` for `422` bodies). Import the subclass you want to branch on.

```typescript
import {
  AlgentaClient,
  AuthenticationError,
  NotFoundError,
  RateLimitError,
  ValidationError,
} from "algenta-sdk";

try {
  await client.getDataset("does-not-exist");
} catch (err) {
  if (err instanceof NotFoundError) {
    console.error("Not found:", err.errorCode);
  } else if (err instanceof RateLimitError) {
    console.error("Rate limited; retry after", err.retryAfter, "seconds");
  } else if (err instanceof AuthenticationError) {
    console.error("Check your API key");
  } else if (err instanceof ValidationError) {
    console.error("Invalid request:", err.validationErrors);
  }
}
```

| Error                 | HTTP status | Retried automatically                          |
| --------------------- | ----------- | ---------------------------------------------- |
| `AuthenticationError` | 401         | No                                             |
| `NotFoundError`       | 404         | No                                             |
| `ValidationError`     | 422         | No                                             |
| `RateLimitError`      | 429         | Yes, honoring `Retry-After` up to `maxRetries` |
| `ServerError`         | 5xx         | Yes, with exponential backoff                  |
| `DecisionEngineError` | other       | Base class for the hierarchy                   |

{% hint style="success" %}
Branch on `err.errorCode` (or `instanceof`), not on the human-readable `message`. Codes are stable; messages are not.
{% endhint %}

## Where to go next

Pick the method group you need — each page tables every method with its HTTP route and runnable examples.

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Simulate and query</strong></td><td>Run Monte Carlo decisions and governed data queries.</td><td><a href="/pages/ajpMQ9mrTXbAhImUrKTA">/pages/ajpMQ9mrTXbAhImUrKTA</a></td></tr><tr><td><strong>Decisions and products</strong></td><td>Log decision memory and call the product endpoints.</td><td><a href="/pages/ONhCwMfELeN1mFWHwnXk">/pages/ONhCwMfELeN1mFWHwnXk</a></td></tr><tr><td><strong>Connectors and data</strong></td><td>Manage connectors, datasets, and repository intelligence.</td><td><a href="/pages/gq3JggKEFEw0ZB5yhfYz">/pages/gq3JggKEFEw0ZB5yhfYz</a></td></tr></tbody></table>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.algenta.ai/sdks/typescript/overview.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
