npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nace-ai/langchain-nace

v0.1.1

Published

LangChain.js integration for Drex decision models by Nace: a classifier, a router, and agent middleware for model routing and tool gating.

Readme


Drex is Nace's family of decision models. It reads text, JSON, LangChain messages and, on Drex Max, images. It answers typed questions (yes/no, pick one, score on a rubric) with a probability for every option. This package brings it to LangChain.js:

| | | | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 🧭 NaceClassifier | A Runnable that answers many questions about one state in a single request, with full probabilities, usage and a request id. | | 🔀 NaceRouter / naceConditionalEdge | Route LCEL chains and LangGraph graphs on Drex's choice; send unsure cases to a person. | | 🛡️ naceAutoModeMiddleware | Check every tool call before it runs: allow, ask a person, or block. Remembers the user's original request, reads screenshots, and blocks if Drex can't answer. | | 💸 naceModelRouterMiddleware | Pick the cheapest chat model that can handle each run; escalate when unsure. | | 🔁 Drop-in for @langchain/typesafe | Change the imports and the API key; your code keeps working. |

Contents: Install · Quickstart · Switching from TypeSafe · Models · Images · Routing · Agent middleware · Backends · Errors · Tracing · Development

Install

npm install @nace-ai/langchain-nace @langchain/core
npm install langchain @langchain/langgraph   # only for @nace-ai/langchain-nace/middleware
export NACE_API_KEY=nace_sk_...

Use 0.1.1 or later. Version 0.1.0 was withdrawn from npm.

  • Node 20 or later. ESM and CommonJS, with TypeScript types.
  • Peers: @langchain/core ≥ 1.2.16; for the middleware, langchain ≥ 1.3.0 and @langchain/langgraph.
  • One copy of @langchain/core and @langchain/langgraph. If your package manager installs two, add overrides/resolutions. With two copies, a Command from one isn't recognized by agents built on the other, so resuming after a person answers fails.

Looking for Python? The langchain-nace package is on PyPI.

Quickstart

import { NaceClassifier } from "@nace-ai/langchain-nace";

const classifier = new NaceClassifier({
  // model: "drex-max" by default
  questions: {
    refund: { type: "noul", instructions: "Is the customer asking for a refund?" },
    team: {
      type: "choice",
      instructions: "Which team should handle this?",
      criteria: { billing: "Payments and refunds", technical: "Bugs" },
    },
    mood: {
      type: "score",
      instructions: "How upset is the customer?",
      criteria: ["calm", "annoyed", "furious"],
    },
  },
});

const response = await classifier.invoke(
  "I was charged twice for March and I'm annoyed. Please refund one.",
);
response.nouls.refund.noul; // 0.98: probability of yes
response.choices.team.probabilities; // { billing: 0.99, technical: 0.01 }
response.scores.mood.score; // 1.1: expected level
response.requestId; // quote it in support requests

| Question | Ask | Get back | | -------- | ----------------------------------------- | -------------------------------------------------------------------------- | | noul | a yes/no proposition | noul: the probability of yes | | choice | pick one of your labels | choice, confidence, and probabilities for every label | | score | a level on an ordered rubric (low → high) | score (may fall between levels), legend, probabilities, confidence |

All questions about one state go in one request, and answers keep their full probabilities, so thresholds stay in your code. The state can be a string, any JSON, a LangChain message, or messages anywhere inside objects and arrays. batch works as on any Runnable; it runs at most 8 requests at once unless you set maxConcurrency. To ask different questions on one call, pass { questions } in the call options.

Switching from @langchain/typesafe

Change the imports and set NACE_API_KEY. Question objects, constructor options, response fields, middleware names and middleware options all stay the same:

- import { TypeSafeClassifier } from "@langchain/typesafe";
- import { autoModeMiddleware, modelRouterMiddleware } from "@langchain/typesafe/middleware";
+ import { NaceClassifier } from "@nace-ai/langchain-nace";
+ import { autoModeMiddleware, modelRouterMiddleware } from "@nace-ai/langchain-nace/middleware";

| @langchain/typesafe | @nace-ai/langchain-nace | | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | TypeSafeClassifier | NaceClassifier (default model drex-max) | | question objects; Noul, Choice, Score | the same | | constructor options (questions, model, apiKey, baseUrl, timeout, fetch, maxRetries, maxConcurrency, …) | the same | | model, answers, usage, requestId, nouls, choices, scores | the same, plus evaluationTimeMs, usage.imageTokens, raw | | modelRouterMiddleware({ choices, instructions, classifierOptions }) | the same; the decision is in state under modelRoute | | autoModeMiddleware({ tools, instructions, criteria, blockedMessage, classifierOptions }) | the same | | TypeSafe*Error | Nace*Error, with .isInstance() | | TYPESAFE_API_KEY, TYPESAFE_BASE_URL | NACE_API_KEY, NACE_BASE_URL |

