@ai-sdk/langchain 3.0.152 → 3.0.154

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +3 -277
  3. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # @ai-sdk/langchain
2
2
 
3
+ ## 3.0.154
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [47236dd]
8
+ - Updated dependencies [c8e8866]
9
+ - Updated dependencies [e64ed82]
10
+ - Updated dependencies [1cf95c6]
11
+ - ai@7.0.154
12
+ - @ai-sdk/provider-utils@5.0.69
13
+
14
+ ## 3.0.153
15
+
16
+ ### Patch Changes
17
+
18
+ - e729d58: chore(docs): update `README.md` for consistent format and to avoid duplication
19
+ - Updated dependencies [5475347]
20
+ - Updated dependencies [e729d58]
21
+ - ai@7.0.153
22
+ - @ai-sdk/provider-utils@5.0.68
23
+
3
24
  ## 3.0.152
4
25
 
5
26
  ### Patch Changes
package/README.md CHANGED
@@ -2,42 +2,14 @@
2
2
 
3
3
  The **[AI SDK](https://ai-sdk.dev)** LangChain adapter provides seamless integration between [LangChain](https://langchain.com/) and the AI SDK, enabling you to use LangChain agents and graphs with AI SDK UI components.
4
4
 
5
- ## Installation
5
+ ## Setup
6
6
 
7
7
  ```bash
8
- npm install @ai-sdk/langchain @langchain/core
8
+ npm i ai @ai-sdk/langchain @langchain/core
9
9
  ```
10
10
 
11
- > **Note:** `@langchain/core` is a required peer dependency.
12
-
13
- ## Features
14
-
15
- - Convert AI SDK `UIMessage` to LangChain `BaseMessage` format
16
- - Transform LangChain/LangGraph streams to AI SDK `UIMessageStream`
17
- - `ChatTransport` implementation for LangSmith deployments
18
- - Full support for text, tool calls, and tool results
19
- - Custom data streaming with typed events (`data-{type}`)
20
-
21
11
  ## Usage
22
12
 
23
- ### Converting Messages
24
-
25
- Use `toBaseMessages` to convert AI SDK messages to LangChain format:
26
-
27
- ```ts
28
- import { toBaseMessages } from '@ai-sdk/langchain';
29
-
30
- // Convert UI messages to LangChain format
31
- const langchainMessages = await toBaseMessages(uiMessages);
32
-
33
- // Use with any LangChain model
34
- const response = await model.invoke(langchainMessages);
35
- ```
36
-
37
- ### Streaming from LangGraph
38
-
39
- Use `toUIMessageStream` to convert LangGraph streams to AI SDK format:
40
-
41
13
  ```ts
42
14
  import { toBaseMessages, toUIMessageStream } from '@ai-sdk/langchain';
43
15
  import { createUIMessageStreamResponse } from 'ai';
@@ -56,250 +28,4 @@ return createUIMessageStreamResponse({
56
28
  });
57
29
  ```
58
30
 
59
- Use the `tools` stream mode when you want to stream LangGraph tool progress. The adapter converts `on_tool_event` events to preliminary tool output (`preliminary: true`) and the final `on_tool_end` event to final tool output.
60
-
61
- ### Streaming with Callbacks
62
-
63
- Use callbacks to access the final LangGraph state, handle errors, or detect aborts:
64
-
65
- ```ts
66
- const langchainStream = await graph.stream(
67
- { messages: langchainMessages },
68
- { streamMode: ['values', 'messages'] },
69
- );
70
-
71
- return createUIMessageStreamResponse({
72
- stream: toUIMessageStream<MyGraphState>(langchainStream, {
73
- onFinish: async finalState => {
74
- if (finalState) {
75
- await saveConversation(finalState.messages);
76
- await sendAnalytics(finalState);
77
- }
78
- },
79
- onError: error => console.error('Stream failed:', error),
80
- onAbort: () => console.log('Client disconnected'),
81
- }),
82
- });
83
- ```
84
-
85
- ### Streaming with `streamEvents`
86
-
87
- You can also use `toUIMessageStream` with `streamEvents()` for more granular event handling:
88
-
89
- ```ts
90
- import { toBaseMessages, toUIMessageStream } from '@ai-sdk/langchain';
91
- import { createUIMessageStreamResponse } from 'ai';
92
-
93
- // Using streamEvents with an agent
94
- const langchainMessages = await toBaseMessages(uiMessages);
95
- const streamEvents = agent.streamEvents(
96
- { messages: langchainMessages },
97
- { version: 'v2' },
98
- );
99
-
100
- // Convert to UI message stream response
101
- return createUIMessageStreamResponse({
102
- stream: toUIMessageStream(streamEvents),
103
- });
104
- ```
105
-
106
- The adapter automatically detects the stream type and handles:
107
-
108
- - `on_chat_model_stream` events for text streaming
109
- - `on_tool_start` and `on_tool_end` events for tool calls
110
- - Reasoning content from contentBlocks
111
-
112
- ### Custom Data Streaming
113
-
114
- LangChain tools can emit custom data events using `config.writer()`. The adapter converts these to typed `data-{type}` parts:
115
-
116
- ```ts
117
- import { tool, type ToolRuntime } from 'langchain';
118
-
119
- const analyzeDataTool = tool(
120
- async ({ query }, config: ToolRuntime) => {
121
- // Emit progress updates - becomes 'data-progress' in the UI
122
- config.writer?.({
123
- type: 'progress',
124
- id: 'analysis-1', // Include 'id' to persist in message.parts
125
- step: 'fetching',
126
- message: 'Fetching data...',
127
- progress: 50,
128
- });
129
-
130
- // ... perform analysis ...
131
-
132
- // Emit status update - becomes 'data-status' in the UI
133
- config.writer?.({
134
- type: 'status',
135
- id: 'analysis-1-status',
136
- status: 'complete',
137
- message: 'Analysis finished',
138
- });
139
-
140
- return 'Analysis complete';
141
- },
142
- {
143
- name: 'analyze_data',
144
- description: 'Analyze data with progress updates',
145
- schema: z.object({ query: z.string() }),
146
- },
147
- );
148
- ```
149
-
150
- Enable the `custom` stream mode to receive these events:
151
-
152
- ```ts
153
- const stream = await graph.stream(
154
- { messages: langchainMessages },
155
- { streamMode: ['values', 'messages', 'custom'] },
156
- );
157
- ```
158
-
159
- **Custom data behavior:**
160
-
161
- - Data with an `id` field is **persistent** (added to `message.parts` for rendering)
162
- - Data without an `id` is **transient** (only delivered via the `onData` callback)
163
- - The `type` field determines the event name: `{ type: 'progress' }` → `data-progress`
164
-
165
- ### LangSmith Deployment Transport
166
-
167
- Use `LangSmithDeploymentTransport` with the AI SDK `useChat` hook to connect directly to a LangGraph deployment from the browser:
168
-
169
- ```tsx
170
- import { useChat } from '@ai-sdk/react';
171
- import { LangSmithDeploymentTransport } from '@ai-sdk/langchain';
172
- import { useMemo } from 'react';
173
-
174
- function Chat() {
175
- const transport = useMemo(
176
- () =>
177
- new LangSmithDeploymentTransport({
178
- url: 'https://your-deployment.us.langgraph.app',
179
- apiKey: process.env.LANGSMITH_API_KEY,
180
- }),
181
- [],
182
- );
183
-
184
- const { messages, input, handleInputChange, handleSubmit } = useChat({
185
- transport,
186
- });
187
-
188
- return (
189
- <div>
190
- {messages.map(m => (
191
- <div key={m.id}>{m.parts.map(part => part.text).join('')}</div>
192
- ))}
193
- <form onSubmit={handleSubmit}>
194
- <input value={input} onChange={handleInputChange} />
195
- <button type="submit">Send</button>
196
- </form>
197
- </div>
198
- );
199
- }
200
- ```
201
-
202
- ## API Reference
203
-
204
- ### `toBaseMessages(messages)`
205
-
206
- Converts AI SDK `UIMessage` objects to LangChain `BaseMessage` objects.
207
-
208
- **Parameters:**
209
-
210
- - `messages`: `UIMessage[]` - Array of AI SDK UI messages
211
-
212
- **Returns:** `Promise<BaseMessage[]>`
213
-
214
- ### `convertModelMessages(modelMessages)`
215
-
216
- Converts AI SDK `ModelMessage` objects to LangChain `BaseMessage` objects.
217
-
218
- **Parameters:**
219
-
220
- - `modelMessages`: `ModelMessage[]` - Array of model messages
221
-
222
- **Returns:** `BaseMessage[]`
223
-
224
- ### `toUIMessageStream(stream, options?)`
225
-
226
- Converts a LangChain/LangGraph stream to an AI SDK `UIMessageStream`.
227
-
228
- **Parameters:**
229
-
230
- - `stream`: `AsyncIterable | ReadableStream` - A stream from LangChain `model.stream()`, LangGraph `graph.stream()`, or `streamEvents()`
231
- - `options?`: `ToUIMessageStreamOptions<TState>` - Optional lifecycle controls and callbacks:
232
- - `sendStart` - Whether to emit the outer `start` chunk (defaults to `true`)
233
- - `sendFinish` - Whether to emit the outer `finish` chunk (defaults to `true`)
234
- - `onStart()` - Called when stream initializes
235
- - `onToken(token)` - Called for each token
236
- - `onText(text)` - Called for each text chunk
237
- - `onFinal(text)` - Called with aggregated text (on success, error, or abort)
238
- - `onFinish(state)` - Called on success with LangGraph state (or `undefined` for other streams)
239
- - `onError(error)` - Called when stream errors
240
- - `onAbort()` - Called when stream is aborted
241
-
242
- **Returns:** `ReadableStream<UIMessageChunk>`
243
-
244
- When composing the adapter output into a stream that owns the message
245
- lifecycle, set `sendStart` and `sendFinish` to `false`:
246
-
247
- ```ts
248
- const stream = createUIMessageStream({
249
- async execute({ writer }) {
250
- writer.write({ type: 'start' });
251
-
252
- const reader = toUIMessageStream(langchainStream, {
253
- sendStart: false,
254
- sendFinish: false,
255
- }).getReader();
256
-
257
- while (true) {
258
- const { done, value: chunk } = await reader.read();
259
- if (done) break;
260
- writer.write(chunk);
261
- }
262
-
263
- writer.write({ type: 'finish' });
264
- },
265
- });
266
- ```
267
-
268
- Only the outer lifecycle chunks are omitted. Text, reasoning, tool, data, and
269
- step chunks are still emitted.
270
-
271
- **Supported stream types:**
272
-
273
- - **Model streams** - Direct `AIMessageChunk` streams from `model.stream()`
274
- - **LangGraph streams** - Streams with `streamMode: ['values', 'messages']`, or `['values', 'messages', 'tools']` for tool progress
275
- - **streamEvents** - Event streams from `agent.streamEvents()` or `model.streamEvents()`
276
-
277
- **Supported LangGraph stream events:**
278
-
279
- - `messages` - Streaming message chunks (text, tool calls)
280
- - `values` - State updates that finalize pending message chunks
281
- - `tools` - Tool progress events (`on_tool_event` emits preliminary tool output with `preliminary: true`, final `on_tool_end` emits final output)
282
- - `custom` - Custom data events (emitted as `data-{type}` chunks)
283
-
284
- **Supported streamEvents events:**
285
-
286
- - `on_chat_model_stream` - Token streaming from chat models
287
- - `on_tool_start` - Tool execution start
288
- - `on_tool_end` - Tool execution end with output
289
-
290
- ### `LangSmithDeploymentTransport`
291
-
292
- A `ChatTransport` implementation for LangSmith/LangGraph deployments.
293
-
294
- **Constructor Parameters:**
295
-
296
- - `options`: `LangSmithDeploymentTransportOptions` - Configuration for the RemoteGraph connection
297
- - `url`: `string` - LangSmith deployment URL or local server URL
298
- - `apiKey?`: `string` - API key for authentication (optional for local development)
299
- - `graphId?`: `string` - The ID of the graph to connect to (defaults to `'agent'`)
300
-
301
- **Implements:** `ChatTransport`
302
-
303
- ## Documentation
304
-
305
- Please check out the [AI SDK documentation](https://ai-sdk.dev) for more information.
31
+ See the [LangChain Adapter documentation](https://ai-sdk.dev/providers/adapters/langchain) for more information.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/langchain",
3
- "version": "3.0.152",
3
+ "version": "3.0.154",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -25,8 +25,8 @@
25
25
  }
26
26
  },
27
27
  "dependencies": {
28
- "@ai-sdk/provider-utils": "5.0.67",
29
- "ai": "7.0.152"
28
+ "@ai-sdk/provider-utils": "5.0.69",
29
+ "ai": "7.0.154"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@langchain/core": "^1.1.46",