# @pleach/langchain (preview) (/docs/langchain)



A vine bridging your trellis to the LangChain one. `@pleach/langchain`
wires LangChain and LangGraph primitives into a `@pleach/core` session.
LangChain `Tool` instances become Pleach tool definitions (and back), a
`LangChainProvider` exposes a LangChain chat model as a Pleach provider,
and checkpointer and store adapters cover LangGraph persistence. In the
reverse direction, `HarnessCheckpointSaver` and `HarnessEventLogCallback`
let a LangChain or LangGraph app persist into Pleach and write its
callbacks to the event log (and, with the `auditLedger` option, one
audit row per model run). `importLangGraphThread` reads a LangGraph
thread for `importSessions`. For an existing `AgentExecutor`, see
[Keeping an `AgentExecutor`](#keeping-an-agentexecutor).

> **Pre-1.0 — pin a tight range.** Pre-1.0 in source; not on npm
> yet. The surface will move before `1.0.0` cuts. Treat every
> minor as potentially breaking and pin via `~0.x.y` (patch only).
> The warning is in the package itself; it is repeated here because
> the migration cost of an unintended major-jump on this adapter is
> the highest of any sibling.

**Package:** `@pleach/langchain` ([not on npm yet](</docs/install#not-on-npm-yet>)) · **Source:** [github.com/pleachhq/langchain](<https://www.getpleach.com/docs/langchain>)

## This page vs the migration guide [#this-page-vs-the-migration-guide]

This page is the reference for the **active adapter** — for hosts
keeping a LangChain tool, agent, or history backend in production
and running it alongside Pleach primitives. The adapter is the
bridge.

If you're moving wholesale off LangChain, the right page is
[Migrating from LangChain](/docs/migrating-from-langchain). That
guide is one-time work: rewrite chains as runtime calls, retire
the LangChain dependency, end with no adapter in the tree. This
page is the opposite shape — long-lived integration, both
libraries in `package.json`, deliberate boundary between them.

## Install [#install]

```bash
npm install @pleach/langchain
# peer deps (install the ones you use):
npm install @pleach/core @langchain/core
npm install @langchain/langgraph-checkpoint   # for the checkpointer adapters
```

| Peer                              | Range                | Required |
| --------------------------------- | -------------------- | -------- |
| `@pleach/core`                    | `>=0.1.0 <1`         | yes      |
| `@langchain/core`                 | `^0.3.0 \|\| ^1.0.0` | optional |
| `@langchain/langgraph-checkpoint` | `^0.1.0 \|\| ^1.0.0` | optional |
| `zod`                             | `^3.0.0 \|\| ^4.0.0` | optional |

The LangChain ranges are optional peers so the adapter doesn't pin a
LangChain version on top of the one the host already uses.
`@langchain/langgraph` 1.4.x depends on
`@langchain/langgraph-checkpoint` 1.x, which the checkpoint adapters
accept. Mismatches surface as peer-dep
warnings at install time — don't ignore them; the converters key
off LangChain type shapes that vary across majors.

```typescript
import {
  fromLangChainTool,
  fromLangChainTools,
  toLangChainTool,
  LangChainProvider,
  LangGraphCheckpointerAdapter,
  LangGraphStoreAdapter,
  HarnessCheckpointSaver,
  HarnessEventLogCallback,
} from "@pleach/langchain";
```

The adapter exposes converters in both directions — LangChain tools
become Pleach `ToolDefinition`s and vice versa — plus a
`LangChainProvider` that exposes a LangChain chat model as a Pleach
provider, plus LangGraph-shaped checkpointer/store adapters in
each direction. The package README carries the version-current
constructor options.

## Bridging a LangChain tool into a Pleach session [#bridging-a-langchain-tool-into-a-pleach-session]

A LangChain `Tool` (or `StructuredTool`) instance wraps a callable
plus a schema. The adapter converts it into a `ToolDefinition`
usable on the Pleach side — registrable through
`setOrchestratorRegistry` or a plugin's `contributeTools`.

```typescript
import { fromLangChainTool } from "@pleach/langchain";
import { definePleachPlugin } from "@pleach/core";
import { DynamicStructuredTool } from "@langchain/core/tools";

const lcSearch = new DynamicStructuredTool({
  name: "search_db",
  description: "Search the product catalog.",
  schema: searchSchema,
  func: async (input) => productDb.query(input),
});

const pleachSearch = fromLangChainTool(lcSearch);

// Register through a plugin's `contributeTools` — the ergonomic path.
// Pass the plugin to `SessionRuntime({ plugins: [...] })`.
const langchainTools = definePleachPlugin("langchain-tools", {
  tools: [pleachSearch],
});
```

For bulk conversion use `fromLangChainTools(tools)` — same converter,
applied across an array.

Conversion notes documented in the package README cover the
LangChain features without a Pleach equivalent — callbacks scoped
to the tool, the `returnDirect` flag, the `tags`/`metadata` pass-
through. Anything the adapter can't carry across becomes a no-op
on the Pleach side; the converter doesn't silently change semantics.

The reverse — Pleach `ToolDefinition` → LangChain `Tool` — ships as
`toLangChainTool(def)`. Use it when a LangChain-driven agent needs
to call a Pleach-native tool:

```typescript
import { toLangChainTool } from "@pleach/langchain";

const lcTool = await toLangChainTool(myPleachToolDef);
// pass `lcTool` into a LangChain AgentExecutor's tools array.
```

## Calling a LangChain chat model as a Pleach provider [#calling-a-langchain-chat-model-as-a-pleach-provider]

`LangChainProvider` wraps any LangChain `BaseChatModel` and exposes it
through the Pleach `AgentProvider` contract. Use this when the
host already owns a configured LangChain model (custom provider, LCEL
chain composed upstream of the chat call, callback wiring) and wants
the Pleach runtime to drive the agent loop against that model.

```typescript
import { LangChainProvider } from "@pleach/langchain";
import { ChatOpenAI } from "@langchain/openai";
import { createPleachRuntime } from "@pleach/core/runtime";

const lcModel = new ChatOpenAI({ model: "gpt-4o-mini" });
// The constructor is positional: `new LangChainProvider(model, maxSteps=10)`.
const provider = new LangChainProvider(lcModel);

const runtime = createPleachRuntime({
  // `provider` is a top-level config slot on createPleachRuntime.
  provider,
});
```

Tool calls round-trip via the `fromLangChainTool` / `toLangChainTool`
converters, so LangChain-native streaming `tool_call_chunks` surface
to Pleach as the same final `tool_calls` shape the runtime expects.

## LangGraph-shaped storage adapters [#langgraph-shaped-storage-adapters]

Two adapter pairs let LangGraph storage co-exist with Pleach's
checkpointer + store contracts:

* **`LangGraphCheckpointerAdapter`** — wraps a LangGraph
  `BaseCheckpointSaver` so Pleach's `SessionRuntime` uses LangGraph
  storage as its checkpointer backend.
* **`LangGraphStoreAdapter`** — wraps a LangGraph `BaseStore` so
  Pleach's memory contract reads/writes against LangGraph's store.
* **`HarnessCheckpointSaver`** — the reverse: a LangGraph-shaped
  `BaseCheckpointSaver` backed by a Pleach checkpointer.
* **`HarnessEventLogCallback`** — a LangChain callback handler that
  writes model and tool callback events into the Pleach event log as
  `@pleach/core` event types. See
  [Recording a LangGraph run](#recording-a-langgraph-run).

The two `Harness*` (Pleach-under-LangChain) adapters also ship on their
own subpath, `@pleach/langchain/to-langchain`, matching the
`@pleach/langchain/from-langchain` direction — import from the subpath
to pull only the direction you use. The root barrel re-exports both.

```typescript
import {
  LangGraphCheckpointerAdapter,
  LangGraphStoreAdapter,
} from "@pleach/langchain";
import { MemorySaver, InMemoryStore } from "@langchain/langgraph";

const checkpointer = new LangGraphCheckpointerAdapter(new MemorySaver());
const store        = new LangGraphStoreAdapter(new InMemoryStore());

const runtime = createPleachRuntime({
  checkpointer,
  advanced: { store },   // store is not a top-level option
  /* ... */
});
```

The reverse direction (Pleach storage exposed as LangGraph storage) is
useful for a host running a LangGraph agent that wants the Pleach
event log as its callback sink and the Pleach checkpointer as its
state store — without rewriting the agent body.

## Recording a LangGraph run [#recording-a-langgraph-run]

Pass `HarnessEventLogCallback` in the run's `callbacks`. The first
argument is any sink with `write(event)`; the second is the session
id every row carries.

```typescript
import { HarnessEventLogCallback } from "@pleach/langchain/to-langchain";

const sink = { write: async (event: unknown) => { /* persist the row */ } };
const callback = new HarnessEventLogCallback(sink, "lg-demo");

await graph.invoke(
  { messages: [{ role: "user", content: "hello" }] },
  { callbacks: [callback] },
);
```

The handler has a fixed `name`, so LangChain
keeps it as passed and its hooks fire in a real LangGraph run. It sets
`awaitHandlers`, so each write finishes before LangChain continues and
rows land in order.

Each row uses a `@pleach/core` event type with core's payload keys,
except the model-start row:

| Callback          | `type`                                | `payload`                                                                                    |
| ----------------- | ------------------------------------- | -------------------------------------------------------------------------------------------- |
| model call starts | `domain.langchain.model_call_started` | `model`, `prompt_count`                                                                      |
| model call ends   | `llm.turn`                            | `model`, `input_tokens`, `output_tokens`, `tool_call_count`, `depth`                         |
| model call errors | `error.propagated`                    | `message` (up to 1000 characters), `error_code` (the error's `name`), `stack_preview`        |
| tool starts       | `tool.started`                        | `tool_name`; `args_preview` only with previews on                                            |
| tool ends         | `tool.completed`                      | `tool_name`, `duration_ms`; `output_preview` only with previews on                           |
| tool errors       | `tool.failed`                         | `tool_name`, `error` (up to 1000 characters), `duration_ms`, `failure_class: "unclassified"` |

* **Envelope.** Each row is `{ type, chatId?, sessionId, runId,
  parentRunId?, toolCallId?, timestamp, payload }`. `chatId` is omitted
  unless you pass the `chatId` option, and `parentRunId` is omitted for a
  root run. Core's event-log writers don't persist `runId` or
  `parentRunId`, so the payload also carries `run_id` and
  `parent_run_id`.
* **Names.** `llm.turn.model` is the model the provider reported
  serving, else the model named at start. The tool name comes from the
  serialized tool's `name`, then `runName`, then the last segment of
  its serialized id. A class-based `StructuredTool` subclass is
  recorded under its class name unless you pass `runName`.
* **`depth`** counts this handler's `llm.turn` rows from 0 in the order
  calls end, across every run. It is not a graph step.
* **`chatId`.** Core's `EventLogWriter` files a row under its `chatId`,
  so pass the chat the run belongs to when you store rows through it.
  With `auditLedger`'s `multiTenant`, the `chatId` option is refused and
  `resolveRunScope` returns each run's `chatId` instead.
* **No cost.** A LangChain result carries no cost, so none is recorded.

Tool arguments and results can hold personal data, so tool rows carry
the tool name only by default. Options go in the third constructor
argument:

```typescript
const callback = new HarnessEventLogCallback(sink, "lg-demo", {
  chatId: "chat-42",             // written on every row; omitted, rows carry no chatId
  enrichToolEventPreviews: true, // add args_preview and output_preview (500-character bound)
  maxPendingRuns: 1000,          // unfinished model and tool runs remembered, each; default 1000
});
```

Past `maxPendingRuns`, the oldest unfinished run is forgotten, and its
end row reads `tool_name: "unknown"` with no `duration_ms`.

**Breaking for readers of older rows.** Earlier releases wrote
`model_call_started`, `model_call_completed`, `model_call_error`,
`tool_call_started`, `tool_call_completed` and `tool_call_error` with
other payload keys, and recorded tool arguments and results by
default. Map those types to the table above when you read both.

## Keeping an `AgentExecutor` [#keeping-an-agentexecutor]

The 0.x surface is intentionally narrow. Two paths to know:

* **Importing history.** There's no event-log importer. Session
  history does import: pass
  `importLangGraphThread(saver, threadId)` (or your own
  `{ id, messages }` objects) to `importSessions` from
  `@pleach/core/sessions`. It writes history only, not event-log or
  audit rows. Event-log rows are written through an
  `eventLogWriter` (see the [Event log](/docs/event-log) reference).
* **`AgentExecutor`.** There's no executor wrapper. The migration
  path uses `LangChainProvider` plus
  `fromLangChainTools` to run the Pleach loop against the LangChain
  model + tools, rather than wrapping LangChain's agent loop. If you
  need to keep an `AgentExecutor` running, instrument it with
  `HarnessEventLogCallback` so its callbacks land in the Pleach
  event log alongside the Pleach loop's rows.

## Back-compat boundary [#back-compat-boundary]

The package sits below `1.0.0` because the converter signatures are
still settling. Like every `@pleach/*` SKU below `1.0.0`, pin it
exactly (see [Packages](/docs/packages) on why a caret range is the
wrong choice here):

```json
{
  "dependencies": {
    "@pleach/langchain": "0.1.0"
  }
}
```

Kinds of changes consumers should expect across minors before 1.0:

* **Export renames.** Function names may shift as the surface
  consolidates pre-1.0; pin patch-only against the package README.
* **Converter signature tweaks.** Optional-argument shapes for the
  three converters are still narrowing — expect new required
  options as edge cases get formalized.
* **Peer-dep range changes.** Supported `@langchain/core` and
  `@langchain/langgraph-checkpoint` ranges may move as LangChain itself moves
  through majors.

Read the package CHANGELOG before each upgrade. The release notes
flag any breaking change in the minor that introduces it.

## Not in scope [#not-in-scope]

* **LangSmith parity.** Distributed-tracing parity with LangSmith
  is out of scope for this adapter. For tracing, use OTel via
  [Observability](/docs/observability) — the audit ledger plus an
  OTel exporter covers the same trace store role.
* **LangGraph node-level bridging.** The adapter operates at the
  tool / message / executor boundary, not at the LangGraph state-
  graph node level. A LangGraph migration is the
  [migration guide's](/docs/migrating-from-langchain) territory.
* **Vector store / retriever wrapping.** LangChain's retrieval
  surface stays inside LangChain; expose it to Pleach as a
  `defineTool` call, the same way the migration guide describes.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Migrating from LangChain" href="/docs/migrating-from-langchain" description="The one-time migration shape — when the adapter isn't the right tool." />

  <Card title="MCP integration" href="/docs/mcp-integration" description="The sibling integration page — Model Context Protocol in both directions." />

  <Card title="Host adapter" href="/docs/host-adapter" description="The dynamic-import seam for hosts mid-migration." />

  <Card title="Plugin contract" href="/docs/plugin-contract" description="Wrapping the LangChain bridge as a `HarnessPlugin` contribution." />
</Cards>