What behaves differently, on purpose:

  • Different model, different numbers. Thresholds tuned on Jev's probabilities may need retuning.
  • The timeout is 60 s (TypeSafe: 30 s), because Drex may take up to 55 s.
  • The tool gate asks more. Besides your instructions/criteria question, which still blocks at 0.5, Drex scores the risk and answers "destructive?" and "did the user ask for this?". The gate can also ask a person (see below).
  • The model router doesn't throw. When Drex fails or isn't confident it uses the strongest model; with no user message, the agent's own model.
  • dangerouslyAllowBrowser defaults to false.

Models

| Model | Reads | Questions per request | | ------------------------ | --------------------- | --------------------- | | drex-max (default) | text, JSON and images | up to 512 | | drex-v2.0 | text and JSON | up to 512 |

Any other model id is sent as given (drex-v1.5, drex-latest, and models released later). Drex enforces each model's limits, and its errors say what to change. Pin a model with model or NACE_DEFAULT_DECISION_MODEL. The package default moves to the newest flagship with each Drex release, so pin one if you need results that never change.

Images (Drex Max)

const damage = new NaceClassifier({
  questions: {
    damaged: {
      type: "choice",
      instructions: "Which image shows damage?",
      criteria: { "Image 1": null, "Image 2": null },
    },
  },
});
await damage.invoke("Two product photos.", {
  images: [readFileSync("a.png"), "data:image/jpeg;base64,..."],
});
  • Accepted:
    • bytes (Buffer, Uint8Array, ArrayBuffer), file paths, base64 and data URLs;
    • LangChain image blocks ({ type: "image", data, mimeType }, source_type: "base64", image_url);
    • provider blocks: OpenAI input_image, Anthropic source, Google media;
    • files uploaded with nace-sdk.
  • Images inside messages are moved to images automatically and referred to as "Image N". This works for message objects and for plain { role, content: [...] } objects.
  • Never dropped silently. Remote URLs are refused, because Drex doesn't fetch them. Images sent to a text-only model (drex-v2.0, drex-v1.5) throw NaceImageModelError before anything is sent.

Routing

import { NaceRouter } from "@nace-ai/langchain-nace";

const router = new NaceRouter({
  question: {
    type: "choice",
    instructions: "Which team?",
    criteria: { billing: null, technical: null },
  },
  state: (input: { text: string }) => input.text,
  minConfidence: 0.6,
  fallback: "human",
});
const chain = router.branch(
  { billing: billingChain, technical: techChain, human: escalate },
  escalate,
);

LangGraph: naceConditionalEdge({ question, state, minConfidence: 0.7 }) is a path function for addConditionalEdges. Below the threshold it returns "human_review", so that node can interrupt() for a person. See examples/langgraph-router.ts.

Agent middleware (experimental)

import { MemorySaver } from "@langchain/langgraph";
import { createAgent } from "langchain";
import {
  naceAutoModeMiddleware,
  naceModelRouterMiddleware,
} from "@nace-ai/langchain-nace/middleware";

const router = naceModelRouterMiddleware({
  choices: {
    fast: { model: "anthropic:claude-haiku-5-5", criteria: "Short lookups" },
    strong: { model: "anthropic:claude-sonnet-5-5", criteria: "Multi-step changes" },
  },
  instructions: "Pick the cheapest model that can do this safely.",
});
const gate = naceAutoModeMiddleware({ screenshots: true }); // drex-max reads the screenshots

const agent = createAgent({
  model: "anthropic:claude-haiku-5-5",
  tools,
  middleware: [router, gate],
  checkpointer: new MemorySaver(), // lets the gate pause for a person
});

naceAutoModeMiddleware: the tool gate

Before each tool call, Drex gets one request with:

  • the user's original request, kept however long the run gets;
  • the latest user message and the last 20 messages;
  • the tool call and its description;
  • with screenshots: true and Drex Max, the newest screenshots.

It answers three questions: a risk score, "destructive?" and "did the user ask for this?". The default thresholdPolicy() then decides:

