Skip to content

The Open Standard for Generative UI

Add @openuidev/langchain package (#920)

Visharad Kashyapa2e0ec0c8c50
diff --git a/.github/workflows/publish-npm-package.yml b/.github/workflows/publish-npm-package.yml
index ce92bf762..958705f95 100644
--- a/.github/workflows/publish-npm-package.yml
+++ b/.github/workflows/publish-npm-package.yml
@@ -17,6 +17,7 @@ on:
- react-lang
- react-email
- lang-core
+ - langchain
- openui-cli
- svelte-lang
- vue-lang
diff --git a/README.md b/README.md
index 1458aa0f9..1d05f6ed4 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,7 @@ Try it yourself in the [Playground](https://www.openui.com/playground): generate
| Package | Best for | Description |
| :--------------------------------------------------------------------------------------------------------- | :----------------------------------------------- | :----------------------------------------------------------------------------------------------------------- |
| [`@openuidev/lang-core`](./packages/lang-core) | Framework-agnostic parsing and prompt generation | Core parser, prompt-generation, runtime-evaluation, and type layer with no React, Vue, or Svelte dependency |
+| [`@openuidev/langchain`](./packages/langchain) | LangChain and LangGraph agents | Agent transformer and server helpers that stream OpenUI through AG-UI |
| [`@openuidev/react-lang`](./packages/react-lang) | React rendering runtimes | Define component libraries, generate prompts, and render streamed OpenUI Lang in React |
| [`@openuidev/react-headless`](./packages/react-headless) | Bring-your-own React chat UI | Headless chat state, streaming adapters, and message format converters |
| [`@openuidev/react-ui`](./packages/react-ui) | Fastest path to a full React chat experience | Prebuilt chat layouts, standalone UI primitives, and two built-in component libraries |
@@ -113,6 +114,9 @@ npm install @openuidev/react-lang @openuidev/react-ui
# Framework-agnostic backend or Edge prompt generation
npm install @openuidev/lang-core
+# LangChain/LangGraph agent and server integration
+npm install @openuidev/langchain @langchain/langgraph
+
# Vue or Svelte runtime
npm install @openuidev/vue-lang
npm install @openuidev/svelte-lang
@@ -158,6 +162,7 @@ openui/
│ ├── react-ui/ # Prebuilt chat layouts & component libraries
│ ├── react-email/ # React Email component library for generated emails
│ ├── lang-core/ # Framework-agnostic parser, prompt, and runtime layer
+│ ├── langchain/ # LangChain/LangGraph streaming integration
│ ├── vue-lang/ # Vue runtime bindings for OpenUI Lang
│ ├── svelte-lang/ # Svelte runtime bindings for OpenUI Lang
│ ├── browser-bundle/ # Script-tag bundle for CDN / iframe / no-build embeds
diff --git a/docs/content/docs/openui-lang/examples/langchain-chat.mdx b/docs/content/docs/openui-lang/examples/langchain-chat.mdx
new file mode 100644
index 000000000..0d15d3864
--- /dev/null
+++ b/docs/content/docs/openui-lang/examples/langchain-chat.mdx
@@ -0,0 +1,193 @@
+---
+title: LangChain Chat
+description: Stream OpenUI generative interfaces from a DeepAgents graph with the supported @openuidev/langchain integration.
+---
+
+OpenUI's renderer is transport-agnostic: it turns streamed OpenUI Lang into
+interactive components no matter which agent produced it. This example uses a
+[DeepAgents](https://docs.langchain.com/oss/javascript/deepagents/overview)
+agent running on LangGraph and the supported `@openuidev/langchain` integration
+to deliver its response as AG-UI events.
+
+[View source on GitHub →](https://github.com/thesysdev/openui/tree/main/examples/langchain-chat)
+
+<div className="bg-[rgba(0,0,0,0.05)] dark:bg-gray-900 rounded-2xl h-[500px] flex p-2">
+ <video
+ src="/videos/langchain-chat.mp4"
+ playsInline
+ muted
+ preload="metadata"
+ className="w-full rounded-lg m-auto"
+ autoPlay
+ loop
+ />
+</div>
+
+## Architecture
+
+```text
+browser ──fetch /api/chat──▶ Next.js route ──protocol v2──▶ LangGraph server
+ ▲ @openuidev/langchain (DeepAgent + tools)
+ └──────────── AG-UI SSE ◀──────────┘ │
+ parsed by agUIAdapter() custom:openui ◀─────┘
+```
+
+The example runs a LangGraph server for the agent and a Next.js app for the UI.
+The browser talks only to the app's `/api/chat` route. That keeps the LangGraph
+deployment URL and optional LangSmith API key on the server.
+
+The integration has two halves:
+
+- `openUIStreamTransformer` runs with the graph and maps LangGraph protocol-v2
+ `messages` and `tools` events to AG-UI events on `custom:openui`.
+- `createLangChainStreamResponse` runs in the app route, starts a stateless
+ graph run, adds AG-UI run lifecycle events, and relays the custom channel as
+ AG-UI SSE.
+
+## Add the agent transformer
+
+Pass the transformer factory to the agent's `streamTransformers` option:
+
+```ts
+import { openUIStreamTransformer } from "@openuidev/langchain/transformer";
+import { createDeepAgent } from "deepagents";
+
+export const graph = createDeepAgent({
+ model: `openai:${process.env.OPENAI_MODEL ?? "gpt-5.5"}`,
+ tools: [getWeather, getStockPrice, searchWeb],
+ systemPrompt: SYSTEM_PROMPT,
+ streamTransformers: [openUIStreamTransformer],
+});
+```
+
+The example's `SYSTEM_PROMPT` includes the prompt generated from its OpenUI
+component library. That teaches the agent to return OpenUI Lang after it uses
+the mock weather, stock-price, and research tools.
+
+The integration package does not depend on DeepAgents. It works with any agent
+surface that accepts LangGraph stream transformers.
+
+## Add the proxy route
+
+The route is a thin Web-standard adapter:
+
+```ts
+import { createLangChainStreamResponse } from "@openuidev/langchain";
+
+export const runtime = "nodejs";
+
+export async function POST(request: Request) {
+ return createLangChainStreamResponse(request, {
+ apiUrl: process.env.LANGGRAPH_API_URL ?? "http://localhost:2024",
+ assistantId: process.env.LANGGRAPH_ASSISTANT_ID ?? "agent",
+ apiKey: process.env.LANGSMITH_API_KEY,
+ debug: process.env.NODE_ENV !== "production",
+ });
+}
+```
+
+`createLangChainStreamResponse` validates AG-UI messages, converts text and
+multimodal content to LangChain messages, preserves complete tool transcripts,
+removes incomplete tool history that cannot be replayed safely, and calls the
+LangGraph protocol-v2 endpoints. Aborting the browser request also aborts the
+upstream subscription and run. Its temporary LangGraph thread is deleted after
+the run completes. The integration requires a server with `custom:*` and root
+`lifecycle` event-channel support; the tested local baseline is
+`@langchain/langgraph-cli` 1.4.x.
+
+Use the lower-level `streamOpenUI()` export when your route needs to build the
+graph input or response itself.
+
+## Connect the frontend
+
+The proxy already returns AG-UI, so no LangChain-specific browser adapter or
+message conversion is needed:
+
+```tsx
+import { AgentInterface, agUIAdapter, fetchLLM, openuiChatLibrary } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: agUIAdapter(),
+});
+
+<AgentInterface
+ llm={llm}
+ componentLibrary={openuiChatLibrary}
+ agentName="OpenUI + DeepAgents Chat"
+/>;
+```
+
+## Project layout
+
+```text
+examples/langchain-chat/
+|- src/app/page.tsx # AgentInterface with agUIAdapter()
+|- src/app/api/chat/route.ts # createLangChainStreamResponse()
+|- src/agent/agent.ts # DeepAgent with openUIStreamTransformer()
+|- src/agent/tools.ts # Mock weather, finance, and research tools
+|- src/library.ts # Components the model can render
+|- src/generated/ # Generated OpenUI system prompt
+|- langgraph.json # Local and deployed graph configuration
+```
+
+## Run the example
+
+From `examples/langchain-chat`, install dependencies and copy the environment
+template:
+
+```bash tab="pnpm" tab-group="pkg"
+pnpm install
+cp .env.example .env
+```
+
+```bash tab="bun" tab-group="pkg"
+bun install
+cp .env.example .env
+```
+
+```bash tab="yarn" tab-group="pkg"
+yarn install
+cp .env.example .env
+```
+
+```bash tab="npm" tab-group="pkg"
+npm install
+cp .env.example .env
+```
+
+Add `OPENAI_API_KEY` to `.env`, then start the LangGraph server and Next.js app
+together:
+
+```bash tab="pnpm" tab-group="pkg"
+pnpm dev
+```
+
+```bash tab="bun" tab-group="pkg"
+bun dev
+```
+
+```bash tab="yarn" tab-group="pkg"
+yarn dev
+```
+
+```bash tab="npm" tab-group="pkg"
+npm run dev
+```
+
+Open [http://localhost:3000](http://localhost:3000) and try "Weather in Tokyo"
+or "AAPL stock price".
+
+## Deploy to LangGraph Platform
+
+The included `langgraph.json` can be deployed without changing app code. Point
+the proxy at the deployment through `.env`:
+
+```bash
+LANGGRAPH_API_URL=https://your-deployment.us.langgraph.app
+LANGGRAPH_ASSISTANT_ID=agent
+LANGSMITH_API_KEY=lsv2-...
+```
+
+`LANGSMITH_API_KEY` is sent as `x-api-key` only from the server route. Restart
+the app after changing the environment.
diff --git a/docs/content/docs/openui-lang/examples/langgraph-chat.mdx b/docs/content/docs/openui-lang/examples/langgraph-chat.mdx
deleted file mode 100644
index 9e820b27f..000000000
--- a/docs/content/docs/openui-lang/examples/langgraph-chat.mdx
+++ /dev/null
@@ -1,235 +0,0 @@
----
-title: LangGraph Chat
-description: A multi-agent LangGraph supervisor that routes each message to a weather, finance, or research specialist and streams OpenUI Lang into live generative UI.
----
-
-OpenUI's renderer is transport-agnostic: it turns a stream of OpenUI Lang markup into interactive React components no matter how that stream is produced. This example produces it with a **multi-agent [LangGraph](https://langchain-ai.github.io/langgraphjs/) graph**: a supervisor routes each user message to one of three specialists (**weather**, **finance**, or **research**), and the chosen agent streams its answer as OpenUI Lang, which `<AgentInterface>` renders into cards, tables, and charts as the tokens arrive.
-
-Because every specialist shares the same OpenUI system prompt (generated from the component library), any agent you add automatically speaks generative UI.
-
-[View source on GitHub →](https://github.com/thesysdev/openui/tree/main/examples/langgraph-chat)
-
-<div className="bg-[rgba(0,0,0,0.05)] dark:bg-gray-900 rounded-2xl h-[500px] flex p-2">
- <video
- src="/videos/langgraph-chat.mp4"
- noControls
- playsInline
- muted
- preload="metadata"
- className="w-full rounded-lg m-auto"
- autoPlay
- loop
- />
-</div>
-
-## Architecture
-
-```
-browser ──fetch /api/chat──▶ Next.js route ──@langchain/langgraph-sdk──▶ LangGraph server
- ▲ │ (router → specialist
- └────── SSE (LangGraph) ───────┘ → tools → OpenUI Lang)
- parsed by langGraphAdapter()
-```
-
-The example runs **two processes**: the LangGraph server runs the graph (and the LLM), and the Next.js app serves the UI. The browser never talks to the LangGraph server directly. A thin Next.js proxy route opens a run, forwards the stream, and keeps the API key and deployment URL server-side.
-
-## Connecting the frontend
-
-The client is a single `<AgentInterface>` — the artifact chat interface. Its `llm.send` posts the conversation to the proxy, and `langGraphAdapter()` parses the LangGraph SSE stream that comes back:
-
-```tsx
-import {
- AgentInterface,
- langGraphAdapter,
- langGraphMessageFormat,
- type ChatLLM,
-} from "@openuidev/react-ui";
-import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";
-
-const llm: ChatLLM = {
- send: ({ messages, signal }) =>
- fetch("/api/chat", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- // Convert OpenUI messages to LangChain shape. The run is stateless,
- // so the full history is sent each turn.
- body: JSON.stringify({ messages: langGraphMessageFormat.toApi(messages) }),
- signal,
- }),
- streamProtocol: langGraphAdapter(),
-};
-
-<AgentInterface
- llm={llm}
- componentLibrary={openuiChatLibrary}
- agentName="OpenUI + LangGraph Chat"
-/>;
-```
-
-- `llm.send`: posts the conversation to the proxy; `langGraphMessageFormat.toApi` converts OpenUI messages into the LangChain message shape the graph expects
-- `llm.streamProtocol={langGraphAdapter()}`: parses LangGraph's `messages` SSE events back into streaming assistant text
-- `componentLibrary={openuiChatLibrary}`: maps OpenUI Lang nodes to the built-in component set (cards, tables, charts, forms)
-
-## The proxy route
-
-The browser posts messages already in LangChain format, and the route opens a **stateless** streaming run against the LangGraph server, forwarding its Server-Sent Events to the browser. Keeping the connection here is what lets you attach the API key and hide the deployment URL.
-
-```tsx
-import { Client } from "@langchain/langgraph-sdk";
-
-// Tokens from internal nodes (the supervisor's routing decision) must not
-// surface as assistant output.
-const INTERNAL_NODES = new Set(["router"]);
-
-const client = new Client({ apiUrl: API_URL, apiKey: API_KEY });
-
-const run = client.runs.stream(null, ASSISTANT_ID, {
- input: { messages: visibleMessages },
- streamMode: ["messages-tuple", "updates"],
- signal: req.signal,
-});
-
-for await (const chunk of run) {
- if (chunk.event?.startsWith("messages")) {
- const meta = Array.isArray(chunk.data) ? chunk.data[1] : undefined;
- if (meta?.langgraph_node && INTERNAL_NODES.has(meta.langgraph_node)) continue;
- // Normalize the event name to what langGraphAdapter() expects.
- send("messages", chunk.data);
- }
-}
-```
-
-The graph streams in `messages-tuple` mode; the proxy filters out the supervisor's tokens and re-emits the rest as `event: messages`, which is exactly what `langGraphAdapter()` consumes.
-
-## The multi-agent graph
-
-Each specialist owns one tool and a short role hint layered on top of the shared OpenUI prompt. The supervisor makes a single structured routing decision, then the chosen specialist runs its own ReAct loop (`agent → tools → agent → … → END`):
-
-```tsx
-const SPECIALISTS = {
- weather: { tools: [getWeather], hint: "You are the weather specialist. Use get_weather, then present conditions and the forecast as generative UI..." },
- finance: { tools: [getStockPrice], hint: "You are the finance specialist. Use get_stock_price, then present the quote and day range as generative UI..." },
- research: { tools: [searchWeb], hint: "You are the research specialist. Use search_web, then summarize the findings as generative UI..." },
-};
-
-function agentNode(specialist) {
- const { tools, hint } = SPECIALISTS[specialist];
- const boundModel = chatModel.bindTools(tools);
- // Every specialist shares the generated OpenUI prompt. This is what makes
- // each agent's streamed output render as generative UI.
- const systemMessage = new SystemMessage(`${OPENUI_SYSTEM_PROMPT}\n\n${hint}`);
- return async (state) => ({ messages: [await boundModel.invoke([systemMessage, ...state.messages])] });
-}
-
-export const graph = new StateGraph(AgentState)
- .addNode("router", router)
- .addNode("weather_agent", agentNode("weather"))
- .addNode("weather_tools", new ToolNode(SPECIALISTS.weather.tools))
- // ...finance and research nodes wired the same way
- .addEdge(START, "router")
- .addConditionalEdges("router", (state) => state.next, {
- weather: "weather_agent",
- finance: "finance_agent",
- research: "research_agent",
- })
- .compile();
-```
-
-The supervisor (`router`) uses `withStructuredOutput` against a small Zod enum to pick exactly one specialist, defaulting to `research` if routing fails. The tools (`get_weather`, `get_stock_price`, `search_web`) return canned-but-plausible JSON, so the example runs without any third-party API keys. Swap the bodies for real API calls when adapting it.
-
-Add a specialist by extending the `SPECIALISTS` map and wiring a matching `*_agent` / `*_tools` node pair; it inherits the OpenUI prompt for free.
-
-## Project layout
-
-```
-examples/langgraph-chat/
-|- src/app/page.tsx # <AgentInterface> wired to langGraphAdapter()
-|- src/app/api/chat/route.ts # Stateless proxy to the LangGraph server (SSE)
-|- src/agent/graph.ts # Supervisor + specialist ReAct loops
-|- src/agent/tools.ts # Mock weather / finance / research tools
-|- src/library.ts # The OpenUI components the model can render
-|- src/generated/ # Generated OpenUI system prompt
-|- langgraph.json # Graph config for `langgraphjs dev` / deploy
-```
-
-## Run the example
-
-This example runs **two processes**, so use two terminals. Run these commands from `examples/langgraph-chat`.
-
-1. Install dependencies and create a `.env` from the template:
-
-```bash tab="pnpm" tab-group="pkg"
-cd examples/langgraph-chat
-pnpm install
-cp .env.example .env
-```
-
-```bash tab="bun" tab-group="pkg"
-cd examples/langgraph-chat
-bun install
-cp .env.example .env
-```
-
-```bash tab="yarn" tab-group="pkg"
-cd examples/langgraph-chat
-yarn install
-cp .env.example .env
-```
-
-```bash tab="npm" tab-group="pkg"
-cd examples/langgraph-chat
-npm install
-cp .env.example .env
-```
-
-Add your `OPENAI_API_KEY` to `.env`. It is read by the **LangGraph server** (which runs the LLM), so it belongs next to `langgraph.json`. The Next.js app only needs the `LANGGRAPH_*` variables, which already default to the local server.
-
-2. **Terminal 1: LangGraph server** (generates the OpenUI prompt, then hot-reloads the graph on `:2024`):
-
-```bash tab="pnpm" tab-group="pkg"
-pnpm langgraph:dev
-```
-
-```bash tab="yarn" tab-group="pkg"
-yarn langgraph:dev
-```
-
-```bash tab="bun" tab-group="pkg"
-bun langgraph:dev
-```
-
-```bash tab="npm" tab-group="pkg"
-npm langgraph:dev
-```
-
-3. **Terminal 2: Next.js app**:
-
-```bash tab="pnpm" tab-group="pkg"
-pnpm dev
-```
-
-```bash tab="bun" tab-group="pkg"
-bun dev
-```
-
-```bash tab="yarn" tab-group="pkg"
-yarn dev
-```
-
-```bash tab="npm" tab-group="pkg"
-npm run dev
-```
-
-Open [http://localhost:3000](http://localhost:3000) and try a starter such as "Weather in Tokyo" or "AAPL stock price".
-
-## Deploy to LangGraph Platform
-
-The folder already ships a `langgraph.json`, so you can deploy the graph and point the app at the deployment with no app code changes, just update `.env`:
-
-```bash
-LANGGRAPH_API_URL=https://your-deployment.us.langgraph.app
-LANGGRAPH_ASSISTANT_ID=agent # graph name, or a created assistant id
-LANGSMITH_API_KEY=lsv2-... # auth for the deployment
-```
-
-The SDK sends `LANGSMITH_API_KEY` as `x-api-key` from the server side only. Restart `pnpm dev` after changing `.env`.
diff --git a/docs/content/docs/openui-lang/meta.json b/docs/content/docs/openui-lang/meta.json
index 89cd30c0f..ad62f7d9f 100644
--- a/docs/content/docs/openui-lang/meta.json
+++ b/docs/content/docs/openui-lang/meta.json
@@ -30,7 +30,7 @@
"examples/shadcn-chat",
"examples/react-native",
"examples/vercel-ai-chat",
- "examples/langgraph-chat",
+ "examples/langchain-chat",
"examples/react-email",
"---Harnesses---",
"examples/harnesses/pi-agent-harness",
diff --git a/docs/public/videos/langgraph-chat.mp4 b/docs/public/videos/langchain-chat.mp4
similarity index 100%
rename from docs/public/videos/langgraph-chat.mp4
rename to docs/public/videos/langchain-chat.mp4
diff --git a/examples/langchain-chat/README.md b/examples/langchain-chat/README.md
index ec2be68b2..242847942 100644
--- a/examples/langchain-chat/README.md
+++ b/examples/langchain-chat/README.md
@@ -4,9 +4,10 @@ A generative-UI chat app where the responses are produced by a
[deepagents](https://www.npmjs.com/package/deepagents) agent and rendered live
with [OpenUI](https://openui.com).
-The agent has mock **weather**, **finance**, and **research** tools. Its
-LangGraph protocol stream is transformed locally into AG-UI events on a custom
-`openui` channel, so the browser can use OpenUI's AG-UI stream adapter.
+The agent has mock **weather**, **finance**, and **research** tools.
+`@openuidev/langchain` transforms its LangGraph protocol stream into AG-UI
+events on a custom `openui` channel, so the browser can use OpenUI's AG-UI
+stream adapter.
```
browser ──fetch /api/chat──▶ Next.js route ──protocol v2──▶ LangGraph server
@@ -17,19 +18,20 @@ browser ──fetch /api/chat──▶ Next.js route ──protocol v2──▶
## How it connects
-| Piece | File | Role |
-| --- | --- | --- |
-| Frontend | `src/app/page.tsx` | `<AgentInterface llm={fetchLLM({ url: "/api/chat", streamAdapter: agUIAdapter() })}>` using the AG-UI stream protocol. |
-| Proxy | `src/app/api/chat/route.ts` | Converts AG-UI messages to LangChain messages, starts a protocol-v2 run, and relays `custom:openui` as AG-UI SSE. Keeps the API key + deployment URL server-side. |
-| Graph | `src/agent/agent.ts` | `createDeepAgent` with the generated OpenUI system prompt, the mock tools, and the local stream transformer. |
-| Transformer | `src/agent/openui-transformer.ts` | Maps root LangGraph protocol `messages` events into AG-UI events and emits them as `custom:openui`. |
-| Stream helper | `src/lib/stream-openui.ts` | Talks to `/threads/:id/stream/events` and `/threads/:id/commands` using raw fetch. |
-| Tools | `src/agent/tools.ts` | Mock `get_weather` / `get_stock_price` / `search_web` (no external keys needed). |
-| Component library | `src/library.ts` | The OpenUI components the model is allowed to render. `pnpm generate:prompt` turns it into `src/generated/system-prompt.txt`. |
+| Piece | File | Role |
+| ----------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Frontend | `src/app/page.tsx` | `<AgentInterface llm={fetchLLM({ url: "/api/chat", streamAdapter: agUIAdapter() })}>` using the AG-UI stream protocol. |
+| Proxy | `src/app/api/chat/route.ts` | Uses `createLangChainStreamResponse` to convert AG-UI messages, start a protocol-v2 run, and relay `custom:openui` as AG-UI SSE. Keeps the API key + deployment URL server-side. |
+| Graph | `src/agent/agent.ts` | `createDeepAgent` with the generated OpenUI system prompt, the mock tools, and `openUIStreamTransformer`. |
+| Integration | `@openuidev/langchain` | Maps LangGraph protocol `messages` and `tools` into AG-UI events, adds run lifecycle events, starts stateless runs, and relays `custom:openui`. |
+| Tools | `src/agent/tools.ts` | Mock `get_weather` / `get_stock_price` / `search_web` (no external keys needed). |
+| Component library | `src/library.ts` | The OpenUI components the model is allowed to render. `pnpm generate:prompt` turns it into `src/generated/system-prompt.txt`. |
-The transformer is intentionally local to this example for now. It mimics the
-LangGraph protocol types instead of adding new toolkit dependencies, making it
-easy to extract later if the OpenUI team wants to publish a shared integration.
+The shared integration package uses Web-standard requests, responses, fetch,
+and streams. It does not depend on Next.js or DeepAgents.
+
+The local server uses `@langchain/langgraph-cli` 1.4.x because the integration
+requires agent-protocol-v2 `custom:*` and root `lifecycle` event channels.
## Getting started (local)
@@ -71,7 +73,8 @@ Open [http://localhost:3000](http://localhost:3000) and try a starter such as
> `OPENAI_API_KEY` is read by the **LangGraph server** (it runs the LLM), so it
> belongs in `.env` next to `langgraph.json`. The Next.js app only needs the
-> `LANGGRAPH_*` variables.
+> `LANGGRAPH_*` variables. The example route enables detailed upstream errors
+> outside production so a misconfigured graph id is visible during local setup.
## Using LangGraph Cloud / Platform
diff --git a/examples/langchain-chat/package.json b/examples/langchain-chat/package.json
index f8354cfb0..818f7e49f 100644
--- a/examples/langchain-chat/package.json
+++ b/examples/langchain-chat/package.json
@@ -14,12 +14,11 @@
"lint": "eslint"
},
"dependencies": {
- "@ag-ui/core": "^0.0.57",
"@langchain/core": "^1.2.1",
"@langchain/langgraph": "^1.4.5",
"@langchain/langgraph-sdk": "^1.9.18",
"@langchain/openai": "^1.5.2",
- "@langchain/protocol": "^0.0.18",
+ "@openuidev/langchain": "workspace:*",
"@openuidev/react-headless": "workspace:*",
"@openuidev/react-lang": "workspace:*",
"@openuidev/react-ui": "workspace:*",
@@ -31,7 +30,7 @@
"zod": "^4.0.0"
},
"devDependencies": {
- "@langchain/langgraph-cli": "^1.2.5",
+ "@langchain/langgraph-cli": "^1.4.3",
"@openuidev/cli": "workspace:*",
"@tailwindcss/postcss": "^4",
"@types/node": "catalog:",
diff --git a/examples/langchain-chat/src/agent/agent.ts b/examples/langchain-chat/src/agent/agent.ts
index 813a11d96..f423725c6 100644
--- a/examples/langchain-chat/src/agent/agent.ts
+++ b/examples/langchain-chat/src/agent/agent.ts
@@ -2,9 +2,9 @@ import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
+import { openUIStreamTransformer } from "@openuidev/langchain/transformer";
import { createDeepAgent } from "deepagents";
-import { openUIStreamTransformer } from "./openui-transformer";
import { getStockPrice, getWeather, searchWeb } from "./tools";
/**
diff --git a/examples/langchain-chat/src/agent/openui-transformer.ts b/examples/langchain-chat/src/agent/openui-transformer.ts
deleted file mode 100644
index e507c3202..000000000
--- a/examples/langchain-chat/src/agent/openui-transformer.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-import { EventType, type AGUIEvent } from "@ag-ui/core";
-import { StreamChannel } from "@langchain/langgraph";
-import type { ProtocolEvent, StreamTransformer } from "@langchain/langgraph";
-import type { ContentBlock, MessagesData } from "@langchain/protocol";
-
-/**
- * Remote channel name. The LangGraph stream mux auto-forwards every
- * `channel.push()` as a `custom:openui` protocol event, which remote clients
- * receive by subscribing to the `custom:openui` channel.
- */
-const OPENUI_CHANNEL_NAME = "openui";
-const OPENUI_CHANNEL_METHOD = `custom:${OPENUI_CHANNEL_NAME}`;
-
-const TOOL_BLOCK_TYPES = new Set([
- "tool_call",
- "tool_call_chunk",
- "server_tool_call",
- "server_tool_call_chunk",
-]);
-
-interface ToolCallState {
- id: string;
- name: string;
- started: boolean;
- ended: boolean;
-}
-
-/**
- * Projects the agent-protocol `messages` stream into AG-UI events and forwards
- * them to remote clients on the `custom:openui` channel.
- *
- * The protocol delivers `MessagesData` envelopes (`message-start`,
- * `content-block-start/delta/finish`, `message-finish`). The deep agent emits
- * its OpenUI Lang reply as a streamed text block on the second model turn
- * (after tool calls resolve); this transformer turns those deltas into the
- * `TEXT_MESSAGE_*` and `TOOL_CALL_*` events the OpenUI renderer understands.
- */
-export function openUIStreamTransformer(): StreamTransformer<{
- openui: StreamChannel<AGUIEvent>;
-}> {
- const channel = StreamChannel.remote<AGUIEvent>(OPENUI_CHANNEL_NAME);
-
- let currentMessageId: string = crypto.randomUUID();
- let textMessageId: string | undefined;
- let textStarted = false;
- let textEnded = false;
-
- const toolCallsByIndex = new Map<string, ToolCallState>();
-
- const emit = (event: AGUIEvent) => channel.push(event);
-
- const ensureTextStart = () => {
- if (textStarted) return;
- textMessageId = currentMessageId;
- emit({
- type: EventType.TEXT_MESSAGE_START,
- messageId: textMessageId,
- role: "assistant",
- } as AGUIEvent);
- textStarted = true;
- };
-
- const emitTextDelta = (delta: string) => {
- if (!delta) return;
- ensureTextStart();
- emit({
- type: EventType.TEXT_MESSAGE_CONTENT,
- messageId: textMessageId ?? currentMessageId,
- delta,
- } as AGUIEvent);
- };
-
- const endText = () => {
- if (!textStarted || textEnded) return;
- emit({
- type: EventType.TEXT_MESSAGE_END,
- messageId: textMessageId ?? currentMessageId,
- } as AGUIEvent);
- textEnded = true;
- };
-
- const startToolCall = (index: number | string, block: ContentBlock): ToolCallState | undefined => {
- if (!isToolBlock(block)) return undefined;
- const key = String(index);
-
- let state = toolCallsByIndex.get(key);
- if (!state) {
- state = {
- id: getToolCallId(block) ?? `tool-${key}`,
- name: getToolCallName(block) ?? "",
- started: false,
- ended: false,
- };
- toolCallsByIndex.set(key, state);
- }
-
- if (!state.started && state.name) {
- emit({
- type: EventType.TOOL_CALL_START,
- toolCallId: state.id,
- toolCallName: state.name,
- } as AGUIEvent);
- state.started = true;
-
- const initialArgs = getArgsString(block);
- if (initialArgs) emitToolArgs(state, initialArgs);
- }
-
- return state;
- };
-
- const emitToolArgs = (state: ToolCallState, delta: string) => {
- if (!delta || !state.started) return;
- emit({
- type: EventType.TOOL_CALL_ARGS,
- toolCallId: state.id,
- delta,
- } as AGUIEvent);
- };
-
- const endToolCall = (state: ToolCallState) => {
- if (state.ended || !state.started) return;
- emit({ type: EventType.TOOL_CALL_END, toolCallId: state.id } as AGUIEvent);
- state.ended = true;
- };
-
- const endAllToolCalls = () => {
- for (const state of toolCallsByIndex.values()) endToolCall(state);
- };
-
- const processMessages = (data: MessagesData) => {
- switch (data.event) {
- case "message-start": {
- currentMessageId = typeof data.id === "string" ? data.id : crypto.randomUUID();
- toolCallsByIndex.clear();
- return;
- }
-
- case "content-block-start": {
- const block = data.content;
- if (isTextBlock(block)) {
- ensureTextStart();
- const text = typeof block.text === "string" ? block.text : "";
- if (text) emitTextDelta(text);
- } else if (isToolBlock(block)) {
- startToolCall(data.index, block);
- }
- return;
- }
-
- case "content-block-delta": {
- const delta = data.delta;
- if (delta.type === "text-delta") {
- emitTextDelta(typeof delta.text === "string" ? delta.text : "");
- } else if (delta.type === "block-delta") {
- const fields = delta.fields as ContentBlock;
- if (isToolBlock(fields)) {
- const key = String(data.index);
- const state = toolCallsByIndex.get(key) ?? startToolCall(data.index, fields);
- if (state) emitToolArgs(state, getArgsString(fields));
- }
- }
- return;
- }
-
- case "content-block-finish": {
- const block = data.content;
- if (isToolBlock(block)) {
- const state = toolCallsByIndex.get(String(data.index)) ?? startToolCall(data.index, block);
- if (state) endToolCall(state);
- }
- return;
- }
-
- case "message-finish": {
- endAllToolCalls();
- endText();
- return;
- }
-
- case "error": {
- const message = "message" in data && typeof data.message === "string"
- ? data.message
- : "LangGraph message stream error";
- emit({ type: EventType.RUN_ERROR, message } as AGUIEvent);
- endText();
- return;
- }
-
- default:
- return;
- }
- };
-
- return {
- init: () => ({ openui: channel }),
- process: (event: ProtocolEvent) => {
- // Ignore the events we forward ourselves to avoid re-entrant processing.
- if (event.method === OPENUI_CHANNEL_METHOD) return true;
- if (event.method !== "messages") return true;
-
- processMessages(event.params.data as MessagesData);
- return true;
- },
- finalize: () => {
- endAllToolCalls();
- endText();
- },
- fail: (err) => {
- emit({
- type: EventType.RUN_ERROR,
- message: err instanceof Error ? err.message : "LangGraph run failed",
- } as AGUIEvent);
- endText();
- },
- };
-}
-
-function isTextBlock(block: ContentBlock): boolean {
- return block.type === "text";
-}
-
-function isToolBlock(block: ContentBlock): boolean {
- return TOOL_BLOCK_TYPES.has(block.type);
-}
-
-function getToolCallId(block: ContentBlock): string | undefined {
- const id = (block as { id?: unknown }).id;
- return typeof id === "string" && id.length > 0 ? id : undefined;
-}
-
-function getToolCallName(block: ContentBlock): string | undefined {
- const name = (block as { name?: unknown }).name;
- return typeof name === "string" && name.length > 0 ? name : undefined;
-}
-
-function getArgsString(block: ContentBlock): string {
- const args = (block as { args?: unknown }).args;
- if (typeof args === "string") return args;
- if (args != null && typeof args === "object") return JSON.stringify(args);
- return "";
-}
diff --git a/examples/langchain-chat/src/app/api/chat/route.ts b/examples/langchain-chat/src/app/api/chat/route.ts
index 31006bde0..c6e718650 100644
--- a/examples/langchain-chat/src/app/api/chat/route.ts
+++ b/examples/langchain-chat/src/app/api/chat/route.ts
@@ -1,4 +1,4 @@
-import { createLangChainStreamResponse } from "@/lib/langchain-stream-response";
+import { createLangChainStreamResponse } from "@openuidev/langchain";
import { NextRequest } from "next/server";
export const runtime = "nodejs";
@@ -19,5 +19,7 @@ export async function POST(req: NextRequest) {
return createLangChainStreamResponse(req, {
apiUrl: API_URL,
assistantId: ASSISTANT_ID,
+ apiKey: process.env.LANGSMITH_API_KEY,
+ debug: process.env.NODE_ENV !== "production",
});
}
diff --git a/examples/langchain-chat/src/lib/langchain-stream-response.ts b/examples/langchain-chat/src/lib/langchain-stream-response.ts
deleted file mode 100644
index 6d015c34e..000000000
--- a/examples/langchain-chat/src/lib/langchain-stream-response.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-import type { Message } from "@ag-ui/core";
-
-import { streamOpenUI } from "@/lib/stream-openui";
-
-/**
- * A LangGraph/LangChain input message, i.e. the `{ type, content, ... }` shape
- * the graph expects on its `messages` input (as opposed to the AG-UI
- * `{ role, content, ... }` shape the browser sends).
- */
-interface LangGraphInputMessage {
- /** LangChain message type: `"human" | "ai" | "tool" | "system"`. */
- type: string;
- content?: unknown;
- tool_calls?: unknown;
- tool_call_id?: string;
- [key: string]: unknown;
-}
-
-/** A single AG-UI assistant tool call, as sent by the browser. */
-type ToolCall = NonNullable<Extract<Message, { role: "assistant" }>["toolCalls"]>[number];
-
-/**
- * Configuration for {@link createLangChainStreamResponse}.
- */
-export interface CreateLangChainStreamResponseOptions {
- /**
- * Base URL of the LangGraph server (agent protocol v2), e.g.
- * `http://localhost:2024`.
- */
- apiUrl: string;
- /** The id of the graph/assistant to run (its registered `graph_id`). */
- assistantId: string;
- /** Optional API key forwarded as `x-api-key` (required for LangSmith). */
- apiKey?: string;
-}
-
-/**
- * Turns an incoming chat request into a streaming OpenUI Server-Sent Events
- * `Response`, suitable for returning directly from a route handler.
- *
- * It reads `{ messages }` (AG-UI format) from the request body, converts them
- * to LangChain input messages, strips internal tool history that must not be
- * replayed, starts the graph over the protocol-v2 endpoints via
- * {@link streamOpenUI}, and relays only the custom OpenUI channel back to the
- * browser. The request's `signal` is wired through so an aborted/disconnected
- * client tears down the upstream run.
- *
- * @param request - The incoming request (its JSON body and abort signal are used).
- * @param options - LangGraph connection settings, see
- * {@link CreateLangChainStreamResponseOptions}.
- * @returns A `Response` streaming `text/event-stream` AG-UI events.
- */
-export async function createLangChainStreamResponse(
- request: Request,
- options: CreateLangChainStreamResponseOptions,
-): Promise<Response> {
- const { messages = [] } = (await request.json()) as { messages?: Message[] };
- const langChainMessages = toLangChainMessages(messages);
- const visibleMessages = stripInternalToolHistory(langChainMessages);
-
- const readable = streamOpenUI({
- apiUrl: options.apiUrl,
- assistantId: options.assistantId,
- apiKey: options.apiKey,
- input: { messages: visibleMessages },
- signal: request.signal,
- });
-
- return new Response(readable, {
- headers: {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache, no-transform",
- Connection: "keep-alive",
- },
- });
-}
-
-/**
- * The browser stores the specialist's streamed tool call and final answer as
- * one assistant message, but it does not store the ToolNode result. Replaying
- * that partial tool transcript makes OpenAI reject the next request. Tool
- * execution belongs to the current graph run, so retain only visible chat
- * history between stateless runs.
- */
-function stripInternalToolHistory(messages: LangGraphInputMessage[]): LangGraphInputMessage[] {
- return messages.flatMap((message) => {
- if (message.type === "tool") return [];
- if (message.type !== "ai" || !message.tool_calls) return [message];
-
- const visibleMessage = { ...message };
- delete visibleMessage.tool_calls;
- return [visibleMessage];
- });
-}
-
-/**
- * Converts AG-UI messages (`{ role, content, ... }`) into LangChain input
- * messages (`{ type, content, ... }`) understood by the graph.
- */
-function toLangChainMessages(messages: Message[]): LangGraphInputMessage[] {
- return messages.map((message) => {
- switch (message.role) {
- case "user":
- return { type: "human", content: extractContent(message.content) };
- case "assistant": {
- const result: LangGraphInputMessage = { type: "ai", content: message.content ?? "" };
- if (message.toolCalls?.length) {
- result.tool_calls = message.toolCalls.map(toLangChainToolCall);
- }
- return result;
- }
- case "tool":
- return {
- type: "tool",
- content: message.content,
- tool_call_id: message.toolCallId,
- };
- case "system":
- return { type: "system", content: message.content };
- case "developer":
- return { type: "system", content: message.content };
- default:
- return { type: "system", content: "" };
- }
- });
-}
-
-/** Maps an AG-UI tool call to the LangChain `{ id, name, args }` shape. */
-function toLangChainToolCall(toolCall: ToolCall) {
- return {
- id: toolCall.id,
- name: toolCall.function.name,
- args: safeParseArgs(toolCall.function.arguments),
- };
-}
-
-/**
- * Flattens AG-UI message content (string or content blocks) into the plain
- * text the graph expects, keeping only `text` blocks.
- */
-function extractContent(content: Message["content"]): string {
- if (typeof content === "string") return content;
- if (!Array.isArray(content)) return "";
- return content
- .filter((block) => block.type === "text")
- .map((block) => block.text)
- .join("");
-}
-
-/**
- * Parses serialized tool-call arguments as JSON, falling back to the raw
- * string when the arguments are not valid JSON.
- */
-function safeParseArgs(args: string): Record<string, unknown> | string {
- try {
- return JSON.parse(args) as Record<string, unknown>;
- } catch {
- return args;
- }
-}
diff --git a/examples/langchain-chat/src/lib/stream-openui.ts b/examples/langchain-chat/src/lib/stream-openui.ts
deleted file mode 100644
index dfdb48061..000000000
--- a/examples/langchain-chat/src/lib/stream-openui.ts
+++ /dev/null
@@ -1,402 +0,0 @@
-import { EventType, type AGUIEvent } from "@ag-ui/core";
-
-/**
- * Options for {@link streamOpenUI}.
- */
-interface StreamOpenUIOptions {
- /**
- * Base URL of the LangGraph server (agent protocol v2), e.g.
- * `http://localhost:2024`. Trailing slashes are stripped before use.
- */
- apiUrl: string;
- /**
- * The id of the graph/assistant to run (the `graph_id` registered with the
- * LangGraph server, e.g. `"agent"`).
- */
- assistantId: string;
- /**
- * Optional API key forwarded as the `x-api-key` header (required by
- * LangSmith deployments, omitted for local `langgraphjs dev`).
- */
- apiKey?: string;
- /**
- * The run input handed to the graph — typically `{ messages: [...] }` in
- * LangChain message format. Kept as `unknown` since this helper does not
- * interpret it.
- */
- input: unknown;
- /**
- * Caller's abort signal (Next.js aborts this when the browser disconnects).
- * Aborting tears down the upstream LangGraph fetches and closes the stream.
- */
- signal?: AbortSignal;
-}
-
-/**
- * A single Server-Sent Events frame parsed out of the LangGraph response body,
- * reduced to the two fields this helper cares about.
- */
-interface ProtocolSSEEvent {
- /** The SSE `event:` field, e.g. `"custom"` or `"custom:openui"`. */
- event: string;
- /** The concatenated SSE `data:` field (raw JSON string, not yet parsed). */
- data: string;
-}
-
-/**
- * The agent-protocol-v2 envelope carried in the SSE `data:` field. The payload
- * of interest lives under `params.data` (for `custom` channels this is itself a
- * {@link NamedCustomPayload}).
- */
-interface ProtocolEvent {
- /** Protocol method that produced the event, e.g. `"messages"` or `"custom"`. */
- method?: string;
- params: {
- /** Channel payload; for `custom:openui` this is a {@link NamedCustomPayload}. */
- data?: unknown;
- };
-}
-
-/**
- * The shape the LangGraph mux uses to forward a named custom channel: the
- * server emits `event: custom` with `{ name: "openui", payload: <AGUIEvent> }`
- * rather than `event: custom:openui` with the bare event, so the channel name
- * must be read from `name` and the real event unwrapped from `payload`.
- */
-interface NamedCustomPayload {
- /** Custom channel name; only `"openui"` payloads are relayed. */
- name?: string;
- /** The actual {@link AGUIEvent} emitted by the transformer. */
- payload?: unknown;
-}
-
-const encoder = new TextEncoder();
-
-/**
- * Drives an agent-protocol-v2 run on a LangGraph server and relays the
- * transformer's AG-UI events to the browser as a Server-Sent Events stream.
- *
- * The flow is:
- * 1. Open a `custom:openui` event subscription on a fresh thread.
- * 2. Start the run (`run.start`) concurrently to avoid a subscribe/start
- * deadlock.
- * 3. For every forwarded `custom:openui` frame, unwrap the {@link AGUIEvent}
- * and re-emit it to the client as `data: <json>\n\n`.
- *
- * The stream closes as soon as a terminal event ({@link EventType.TEXT_MESSAGE_END}
- * or {@link EventType.RUN_ERROR}) is seen, on upstream completion, or when the
- * caller's {@link StreamOpenUIOptions.signal | signal} aborts. Errors are surfaced
- * to the client as a {@link EventType.RUN_ERROR} event rather than throwing.
- *
- * @param options - See {@link StreamOpenUIOptions}.
- * @returns A `ReadableStream` of UTF-8 encoded SSE frames suitable for a
- * `text/event-stream` HTTP response.
- */
-export function streamOpenUI({
- apiUrl,
- assistantId,
- apiKey,
- input,
- signal,
-}: StreamOpenUIOptions): ReadableStream<Uint8Array> {
- return new ReadableStream<Uint8Array>({
- async start(controller) {
- const upstreamAbort = new AbortController();
- const onAbort = () => upstreamAbort.abort();
- signal?.addEventListener("abort", onAbort, { once: true });
-
- const close = () => {
- try {
- controller.close();
- } catch {
- // The browser may have already disconnected.
- }
- };
-
- const send = (event: AGUIEvent) => {
- controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
- };
-
- try {
- const headers = buildHeaders(apiKey);
- const baseUrl = apiUrl.replace(/\/+$/, "");
- const threadId = crypto.randomUUID();
-
- // Subscribe to the `custom:openui` channel without a namespace/depth
- // filter: the transformer forwards events from the agent's model node
- // (a nested namespace like `model_request:<uuid>`), so restricting to
- // the root namespace would drop them.
- const eventsResponsePromise = fetch(`${baseUrl}/threads/${threadId}/stream/events`, {
- method: "POST",
- headers,
- body: JSON.stringify({
- channels: ["custom:openui"],
- }),
- signal: upstreamAbort.signal,
- });
-
- const startRunPromise = startRun({
- baseUrl,
- threadId,
- assistantId,
- input,
- headers,
- signal: upstreamAbort.signal,
- });
-
- const eventsResponse = await eventsResponsePromise;
-
- if (!eventsResponse.ok || !eventsResponse.body) {
- throw new Error(`LangGraph event stream failed: ${eventsResponse.status}`);
- }
-
- await startRunPromise;
-
- const reader = eventsResponse.body.getReader();
- const decoder = new TextDecoder();
- let buffer = "";
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const blocks = buffer.split("\n\n");
- buffer = blocks.pop() ?? "";
-
- for (const block of blocks) {
- const parsed = parseSSEBlock(block);
- if (!isOpenUIEventName(parsed.event) || !parsed.data) continue;
-
- const agUIEvent = extractAGUIEvent(parsed.data);
- if (!agUIEvent) continue;
-
- send(agUIEvent);
-
- if (
- agUIEvent.type === EventType.TEXT_MESSAGE_END ||
- agUIEvent.type === EventType.RUN_ERROR
- ) {
- upstreamAbort.abort();
- close();
- return;
- }
- }
- }
- } catch (error) {
- if (!signal?.aborted) {
- send({
- type: EventType.RUN_ERROR,
- message: error instanceof Error ? error.message : "OpenUI stream failed",
- } as AGUIEvent);
- }
- } finally {
- signal?.removeEventListener("abort", onAbort);
- close();
- }
- },
- cancel() {
- // The upstream fetch is tied to the caller's request signal, which Next.js
- // aborts when the browser disconnects.
- },
- });
-}
-
-/**
- * Issues the `run.start` command that kicks off graph execution on the given
- * thread. Throws with an enriched message on failure — including a list of
- * registered graph ids when the assistant is not found (404).
- */
-async function startRun({
- baseUrl,
- threadId,
- assistantId,
- input,
- headers,
- signal,
-}: {
- /** Normalized LangGraph base URL (no trailing slash). */
- baseUrl: string;
- /** The thread the run is bound to (shared with the event subscription). */
- threadId: string;
- /** Graph/assistant id to run. */
- assistantId: string;
- /** Run input forwarded verbatim to the graph. */
- input: unknown;
- /** Request headers (content type plus optional `x-api-key`). */
- headers: HeadersInit;
- /** Abort signal tying this fetch to the overall stream lifecycle. */
- signal: AbortSignal;
-}) {
- const response = await fetch(`${baseUrl}/threads/${threadId}/commands`, {
- method: "POST",
- headers,
- body: JSON.stringify({
- id: 1,
- method: "run.start",
- params: {
- assistant_id: assistantId,
- input,
- },
- }),
- signal,
- });
-
- if (!response.ok) {
- const details = await response.text();
- const hint =
- response.status === 404
- ? await getAssistantHint(baseUrl, headers, assistantId, signal)
- : undefined;
- throw new Error(
- [
- `LangGraph run.start failed: ${response.status}`,
- details.trim() || undefined,
- hint,
- ]
- .filter(Boolean)
- .join(". "),
- );
- }
-
- const payload = (await response.json()) as { type?: string; message?: string };
- if (payload.type === "error") {
- throw new Error(payload.message ?? "LangGraph run.start failed");
- }
-}
-
-/**
- * Best-effort diagnostic for a 404 from `run.start`: queries the server's
- * registered assistants and returns a human-readable hint listing the
- * available graph ids, or `undefined` if it cannot be determined.
- */
-async function getAssistantHint(
- baseUrl: string,
- headers: HeadersInit,
- assistantId: string,
- signal: AbortSignal,
-): Promise<string | undefined> {
- try {
- const response = await fetch(`${baseUrl}/assistants/search`, {
- method: "POST",
- headers,
- body: JSON.stringify({}),
- signal,
- });
- if (!response.ok) return undefined;
-
- const assistants = (await response.json()) as Array<{
- assistant_id?: string;
- graph_id?: string;
- name?: string | null;
- }>;
- const registered = assistants
- .map((assistant) => assistant.graph_id ?? assistant.name ?? assistant.assistant_id)
- .filter(Boolean);
-
- if (!registered.length) return undefined;
- return `Configured assistant "${assistantId}" is not registered on this LangGraph server; available graph ids: ${registered.join(", ")}`;
- } catch {
- return undefined;
- }
-}
-
-/**
- * Builds the JSON request headers, adding the `x-api-key` header only when an
- * {@link StreamOpenUIOptions.apiKey | apiKey} is provided.
- */
-function buildHeaders(apiKey?: string): HeadersInit {
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- };
-
- if (apiKey) {
- headers["x-api-key"] = apiKey;
- }
-
- return headers;
-}
-
-/**
- * Parses one SSE frame (the text between blank-line delimiters) into its
- * `event` and concatenated `data` fields. Lines that are neither are ignored.
- */
-function parseSSEBlock(block: string): ProtocolSSEEvent {
- let event = "";
- const dataLines: string[] = [];
-
- for (const line of block.split("\n")) {
- if (line.startsWith("event:")) {
- event = line.slice(6).trim();
- } else if (line.startsWith("data:")) {
- dataLines.push(line.slice(5).trim());
- }
- }
-
- return { event, data: dataLines.join("\n") };
-}
-
-/**
- * Unwraps the {@link AGUIEvent} from a raw SSE `data:` JSON string. Handles both
- * the protocol-envelope form ({@link ProtocolEvent} → {@link NamedCustomPayload})
- * and a bare event that was already unwrapped upstream.
- *
- * @returns The event, or `undefined` if the payload is not an `openui` event.
- */
-function extractAGUIEvent(data: string): AGUIEvent | undefined {
- const parsed = JSON.parse(data) as ProtocolEvent | AGUIEvent;
- if (isProtocolEvent(parsed)) {
- return extractCustomPayload(parsed.params.data);
- }
- return parsed as AGUIEvent;
-}
-
-/**
- * Whether an SSE `event:` name corresponds to the OpenUI custom channel. The
- * server may emit either the generic `custom` (with a named payload) or the
- * fully-qualified `custom:openui`.
- */
-function isOpenUIEventName(event: string): boolean {
- return event === "custom" || event === "custom:openui";
-}
-
-/**
- * Extracts the {@link AGUIEvent} from a `custom` channel payload, returning
- * `undefined` for named payloads whose channel is not `"openui"`.
- */
-function extractCustomPayload(data: unknown): AGUIEvent | undefined {
- if (isNamedCustomPayload(data)) {
- if (data.name !== "openui") return undefined;
- return data.payload as AGUIEvent;
- }
-
- return data as AGUIEvent;
-}
-
-/**
- * Type guard for the {@link NamedCustomPayload} `{ name, payload }` shape used
- * when the server forwards a named custom channel.
- */
-function isNamedCustomPayload(value: unknown): value is NamedCustomPayload {
- return (
- typeof value === "object" &&
- value !== null &&
- "name" in value &&
- "payload" in value
- );
-}
-
-/**
- * Type guard distinguishing a {@link ProtocolEvent} envelope (has
- * `params.data`) from a bare {@link AGUIEvent}.
- */
-function isProtocolEvent(value: ProtocolEvent | AGUIEvent): value is ProtocolEvent {
- return (
- typeof value === "object" &&
- value !== null &&
- "params" in value &&
- typeof value.params === "object" &&
- value.params !== null &&
- "data" in value.params
- );
-}
diff --git a/packages/langchain/README.md b/packages/langchain/README.md
new file mode 100644
index 000000000..3a69fcc1c
--- /dev/null
+++ b/packages/langchain/README.md
@@ -0,0 +1,150 @@
+# `@openuidev/langchain`
+
+Supported LangChain and LangGraph integration primitives for streaming OpenUI
+generative interfaces over AG-UI.
+
+The package connects three pieces:
+
+1. A LangGraph stream transformer converts protocol-v2 `messages` and `tools`
+ events to AG-UI events on the remote `custom:openui` channel.
+2. A server helper starts a stateless LangGraph run, adds strict AG-UI run
+ lifecycle events, and relays that channel as Server-Sent Events.
+3. OpenUI's `agUIAdapter()` consumes the response without LangChain-specific
+ frontend code.
+
+The APIs use Web-standard `Request`, `Response`, `fetch`, and `ReadableStream`.
+They do not depend on Next.js or DeepAgents.
+
+## Install
+
+```bash
+npm install @openuidev/langchain
+```
+
+The server helpers communicate with LangGraph over HTTP and do not load the
+LangGraph runtime. Install `@langchain/langgraph` only in applications that use
+the agent-side transformer:
+
+```bash
+npm install @openuidev/langchain @langchain/langgraph
+```
+
+`@langchain/langgraph` is an optional peer dependency. The supported range is
+declared in this package's `peerDependencies` so applications retain control of
+their LangGraph version.
+
+The server helpers require an agent-protocol-v2 server that supports both the
+`custom:*` and root `lifecycle` event channels. The tested local-server baseline
+is `@langchain/langgraph-cli` 1.4.x; older servers that reject the `lifecycle`
+channel are not supported.
+
+## Add the agent transformer
+
+The transformer works with any agent that accepts LangGraph
+`streamTransformers`. Here is the minimal DeepAgents setup:
+
+```ts
+import { openUIStreamTransformer } from "@openuidev/langchain/transformer";
+import { createDeepAgent } from "deepagents";
+
+export const graph = createDeepAgent({
+ model: "openai:gpt-5.5",
+ tools: [getWeather, getStockPrice, searchWeb],
+ systemPrompt: SYSTEM_PROMPT,
+ streamTransformers: [openUIStreamTransformer],
+});
+```
+
+`openUIStreamTransformer()` converts assistant text, tool-call deltas, tool
+results, and run errors into AG-UI events. LangGraph forwards those events
+remotely under the `custom:openui` channel.
+
+## Add a server route
+
+`createLangChainStreamResponse` accepts any Web-standard `Request`, so it can be
+returned directly from Next.js and other compatible route handlers:
+
+```ts
+import { createLangChainStreamResponse } from "@openuidev/langchain";
+
+export const runtime = "nodejs";
+
+export async function POST(request: Request) {
+ return createLangChainStreamResponse(request, {
+ apiUrl: process.env.LANGGRAPH_API_URL ?? "http://localhost:2024",
+ assistantId: process.env.LANGGRAPH_ASSISTANT_ID ?? "agent",
+ apiKey: process.env.LANGSMITH_API_KEY,
+ debug: process.env.NODE_ENV !== "production",
+ });
+}
+```
+
+The route expects a non-empty `{ messages: Message[] }` body in AG-UI format and
+returns a JSON `400` response for malformed input. It converts text and
+multimodal user content to LangChain messages. Complete assistant tool-call and
+tool-result pairs are preserved; only incomplete calls and orphaned results are
+removed before starting the stateless run.
+
+Each call uses a temporary LangGraph thread and makes a bounded cleanup attempt
+before closing a normally completed response. Pass `cleanupThread: false` when
+the thread must remain available for local debugging. On serverless platforms,
+pass the platform's `waitUntil`-style registration function through the
+`waitUntil` option so cleanup can survive a client disconnect. Upstream response
+bodies and registered graph ids are redacted from stream errors by default;
+pass `debug: true` only in a trusted development environment to include them.
+
+## Connect OpenUI
+
+The route returns AG-UI SSE with `RUN_STARTED` and `RUN_FINISHED`/`RUN_ERROR`
+lifecycle events, so the browser only needs OpenUI's AG-UI adapter:
+
+```tsx
+import { AgentInterface, agUIAdapter, fetchLLM } from "@openuidev/react-ui";
+
+const llm = fetchLLM({
+ url: "/api/chat",
+ streamAdapter: agUIAdapter(),
+});
+
+export function Chat() {
+ return <AgentInterface llm={llm} />;
+}
+```
+
+## Lower-level streaming
+
+Use `streamOpenUI` when a route needs to build the LangGraph input itself:
+
+```ts
+import { streamOpenUI } from "@openuidev/langchain";
+
+const body = streamOpenUI({
+ apiUrl: "http://localhost:2024",
+ assistantId: "agent",
+ input: { messages: [{ type: "human", content: "Hello" }] },
+ signal: request.signal,
+});
+
+return new Response(body, {
+ headers: { "Content-Type": "text/event-stream" },
+});
+```
+
+Cancelling the returned stream or aborting the supplied signal aborts both
+upstream LangGraph requests.
+
+## API
+
+- `openUIStreamTransformer()` from `@openuidev/langchain/transformer` —
+ LangGraph stream-transformer factory that publishes message and tool events
+ on `custom:openui`.
+- `createLangChainStreamResponse(request, options)` — complete AG-UI request to
+ LangGraph response path for stateless chat routes.
+- `streamOpenUI(options)` — lower-level protocol-v2 runner and custom-channel
+ relay.
+- `CreateLangChainStreamResponseOptions`, `StreamOpenUIOptions`, and
+ `LangChainInputMessage` — exported TypeScript types.
+
+See the repository's
+[`examples/langchain-chat`](https://github.com/thesysdev/openui/tree/main/examples/langchain-chat)
+for a complete local and LangGraph Platform example.
diff --git a/packages/langchain/eslint.config.cjs b/packages/langchain/eslint.config.cjs
new file mode 100644
index 000000000..413c49627
--- /dev/null
+++ b/packages/langchain/eslint.config.cjs
@@ -0,0 +1,73 @@
+const tseslint = require("@typescript-eslint/eslint-plugin");
+const typescript = require("@typescript-eslint/parser");
+const prettier = require("eslint-config-prettier");
+const unusedImports = require("eslint-plugin-unused-imports");
+const eslintPluginPrettier = require("eslint-plugin-prettier");
+
+module.exports = [
+ {
+ files: ["**/__tests__/**/*.{ts,tsx}", "**/*.test.{ts,tsx}", "**/*.spec.{ts,tsx}"],
+ languageOptions: {
+ parser: typescript,
+ parserOptions: {
+ project: "./tsconfig.test.json",
+ sourceType: "module",
+ },
+ },
+ },
+ {
+ files: ["**/*.{ts,tsx}"],
+ ignores: [
+ "**/*.stories.tsx",
+ "**/__tests__/**/*.{ts,tsx}",
+ "**/*.test.{ts,tsx}",
+ "**/*.spec.{ts,tsx}",
+ "*.config.ts",
+ ],
+ languageOptions: {
+ parser: typescript,
+ parserOptions: {
+ project: "./tsconfig.json",
+ sourceType: "module",
+ },
+ },
+ plugins: {
+ "@typescript-eslint": tseslint,
+ "unused-imports": unusedImports,
+ prettier: eslintPluginPrettier,
+ },
+ rules: {
+ "@typescript-eslint/interface-name-prefix": "off",
+ "@typescript-eslint/explicit-function-return-type": "off",
+ "@typescript-eslint/explicit-module-boundary-types": "off",
+ "@typescript-eslint/no-explicit-any": "off",
+ "no-undefined": "off",
+ "@typescript-eslint/no-unused-vars": [
+ "error",
+ {
+ vars: "all",
+ varsIgnorePattern: "^_",
+ args: "after-used",
+ argsIgnorePattern: "^_",
+ },
+ ],
+ "@typescript-eslint/no-use-before-define": [
+ "error",
+ {
+ functions: false,
+ classes: false,
+ variables: false,
+ },
+ ],
+ "unused-imports/no-unused-imports": "error",
+ "no-console": [
+ "error",
+ {
+ allow: ["error", "warn", "info"],
+ },
+ ],
+ ...eslintPluginPrettier.configs.recommended.rules,
+ },
+ },
+ prettier,
+];
diff --git a/packages/langchain/package.json b/packages/langchain/package.json
new file mode 100644
index 000000000..a5a745a06
--- /dev/null
+++ b/packages/langchain/package.json
@@ -0,0 +1,100 @@
+{
+ "name": "@openuidev/langchain",
+ "version": "0.0.1",
+ "description": "LangChain and LangGraph integration primitives for streaming OpenUI generative interfaces",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "type": "module",
+ "main": "dist/index.cjs",
+ "module": "dist/index.mjs",
+ "types": "dist/index.d.cts",
+ "typesVersions": {
+ "*": {
+ "transformer": [
+ "dist/transformer.d.cts"
+ ]
+ }
+ },
+ "sideEffects": false,
+ "files": [
+ "dist",
+ "README.md"
+ ],
+ "exports": {
+ ".": {
+ "import": {
+ "types": "./dist/index.d.mts",
+ "default": "./dist/index.mjs"
+ },
+ "require": {
+ "types": "./dist/index.d.cts",
+ "default": "./dist/index.cjs"
+ }
+ },
+ "./transformer": {
+ "import": {
+ "types": "./dist/transformer.d.mts",
+ "default": "./dist/transformer.mjs"
+ },
+ "require": {
+ "types": "./dist/transformer.d.cts",
+ "default": "./dist/transformer.cjs"
+ }
+ }
+ },
+ "scripts": {
+ "test": "vitest run",
+ "build": "tsdown",
+ "watch": "tsdown --watch",
+ "typecheck": "tsc --noEmit",
+ "lint:check": "eslint ./src",
+ "lint:fix": "eslint ./src --fix",
+ "format:fix": "prettier --write ./src README.md",
+ "format:check": "prettier --check ./src README.md",
+ "check:publint": "publint",
+ "check:attw": "attw --pack .",
+ "prepare": "pnpm run build",
+ "prepublishOnly": "pnpm run check:publint && pnpm run check:attw",
+ "ci": "pnpm run typecheck && pnpm run test && pnpm run lint:check && pnpm run format:check"
+ },
+ "keywords": [
+ "openui",
+ "langchain",
+ "langgraph",
+ "deepagents",
+ "ag-ui",
+ "generative-ui",
+ "streaming",
+ "sse"
+ ],
+ "homepage": "https://openui.com",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/thesysdev/openui.git",
+ "directory": "packages/langchain"
+ },
+ "bugs": {
+ "url": "https://github.com/thesysdev/openui/issues"
+ },
+ "author": "[email protected]",
+ "dependencies": {
+ "@ag-ui/core": "^0.0.57"
+ },
+ "peerDependencies": {
+ "@langchain/langgraph": "^1.4.5"
+ },
+ "peerDependenciesMeta": {
+ "@langchain/langgraph": {
+ "optional": true
+ }
+ },
+ "devDependencies": {
+ "@langchain/core": "^1.2.1",
+ "@langchain/langgraph": "^1.4.5",
+ "@langchain/protocol": "^0.0.18",
+ "vitest": "^4.1.0",
+ "zod": "^4.2.0"
+ }
+}
diff --git a/packages/langchain/src/__tests__/langchain-integration.test.ts b/packages/langchain/src/__tests__/langchain-integration.test.ts
new file mode 100644
index 000000000..267b001b8
--- /dev/null
+++ b/packages/langchain/src/__tests__/langchain-integration.test.ts
@@ -0,0 +1,139 @@
+import { EventSchemas, EventType, type AGUIEvent } from "@ag-ui/core";
+import type { ProtocolEvent } from "@langchain/langgraph";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { streamOpenUI } from "../stream-relay";
+import { openUIStreamTransformer } from "../transformer";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("LangGraph to AG-UI integration", () => {
+ it("preserves preamble, tool result, and final assistant UI through the relay", async () => {
+ const transformer = openUIStreamTransformer();
+ const { openui } = transformer.init();
+
+ transformer.process(messageEvent({ event: "message-start", id: "m1", run_id: "model-1" }));
+ transformer.process(
+ messageEvent({
+ event: "content-block-delta",
+ index: 0,
+ delta: { type: "text-delta", text: "Let me check the weather." },
+ }),
+ );
+ transformer.process(
+ messageEvent({
+ event: "content-block-start",
+ index: 1,
+ content: {
+ type: "tool_call_chunk",
+ id: "call-1",
+ name: "get_weather",
+ args: '{"city":"Paris"}',
+ },
+ }),
+ );
+ transformer.process(
+ messageEvent({
+ event: "content-block-finish",
+ index: 1,
+ content: {
+ type: "tool_call",
+ id: "call-1",
+ name: "get_weather",
+ args: { city: "Paris" },
+ },
+ }),
+ );
+ transformer.process(messageEvent({ event: "message-finish" }));
+ transformer.process(
+ toolsEvent({
+ event: "tool-finished",
+ tool_call_id: "call-1",
+ output: { temperature: 21 },
+ }),
+ );
+ transformer.process(messageEvent({ event: "message-start", id: "m2", run_id: "model-2" }));
+ transformer.process(
+ messageEvent({
+ event: "content-block-delta",
+ index: 0,
+ delta: { type: "text-delta", text: '<Card title="Paris">21C</Card>' },
+ }),
+ );
+ transformer.process(messageEvent({ event: "message-finish" }));
+ transformer.finalize?.();
+
+ const transformed = Array.from({ length: openui.size }, (_, index) => openui.get(index));
+ const upstreamSSE = [
+ ...transformed.map(
+ (event) =>
+ `event: custom\ndata: ${JSON.stringify({ type: "event", params: { data: { name: "openui", payload: event } } })}\n\n`,
+ ),
+ `event: lifecycle\ndata: ${JSON.stringify({ type: "event", params: { namespace: [], data: { event: "completed" } } })}\n\n`,
+ ].join("");
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: string | URL | Request) => {
+ if (String(input).endsWith("/stream/events")) return new Response(upstreamSSE);
+ return Response.json({ type: "success", id: 1, result: { run_id: "run-1" } });
+ }),
+ );
+
+ const relayed = parseOutput(
+ await new Response(
+ streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ input: { messages: [] },
+ cleanupThread: false,
+ }),
+ ).text(),
+ );
+
+ expect(relayed.slice(1, -1)).toEqual(transformed);
+ expect(relayed.map((event) => event.type)).toEqual([
+ EventType.RUN_STARTED,
+ EventType.TEXT_MESSAGE_START,
+ EventType.TEXT_MESSAGE_CONTENT,
+ EventType.TOOL_CALL_START,
+ EventType.TOOL_CALL_ARGS,
+ EventType.TOOL_CALL_END,
+ EventType.TEXT_MESSAGE_END,
+ EventType.TOOL_CALL_RESULT,
+ EventType.TEXT_MESSAGE_START,
+ EventType.TEXT_MESSAGE_CONTENT,
+ EventType.TEXT_MESSAGE_END,
+ EventType.RUN_FINISHED,
+ ]);
+ expect(relayed.every((event) => EventSchemas.safeParse(event).success)).toBe(true);
+ });
+});
+
+function messageEvent(data: unknown): ProtocolEvent {
+ return {
+ type: "event",
+ seq: 0,
+ method: "messages",
+ params: { namespace: ["model_request:1"], timestamp: 0, data },
+ };
+}
+
+function toolsEvent(data: unknown): ProtocolEvent {
+ return {
+ type: "event",
+ seq: 0,
+ method: "tools",
+ params: { namespace: ["tools:1"], timestamp: 0, data },
+ };
+}
+
+function parseOutput(output: string): AGUIEvent[] {
+ return output
+ .trim()
+ .split("\n\n")
+ .filter(Boolean)
+ .map((frame) => JSON.parse(frame.replace(/^data: /, "")) as AGUIEvent);
+}
diff --git a/packages/langchain/src/__tests__/request-handler.test.ts b/packages/langchain/src/__tests__/request-handler.test.ts
new file mode 100644
index 000000000..941a67e38
--- /dev/null
+++ b/packages/langchain/src/__tests__/request-handler.test.ts
@@ -0,0 +1,223 @@
+import { EventType } from "@ag-ui/core";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createLangChainStreamResponse } from "../request-handler";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("createLangChainStreamResponse", () => {
+ it("converts visible AG-UI history and returns an AG-UI event stream", async () => {
+ const endEvent = { type: EventType.TEXT_MESSAGE_END, messageId: "response-1" };
+ const fetchMock = vi.fn(async (input: string | URL | Request) => {
+ if (String(input).endsWith("/stream/events")) {
+ return new Response(
+ [
+ `event: custom\ndata: ${JSON.stringify({ type: "event", params: { data: { name: "openui", payload: endEvent } } })}\n\n`,
+ `event: lifecycle\ndata: ${JSON.stringify({ type: "event", params: { namespace: [], data: { event: "completed" } } })}\n\n`,
+ ].join(""),
+ );
+ }
+ return Response.json({ type: "success", id: 1, result: { run_id: "run-1" } });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const request = new Request("https://app.example/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ messages: [
+ {
+ id: "user-1",
+ role: "user",
+ content: [
+ { type: "text", text: "Describe this" },
+ { type: "image", source: { type: "url", value: "https://example.com/a.png" } },
+ ],
+ },
+ {
+ id: "assistant-1",
+ role: "assistant",
+ content: "I will check",
+ toolCalls: [
+ {
+ id: "call-1",
+ type: "function",
+ function: { name: "inspect", arguments: '{"id":1}' },
+ },
+ ],
+ },
+ {
+ id: "tool-1",
+ role: "tool",
+ content: "internal result",
+ toolCallId: "call-1",
+ },
+ { id: "developer-1", role: "developer", content: "Be concise" },
+ { id: "activity-1", role: "activity", activityType: "status", content: {} },
+ ],
+ }),
+ });
+
+ const response = await createLangChainStreamResponse(request, {
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ cleanupThread: false,
+ });
+
+ expect(response.headers.get("content-type")).toBe("text/event-stream");
+ expect(response.headers.get("connection")).toBeNull();
+ const output = parseOutput(await response.text());
+ expect(output).toEqual([
+ {
+ type: EventType.RUN_STARTED,
+ threadId: expect.any(String),
+ runId: "run-1",
+ },
+ endEvent,
+ {
+ type: EventType.RUN_FINISHED,
+ threadId: expect.any(String),
+ runId: "run-1",
+ },
+ ]);
+ expect(output[0]?.threadId).toBe(output.at(-1)?.threadId);
+
+ const commandCall = fetchMock.mock.calls.find(([input]) => String(input).endsWith("/commands"));
+ const command = JSON.parse(String(commandCall?.[1]?.body));
+ expect(command.params.input.messages).toEqual([
+ {
+ type: "human",
+ content: [
+ { type: "text", text: "Describe this" },
+ { type: "image", url: "https://example.com/a.png" },
+ ],
+ },
+ {
+ type: "ai",
+ content: "I will check",
+ tool_calls: [{ id: "call-1", name: "inspect", args: { id: 1 } }],
+ },
+ { type: "tool", content: "internal result", tool_call_id: "call-1" },
+ { type: "system", content: "Be concise" },
+ ]);
+ });
+
+ it("removes only incomplete tool transcripts", async () => {
+ let commandInput: unknown;
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ if (String(input).endsWith("/stream/events")) {
+ return new Response(
+ `event: lifecycle\ndata: ${JSON.stringify({ type: "event", params: { namespace: [], data: { event: "completed" } } })}\n\n`,
+ );
+ }
+ commandInput = JSON.parse(String(init?.body)).params.input;
+ return Response.json({ type: "success", id: 1, result: { run_id: "run-2" } });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const request = chatRequest([
+ { id: "user-1", role: "user", content: "Check both" },
+ {
+ id: "assistant-1",
+ role: "assistant",
+ content: "Checking",
+ toolCalls: [
+ {
+ id: "complete-call",
+ type: "function",
+ function: { name: "weather", arguments: '{"city":"Paris"}' },
+ },
+ {
+ id: "incomplete-call",
+ type: "function",
+ function: { name: "weather", arguments: '{"city":"Rome"}' },
+ },
+ ],
+ },
+ {
+ id: "tool-1",
+ role: "tool",
+ content: "21C",
+ toolCallId: "complete-call",
+ },
+ { id: "user-2", role: "user", content: "Thanks" },
+ {
+ id: "orphan-tool",
+ role: "tool",
+ content: "orphan",
+ toolCallId: "unknown-call",
+ },
+ ]);
+
+ const response = await createLangChainStreamResponse(request, {
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ cleanupThread: false,
+ });
+ await response.text();
+
+ expect(commandInput).toEqual({
+ messages: [
+ { type: "human", content: "Check both" },
+ {
+ type: "ai",
+ content: "Checking",
+ tool_calls: [
+ {
+ id: "complete-call",
+ name: "weather",
+ args: { city: "Paris" },
+ },
+ ],
+ },
+ { type: "tool", content: "21C", tool_call_id: "complete-call" },
+ { type: "human", content: "Thanks" },
+ ],
+ });
+ });
+
+ it.each([
+ ["malformed JSON", "{"],
+ ["a missing messages property", JSON.stringify({})],
+ ["a non-array messages property", JSON.stringify({ messages: "invalid" })],
+ ["an empty messages array", JSON.stringify({ messages: [] })],
+ ["invalid message objects", JSON.stringify({ messages: [{ role: "user" }] })],
+ ])("returns 400 for %s without starting a run", async (_label, body) => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const request = new Request("https://app.example/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body,
+ });
+
+ const response = await createLangChainStreamResponse(request, {
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ });
+
+ expect(response.status).toBe(400);
+ await expect(response.json()).resolves.toEqual({
+ error: "Expected a JSON request body containing a non-empty messages array",
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+function chatRequest(messages: unknown[]): Request {
+ return new Request("https://app.example/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ messages }),
+ });
+}
+
+function parseOutput(output: string): Array<Record<string, unknown>> {
+ return output
+ .trim()
+ .split("\n\n")
+ .filter(Boolean)
+ .map((frame) => JSON.parse(frame.replace(/^data: /, "")) as Record<string, unknown>);
+}
diff --git a/packages/langchain/src/__tests__/stream-relay.test.ts b/packages/langchain/src/__tests__/stream-relay.test.ts
new file mode 100644
index 000000000..1b554e710
--- /dev/null
+++ b/packages/langchain/src/__tests__/stream-relay.test.ts
@@ -0,0 +1,499 @@
+import { EventSchemas, EventType, type AGUIEvent } from "@ag-ui/core";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { streamOpenUI } from "../stream-relay";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("streamOpenUI", () => {
+ it("relays only valid OpenUI custom-channel events across chunked CRLF SSE", async () => {
+ const start = { type: EventType.TEXT_MESSAGE_START, messageId: "m1", role: "assistant" };
+ const content = { type: EventType.TEXT_MESSAGE_CONTENT, messageId: "m1", delta: "Hello" };
+ const end = { type: EventType.TEXT_MESSAGE_END, messageId: "m1" };
+ const sse = [
+ protocolFrame("custom", { name: "other", payload: start }, "\r\n"),
+ "event: custom\r\ndata: not-json\r\n\r\n",
+ protocolFrame("custom", { name: "openui", payload: start }, "\r\n"),
+ bareFrame("custom:openui", content, "\r\n"),
+ protocolFrame("custom", { name: "openui", payload: end }, "\r\n"),
+ ].join("");
+
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ if (url.endsWith("/stream/events")) {
+ return new Response(chunkedBody([sse.slice(0, 47), sse.slice(47, 131), sse.slice(131)]));
+ }
+ expect(init?.method).toBe("POST");
+ return runStartedResponse("run-1");
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const output = await new Response(
+ streamOpenUI({
+ apiUrl: "https://langgraph.example/",
+ assistantId: "agent",
+ apiKey: "secret",
+ input: { messages: [] },
+ cleanupThread: false,
+ }),
+ ).text();
+
+ const events = parseOutput(output);
+ expect(events).toEqual([
+ {
+ type: EventType.RUN_STARTED,
+ threadId: expect.any(String),
+ runId: "run-1",
+ },
+ start,
+ content,
+ end,
+ {
+ type: EventType.RUN_FINISHED,
+ threadId: expect.any(String),
+ runId: "run-1",
+ },
+ ]);
+ expect(events[0]?.threadId).toBe(events.at(-1)?.threadId);
+ expectValidAGUIEvents(events);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+
+ const commandCall = fetchMock.mock.calls.find(([input]) => String(input).endsWith("/commands"));
+ expect(commandCall).toBeDefined();
+ expect(commandCall?.[1]?.headers).toEqual({
+ "Content-Type": "application/json",
+ "x-api-key": "secret",
+ });
+ expect(JSON.parse(String(commandCall?.[1]?.body))).toMatchObject({
+ method: "run.start",
+ params: { assistant_id: "agent", input: { messages: [] } },
+ });
+ const streamCall = fetchMock.mock.calls.find(([input]) =>
+ String(input).endsWith("/stream/events"),
+ );
+ expect(JSON.parse(String(streamCall?.[1]?.body))).toEqual({
+ channels: ["custom:openui", "lifecycle"],
+ });
+ });
+
+ it("relays multiple assistant messages and tool results until root lifecycle completes", async () => {
+ const relayed = [
+ { type: EventType.TEXT_MESSAGE_START, messageId: "m1", role: "assistant" },
+ { type: EventType.TEXT_MESSAGE_CONTENT, messageId: "m1", delta: "Let me check." },
+ { type: EventType.TOOL_CALL_START, toolCallId: "call-1", toolCallName: "weather" },
+ { type: EventType.TOOL_CALL_ARGS, toolCallId: "call-1", delta: '{"city":"Paris"}' },
+ { type: EventType.TOOL_CALL_END, toolCallId: "call-1" },
+ { type: EventType.TEXT_MESSAGE_END, messageId: "m1" },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ messageId: "tool-result-call-1",
+ toolCallId: "call-1",
+ content: '{"temperature":21}',
+ role: "tool",
+ },
+ { type: EventType.TEXT_MESSAGE_START, messageId: "m2", role: "assistant" },
+ {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ messageId: "m2",
+ delta: '<Card title="Paris">21C</Card>',
+ },
+ { type: EventType.TEXT_MESSAGE_END, messageId: "m2" },
+ ] satisfies AGUIEvent[];
+ const sse = [
+ ...relayed.map((event) => protocolFrame("custom", { name: "openui", payload: event })),
+ lifecycleFrame({ event: "completed" }),
+ ].join("");
+
+ const fetchMock = vi.fn(async (input: string | URL | Request) => {
+ if (String(input).endsWith("/stream/events")) return new Response(sse);
+ return runStartedResponse("run-multiple");
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const events = parseOutput(
+ await new Response(
+ streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ input: { messages: [] },
+ cleanupThread: false,
+ }),
+ ).text(),
+ );
+
+ expect(events.slice(1, -1)).toEqual(relayed);
+ expect(events[0]).toMatchObject({ type: EventType.RUN_STARTED, runId: "run-multiple" });
+ expect(events.at(-1)).toMatchObject({
+ type: EventType.RUN_FINISHED,
+ runId: "run-multiple",
+ });
+ expectValidAGUIEvents(events);
+ });
+
+ it("ignores nested lifecycle completion until the root run completes", async () => {
+ const start = {
+ type: EventType.TEXT_MESSAGE_START,
+ messageId: "nested-message",
+ role: "assistant",
+ } satisfies AGUIEvent;
+ const content = {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ messageId: "nested-message",
+ delta: "Still running",
+ } satisfies AGUIEvent;
+ const sse = [
+ protocolFrame("custom", { name: "openui", payload: start }),
+ lifecycleFrame({ event: "completed" }, ["subgraph:worker"]),
+ protocolFrame("custom", { name: "openui", payload: content }),
+ lifecycleFrame({ event: "completed" }),
+ ].join("");
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: string | URL | Request) => {
+ if (String(input).endsWith("/stream/events")) return new Response(sse);
+ return runStartedResponse("run-root");
+ }),
+ );
+
+ const events = parseOutput(
+ await new Response(
+ streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ input: {},
+ cleanupThread: false,
+ }),
+ ).text(),
+ );
+
+ expect(events).toEqual([
+ expect.objectContaining({ type: EventType.RUN_STARTED, runId: "run-root" }),
+ start,
+ content,
+ expect.objectContaining({ type: EventType.RUN_FINISHED, runId: "run-root" }),
+ ]);
+ expectValidAGUIEvents(events);
+ });
+
+ it("redacts run-start internals by default", async () => {
+ let eventStreamSignal: AbortSignal | null | undefined;
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ if (url.endsWith("/stream/events")) {
+ eventStreamSignal = init?.signal;
+ return new Response(abortableBody(eventStreamSignal));
+ }
+ if (url.endsWith("/commands")) return new Response("assistant not found", { status: 404 });
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const output = await new Response(
+ streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "missing-agent",
+ input: {},
+ cleanupThread: false,
+ }),
+ ).text();
+
+ expect(parseOutput(output)).toEqual([
+ {
+ type: EventType.RUN_ERROR,
+ message: "Unable to complete LangGraph run",
+ },
+ ]);
+ expect(eventStreamSignal?.aborted).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("includes assistant hints only when debug errors are enabled", async () => {
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ if (url.endsWith("/stream/events")) return new Response(abortableBody(init?.signal));
+ if (url.endsWith("/commands")) return new Response("assistant not found", { status: 404 });
+ if (url.endsWith("/assistants/search")) {
+ return Response.json([{ graph_id: "weather-agent" }, { graph_id: "research-agent" }]);
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const output = await new Response(
+ streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "missing-agent",
+ input: {},
+ debug: true,
+ cleanupThread: false,
+ }),
+ ).text();
+
+ expect(parseOutput(output)).toEqual([
+ {
+ type: EventType.RUN_ERROR,
+ message: expect.stringContaining(
+ 'Configured assistant "missing-agent" is not registered on this LangGraph server; available graph ids: weather-agent, research-agent',
+ ),
+ },
+ ]);
+ });
+
+ it("deletes its temporary LangGraph thread after completion by default", async () => {
+ let finishDelete: (() => void) | undefined;
+ const deleteGate = new Promise<void>((resolve) => {
+ finishDelete = resolve;
+ });
+ const waitUntil = vi.fn<(task: Promise<void>) => void>();
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ if (url.endsWith("/stream/events")) {
+ return new Response(lifecycleFrame({ event: "completed" }));
+ }
+ if (url.endsWith("/commands")) return runStartedResponse("run-cleanup");
+ if (init?.method === "DELETE") {
+ await deleteGate;
+ return new Response(null, { status: 204 });
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const outputPromise = new Response(
+ streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ input: {},
+ waitUntil,
+ }),
+ ).text();
+ let responseClosed = false;
+ void outputPromise.then(() => {
+ responseClosed = true;
+ });
+
+ await vi.waitFor(() =>
+ expect(fetchMock.mock.calls.some(([, init]) => init?.method === "DELETE")).toBe(true),
+ );
+ expect(responseClosed).toBe(false);
+ expect(waitUntil).toHaveBeenCalledTimes(1);
+
+ finishDelete?.();
+ const events = parseOutput(await outputPromise);
+
+ expect(responseClosed).toBe(true);
+ const threadId = events[0]?.type === EventType.RUN_STARTED ? events[0].threadId : undefined;
+ const deleteCall = fetchMock.mock.calls.find(([, init]) => init?.method === "DELETE");
+ expect(String(deleteCall?.[0])).toBe(`https://langgraph.example/threads/${threadId}`);
+ });
+
+ it.each([
+ ["an empty response", ""],
+ ["a response without run_id", JSON.stringify({ type: "success", id: 1, result: {} })],
+ ])("rejects %s instead of fabricating a run id", async (_label, commandBody) => {
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ if (String(input).endsWith("/stream/events")) {
+ return new Response(abortableBody(init?.signal));
+ }
+ return new Response(commandBody);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const events = parseOutput(
+ await new Response(
+ streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ input: {},
+ debug: true,
+ cleanupThread: false,
+ }),
+ ).text(),
+ );
+
+ expect(events).toEqual([
+ { type: EventType.RUN_ERROR, message: "LangGraph run.start returned no run id" },
+ ]);
+ });
+
+ it("aborts upstream requests when the consumer cancels", async () => {
+ const signals: AbortSignal[] = [];
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ if (init?.signal) signals.push(init.signal);
+ const url = String(input);
+ if (url.endsWith("/stream/events")) {
+ return new Response(abortableBody(init?.signal));
+ }
+ return Response.json({ type: "success" });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const reader = streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ input: {},
+ cleanupThread: false,
+ }).getReader();
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ await reader.cancel();
+
+ expect(signals).toHaveLength(2);
+ expect(signals.every((signal) => signal.aborted)).toBe(true);
+ });
+
+ it("registers and awaits thread cleanup when the consumer cancels after run start", async () => {
+ const waitUntil = vi.fn<(task: Promise<void>) => void>();
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ if (url.endsWith("/stream/events")) return new Response(abortableBody(init?.signal));
+ if (url.endsWith("/commands")) return runStartedResponse("run-cancel-cleanup");
+ if (init?.method === "DELETE") return new Response(null, { status: 204 });
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const reader = streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ input: {},
+ waitUntil,
+ }).getReader();
+
+ const started = await reader.read();
+ expect(parseOutput(new TextDecoder().decode(started.value))).toEqual([
+ expect.objectContaining({ type: EventType.RUN_STARTED, runId: "run-cancel-cleanup" }),
+ ]);
+ await reader.cancel();
+
+ expect(waitUntil).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls.some(([, init]) => init?.method === "DELETE")).toBe(true);
+ });
+
+ it("closes the relay when the caller signal aborts while output is backpressured", async () => {
+ const signals: AbortSignal[] = [];
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ if (init?.signal) signals.push(init.signal);
+ if (String(input).endsWith("/stream/events")) {
+ return new Response(abortableBody(init?.signal));
+ }
+ return runStartedResponse("run-abort");
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const callerAbort = new AbortController();
+ const outputReader = streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ input: {},
+ signal: callerAbort.signal,
+ cleanupThread: false,
+ }).getReader();
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ callerAbort.abort();
+
+ await expect(outputReader.read()).resolves.toEqual({ done: true, value: undefined });
+ expect(signals).toHaveLength(2);
+ expect(signals.every((signal) => signal.aborted)).toBe(true);
+ });
+
+ it("waits for downstream demand before reading the upstream event stream", async () => {
+ let upstreamPulls = 0;
+ const eventBody = new ReadableStream<Uint8Array>(
+ {
+ pull(controller) {
+ upstreamPulls += 1;
+ controller.enqueue(new TextEncoder().encode(lifecycleFrame({ event: "completed" })));
+ controller.close();
+ },
+ },
+ { highWaterMark: 0 },
+ );
+ const fetchMock = vi.fn(async (input: string | URL | Request) => {
+ if (String(input).endsWith("/stream/events")) return new Response(eventBody);
+ return runStartedResponse("run-backpressure");
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const outputReader = streamOpenUI({
+ apiUrl: "https://langgraph.example",
+ assistantId: "agent",
+ input: {},
+ cleanupThread: false,
+ }).getReader();
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ expect(upstreamPulls).toBe(0);
+
+ const start = await outputReader.read();
+ expect(parseOutput(new TextDecoder().decode(start.value))).toEqual([
+ expect.objectContaining({ type: EventType.RUN_STARTED, runId: "run-backpressure" }),
+ ]);
+ await vi.waitFor(() => expect(upstreamPulls).toBe(1));
+
+ const finish = await outputReader.read();
+ expect(parseOutput(new TextDecoder().decode(finish.value))).toEqual([
+ expect.objectContaining({ type: EventType.RUN_FINISHED, runId: "run-backpressure" }),
+ ]);
+ await expect(outputReader.read()).resolves.toEqual({ done: true, value: undefined });
+ });
+});
+
+function runStartedResponse(runId: string): Response {
+ return Response.json({ type: "success", id: 1, result: { run_id: runId } });
+}
+
+function protocolFrame(event: string, data: unknown, newline = "\n"): string {
+ return `${bareFrame(event, { type: "event", params: { data } }, newline)}`;
+}
+
+function bareFrame(event: string, data: unknown, newline = "\n"): string {
+ return `event: ${event}${newline}data: ${JSON.stringify(data)}${newline}${newline}`;
+}
+
+function lifecycleFrame(data: unknown, namespace: string[] = []): string {
+ return bareFrame("lifecycle", {
+ type: "event",
+ method: "lifecycle",
+ params: { namespace, data },
+ });
+}
+
+function chunkedBody(chunks: string[]): ReadableStream<Uint8Array> {
+ const textEncoder = new TextEncoder();
+ return new ReadableStream({
+ start(controller) {
+ for (const chunk of chunks) controller.enqueue(textEncoder.encode(chunk));
+ controller.close();
+ },
+ });
+}
+
+function abortableBody(signal?: AbortSignal | null): ReadableStream<Uint8Array> {
+ return new ReadableStream({
+ start(controller) {
+ signal?.addEventListener(
+ "abort",
+ () => controller.error(new DOMException("Aborted", "AbortError")),
+ { once: true },
+ );
+ },
+ });
+}
+
+function parseOutput(output: string): AGUIEvent[] {
+ return output
+ .trim()
+ .split("\n\n")
+ .filter(Boolean)
+ .map((frame) => JSON.parse(frame.replace(/^data: /, "")) as AGUIEvent);
+}
+
+function expectValidAGUIEvents(events: AGUIEvent[]): void {
+ for (const event of events) {
+ expect(EventSchemas.safeParse(event).success, JSON.stringify(event)).toBe(true);
+ }
+}
diff --git a/packages/langchain/src/__tests__/transformer.test.ts b/packages/langchain/src/__tests__/transformer.test.ts
new file mode 100644
index 000000000..cb10c3a31
--- /dev/null
+++ b/packages/langchain/src/__tests__/transformer.test.ts
@@ -0,0 +1,303 @@
+import { EventType, type AGUIEvent } from "@ag-ui/core";
+import type { ProtocolEvent, ToolsEventData } from "@langchain/langgraph";
+import type { MessagesData } from "@langchain/protocol";
+import { describe, expect, it } from "vitest";
+
+import { openUIStreamTransformer } from "../transformer";
+
+describe("openUIStreamTransformer", () => {
+ it("converts streamed assistant text when the runtime omits message-start role", () => {
+ const transformer = openUIStreamTransformer();
+ const { openui } = transformer.init();
+
+ transformer.process(
+ runtimeMessageEvent({
+ event: "message-start",
+ id: "message-1",
+ run_id: "run-1",
+ }),
+ );
+ transformer.process(
+ messageEvent({ event: "content-block-start", index: 0, content: { type: "text", text: "" } }),
+ );
+ transformer.process(
+ messageEvent({
+ event: "content-block-delta",
+ index: 0,
+ delta: { type: "text-delta", text: "Hello" },
+ }),
+ );
+ transformer.process(
+ messageEvent({
+ event: "content-block-delta",
+ index: 0,
+ delta: { type: "text-delta", text: " world" },
+ }),
+ );
+ transformer.process(messageEvent({ event: "message-finish" }));
+ transformer.finalize?.();
+
+ expect(channelItems(openui)).toEqual([
+ {
+ type: EventType.TEXT_MESSAGE_START,
+ messageId: "message-1",
+ role: "assistant",
+ },
+ {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ messageId: "message-1",
+ delta: "Hello",
+ },
+ {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ messageId: "message-1",
+ delta: " world",
+ },
+ { type: EventType.TEXT_MESSAGE_END, messageId: "message-1" },
+ ]);
+ });
+
+ it("converts incremental tool calls without duplicating finalized arguments", () => {
+ const transformer = openUIStreamTransformer();
+ const { openui } = transformer.init();
+
+ transformer.process(messageEvent({ event: "message-start", id: "message-2", role: "ai" }));
+ transformer.process(
+ messageEvent({
+ event: "content-block-start",
+ index: 0,
+ content: { type: "tool_call_chunk", id: "call-1", name: "", args: "" },
+ }),
+ );
+ transformer.process(
+ messageEvent({
+ event: "content-block-delta",
+ index: 0,
+ delta: { type: "block-delta", fields: { name: "get_weather", args: '{"city":' } },
+ }),
+ );
+ transformer.process(
+ messageEvent({
+ event: "content-block-delta",
+ index: 0,
+ delta: { type: "block-delta", fields: { args: '"Paris"}' } },
+ }),
+ );
+ transformer.process(
+ messageEvent({
+ event: "content-block-finish",
+ index: 0,
+ content: {
+ type: "tool_call",
+ id: "call-1",
+ name: "get_weather",
+ args: { city: "Paris" },
+ },
+ }),
+ );
+ transformer.process(messageEvent({ event: "message-finish" }));
+ transformer.process(
+ toolsEvent({
+ event: "tool-output-delta",
+ tool_call_id: "call-1",
+ delta: "streamed but superseded",
+ }),
+ );
+ transformer.process(
+ toolsEvent({
+ event: "tool-finished",
+ tool_call_id: "call-1",
+ output: { temperature: 21 },
+ }),
+ );
+
+ expect(channelItems(openui)).toEqual([
+ {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "call-1",
+ toolCallName: "get_weather",
+ },
+ { type: EventType.TOOL_CALL_ARGS, toolCallId: "call-1", delta: '{"city":' },
+ { type: EventType.TOOL_CALL_ARGS, toolCallId: "call-1", delta: '"Paris"}' },
+ { type: EventType.TOOL_CALL_END, toolCallId: "call-1" },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ messageId: "tool-result-call-1",
+ toolCallId: "call-1",
+ content: '{"temperature":21}',
+ role: "tool",
+ },
+ ]);
+ });
+
+ it("ends an active tool call before an early result and ignores a later message end", () => {
+ const transformer = openUIStreamTransformer();
+ const { openui } = transformer.init();
+
+ transformer.process(messageEvent({ event: "message-start", id: "message-early", role: "ai" }));
+ transformer.process(
+ messageEvent({
+ event: "content-block-start",
+ index: 0,
+ content: {
+ type: "tool_call",
+ id: "call-early",
+ name: "get_weather",
+ args: { city: "Paris" },
+ },
+ }),
+ );
+ transformer.process(
+ toolsEvent({
+ event: "tool-finished",
+ tool_call_id: "call-early",
+ output: { temperature: 21 },
+ }),
+ );
+ transformer.process(
+ messageEvent({
+ event: "content-block-finish",
+ index: 0,
+ content: {
+ type: "tool_call",
+ id: "call-early",
+ name: "get_weather",
+ args: { city: "Paris" },
+ },
+ }),
+ );
+
+ expect(channelItems(openui)).toEqual([
+ {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "call-early",
+ toolCallName: "get_weather",
+ },
+ {
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: "call-early",
+ delta: '{"city":"Paris"}',
+ },
+ { type: EventType.TOOL_CALL_END, toolCallId: "call-early" },
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ messageId: "tool-result-call-early",
+ toolCallId: "call-early",
+ content: '{"temperature":21}',
+ role: "tool",
+ },
+ ]);
+ });
+
+ it("ignores non-assistant and ambiguous role-less messages plus its own remote channel", () => {
+ const transformer = openUIStreamTransformer();
+ const { openui } = transformer.init();
+
+ transformer.process(messageEvent({ event: "message-start", id: "message-3", role: "human" }));
+ transformer.process(
+ messageEvent({
+ event: "content-block-start",
+ index: 0,
+ content: { type: "text", text: "input" },
+ }),
+ );
+ transformer.process(runtimeMessageEvent({ event: "message-start", id: "ambiguous-message" }));
+ transformer.process(
+ messageEvent({
+ event: "content-block-start",
+ index: 0,
+ content: { type: "text", text: "ambiguous" },
+ }),
+ );
+ transformer.process({
+ type: "event",
+ seq: 1,
+ method: "custom:openui",
+ params: { namespace: [], timestamp: 0, data: { type: EventType.RUN_ERROR } },
+ });
+
+ expect(channelItems(openui)).toEqual([]);
+ });
+
+ it("surfaces tool failures as completed AG-UI tool results", () => {
+ const transformer = openUIStreamTransformer();
+ const { openui } = transformer.init();
+
+ transformer.process(
+ toolsEvent({
+ event: "tool-error",
+ tool_call_id: "call-error",
+ message: "weather provider unavailable",
+ }),
+ );
+
+ expect(channelItems(openui)).toEqual([
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ messageId: "tool-result-call-error",
+ toolCallId: "call-error",
+ content: "weather provider unavailable",
+ role: "tool",
+ isError: true,
+ error: "weather provider unavailable",
+ },
+ ]);
+ });
+
+ it("finalizes active text and reports run failures", () => {
+ const transformer = openUIStreamTransformer();
+ const { openui } = transformer.init();
+
+ transformer.process(messageEvent({ event: "message-start", id: "message-4", role: "ai" }));
+ transformer.process(
+ messageEvent({
+ event: "content-block-delta",
+ index: 0,
+ delta: { type: "text-delta", text: "Partial" },
+ }),
+ );
+ transformer.finalize?.();
+ transformer.fail?.(new Error("model unavailable"));
+
+ expect(channelItems(openui)).toEqual([
+ {
+ type: EventType.TEXT_MESSAGE_START,
+ messageId: "message-4",
+ role: "assistant",
+ },
+ {
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ messageId: "message-4",
+ delta: "Partial",
+ },
+ { type: EventType.TEXT_MESSAGE_END, messageId: "message-4" },
+ { type: EventType.RUN_ERROR, message: "model unavailable" },
+ ]);
+ });
+});
+
+function messageEvent(data: MessagesData): ProtocolEvent {
+ return runtimeMessageEvent(data);
+}
+
+function runtimeMessageEvent(data: unknown): ProtocolEvent {
+ return {
+ type: "event",
+ seq: 0,
+ method: "messages",
+ params: { namespace: [], timestamp: 0, data },
+ };
+}
+
+function toolsEvent(data: ToolsEventData): ProtocolEvent {
+ return {
+ type: "event",
+ seq: 0,
+ method: "tools",
+ params: { namespace: ["tools:call"], timestamp: 0, data },
+ };
+}
+
+function channelItems(channel: { size: number; get(index: number): AGUIEvent }): AGUIEvent[] {
+ return Array.from({ length: channel.size }, (_, index) => channel.get(index));
+}
diff --git a/packages/langchain/src/id.ts b/packages/langchain/src/id.ts
new file mode 100644
index 000000000..341fdd2fa
--- /dev/null
+++ b/packages/langchain/src/id.ts
@@ -0,0 +1,18 @@
+/** Creates an opaque correlation id without requiring a Node-only import. */
+export function createId(): string {
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
+
+ const bytes = new Uint8Array(16);
+ if (globalThis.crypto?.getRandomValues) {
+ globalThis.crypto.getRandomValues(bytes);
+ } else {
+ for (let index = 0; index < bytes.length; index += 1) {
+ bytes[index] = Math.floor(Math.random() * 256);
+ }
+ }
+
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
diff --git a/packages/langchain/src/index.ts b/packages/langchain/src/index.ts
new file mode 100644
index 000000000..442cb2d9a
--- /dev/null
+++ b/packages/langchain/src/index.ts
@@ -0,0 +1,7 @@
+export { createLangChainStreamResponse } from "./request-handler";
+export type {
+ CreateLangChainStreamResponseOptions,
+ LangChainInputMessage,
+} from "./request-handler";
+export { streamOpenUI } from "./stream-relay";
+export type { StreamOpenUIOptions } from "./stream-relay";
diff --git a/packages/langchain/src/request-handler.ts b/packages/langchain/src/request-handler.ts
new file mode 100644
index 000000000..09a93ce2d
--- /dev/null
+++ b/packages/langchain/src/request-handler.ts
@@ -0,0 +1,239 @@
+import { MessageSchema, type InputContent, type Message } from "@ag-ui/core";
+
+import { streamOpenUI } from "./stream-relay";
+
+/** A LangChain/LangGraph input message accepted by a graph's `messages` field. */
+export interface LangChainInputMessage {
+ type: string;
+ content?: unknown;
+ tool_calls?: unknown;
+ tool_call_id?: string;
+ [key: string]: unknown;
+}
+
+/** Configuration for {@link createLangChainStreamResponse}. */
+export interface CreateLangChainStreamResponseOptions {
+ /** LangGraph agent-protocol-v2 base URL, for example `http://localhost:2024`. */
+ apiUrl: string;
+ /** Graph or assistant id registered on the LangGraph server. */
+ assistantId: string;
+ /** Optional LangSmith/LangGraph Platform API key, sent as `x-api-key`. */
+ apiKey?: string;
+ /** Include upstream response details and registered graph ids in errors. Defaults to `false`. */
+ debug?: boolean;
+ /** Delete the temporary LangGraph thread after the run. Defaults to `true`. */
+ cleanupThread?: boolean;
+ /** Register thread cleanup with a serverless execution context such as `waitUntil`. */
+ waitUntil?: (task: Promise<void>) => void;
+}
+
+type AssistantMessage = Extract<Message, { role: "assistant" }>;
+type ToolCall = NonNullable<AssistantMessage["toolCalls"]>[number];
+
+/**
+ * Converts an incoming AG-UI chat request into a streaming response backed by
+ * a stateless LangGraph protocol-v2 run.
+ *
+ * The request body must contain `{ messages: Message[] }`. Visible conversation
+ * history is converted to LangChain input messages; complete tool transcripts
+ * are retained while incomplete pairs are removed before the run starts. The
+ * returned response emits `text/event-stream` AG-UI events and is suitable for
+ * a Next.js, Remix, Hono, or other Web-standard route handler.
+ */
+export async function createLangChainStreamResponse(
+ request: Request,
+ options: CreateLangChainStreamResponseOptions,
+): Promise<Response> {
+ let body: unknown;
+ try {
+ body = (await request.json()) as unknown;
+ } catch {
+ return badRequest("Expected a JSON request body containing a non-empty messages array");
+ }
+
+ const messages = parseChatRequestBody(body);
+ if (!messages) {
+ return badRequest("Expected a JSON request body containing a non-empty messages array");
+ }
+
+ const langChainMessages = toLangChainMessages(messages);
+ const visibleMessages = sanitizeToolHistory(langChainMessages);
+
+ const readable = streamOpenUI({
+ apiUrl: options.apiUrl,
+ assistantId: options.assistantId,
+ apiKey: options.apiKey,
+ input: { messages: visibleMessages },
+ signal: request.signal,
+ debug: options.debug,
+ cleanupThread: options.cleanupThread,
+ waitUntil: options.waitUntil,
+ });
+
+ return new Response(readable, {
+ headers: {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache, no-transform",
+ },
+ });
+}
+
+function badRequest(message: string): Response {
+ return Response.json({ error: message }, { status: 400 });
+}
+
+function sanitizeToolHistory(messages: LangChainInputMessage[]): LangChainInputMessage[] {
+ const sanitized: LangChainInputMessage[] = [];
+
+ for (let index = 0; index < messages.length; index += 1) {
+ const message = messages[index];
+ if (!message) continue;
+
+ // Orphaned tool results are invalid without a preceding assistant call.
+ if (message.type === "tool") continue;
+
+ const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
+ if (message.type !== "ai" || toolCalls.length === 0) {
+ sanitized.push(message);
+ continue;
+ }
+
+ const followingToolMessages: LangChainInputMessage[] = [];
+ let nextIndex = index + 1;
+ while (messages[nextIndex]?.type === "tool") {
+ followingToolMessages.push(messages[nextIndex] as LangChainInputMessage);
+ nextIndex += 1;
+ }
+
+ const resultIds = new Set(
+ followingToolMessages
+ .map((toolMessage) => toolMessage.tool_call_id)
+ .filter((id): id is string => typeof id === "string" && id.length > 0),
+ );
+ const completeToolCalls = toolCalls.filter((toolCall) => {
+ const id = getInputToolCallId(toolCall);
+ return id !== undefined && resultIds.has(id);
+ });
+ const completeIds = new Set(
+ completeToolCalls.map(getInputToolCallId).filter((id): id is string => id !== undefined),
+ );
+
+ const assistantMessage = { ...message };
+ if (completeToolCalls.length > 0) {
+ assistantMessage.tool_calls = completeToolCalls;
+ } else {
+ delete assistantMessage.tool_calls;
+ }
+ sanitized.push(assistantMessage);
+ sanitized.push(
+ ...followingToolMessages.filter(
+ (toolMessage) =>
+ typeof toolMessage.tool_call_id === "string" && completeIds.has(toolMessage.tool_call_id),
+ ),
+ );
+ index = nextIndex - 1;
+ }
+
+ return sanitized;
+}
+
+function toLangChainMessages(messages: Message[]): LangChainInputMessage[] {
+ return messages.flatMap((message) => {
+ switch (message.role) {
+ case "user":
+ return [{ type: "human", content: toLangChainContent(message.content) }];
+ case "assistant": {
+ const result: LangChainInputMessage = { type: "ai", content: message.content ?? "" };
+ if (message.toolCalls?.length) {
+ result.tool_calls = message.toolCalls.map(toLangChainToolCall);
+ }
+ return [result];
+ }
+ case "tool":
+ return [
+ {
+ type: "tool",
+ content: message.content,
+ tool_call_id: message.toolCallId,
+ },
+ ];
+ case "system":
+ case "developer":
+ return [{ type: "system", content: message.content }];
+ case "activity":
+ case "reasoning":
+ return [];
+ default:
+ return [];
+ }
+ });
+}
+
+function toLangChainToolCall(toolCall: ToolCall) {
+ return {
+ id: toolCall.id,
+ name: toolCall.function.name,
+ args: safeParseArgs(toolCall.function.arguments),
+ };
+}
+
+function toLangChainContent(
+ content: Extract<Message, { role: "user" }>["content"],
+): string | Array<Record<string, unknown>> {
+ if (typeof content === "string") return content;
+ return content.map(toLangChainContentBlock);
+}
+
+function toLangChainContentBlock(block: InputContent): Record<string, unknown> {
+ if (block.type === "text") return { type: "text", text: block.text };
+
+ if (block.type === "binary") {
+ return {
+ type: "file",
+ mimeType: block.mimeType,
+ ...(block.url ? { url: block.url } : {}),
+ ...(block.data ? { data: block.data } : {}),
+ ...(block.id ? { fileId: block.id } : {}),
+ ...(block.filename ? { metadata: { filename: block.filename } } : {}),
+ };
+ }
+
+ const type = block.type === "document" ? "file" : block.type;
+ const source = block.source;
+ const metadata = "metadata" in block && block.metadata !== undefined ? block.metadata : undefined;
+
+ if (source.type === "url") {
+ return {
+ type,
+ url: source.value,
+ ...(source.mimeType ? { mimeType: source.mimeType } : {}),
+ ...(metadata !== undefined ? { metadata } : {}),
+ };
+ }
+
+ return {
+ type,
+ data: source.value,
+ mimeType: source.mimeType,
+ ...(metadata !== undefined ? { metadata } : {}),
+ };
+}
+
+function safeParseArgs(args: string): Record<string, unknown> | string {
+ try {
+ return JSON.parse(args) as Record<string, unknown>;
+ } catch {
+ return args;
+ }
+}
+
+function getInputToolCallId(value: unknown): string | undefined {
+ if (typeof value !== "object" || value === null || !("id" in value)) return undefined;
+ return typeof value.id === "string" && value.id.length > 0 ? value.id : undefined;
+}
+
+function parseChatRequestBody(value: unknown): Message[] | undefined {
+ if (typeof value !== "object" || value === null || !("messages" in value)) return undefined;
+ const parsed = MessageSchema.array().safeParse(value.messages);
+ return parsed.success && parsed.data.length > 0 ? parsed.data : undefined;
+}
diff --git a/packages/langchain/src/stream-relay.ts b/packages/langchain/src/stream-relay.ts
new file mode 100644
index 000000000..c5d2af532
--- /dev/null
+++ b/packages/langchain/src/stream-relay.ts
@@ -0,0 +1,513 @@
+import { EventType, type AGUIEvent } from "@ag-ui/core";
+
+import { createId } from "./id";
+
+/** Configuration for {@link streamOpenUI}. */
+export interface StreamOpenUIOptions {
+ /** LangGraph agent-protocol-v2 base URL, for example `http://localhost:2024`. */
+ apiUrl: string;
+ /** Graph or assistant id registered on the LangGraph server. */
+ assistantId: string;
+ /** Optional LangSmith/LangGraph Platform API key, sent as `x-api-key`. */
+ apiKey?: string;
+ /** Input passed verbatim to `run.start`, commonly `{ messages: [...] }`. */
+ input: unknown;
+ /** Aborts both upstream LangGraph requests when the caller disconnects. */
+ signal?: AbortSignal;
+ /** Include upstream response details and registered graph ids in errors. Defaults to `false`. */
+ debug?: boolean;
+ /** Delete the temporary LangGraph thread after the run. Defaults to `true`. */
+ cleanupThread?: boolean;
+ /** Register thread cleanup with a serverless execution context such as `waitUntil`. */
+ waitUntil?: (task: Promise<void>) => void;
+}
+
+interface ProtocolSSEEvent {
+ event: string;
+ data: string;
+}
+
+interface ProtocolEventEnvelope {
+ method?: string;
+ params: {
+ namespace?: unknown;
+ data?: unknown;
+ };
+}
+
+interface NamedCustomPayload {
+ name?: string;
+ payload?: unknown;
+}
+
+interface LifecyclePayload {
+ event?: unknown;
+ error?: unknown;
+}
+
+interface StartRunResult {
+ runId?: string;
+}
+
+const encoder = new TextEncoder();
+const THREAD_CLEANUP_TIMEOUT_MS = 5_000;
+
+/**
+ * Starts a stateless LangGraph protocol-v2 run and relays its `custom:openui`
+ * channel as AG-UI Server-Sent Events, wrapped in the run lifecycle from the
+ * LangGraph `lifecycle` channel.
+ *
+ * The returned stream is framework-independent and can be passed directly to
+ * `new Response(...)`. Cancelling it or aborting `options.signal` tears down
+ * both the event subscription and the run request.
+ */
+export function streamOpenUI({
+ apiUrl,
+ assistantId,
+ apiKey,
+ input,
+ signal,
+ debug = false,
+ cleanupThread = true,
+ waitUntil,
+}: StreamOpenUIOptions): ReadableStream<Uint8Array> {
+ const upstreamAbort = new AbortController();
+ const relay = new TransformStream<Uint8Array, Uint8Array>();
+ const writer = relay.writable.getWriter();
+ const reader = relay.readable.getReader();
+ let closed = false;
+
+ const abortUpstream = () => {
+ closed = true;
+ upstreamAbort.abort(signal?.reason);
+ void writer.abort(signal?.reason).catch(() => undefined);
+ };
+ if (signal?.aborted) {
+ abortUpstream();
+ } else {
+ signal?.addEventListener("abort", abortUpstream, { once: true });
+ }
+
+ const send = async (event: AGUIEvent): Promise<boolean> => {
+ if (closed) return false;
+ try {
+ // TransformStream.write waits for downstream demand, so a fast agent
+ // cannot grow an unbounded queue when the HTTP client reads slowly.
+ await writer.write(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
+ return true;
+ } catch {
+ closed = true;
+ upstreamAbort.abort();
+ return false;
+ }
+ };
+
+ const headers = buildHeaders(apiKey);
+ const baseUrl = apiUrl.replace(/\/+$/, "");
+ const threadId = createId();
+ let threadCreated = false;
+ let threadCleanupPromise: Promise<void> | undefined;
+
+ const cleanupTemporaryThread = (): Promise<void> => {
+ if (!cleanupThread || !threadCreated) return Promise.resolve();
+ if (!threadCleanupPromise) {
+ threadCleanupPromise = deleteThread(baseUrl, threadId, headers);
+ try {
+ waitUntil?.(threadCleanupPromise);
+ } catch {
+ // Cleanup is still awaited below when a runtime hook rejects registration.
+ }
+ }
+ return threadCleanupPromise;
+ };
+
+ const pump = async () => {
+ try {
+ // The event stream must be open before run.start. Reversing this order
+ // can miss early events or deadlock against servers waiting for a
+ // subscriber. No namespace filter is intentional: DeepAgents emits
+ // from nested `model_request:*` and `tools:*` namespaces.
+ const eventsResponsePromise = fetch(`${baseUrl}/threads/${threadId}/stream/events`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ channels: ["custom:openui", "lifecycle"] }),
+ signal: upstreamAbort.signal,
+ });
+
+ // Settle immediately so a fast run.start failure can never become an
+ // unhandled rejection while the event subscription is connecting.
+ const startRunResultPromise = startRun({
+ baseUrl,
+ threadId,
+ assistantId,
+ input,
+ headers,
+ signal: upstreamAbort.signal,
+ debug,
+ }).then(
+ (result) => ({ ok: true as const, result }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+
+ const eventsResponse = await eventsResponsePromise;
+ if (!eventsResponse.ok || !eventsResponse.body) {
+ upstreamAbort.abort();
+ const startResult = await startRunResultPromise;
+ threadCreated = startResult.ok;
+ throw new Error(`LangGraph event stream failed: ${eventsResponse.status}`);
+ }
+
+ const startResult = await startRunResultPromise;
+ if (!startResult.ok) throw startResult.error;
+ threadCreated = true;
+ const { runId } = startResult.result;
+ if (!runId) throw new Error("LangGraph run.start returned no run id");
+
+ await send({
+ type: EventType.RUN_STARTED,
+ threadId,
+ runId,
+ });
+
+ const eventReader = eventsResponse.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+
+ const processBlock = async (block: string): Promise<boolean> => {
+ const parsed = parseSSEBlock(block);
+ if (!parsed.data) return false;
+
+ if (isOpenUIEventName(parsed.event)) {
+ const event = extractAGUIEvent(parsed.data);
+ if (!event) return false;
+
+ const publicEvent = sanitizeAGUIEvent(event, debug);
+ if (!(await send(publicEvent))) return true;
+ return isTerminalEvent(publicEvent);
+ }
+
+ if (parsed.event !== "lifecycle") return false;
+ const lifecycle = extractRootLifecycle(parsed.data);
+ if (!lifecycle) return false;
+
+ if (lifecycle.event === "completed" || lifecycle.event === "interrupted") {
+ return send({ type: EventType.RUN_FINISHED, threadId, runId });
+ }
+
+ if (lifecycle.event === "failed") {
+ const message =
+ debug && typeof lifecycle.error === "string" ? lifecycle.error : "LangGraph run failed";
+ return send({ type: EventType.RUN_ERROR, message });
+ }
+
+ return false;
+ };
+
+ while (!closed) {
+ const { done, value } = await eventReader.read();
+ buffer += decoder.decode(value, { stream: !done });
+
+ const { blocks, remainder } = splitSSEBlocks(buffer);
+ buffer = remainder;
+
+ for (const block of blocks) {
+ if (await processBlock(block)) {
+ upstreamAbort.abort();
+ return;
+ }
+ }
+
+ if (done) {
+ if (buffer.trim() && (await processBlock(buffer))) {
+ upstreamAbort.abort();
+ return;
+ }
+ if (!closed) await send({ type: EventType.RUN_FINISHED, threadId, runId });
+ break;
+ }
+ }
+ } catch (error) {
+ if (!signal?.aborted && !closed) {
+ await send({
+ type: EventType.RUN_ERROR,
+ message:
+ debug && error instanceof Error ? error.message : "Unable to complete LangGraph run",
+ });
+ }
+ } finally {
+ upstreamAbort.abort();
+ signal?.removeEventListener("abort", abortUpstream);
+ await cleanupTemporaryThread();
+ if (!closed) {
+ try {
+ await writer.close();
+ } catch {
+ // The consumer may already have cancelled the stream.
+ }
+ }
+ closed = true;
+ }
+ };
+
+ void pump();
+
+ return new ReadableStream<Uint8Array>(
+ {
+ async pull(controller) {
+ try {
+ const { done, value } = await reader.read();
+ if (done) {
+ controller.close();
+ } else {
+ controller.enqueue(value);
+ }
+ } catch (error) {
+ if (closed) {
+ controller.close();
+ } else {
+ controller.error(error);
+ }
+ }
+ },
+ async cancel(reason) {
+ closed = true;
+ upstreamAbort.abort(reason);
+ await Promise.allSettled([reader.cancel(reason), cleanupTemporaryThread()]);
+ },
+ },
+ { highWaterMark: 0 },
+ );
+}
+
+async function startRun({
+ baseUrl,
+ threadId,
+ assistantId,
+ input,
+ headers,
+ signal,
+ debug,
+}: {
+ baseUrl: string;
+ threadId: string;
+ assistantId: string;
+ input: unknown;
+ headers: HeadersInit;
+ signal: AbortSignal;
+ debug: boolean;
+}): Promise<StartRunResult> {
+ const response = await fetch(`${baseUrl}/threads/${threadId}/commands`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ id: 1,
+ method: "run.start",
+ params: {
+ assistant_id: assistantId,
+ input,
+ },
+ }),
+ signal,
+ });
+
+ const responseText = await response.text();
+ if (!response.ok) {
+ const hint =
+ debug && response.status === 404
+ ? await getAssistantHint(baseUrl, headers, assistantId, signal)
+ : undefined;
+ throw new Error(
+ [
+ `LangGraph run.start failed: ${response.status}`,
+ debug ? responseText.trim() || undefined : undefined,
+ hint,
+ ]
+ .filter(Boolean)
+ .join(". "),
+ );
+ }
+
+ if (!responseText) return {};
+
+ const payload = safeParseJSON(responseText);
+ if (isErrorPayload(payload)) {
+ throw new Error(
+ debug ? (payload.message ?? "LangGraph run.start failed") : "LangGraph run.start failed",
+ );
+ }
+
+ return { runId: getRunId(payload) };
+}
+
+async function deleteThread(
+ baseUrl: string,
+ threadId: string,
+ headers: HeadersInit,
+): Promise<void> {
+ const cleanupAbort = new AbortController();
+ const timeout = setTimeout(() => cleanupAbort.abort(), THREAD_CLEANUP_TIMEOUT_MS);
+ try {
+ await fetch(`${baseUrl}/threads/${threadId}`, {
+ method: "DELETE",
+ headers,
+ signal: cleanupAbort.signal,
+ });
+ } catch {
+ // Cleanup is best-effort and must not replace the run's terminal event.
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
+async function getAssistantHint(
+ baseUrl: string,
+ headers: HeadersInit,
+ assistantId: string,
+ signal: AbortSignal,
+): Promise<string | undefined> {
+ try {
+ const response = await fetch(`${baseUrl}/assistants/search`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({}),
+ signal,
+ });
+ if (!response.ok) return undefined;
+
+ const assistants = (await response.json()) as Array<{
+ assistant_id?: string;
+ graph_id?: string;
+ name?: string | null;
+ }>;
+ const registered = assistants
+ .map((assistant) => assistant.graph_id ?? assistant.name ?? assistant.assistant_id)
+ .filter((value): value is string => Boolean(value));
+
+ if (!registered.length) return undefined;
+ return `Configured assistant "${assistantId}" is not registered on this LangGraph server; available graph ids: ${registered.join(", ")}`;
+ } catch {
+ return undefined;
+ }
+}
+
+function buildHeaders(apiKey?: string): HeadersInit {
+ const headers: Record<string, string> = {
+ "Content-Type": "application/json",
+ };
+
+ if (apiKey) headers["x-api-key"] = apiKey;
+ return headers;
+}
+
+function splitSSEBlocks(buffer: string): { blocks: string[]; remainder: string } {
+ const blocks = buffer.split(/\r\n\r\n|\n\n|\r\r/);
+ return { blocks: blocks.slice(0, -1), remainder: blocks.at(-1) ?? "" };
+}
+
+function parseSSEBlock(block: string): ProtocolSSEEvent {
+ let event = "";
+ const dataLines: string[] = [];
+
+ for (const line of block.split(/\r\n|\r|\n/)) {
+ if (line.startsWith("event:")) {
+ event = stripSSEFieldPrefix(line.slice(6));
+ } else if (line.startsWith("data:")) {
+ dataLines.push(stripSSEFieldPrefix(line.slice(5)));
+ }
+ }
+
+ return { event, data: dataLines.join("\n") };
+}
+
+function stripSSEFieldPrefix(value: string): string {
+ return value.startsWith(" ") ? value.slice(1) : value;
+}
+
+function extractAGUIEvent(data: string): AGUIEvent | undefined {
+ const parsed = safeParseJSON(data);
+ if (isProtocolEventEnvelope(parsed)) {
+ return extractCustomPayload(parsed.params.data);
+ }
+ return isAGUIEvent(parsed) ? parsed : undefined;
+}
+
+function extractRootLifecycle(data: string): LifecyclePayload | undefined {
+ const parsed = safeParseJSON(data);
+ if (!isProtocolEventEnvelope(parsed)) return undefined;
+ if (!Array.isArray(parsed.params.namespace) || parsed.params.namespace.length !== 0) {
+ return undefined;
+ }
+ return isLifecyclePayload(parsed.params.data) ? parsed.params.data : undefined;
+}
+
+function sanitizeAGUIEvent(event: AGUIEvent, debug: boolean): AGUIEvent {
+ if (debug || event.type !== EventType.RUN_ERROR) return event;
+ return { type: EventType.RUN_ERROR, message: "LangGraph run failed" };
+}
+
+function isOpenUIEventName(event: string): boolean {
+ return event === "custom" || event === "custom:openui";
+}
+
+function extractCustomPayload(data: unknown): AGUIEvent | undefined {
+ if (isNamedCustomPayload(data)) {
+ if (data.name !== "openui") return undefined;
+ return isAGUIEvent(data.payload) ? data.payload : undefined;
+ }
+
+ return isAGUIEvent(data) ? data : undefined;
+}
+
+function safeParseJSON(value: string): unknown {
+ try {
+ return JSON.parse(value) as unknown;
+ } catch {
+ return undefined;
+ }
+}
+
+function isProtocolEventEnvelope(value: unknown): value is ProtocolEventEnvelope {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "params" in value &&
+ typeof value.params === "object" &&
+ value.params !== null &&
+ "data" in value.params
+ );
+}
+
+function isNamedCustomPayload(value: unknown): value is NamedCustomPayload {
+ return typeof value === "object" && value !== null && "name" in value && "payload" in value;
+}
+
+function isLifecyclePayload(value: unknown): value is LifecyclePayload {
+ return typeof value === "object" && value !== null && "event" in value;
+}
+
+function isAGUIEvent(value: unknown): value is AGUIEvent {
+ return (
+ typeof value === "object" && value !== null && "type" in value && typeof value.type === "string"
+ );
+}
+
+function isErrorPayload(value: unknown): value is { type: "error"; message?: string } {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "type" in value &&
+ value.type === "error" &&
+ (!("message" in value) || typeof value.message === "string")
+ );
+}
+
+function getRunId(value: unknown): string | undefined {
+ if (typeof value !== "object" || value === null || !("result" in value)) return undefined;
+ const result = value.result;
+ if (typeof result !== "object" || result === null || !("run_id" in result)) return undefined;
+ return typeof result.run_id === "string" && result.run_id.length > 0 ? result.run_id : undefined;
+}
+
+function isTerminalEvent(event: AGUIEvent): boolean {
+ return event.type === EventType.RUN_ERROR || event.type === EventType.RUN_FINISHED;
+}
diff --git a/packages/langchain/src/transformer.ts b/packages/langchain/src/transformer.ts
new file mode 100644
index 000000000..28b779b32
--- /dev/null
+++ b/packages/langchain/src/transformer.ts
@@ -0,0 +1,334 @@
+import { EventType, type AGUIEvent } from "@ag-ui/core";
+import type { ProtocolEvent, StreamTransformer, ToolsEventData } from "@langchain/langgraph";
+import { StreamChannel } from "@langchain/langgraph";
+import type { ContentBlock, MessagesData } from "@langchain/protocol";
+
+import { createId } from "./id";
+
+const OPENUI_CHANNEL_NAME = "openui";
+const OPENUI_CHANNEL_METHOD = `custom:${OPENUI_CHANNEL_NAME}`;
+
+const TOOL_BLOCK_TYPES = new Set([
+ "tool_call",
+ "tool_call_chunk",
+ "server_tool_call",
+ "server_tool_call_chunk",
+]);
+
+interface ToolCallState {
+ id: string;
+ name: string;
+ started: boolean;
+ ended: boolean;
+ argsEmitted: boolean;
+}
+
+/**
+ * Projects LangGraph's protocol-v2 `messages` and `tools` streams into AG-UI
+ * events and publishes them on the remote `custom:openui` channel.
+ *
+ * Add the returned factory to an agent's `streamTransformers` array. Remote
+ * clients can then subscribe to `custom:openui`, or use {@link streamOpenUI}
+ * and {@link createLangChainStreamResponse} to relay that channel as AG-UI
+ * Server-Sent Events.
+ */
+export function openUIStreamTransformer(): StreamTransformer<{
+ openui: StreamChannel<AGUIEvent>;
+}> {
+ const channel = StreamChannel.remote<AGUIEvent>(OPENUI_CHANNEL_NAME);
+
+ let currentMessageId: string = createId();
+ let acceptsCurrentMessage = false;
+ let textMessageId: string | undefined;
+ let textStarted = false;
+ let textEnded = false;
+ let runErrorEmitted = false;
+
+ const toolCallsByIndex = new Map<string, ToolCallState>();
+ const toolOutputByCallId = new Map<string, string>();
+
+ const emit = (event: AGUIEvent) => channel.push(event);
+
+ const ensureTextStart = () => {
+ if (textStarted) return;
+ textMessageId = currentMessageId;
+ emit({
+ type: EventType.TEXT_MESSAGE_START,
+ messageId: textMessageId,
+ role: "assistant",
+ });
+ textStarted = true;
+ };
+
+ const emitTextDelta = (delta: string) => {
+ if (!delta) return;
+ ensureTextStart();
+ emit({
+ type: EventType.TEXT_MESSAGE_CONTENT,
+ messageId: textMessageId ?? currentMessageId,
+ delta,
+ });
+ };
+
+ const endText = () => {
+ if (!textStarted || textEnded) return;
+ emit({
+ type: EventType.TEXT_MESSAGE_END,
+ messageId: textMessageId ?? currentMessageId,
+ });
+ textEnded = true;
+ };
+
+ const syncToolCall = (
+ index: number | string,
+ block: Partial<ContentBlock> & Record<string, unknown>,
+ emitArgs: boolean,
+ ): ToolCallState => {
+ const key = String(index);
+ let state = toolCallsByIndex.get(key);
+
+ if (!state) {
+ state = {
+ id: getToolCallId(block) ?? `tool-${key}`,
+ name: getToolCallName(block) ?? "",
+ started: false,
+ ended: false,
+ argsEmitted: false,
+ };
+ toolCallsByIndex.set(key, state);
+ } else if (!state.started) {
+ state.id = getToolCallId(block) ?? state.id;
+ state.name = getToolCallName(block) ?? state.name;
+ }
+
+ if (state.ended) return state;
+
+ if (!state.started && state.name) {
+ emit({
+ type: EventType.TOOL_CALL_START,
+ toolCallId: state.id,
+ toolCallName: state.name,
+ });
+ state.started = true;
+ }
+
+ const args = getArgsString(block);
+ if (emitArgs && args && state.started) {
+ emit({
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: state.id,
+ delta: args,
+ });
+ state.argsEmitted = true;
+ }
+
+ return state;
+ };
+
+ const endToolCall = (state: ToolCallState) => {
+ if (state.ended || !state.started) return;
+ emit({ type: EventType.TOOL_CALL_END, toolCallId: state.id });
+ state.ended = true;
+ };
+
+ const endAllToolCalls = () => {
+ for (const state of toolCallsByIndex.values()) endToolCall(state);
+ };
+
+ const endToolCallById = (toolCallId: string) => {
+ const state = Array.from(toolCallsByIndex.values()).find(({ id }) => id === toolCallId);
+ if (state) endToolCall(state);
+ };
+
+ const resetMessage = (data: Extract<MessagesData, { event: "message-start" }>) => {
+ endAllToolCalls();
+ endText();
+
+ currentMessageId = data.id || createId();
+ // StreamProtocolMessagesHandler intentionally omits `role` only for live
+ // AI model output and attaches its model run id. Replayed human/system/tool
+ // messages always carry an explicit role. Requiring that run id keeps the
+ // compatibility path from failing open for arbitrary role-less messages.
+ const { role: runtimeRole, run_id: runtimeRunId } = data as {
+ role?: unknown;
+ run_id?: unknown;
+ };
+ acceptsCurrentMessage =
+ runtimeRole === "ai" ||
+ runtimeRole === "assistant" ||
+ (runtimeRole == null && typeof runtimeRunId === "string" && runtimeRunId.length > 0);
+ textMessageId = undefined;
+ textStarted = false;
+ textEnded = false;
+ toolCallsByIndex.clear();
+ };
+
+ const processMessages = (data: MessagesData) => {
+ if (data.event === "message-start") {
+ resetMessage(data);
+ return;
+ }
+
+ if (!acceptsCurrentMessage) return;
+
+ switch (data.event) {
+ case "content-block-start": {
+ const block = data.content;
+ if (isTextBlock(block)) {
+ ensureTextStart();
+ emitTextDelta(typeof block.text === "string" ? block.text : "");
+ } else if (isToolBlock(block)) {
+ syncToolCall(data.index, block, true);
+ }
+ return;
+ }
+
+ case "content-block-delta": {
+ const delta = data.delta;
+ if (delta.type === "text-delta") {
+ emitTextDelta(typeof delta.text === "string" ? delta.text : "");
+ } else if (delta.type === "block-delta") {
+ const fields = delta.fields as Partial<ContentBlock> & Record<string, unknown>;
+ if (toolCallsByIndex.has(String(data.index)) || isToolBlock(fields)) {
+ syncToolCall(data.index, fields, true);
+ }
+ }
+ return;
+ }
+
+ case "content-block-finish": {
+ const block = data.content;
+ if (isToolBlock(block)) {
+ const state = syncToolCall(data.index, block, false);
+ if (!state.argsEmitted) {
+ syncToolCall(data.index, block, true);
+ }
+ endToolCall(state);
+ }
+ return;
+ }
+
+ case "message-finish":
+ endAllToolCalls();
+ endText();
+ return;
+
+ case "error":
+ endAllToolCalls();
+ emit({ type: EventType.RUN_ERROR, message: data.message });
+ runErrorEmitted = true;
+ return;
+
+ default:
+ return;
+ }
+ };
+
+ const processTools = (data: ToolsEventData) => {
+ const toolCallId = data.tool_call_id;
+
+ switch (data.event) {
+ case "tool-output-delta":
+ toolOutputByCallId.set(toolCallId, (toolOutputByCallId.get(toolCallId) ?? "") + data.delta);
+ return;
+
+ case "tool-finished": {
+ const streamedOutput = toolOutputByCallId.get(toolCallId);
+ toolOutputByCallId.delete(toolCallId);
+ endToolCallById(toolCallId);
+ emit({
+ type: EventType.TOOL_CALL_RESULT,
+ messageId: `tool-result-${toolCallId}`,
+ toolCallId,
+ content: serializeToolOutput(data.output, streamedOutput),
+ role: "tool",
+ });
+ return;
+ }
+
+ case "tool-error":
+ toolOutputByCallId.delete(toolCallId);
+ endToolCallById(toolCallId);
+ emit({
+ type: EventType.TOOL_CALL_RESULT,
+ messageId: `tool-result-${toolCallId}`,
+ toolCallId,
+ content: data.message,
+ role: "tool",
+ isError: true,
+ error: data.message,
+ });
+ return;
+
+ case "tool-started":
+ default:
+ return;
+ }
+ };
+
+ return {
+ init: () => ({ openui: channel }),
+ process: (event: ProtocolEvent) => {
+ // Ignore the events emitted by this transformer to avoid re-entry.
+ if (event.method === OPENUI_CHANNEL_METHOD) return true;
+ // Do not filter by namespace: DeepAgents emits model and tool events
+ // from nested `model_request:*` and `tools:*` namespaces.
+ if (event.method === "messages") {
+ processMessages(event.params.data as MessagesData);
+ } else if (event.method === "tools") {
+ processTools(event.params.data as ToolsEventData);
+ }
+ return true;
+ },
+ finalize: () => {
+ endAllToolCalls();
+ endText();
+ },
+ fail: (error) => {
+ endAllToolCalls();
+ if (!runErrorEmitted) {
+ emit({
+ type: EventType.RUN_ERROR,
+ message: error instanceof Error ? error.message : "LangGraph run failed",
+ });
+ runErrorEmitted = true;
+ }
+ },
+ };
+}
+
+function serializeToolOutput(output: unknown, streamedOutput?: string): string {
+ if (typeof output === "string") return output;
+ if (output === undefined && streamedOutput !== undefined) return streamedOutput;
+ if (output === undefined) return "";
+
+ try {
+ return JSON.stringify(output) ?? String(output);
+ } catch {
+ return String(output);
+ }
+}
+
+function isTextBlock(block: Partial<ContentBlock> & Record<string, unknown>): boolean {
+ return block.type === "text";
+}
+
+function isToolBlock(block: Partial<ContentBlock> & Record<string, unknown>): boolean {
+ return typeof block.type === "string" && TOOL_BLOCK_TYPES.has(block.type);
+}
+
+function getToolCallId(block: Partial<ContentBlock> & Record<string, unknown>): string | undefined {
+ return typeof block.id === "string" && block.id.length > 0 ? block.id : undefined;
+}
+
+function getToolCallName(
+ block: Partial<ContentBlock> & Record<string, unknown>,
+): string | undefined {
+ return typeof block.name === "string" && block.name.length > 0 ? block.name : undefined;
+}
+
+function getArgsString(block: Partial<ContentBlock> & Record<string, unknown>): string {
+ if (typeof block.args === "string") return block.args;
+ if (block.args != null && typeof block.args === "object") return JSON.stringify(block.args);
+ return "";
+}
diff --git a/packages/langchain/tsconfig.json b/packages/langchain/tsconfig.json
new file mode 100644
index 000000000..050ddeb9a
--- /dev/null
+++ b/packages/langchain/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "../../tsconfig.json",
+ "include": ["src/**/*"],
+ "exclude": ["src/**/__tests__/**", "src/**/*.test.ts"],
+ "compilerOptions": {
+ "moduleResolution": "bundler",
+ "module": "ESNext",
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "noEmit": true
+ }
+}
diff --git a/packages/langchain/tsconfig.test.json b/packages/langchain/tsconfig.test.json
new file mode 100644
index 000000000..60b3001d5
--- /dev/null
+++ b/packages/langchain/tsconfig.test.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": true
+ },
+ "include": ["src/**/*"],
+ "exclude": ["dist", "node_modules"]
+}
diff --git a/packages/langchain/tsdown.config.ts b/packages/langchain/tsdown.config.ts
new file mode 100644
index 000000000..701073e67
--- /dev/null
+++ b/packages/langchain/tsdown.config.ts
@@ -0,0 +1,14 @@
+import { defineConfig } from "tsdown";
+
+export default defineConfig({
+ entry: ["src/index.ts", "src/transformer.ts"],
+ format: ["esm", "cjs"],
+ dts: true,
+ sourcemap: true,
+ target: "es2022",
+ outDir: "dist",
+ clean: true,
+ deps: {
+ neverBundle: [/^(?![./]|[A-Za-z]:[/\\])/],
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index dafd0f0e5..5ce567213 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -688,9 +688,6 @@ importers:
examples/langchain-chat:
dependencies:
- '@ag-ui/core':
- specifier: ^0.0.57
- version: 0.0.57
'@langchain/core':
specifier: ^1.2.1
@@ -703,9 +700,9 @@ importers:
'@langchain/openai':
specifier: ^1.5.2
- '@langchain/protocol':
- specifier: ^0.0.18
- version: 0.0.18
+ '@openuidev/langchain':
+ specifier: workspace:*
+ version: link:../../packages/langchain
'@openuidev/react-headless':
specifier: workspace:*
version: link:../../packages/react-headless
@@ -735,7 +732,7 @@ importers:
version: 4.4.3
devDependencies:
'@langchain/langgraph-cli':
- specifier: ^1.2.5
+ specifier: ^1.4.3
version: 1.4.3(bhtnaejseqq2m7qzl44jvsnn2m)
'@openuidev/cli':
specifier: workspace:*
@@ -1783,6 +1780,28 @@ importers:
specifier: ^4.0.18
+ packages/langchain:
+ dependencies:
+ '@ag-ui/core':
+ specifier: ^0.0.57
+ version: 0.0.57
+ devDependencies:
+ '@langchain/core':
+ specifier: ^1.2.1
+ '@langchain/langgraph':
+ specifier: ^1.4.5
+ '@langchain/protocol':
+ specifier: ^0.0.18
+ version: 0.0.18
+ vitest:
+ specifier: ^4.1.0
+ zod:
+ specifier: ^4.2.0
+ version: 4.4.3
+
packages/observability:
devDependencies:
vitest:
@@ -21826,6 +21845,19 @@ snapshots:
svelte: 5.56.8(@typescript-eslint/[email protected])
vue: 3.5.40([email protected])
+ dependencies:
+ '@langchain/protocol': 0.0.18
+ '@types/json-schema': 7.0.15
+ p-queue: 9.3.3
+ p-retry: 7.1.1
+ optionalDependencies:
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+ svelte: 5.56.8(@typescript-eslint/[email protected])
+ vue: 3.5.40([email protected])
+
'@langchain/[email protected]':
dependencies:
'@commander-js/extra-typings': 13.1.0([email protected])
@@ -21848,6 +21880,20 @@ snapshots:
- svelte
- vue
+ dependencies:
+ '@langchain/langgraph-checkpoint': 1.1.3(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected]))([email protected]))
+ '@langchain/protocol': 0.0.18
+ '@standard-schema/spec': 1.1.0
+ zod: 4.4.3
+ transitivePeerDependencies:
+ - react
+ - react-dom
+ - svelte
+ - vue
+
dependencies:
@@ -30240,7 +30286,7 @@ snapshots:
dependencies:
- dotenv: 16.4.7
+ dotenv: 16.6.1
@@ -30586,7 +30632,7 @@ snapshots:
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -30662,35 +30708,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@rtsao/scc': 1.1.0
- array-includes: 3.1.9
- array.prototype.findlastindex: 1.2.6
- array.prototype.flat: 1.3.3
- array.prototype.flatmap: 1.3.3
- debug: 3.2.7
- doctrine: 2.1.0
- eslint: 9.39.5([email protected])
- eslint-import-resolver-node: 0.3.10
- hasown: 2.0.4
- is-core-module: 2.16.2
- is-glob: 4.0.3
- minimatch: 3.1.5
- object.fromentries: 2.0.8
- object.groupby: 1.0.3
- object.values: 1.2.1
- semver: 6.3.1
- string.prototype.trimend: 1.0.10
- tsconfig-paths: 3.15.0
- optionalDependencies:
- '@typescript-eslint/parser': 8.65.0([email protected]([email protected]))([email protected])
- transitivePeerDependencies:
- - eslint-import-resolver-typescript
- - eslint-import-resolver-webpack
- - supports-color
-
dependencies:
'@rtsao/scc': 1.1.0