| Decision | When | | ------------------- | --------------------------------------------- | | 🛑 Block | risk ≥ 0.75, or destructive and not asked for | | ✋ Ask a person | risk ≥ 0.4, or destructive and asked for | | ✅ Allow | otherwise |

  • Asking a person raises a LangGraph interrupt with a { type: "nace_tool_approval", name, args, verdict, … } value. Resume with new Command({ resume }), where resume is { type: "approve" }, { type: "reject", message } or { type: "edit", args }.
    • Asking needs a checkpointer. Without one the call is blocked, and the message says so. Use askHuman: false to always block instead.
  • If Drex can't answer, the call is blocked (onError: "block"). A screenshot Drex can't read is dropped, and the check runs again without it.
    • With onError: "throw", a failed check (including a screenshots function that throws) fails the run, and retrying the run (invoke(null)) checks again. In a run with a thread_id, LangGraph doesn't let an outer middleware catch it and continue: agent.invoke rejects with the error itself (for example a NaceAPIError), or with an AggregateError whose errors include it when an outer middleware keeps scheduling tasks after catching it. Without a thread_id, or outside a LangGraph run, the gate decides directly, and its error is an ordinary error that outer middleware may catch.
    • With onError: "block" the block is saved like any other decision, so a resume replays the same block without capturing screenshots or asking Drex again.
  • Everything is replaceable: pass questions, thresholdPolicy({ ... }), or your own (verdict) => GateDecision.
  • Resuming: each checked call's decision is saved in the agent's checkpoint, as a LangGraph task named NaceGateDecision: Drex's answer, the decision, and a digest of what Drex saw (never screenshots or keys). A resume, on any worker, replays that decision and does not ask Drex again. If the conversation, the tool call, the screenshots or the policy's decision changed while the call was paused, the call is blocked and must be requested again, and so it is when the current screenshots can't be captured to compare; an earlier answer can't authorize something else. Completed calls and new turns are checked again.
    • Editing the paused state (for example with updateState) or resuming an earlier checkpoint makes LangGraph run the tool call as a new task, so the gate checks it again as a new call. A plain resume value waiting for it blocks the call, and answers addressed by id to the earlier pause don't carry over (neither an approval nor a rejection).
    • A custom GateDecision needs an id to be resumed after a pause; without one the call is blocked and must be requested again.
    • With a checkpointer, each checked call adds one checkpoint write, and the task appears in traces and in the updates, tasks and debug stream modes.
    • Approving several parallel calls needs createAgent's default version: "v2".
    • On a resume, LangGraph runs the tool step again from the start, so the code around the gate must call LangGraph tasks and interrupts in the same order every time. Put the gate first in middleware, before any retry middleware, so a retried tool is checked once: a retry wrapped around the gate can resume an earlier decision when the tool fails only sometimes. A screenshots function must not call LangGraph task() or interrupt().

naceModelRouterMiddleware: the model picker

The router picks the model once per run. Below minConfidence (default 0.6), or if Drex can't be reached, it uses escalateTo: the last choice by default, so list choices cheapest first. The decision and probabilities are kept in state under modelRoute.

examples/support-agent.ts runs four live scenarios:

  • an allowed read;
  • a blocked unrequested delete;
  • a person approving a requested delete;
  • a screenshot-based block on a computer-use click.

Backends

| Backend | baseUrl | Notes | | ------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------ | | Nace (default) | https://console.nace.ai | or NACE_BASE_URL | | OpenRouter | https://openrouter.ai/api/v1 | models nace-ai/drex-v2.0, nace-ai/drex-max; images are sent the way OpenRouter expects | | TypeSafe-compatible hosts | the host's System One root | same request format as Nace |

Every request sends User-Agent and X-Nace-Client: langchain-nace-js/<version>. On OpenRouter it also sends HTTP-Referer and X-OpenRouter-Title.

Custom defaultHeaders are sent on requests but omitted from object inspection and serialized classifiers because they may contain credentials. Construct a new classifier with those headers when restoring a setup that needs them.

Credentials and custom providers

An explicit apiKey always wins; a blank one is refused. Without it, the key follows the endpoint:

  • console.nace.ai and its legacy production alias drex.nace.ai (HTTPS, port 443) use NACE_API_KEY.

  • An endpoint set with NACE_BASE_URL, such as an on-prem deployment, also uses NACE_API_KEY:

    export NACE_API_KEY=... NACE_BASE_URL=https://nace.customer.example
    const classifier = new NaceClassifier();
  • OpenRouter (https://openrouter.ai/api/v1) uses OPENROUTER_API_KEY, never NACE_API_KEY, even with openrouter: false.

  • A custom baseUrl in code needs its own apiKey. To use NACE_API_KEY for a custom endpoint, set it with NACE_BASE_URL instead.

const classifier = new NaceClassifier({
  baseUrl: "https://openrouter.ai/api/v1",
  apiKey: process.env.OPENROUTER_API_KEY,
});

A base URL that contains a user name or password is refused; pass the key as apiKey. Pass the same settings through classifierOptions when constructing a router. Vercel bypass headers are stripped for custom destinations. Requests refuse HTTP redirects; configure the final API URL directly. Serialized classifiers keep the resolved destination and use OPENROUTER_API_KEY for OpenRouter or NACE_CUSTOM_API_KEY for other custom hosts. A classifier serialized for a custom endpoint refers to NACE_CUSTOM_API_KEY; pass that one secret in load's secretsMap.

Malformed probabilities, confidence values or score rubrics raise NaceAPIResponseValidationError. The default tool-gate error policy blocks the call.

Errors

Every error extends LangChain's LangChainError. Check errors with .isInstance(), which keeps working when two copies of the package are installed. This package never adds your state, questions or keys to an error message. A message does include text from the provider's error response (for a 422, each issue's path: message), clipped to 500 characters, so if a provider repeats part of your request in its error, that text is in the message. The full response stays on error.body and every issue on error.issues; both are non-enumerable, so console.log(error) and JSON.stringify(error) don't print them. error.type is cut to 64 characters, and error.requestId is kept only when it is a short token.

| Error | When | | --------------------------------------------------------- | ---------------------------------------------------- | | NaceAuthenticationError | 401 | | NaceInsufficientCreditError | 402, with the Billing link | | NaceUnprocessableEntityError | 422; lists each issue's path: message | | NaceRateLimitError | 429, after retries (retryAfterMs) | | NaceOverloadedError | 529, after retries | | NaceAPIConnectionError, NaceAPITimeoutError | network problems | | NaceImageModelError, NaceImageError, NaceMediaError | images or media that can't be sent; nothing was sent | | NaceBatchStoppedError | a batch input that was never sent |

  • Retries: 408, 429, 5xx and 529 responses are retried (maxRetries: 2), waiting as long as retry-after-ms asks. Each attempt may take up to 60 s.
  • Cancelling: a call's signal or timeout, or a cancelled agent run, also aborts the HTTP request.
  • Batches: batch is LangChain's own, with one addition: it stops sending. A 401, 402 or 403 stops the batch it happens in, and the batches nested in it. Another batch running at the same time stops at its own first 401, 402 or 403. No new input is sent after one, with or without returnExceptions, because the classifier's key or account can't be used and every later request would fail the same way. Without returnExceptions, no new input is sent once the batch has rejected. Requests already sent finish, including the SDK's own retries of them, and their results are discarded when the batch rejects. An input that was not sent fails with a NaceBatchStoppedError (its cause is the failure that stopped the batch) inside its own run, so your callbacks see it. A batch that an invoke override starts with this.batch runs inside the batch it came from: it stops when that batch stops, and a 401, 402 or 403 inside it stops that batch too. Batches started on their own stay independent. LangChain runs callback handlers on a shared queue, so a classifier call made from inside a callback handler can be refused with NaceBatchStoppedError while another batch on the same classifier is stopping; nothing is sent in that case. Limit: after any other failure, such as a 422, the batch stops when it rejects, a moment after the failure, so an input dispatched in between can still be sent: the next one in the queue, or one started while the failed input's error callbacks are still running. With returnExceptions: true such a failure stays with its own input and the rest are sent. A cancelled input fails alone. maxConcurrency comes from the call options, then batchOptions, then the constructor (default 8); an invalid value such as NaN is rejected, as on any Runnable. Each input goes through invoke, so a subclass that overrides invoke (to redact input, say) applies to every input, sent or not. An invoke override that recovers from an error keeps the batch going, except after a 401, 402 or 403, which always stop it.

Tracing

Calls show up in LangSmith as llm runs (ls_provider: "nace") with the questions, the full answers and probabilities, token usage and the Drex request id. The router and the middlewares add their thresholds to the run metadata.

Development

pnpm install
pnpm lint && pnpm typecheck && pnpm test     # offline, against a fake Drex
NACE_API_KEY_LIVE=nace_sk_... pnpm test:int  # live contract tests
pnpm build && pnpm smoke                     # install the packed tarball in a fresh project

License

MIT