@ai-sdk/langchain 0.0.0-02dba89b-20251009204516 → 0.0.0-1c33ba03-20260114162300

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.
package/dist/index.mjs CHANGED
@@ -1,75 +1,1064 @@
1
- // src/stream-callbacks.ts
2
- function createCallbacksTransformer(callbacks = {}) {
3
- let aggregatedResponse = "";
4
- return new TransformStream({
5
- async start() {
6
- if (callbacks.onStart) await callbacks.onStart();
7
- },
8
- async transform(message, controller) {
9
- controller.enqueue(message);
10
- aggregatedResponse += message;
11
- if (callbacks.onToken) await callbacks.onToken(message);
12
- if (callbacks.onText && typeof message === "string") {
13
- await callbacks.onText(message);
14
- }
15
- },
16
- async flush() {
17
- if (callbacks.onFinal) {
18
- await callbacks.onFinal(aggregatedResponse);
19
- }
1
+ // src/adapter.ts
2
+ import {
3
+ SystemMessage
4
+ } from "@langchain/core/messages";
5
+ import {
6
+ convertToModelMessages
7
+ } from "ai";
8
+
9
+ // src/utils.ts
10
+ import {
11
+ AIMessage,
12
+ HumanMessage,
13
+ ToolMessage,
14
+ AIMessageChunk
15
+ } from "@langchain/core/messages";
16
+ function convertToolResultPart(block) {
17
+ const content = (() => {
18
+ if (block.output.type === "text" || block.output.type === "error-text") {
19
+ return block.output.value;
20
+ }
21
+ if (block.output.type === "json" || block.output.type === "error-json") {
22
+ return JSON.stringify(block.output.value);
20
23
  }
24
+ if (block.output.type === "content") {
25
+ return block.output.value.map((outputBlock) => {
26
+ if (outputBlock.type === "text") {
27
+ return outputBlock.text;
28
+ }
29
+ return "";
30
+ }).join("");
31
+ }
32
+ return "";
33
+ })();
34
+ return new ToolMessage({
35
+ tool_call_id: block.toolCallId,
36
+ content
21
37
  });
22
38
  }
23
-
24
- // src/langchain-adapter.ts
25
- function toUIMessageStream(stream, callbacks) {
26
- return stream.pipeThrough(
27
- new TransformStream({
28
- transform: async (value, controller) => {
29
- var _a;
30
- if (typeof value === "string") {
31
- controller.enqueue(value);
39
+ function convertAssistantContent(content) {
40
+ if (typeof content === "string") {
41
+ return new AIMessage({ content });
42
+ }
43
+ const textParts = [];
44
+ const toolCalls = [];
45
+ for (const part of content) {
46
+ if (part.type === "text") {
47
+ textParts.push(part.text);
48
+ } else if (part.type === "tool-call") {
49
+ toolCalls.push({
50
+ id: part.toolCallId,
51
+ name: part.toolName,
52
+ args: part.input
53
+ });
54
+ }
55
+ }
56
+ return new AIMessage({
57
+ content: textParts.join(""),
58
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
59
+ });
60
+ }
61
+ function getDefaultFilename(mediaType, prefix = "file") {
62
+ const ext = mediaType.split("/")[1] || "bin";
63
+ return `${prefix}.${ext}`;
64
+ }
65
+ function convertUserContent(content) {
66
+ var _a;
67
+ if (typeof content === "string") {
68
+ return new HumanMessage({ content });
69
+ }
70
+ const contentBlocks = [];
71
+ for (const part of content) {
72
+ if (part.type === "text") {
73
+ contentBlocks.push({ type: "text", text: part.text });
74
+ } else if (part.type === "image") {
75
+ const imagePart = part;
76
+ if (imagePart.image instanceof URL) {
77
+ contentBlocks.push({
78
+ type: "image_url",
79
+ image_url: { url: imagePart.image.toString() }
80
+ });
81
+ } else if (typeof imagePart.image === "string") {
82
+ if (imagePart.image.startsWith("http://") || imagePart.image.startsWith("https://") || imagePart.image.startsWith("data:")) {
83
+ contentBlocks.push({
84
+ type: "image_url",
85
+ image_url: { url: imagePart.image }
86
+ });
87
+ } else {
88
+ const mimeType = imagePart.mediaType || "image/png";
89
+ contentBlocks.push({
90
+ type: "image_url",
91
+ image_url: { url: `data:${mimeType};base64,${imagePart.image}` }
92
+ });
93
+ }
94
+ } else if (
95
+ /**
96
+ * Handle Uint8Array or ArrayBuffer (binary data)
97
+ */
98
+ imagePart.image instanceof Uint8Array || imagePart.image instanceof ArrayBuffer
99
+ ) {
100
+ const bytes = imagePart.image instanceof ArrayBuffer ? new Uint8Array(imagePart.image) : imagePart.image;
101
+ const base64 = btoa(String.fromCharCode(...bytes));
102
+ const mimeType = imagePart.mediaType || "image/png";
103
+ contentBlocks.push({
104
+ type: "image_url",
105
+ image_url: { url: `data:${mimeType};base64,${base64}` }
106
+ });
107
+ }
108
+ } else if (part.type === "file") {
109
+ const filePart = part;
110
+ const isImage = (_a = filePart.mediaType) == null ? void 0 : _a.startsWith("image/");
111
+ if (isImage) {
112
+ if (filePart.data instanceof URL) {
113
+ contentBlocks.push({
114
+ type: "image_url",
115
+ image_url: { url: filePart.data.toString() }
116
+ });
117
+ } else if (typeof filePart.data === "string") {
118
+ if (filePart.data.startsWith("http://") || filePart.data.startsWith("https://") || filePart.data.startsWith("data:")) {
119
+ contentBlocks.push({
120
+ type: "image_url",
121
+ image_url: { url: filePart.data }
122
+ });
123
+ } else {
124
+ contentBlocks.push({
125
+ type: "image_url",
126
+ image_url: {
127
+ url: `data:${filePart.mediaType};base64,${filePart.data}`
128
+ }
129
+ });
130
+ }
131
+ } else if (filePart.data instanceof Uint8Array || filePart.data instanceof ArrayBuffer) {
132
+ const bytes = filePart.data instanceof ArrayBuffer ? new Uint8Array(filePart.data) : filePart.data;
133
+ const base64 = btoa(String.fromCharCode(...bytes));
134
+ contentBlocks.push({
135
+ type: "image_url",
136
+ image_url: { url: `data:${filePart.mediaType};base64,${base64}` }
137
+ });
138
+ }
139
+ } else {
140
+ const filename = filePart.filename || getDefaultFilename(filePart.mediaType, "file");
141
+ if (filePart.data instanceof URL) {
142
+ contentBlocks.push({
143
+ type: "file",
144
+ url: filePart.data.toString(),
145
+ mimeType: filePart.mediaType,
146
+ filename
147
+ });
148
+ } else if (typeof filePart.data === "string") {
149
+ if (filePart.data.startsWith("http://") || filePart.data.startsWith("https://")) {
150
+ contentBlocks.push({
151
+ type: "file",
152
+ url: filePart.data,
153
+ mimeType: filePart.mediaType,
154
+ filename
155
+ });
156
+ } else if (filePart.data.startsWith("data:")) {
157
+ const matches = filePart.data.match(/^data:([^;]+);base64,(.+)$/);
158
+ if (matches) {
159
+ contentBlocks.push({
160
+ type: "file",
161
+ data: matches[2],
162
+ mimeType: matches[1],
163
+ filename
164
+ });
165
+ } else {
166
+ contentBlocks.push({
167
+ type: "file",
168
+ url: filePart.data,
169
+ mimeType: filePart.mediaType,
170
+ filename
171
+ });
172
+ }
173
+ } else {
174
+ contentBlocks.push({
175
+ type: "file",
176
+ data: filePart.data,
177
+ mimeType: filePart.mediaType,
178
+ filename
179
+ });
180
+ }
181
+ } else if (filePart.data instanceof Uint8Array || filePart.data instanceof ArrayBuffer) {
182
+ const bytes = filePart.data instanceof ArrayBuffer ? new Uint8Array(filePart.data) : filePart.data;
183
+ const base64 = btoa(String.fromCharCode(...bytes));
184
+ contentBlocks.push({
185
+ type: "file",
186
+ data: base64,
187
+ mimeType: filePart.mediaType,
188
+ filename
189
+ });
190
+ }
191
+ }
192
+ }
193
+ }
194
+ if (contentBlocks.every((block) => block.type === "text")) {
195
+ return new HumanMessage({
196
+ content: contentBlocks.map((block) => block.text).join("")
197
+ });
198
+ }
199
+ return new HumanMessage({ content: contentBlocks });
200
+ }
201
+ function isToolResultPart(item) {
202
+ return item != null && typeof item === "object" && "type" in item && item.type === "tool-result";
203
+ }
204
+ function processModelChunk(chunk, state, controller) {
205
+ var _a, _b, _c;
206
+ if (!state.emittedImages) {
207
+ state.emittedImages = /* @__PURE__ */ new Set();
208
+ }
209
+ if (chunk.id) {
210
+ state.messageId = chunk.id;
211
+ }
212
+ const chunkObj = chunk;
213
+ const additionalKwargs = chunkObj.additional_kwargs;
214
+ const imageOutputs = extractImageOutputs(additionalKwargs);
215
+ for (const imageOutput of imageOutputs) {
216
+ if (imageOutput.result && !state.emittedImages.has(imageOutput.id)) {
217
+ state.emittedImages.add(imageOutput.id);
218
+ const mediaType = `image/${imageOutput.output_format || "png"}`;
219
+ controller.enqueue({
220
+ type: "file",
221
+ mediaType,
222
+ url: `data:${mediaType};base64,${imageOutput.result}`
223
+ });
224
+ state.started = true;
225
+ }
226
+ }
227
+ const reasoning = extractReasoningFromContentBlocks(chunk) || extractReasoningFromValuesMessage(chunk);
228
+ if (reasoning) {
229
+ if (!state.reasoningStarted) {
230
+ state.reasoningMessageId = state.messageId;
231
+ controller.enqueue({ type: "reasoning-start", id: state.messageId });
232
+ state.reasoningStarted = true;
233
+ state.started = true;
234
+ }
235
+ controller.enqueue({
236
+ type: "reasoning-delta",
237
+ delta: reasoning,
238
+ id: (_a = state.reasoningMessageId) != null ? _a : state.messageId
239
+ });
240
+ }
241
+ const text = typeof chunk.content === "string" ? chunk.content : Array.isArray(chunk.content) ? chunk.content.filter(
242
+ (c) => typeof c === "object" && c !== null && "type" in c && c.type === "text"
243
+ ).map((c) => c.text).join("") : "";
244
+ if (text) {
245
+ if (state.reasoningStarted && !state.textStarted) {
246
+ controller.enqueue({
247
+ type: "reasoning-end",
248
+ id: (_b = state.reasoningMessageId) != null ? _b : state.messageId
249
+ });
250
+ state.reasoningStarted = false;
251
+ }
252
+ if (!state.textStarted) {
253
+ state.textMessageId = state.messageId;
254
+ controller.enqueue({ type: "text-start", id: state.messageId });
255
+ state.textStarted = true;
256
+ state.started = true;
257
+ }
258
+ controller.enqueue({
259
+ type: "text-delta",
260
+ delta: text,
261
+ id: (_c = state.textMessageId) != null ? _c : state.messageId
262
+ });
263
+ }
264
+ }
265
+ function isPlainMessageObject(msg) {
266
+ if (msg == null || typeof msg !== "object") return false;
267
+ return typeof msg._getType !== "function";
268
+ }
269
+ function getMessageId(msg) {
270
+ if (msg == null || typeof msg !== "object") return void 0;
271
+ const msgObj = msg;
272
+ if (typeof msgObj.id === "string") {
273
+ return msgObj.id;
274
+ }
275
+ if (msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object") {
276
+ const kwargs = msgObj.kwargs;
277
+ if (typeof kwargs.id === "string") {
278
+ return kwargs.id;
279
+ }
280
+ }
281
+ return void 0;
282
+ }
283
+ function isAIMessageChunk(msg) {
284
+ if (AIMessageChunk.isInstance(msg)) return true;
285
+ if (isPlainMessageObject(msg)) {
286
+ const obj = msg;
287
+ if ("type" in obj && obj.type === "ai") return true;
288
+ if (obj.type === "constructor" && Array.isArray(obj.id) && (obj.id.includes("AIMessageChunk") || obj.id.includes("AIMessage"))) {
289
+ return true;
290
+ }
291
+ }
292
+ return false;
293
+ }
294
+ function isToolMessageType(msg) {
295
+ if (ToolMessage.isInstance(msg)) return true;
296
+ if (isPlainMessageObject(msg)) {
297
+ const obj = msg;
298
+ if ("type" in obj && obj.type === "tool") return true;
299
+ if (obj.type === "constructor" && Array.isArray(obj.id) && obj.id.includes("ToolMessage")) {
300
+ return true;
301
+ }
302
+ }
303
+ return false;
304
+ }
305
+ function getMessageText(msg) {
306
+ var _a;
307
+ if (AIMessageChunk.isInstance(msg)) {
308
+ return (_a = msg.text) != null ? _a : "";
309
+ }
310
+ if (msg == null || typeof msg !== "object") return "";
311
+ const msgObj = msg;
312
+ const dataSource = msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
313
+ if ("content" in dataSource) {
314
+ const content = dataSource.content;
315
+ if (typeof content === "string") {
316
+ return content;
317
+ }
318
+ if (Array.isArray(content)) {
319
+ return content.filter(
320
+ (block) => block != null && typeof block === "object" && block.type === "text" && typeof block.text === "string"
321
+ ).map((block) => block.text).join("");
322
+ }
323
+ return "";
324
+ }
325
+ return "";
326
+ }
327
+ function isReasoningContentBlock(obj) {
328
+ return obj != null && typeof obj === "object" && "type" in obj && obj.type === "reasoning" && "reasoning" in obj && typeof obj.reasoning === "string";
329
+ }
330
+ function isThinkingContentBlock(obj) {
331
+ return obj != null && typeof obj === "object" && "type" in obj && obj.type === "thinking" && "thinking" in obj && typeof obj.thinking === "string";
332
+ }
333
+ function isGPT5ReasoningOutput(obj) {
334
+ return obj != null && typeof obj === "object" && "type" in obj && obj.type === "reasoning" && "summary" in obj && Array.isArray(obj.summary);
335
+ }
336
+ function extractReasoningId(msg) {
337
+ var _a;
338
+ if (msg == null || typeof msg !== "object") return void 0;
339
+ const msgObj = msg;
340
+ const kwargs = msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
341
+ const additionalKwargs = kwargs.additional_kwargs;
342
+ if ((_a = additionalKwargs == null ? void 0 : additionalKwargs.reasoning) == null ? void 0 : _a.id) {
343
+ return additionalKwargs.reasoning.id;
344
+ }
345
+ const responseMetadata = kwargs.response_metadata;
346
+ if (responseMetadata && Array.isArray(responseMetadata.output)) {
347
+ for (const item of responseMetadata.output) {
348
+ if (isGPT5ReasoningOutput(item)) {
349
+ return item.id;
350
+ }
351
+ }
352
+ }
353
+ return void 0;
354
+ }
355
+ function extractReasoningFromContentBlocks(msg) {
356
+ if (msg == null || typeof msg !== "object") return void 0;
357
+ const msgObj = msg;
358
+ const kwargs = msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
359
+ const contentBlocks = kwargs.contentBlocks;
360
+ if (Array.isArray(contentBlocks)) {
361
+ const reasoningParts = [];
362
+ for (const block of contentBlocks) {
363
+ if (isReasoningContentBlock(block)) {
364
+ reasoningParts.push(block.reasoning);
365
+ } else if (isThinkingContentBlock(block)) {
366
+ reasoningParts.push(block.thinking);
367
+ }
368
+ }
369
+ if (reasoningParts.length > 0) {
370
+ return reasoningParts.join("");
371
+ }
372
+ }
373
+ const additionalKwargs = kwargs.additional_kwargs;
374
+ if ((additionalKwargs == null ? void 0 : additionalKwargs.reasoning) && Array.isArray(additionalKwargs.reasoning.summary)) {
375
+ const reasoningParts = [];
376
+ for (const summaryItem of additionalKwargs.reasoning.summary) {
377
+ if (typeof summaryItem === "object" && summaryItem !== null && "text" in summaryItem && typeof summaryItem.text === "string") {
378
+ reasoningParts.push(summaryItem.text);
379
+ }
380
+ }
381
+ if (reasoningParts.length > 0) {
382
+ return reasoningParts.join("");
383
+ }
384
+ }
385
+ return void 0;
386
+ }
387
+ function extractReasoningFromValuesMessage(msg) {
388
+ if (msg == null || typeof msg !== "object") return void 0;
389
+ const msgObj = msg;
390
+ const kwargs = msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
391
+ const responseMetadata = kwargs.response_metadata;
392
+ if (responseMetadata && Array.isArray(responseMetadata.output)) {
393
+ const reasoningParts = [];
394
+ for (const item of responseMetadata.output) {
395
+ if (isGPT5ReasoningOutput(item)) {
396
+ for (const summaryItem of item.summary) {
397
+ if (typeof summaryItem === "object" && summaryItem !== null) {
398
+ const text = summaryItem.text;
399
+ if (typeof text === "string" && text) {
400
+ reasoningParts.push(text);
401
+ }
402
+ }
403
+ }
404
+ }
405
+ }
406
+ if (reasoningParts.length > 0) {
407
+ return reasoningParts.join("");
408
+ }
409
+ }
410
+ const additionalKwargs = kwargs.additional_kwargs;
411
+ if ((additionalKwargs == null ? void 0 : additionalKwargs.reasoning) && Array.isArray(additionalKwargs.reasoning.summary)) {
412
+ const reasoningParts = [];
413
+ for (const summaryItem of additionalKwargs.reasoning.summary) {
414
+ if (typeof summaryItem === "object" && summaryItem !== null && "text" in summaryItem && typeof summaryItem.text === "string") {
415
+ reasoningParts.push(summaryItem.text);
416
+ }
417
+ }
418
+ if (reasoningParts.length > 0) {
419
+ return reasoningParts.join("");
420
+ }
421
+ }
422
+ return void 0;
423
+ }
424
+ function isImageGenerationOutput(obj) {
425
+ return obj != null && typeof obj === "object" && "type" in obj && obj.type === "image_generation_call";
426
+ }
427
+ function extractImageOutputs(additionalKwargs) {
428
+ if (!additionalKwargs) return [];
429
+ const toolOutputs = additionalKwargs.tool_outputs;
430
+ if (!Array.isArray(toolOutputs)) return [];
431
+ return toolOutputs.filter(isImageGenerationOutput);
432
+ }
433
+ function processLangGraphEvent(event, state, controller) {
434
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
435
+ const {
436
+ messageSeen,
437
+ messageConcat,
438
+ emittedToolCalls,
439
+ emittedImages,
440
+ emittedReasoningIds,
441
+ messageReasoningIds,
442
+ toolCallInfoByIndex,
443
+ emittedToolCallsByKey
444
+ } = state;
445
+ const [type, data] = event.length === 3 ? event.slice(1) : event;
446
+ switch (type) {
447
+ case "custom": {
448
+ let customTypeName = "custom";
449
+ let partId;
450
+ if (data != null && typeof data === "object" && !Array.isArray(data)) {
451
+ const dataObj = data;
452
+ if (typeof dataObj.type === "string" && dataObj.type) {
453
+ customTypeName = dataObj.type;
454
+ }
455
+ if (typeof dataObj.id === "string" && dataObj.id) {
456
+ partId = dataObj.id;
457
+ }
458
+ }
459
+ controller.enqueue({
460
+ type: `data-${customTypeName}`,
461
+ id: partId,
462
+ transient: partId == null,
463
+ data
464
+ });
465
+ break;
466
+ }
467
+ case "messages": {
468
+ const [rawMsg, metadata] = data;
469
+ const msg = rawMsg;
470
+ const msgId = getMessageId(msg);
471
+ if (!msgId) return;
472
+ const langgraphStep = typeof (metadata == null ? void 0 : metadata.langgraph_step) === "number" ? metadata.langgraph_step : null;
473
+ if (langgraphStep !== null && langgraphStep !== state.currentStep) {
474
+ if (state.currentStep !== null) {
475
+ controller.enqueue({ type: "finish-step" });
476
+ }
477
+ controller.enqueue({ type: "start-step" });
478
+ state.currentStep = langgraphStep;
479
+ }
480
+ if (AIMessageChunk.isInstance(msg)) {
481
+ if (messageConcat[msgId]) {
482
+ messageConcat[msgId] = messageConcat[msgId].concat(
483
+ msg
484
+ );
485
+ } else {
486
+ messageConcat[msgId] = msg;
487
+ }
488
+ }
489
+ if (isAIMessageChunk(msg)) {
490
+ const concatChunk = messageConcat[msgId];
491
+ const msgObj = msg;
492
+ const dataSource = msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
493
+ const additionalKwargs = dataSource.additional_kwargs;
494
+ const imageOutputs = extractImageOutputs(additionalKwargs);
495
+ for (const imageOutput of imageOutputs) {
496
+ if (imageOutput.result && !emittedImages.has(imageOutput.id)) {
497
+ emittedImages.add(imageOutput.id);
498
+ const mediaType = `image/${imageOutput.output_format || "png"}`;
499
+ controller.enqueue({
500
+ type: "file",
501
+ mediaType,
502
+ url: `data:${mediaType};base64,${imageOutput.result}`
503
+ });
504
+ }
505
+ }
506
+ const toolCallChunks = dataSource.tool_call_chunks;
507
+ if (toolCallChunks == null ? void 0 : toolCallChunks.length) {
508
+ for (const toolCallChunk of toolCallChunks) {
509
+ const idx = (_a = toolCallChunk.index) != null ? _a : 0;
510
+ if (toolCallChunk.id) {
511
+ (_b = toolCallInfoByIndex[msgId]) != null ? _b : toolCallInfoByIndex[msgId] = {};
512
+ toolCallInfoByIndex[msgId][idx] = {
513
+ id: toolCallChunk.id,
514
+ name: toolCallChunk.name || ((_d = (_c = concatChunk == null ? void 0 : concatChunk.tool_call_chunks) == null ? void 0 : _c[idx]) == null ? void 0 : _d.name) || "unknown"
515
+ };
516
+ }
517
+ const toolCallId = toolCallChunk.id || ((_f = (_e = toolCallInfoByIndex[msgId]) == null ? void 0 : _e[idx]) == null ? void 0 : _f.id) || ((_h = (_g = concatChunk == null ? void 0 : concatChunk.tool_call_chunks) == null ? void 0 : _g[idx]) == null ? void 0 : _h.id);
518
+ if (!toolCallId) {
519
+ continue;
520
+ }
521
+ const toolName = toolCallChunk.name || ((_j = (_i = toolCallInfoByIndex[msgId]) == null ? void 0 : _i[idx]) == null ? void 0 : _j.name) || ((_l = (_k = concatChunk == null ? void 0 : concatChunk.tool_call_chunks) == null ? void 0 : _k[idx]) == null ? void 0 : _l.name) || "unknown";
522
+ if (!((_n = (_m = messageSeen[msgId]) == null ? void 0 : _m.tool) == null ? void 0 : _n[toolCallId])) {
523
+ controller.enqueue({
524
+ type: "tool-input-start",
525
+ toolCallId,
526
+ toolName,
527
+ dynamic: true
528
+ });
529
+ (_o = messageSeen[msgId]) != null ? _o : messageSeen[msgId] = {};
530
+ (_q = (_p = messageSeen[msgId]).tool) != null ? _q : _p.tool = {};
531
+ messageSeen[msgId].tool[toolCallId] = true;
532
+ emittedToolCalls.add(toolCallId);
533
+ }
534
+ if (toolCallChunk.args) {
535
+ controller.enqueue({
536
+ type: "tool-input-delta",
537
+ toolCallId,
538
+ inputTextDelta: toolCallChunk.args
539
+ });
540
+ }
541
+ }
32
542
  return;
33
543
  }
34
- if ("event" in value) {
35
- if (value.event === "on_chat_model_stream") {
36
- forwardAIMessageChunk(
37
- (_a = value.data) == null ? void 0 : _a.chunk,
38
- controller
544
+ const chunkReasoningId = extractReasoningId(msg);
545
+ if (chunkReasoningId) {
546
+ if (!messageReasoningIds[msgId]) {
547
+ messageReasoningIds[msgId] = chunkReasoningId;
548
+ }
549
+ emittedReasoningIds.add(chunkReasoningId);
550
+ }
551
+ const reasoning = extractReasoningFromContentBlocks(msg);
552
+ if (reasoning) {
553
+ const reasoningId = (_s = (_r = messageReasoningIds[msgId]) != null ? _r : chunkReasoningId) != null ? _s : msgId;
554
+ if (!((_t = messageSeen[msgId]) == null ? void 0 : _t.reasoning)) {
555
+ controller.enqueue({ type: "reasoning-start", id: msgId });
556
+ (_u = messageSeen[msgId]) != null ? _u : messageSeen[msgId] = {};
557
+ messageSeen[msgId].reasoning = true;
558
+ }
559
+ controller.enqueue({
560
+ type: "reasoning-delta",
561
+ delta: reasoning,
562
+ id: msgId
563
+ });
564
+ emittedReasoningIds.add(reasoningId);
565
+ }
566
+ const text = getMessageText(msg);
567
+ if (text) {
568
+ if (!((_v = messageSeen[msgId]) == null ? void 0 : _v.text)) {
569
+ controller.enqueue({ type: "text-start", id: msgId });
570
+ (_w = messageSeen[msgId]) != null ? _w : messageSeen[msgId] = {};
571
+ messageSeen[msgId].text = true;
572
+ }
573
+ controller.enqueue({
574
+ type: "text-delta",
575
+ delta: text,
576
+ id: msgId
577
+ });
578
+ }
579
+ } else if (isToolMessageType(msg)) {
580
+ const msgObj = msg;
581
+ const dataSource = msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
582
+ const toolCallId = dataSource.tool_call_id;
583
+ const status = dataSource.status;
584
+ if (toolCallId) {
585
+ if (status === "error") {
586
+ controller.enqueue({
587
+ type: "tool-output-error",
588
+ toolCallId,
589
+ errorText: typeof dataSource.content === "string" ? dataSource.content : "Tool execution failed"
590
+ });
591
+ } else {
592
+ controller.enqueue({
593
+ type: "tool-output-available",
594
+ toolCallId,
595
+ output: dataSource.content
596
+ });
597
+ }
598
+ }
599
+ }
600
+ return;
601
+ }
602
+ case "values": {
603
+ for (const [id, seen] of Object.entries(messageSeen)) {
604
+ if (seen.text) controller.enqueue({ type: "text-end", id });
605
+ if (seen.tool) {
606
+ for (const [toolCallId, toolCallSeen] of Object.entries(seen.tool)) {
607
+ const concatMsg = messageConcat[id];
608
+ const toolCall = (_x = concatMsg == null ? void 0 : concatMsg.tool_calls) == null ? void 0 : _x.find(
609
+ (call) => call.id === toolCallId
39
610
  );
611
+ if (toolCallSeen && toolCall) {
612
+ emittedToolCalls.add(toolCallId);
613
+ const toolCallKey = `${toolCall.name}:${JSON.stringify(toolCall.args)}`;
614
+ emittedToolCallsByKey.set(toolCallKey, toolCallId);
615
+ controller.enqueue({
616
+ type: "tool-input-available",
617
+ toolCallId,
618
+ toolName: toolCall.name,
619
+ input: toolCall.args,
620
+ dynamic: true
621
+ });
622
+ }
40
623
  }
41
- return;
42
624
  }
43
- forwardAIMessageChunk(value, controller);
625
+ if (seen.reasoning) {
626
+ controller.enqueue({ type: "reasoning-end", id });
627
+ }
628
+ delete messageSeen[id];
629
+ delete messageConcat[id];
630
+ delete messageReasoningIds[id];
44
631
  }
45
- })
46
- ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(
47
- new TransformStream({
48
- start: async (controller) => {
49
- controller.enqueue({ type: "text-start", id: "1" });
50
- },
51
- transform: async (chunk, controller) => {
52
- controller.enqueue({ type: "text-delta", delta: chunk, id: "1" });
53
- },
54
- flush: async (controller) => {
55
- controller.enqueue({ type: "text-end", id: "1" });
632
+ if (data != null && typeof data === "object" && "messages" in data) {
633
+ const messages = data.messages;
634
+ if (Array.isArray(messages)) {
635
+ const completedToolCallIds = /* @__PURE__ */ new Set();
636
+ for (const msg of messages) {
637
+ if (!msg || typeof msg !== "object") continue;
638
+ if (isToolMessageType(msg)) {
639
+ const msgObj = msg;
640
+ const dataSource = msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
641
+ const toolCallId = dataSource.tool_call_id;
642
+ if (toolCallId) {
643
+ completedToolCallIds.add(toolCallId);
644
+ }
645
+ }
646
+ }
647
+ for (const msg of messages) {
648
+ if (!msg || typeof msg !== "object") continue;
649
+ const msgId = getMessageId(msg);
650
+ if (!msgId) continue;
651
+ let toolCalls;
652
+ if (AIMessageChunk.isInstance(msg) || AIMessage.isInstance(msg)) {
653
+ toolCalls = msg.tool_calls;
654
+ } else if (isPlainMessageObject(msg)) {
655
+ const obj = msg;
656
+ const isSerializedFormat = obj.type === "constructor" && Array.isArray(obj.id) && (obj.id.includes("AIMessageChunk") || obj.id.includes("AIMessage"));
657
+ const dataSource = isSerializedFormat ? obj.kwargs : obj;
658
+ if (obj.type === "ai" || isSerializedFormat) {
659
+ if (Array.isArray(dataSource == null ? void 0 : dataSource.tool_calls)) {
660
+ toolCalls = dataSource.tool_calls;
661
+ } else if (
662
+ /**
663
+ * Fall back to additional_kwargs.tool_calls (OpenAI format)
664
+ */
665
+ (dataSource == null ? void 0 : dataSource.additional_kwargs) && typeof dataSource.additional_kwargs === "object"
666
+ ) {
667
+ const additionalKwargs = dataSource.additional_kwargs;
668
+ if (Array.isArray(additionalKwargs.tool_calls)) {
669
+ toolCalls = additionalKwargs.tool_calls.map((tc, idx) => {
670
+ const functionData = tc.function;
671
+ let args;
672
+ try {
673
+ args = (functionData == null ? void 0 : functionData.arguments) ? JSON.parse(functionData.arguments) : {};
674
+ } catch (e) {
675
+ args = {};
676
+ }
677
+ return {
678
+ id: tc.id || `call_${idx}`,
679
+ name: (functionData == null ? void 0 : functionData.name) || "unknown",
680
+ args
681
+ };
682
+ });
683
+ }
684
+ }
685
+ }
686
+ }
687
+ if (toolCalls && toolCalls.length > 0) {
688
+ for (const toolCall of toolCalls) {
689
+ if (toolCall.id && !emittedToolCalls.has(toolCall.id) && !completedToolCallIds.has(toolCall.id)) {
690
+ emittedToolCalls.add(toolCall.id);
691
+ const toolCallKey = `${toolCall.name}:${JSON.stringify(toolCall.args)}`;
692
+ emittedToolCallsByKey.set(toolCallKey, toolCall.id);
693
+ controller.enqueue({
694
+ type: "tool-input-start",
695
+ toolCallId: toolCall.id,
696
+ toolName: toolCall.name,
697
+ dynamic: true
698
+ });
699
+ controller.enqueue({
700
+ type: "tool-input-available",
701
+ toolCallId: toolCall.id,
702
+ toolName: toolCall.name,
703
+ input: toolCall.args,
704
+ dynamic: true
705
+ });
706
+ }
707
+ }
708
+ }
709
+ const reasoningId = extractReasoningId(msg);
710
+ const wasStreamedThisRequest = !!messageSeen[msgId];
711
+ const hasToolCalls = toolCalls && toolCalls.length > 0;
712
+ const shouldEmitReasoning = reasoningId && !emittedReasoningIds.has(reasoningId) && (wasStreamedThisRequest || !hasToolCalls);
713
+ if (shouldEmitReasoning) {
714
+ const reasoning = extractReasoningFromValuesMessage(msg);
715
+ if (reasoning) {
716
+ controller.enqueue({ type: "reasoning-start", id: msgId });
717
+ controller.enqueue({
718
+ type: "reasoning-delta",
719
+ delta: reasoning,
720
+ id: msgId
721
+ });
722
+ controller.enqueue({ type: "reasoning-end", id: msgId });
723
+ emittedReasoningIds.add(reasoningId);
724
+ }
725
+ }
726
+ }
727
+ }
728
+ }
729
+ if (data != null && typeof data === "object") {
730
+ const interrupt = data.__interrupt__;
731
+ if (Array.isArray(interrupt) && interrupt.length > 0) {
732
+ for (const interruptItem of interrupt) {
733
+ const interruptValue = interruptItem == null ? void 0 : interruptItem.value;
734
+ if (!interruptValue) continue;
735
+ const actionRequests = interruptValue.actionRequests || interruptValue.action_requests;
736
+ if (!Array.isArray(actionRequests)) continue;
737
+ for (const actionRequest of actionRequests) {
738
+ const toolName = actionRequest.name;
739
+ const input = actionRequest.args || actionRequest.arguments;
740
+ const toolCallKey = `${toolName}:${JSON.stringify(input)}`;
741
+ const toolCallId = emittedToolCallsByKey.get(toolCallKey) || actionRequest.id || `hitl-${toolName}-${Date.now()}`;
742
+ if (!emittedToolCalls.has(toolCallId)) {
743
+ emittedToolCalls.add(toolCallId);
744
+ emittedToolCallsByKey.set(toolCallKey, toolCallId);
745
+ controller.enqueue({
746
+ type: "tool-input-start",
747
+ toolCallId,
748
+ toolName,
749
+ dynamic: true
750
+ });
751
+ controller.enqueue({
752
+ type: "tool-input-available",
753
+ toolCallId,
754
+ toolName,
755
+ input,
756
+ dynamic: true
757
+ });
758
+ }
759
+ controller.enqueue({
760
+ type: "tool-approval-request",
761
+ approvalId: toolCallId,
762
+ toolCallId
763
+ });
764
+ }
765
+ }
766
+ }
767
+ }
768
+ break;
769
+ }
770
+ }
771
+ }
772
+
773
+ // src/adapter.ts
774
+ async function toBaseMessages(messages) {
775
+ const modelMessages = await convertToModelMessages(messages);
776
+ return convertModelMessages(modelMessages);
777
+ }
778
+ function convertModelMessages(modelMessages) {
779
+ const result = [];
780
+ for (const message of modelMessages) {
781
+ switch (message.role) {
782
+ case "tool": {
783
+ for (const item of message.content) {
784
+ if (isToolResultPart(item)) {
785
+ result.push(convertToolResultPart(item));
786
+ }
787
+ }
788
+ break;
789
+ }
790
+ case "assistant": {
791
+ result.push(convertAssistantContent(message.content));
792
+ break;
793
+ }
794
+ case "system": {
795
+ result.push(new SystemMessage({ content: message.content }));
796
+ break;
797
+ }
798
+ case "user": {
799
+ result.push(convertUserContent(message.content));
800
+ break;
56
801
  }
57
- })
58
- );
802
+ }
803
+ }
804
+ return result;
805
+ }
806
+ function isStreamEventsEvent(value) {
807
+ if (value == null || typeof value !== "object") return false;
808
+ const obj = value;
809
+ if (!("event" in obj) || typeof obj.event !== "string") return false;
810
+ if (!("data" in obj)) return false;
811
+ return obj.data === null || typeof obj.data === "object";
59
812
  }
60
- function forwardAIMessageChunk(chunk, controller) {
61
- if (typeof chunk.content === "string") {
62
- controller.enqueue(chunk.content);
63
- } else {
64
- const content = chunk.content;
65
- for (const item of content) {
66
- if (item.type === "text") {
67
- controller.enqueue(item.text);
813
+ function processStreamEventsEvent(event, state, controller) {
814
+ var _a, _b, _c;
815
+ if (event.run_id && !state.started) {
816
+ state.messageId = event.run_id;
817
+ }
818
+ if (!event.data) return;
819
+ switch (event.event) {
820
+ case "on_chat_model_start": {
821
+ const runId = event.run_id || event.data.run_id;
822
+ if (runId) {
823
+ state.messageId = runId;
68
824
  }
825
+ break;
826
+ }
827
+ case "on_chat_model_stream": {
828
+ const chunk = event.data.chunk;
829
+ if (chunk && typeof chunk === "object") {
830
+ const chunkId = chunk.id;
831
+ if (chunkId) {
832
+ state.messageId = chunkId;
833
+ }
834
+ const reasoning = extractReasoningFromContentBlocks(chunk);
835
+ if (reasoning) {
836
+ if (!state.reasoningStarted) {
837
+ state.reasoningMessageId = state.messageId;
838
+ controller.enqueue({
839
+ type: "reasoning-start",
840
+ id: state.messageId
841
+ });
842
+ state.reasoningStarted = true;
843
+ state.started = true;
844
+ }
845
+ controller.enqueue({
846
+ type: "reasoning-delta",
847
+ delta: reasoning,
848
+ id: (_a = state.reasoningMessageId) != null ? _a : state.messageId
849
+ });
850
+ }
851
+ const content = chunk.content;
852
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.filter(
853
+ (c) => typeof c === "object" && c !== null && "type" in c && c.type === "text"
854
+ ).map((c) => c.text).join("") : "";
855
+ if (text) {
856
+ if (state.reasoningStarted && !state.textStarted) {
857
+ controller.enqueue({
858
+ type: "reasoning-end",
859
+ id: (_b = state.reasoningMessageId) != null ? _b : state.messageId
860
+ });
861
+ state.reasoningStarted = false;
862
+ }
863
+ if (!state.textStarted) {
864
+ state.textMessageId = state.messageId;
865
+ controller.enqueue({ type: "text-start", id: state.messageId });
866
+ state.textStarted = true;
867
+ state.started = true;
868
+ }
869
+ controller.enqueue({
870
+ type: "text-delta",
871
+ delta: text,
872
+ id: (_c = state.textMessageId) != null ? _c : state.messageId
873
+ });
874
+ }
875
+ }
876
+ break;
877
+ }
878
+ case "on_tool_start": {
879
+ const runId = event.run_id || event.data.run_id;
880
+ const name = event.name || event.data.name;
881
+ if (runId && name) {
882
+ controller.enqueue({
883
+ type: "tool-input-start",
884
+ toolCallId: runId,
885
+ toolName: name,
886
+ dynamic: true
887
+ });
888
+ }
889
+ break;
890
+ }
891
+ case "on_tool_end": {
892
+ const runId = event.run_id || event.data.run_id;
893
+ const output = event.data.output;
894
+ if (runId) {
895
+ controller.enqueue({
896
+ type: "tool-output-available",
897
+ toolCallId: runId,
898
+ output
899
+ });
900
+ }
901
+ break;
69
902
  }
70
903
  }
71
904
  }
905
+ function toUIMessageStream(stream, callbacks) {
906
+ const textChunks = [];
907
+ const modelState = {
908
+ started: false,
909
+ messageId: "langchain-msg-1",
910
+ reasoningStarted: false,
911
+ textStarted: false,
912
+ /** Track the ID used for text-start to ensure text-end uses the same ID */
913
+ textMessageId: null,
914
+ /** Track the ID used for reasoning-start to ensure reasoning-end uses the same ID */
915
+ reasoningMessageId: null
916
+ };
917
+ const langGraphState = {
918
+ messageSeen: {},
919
+ messageConcat: {},
920
+ emittedToolCalls: /* @__PURE__ */ new Set(),
921
+ emittedImages: /* @__PURE__ */ new Set(),
922
+ emittedReasoningIds: /* @__PURE__ */ new Set(),
923
+ messageReasoningIds: {},
924
+ toolCallInfoByIndex: {},
925
+ currentStep: null,
926
+ emittedToolCallsByKey: /* @__PURE__ */ new Map()
927
+ };
928
+ let streamType = null;
929
+ const getAsyncIterator = () => {
930
+ if (Symbol.asyncIterator in stream) {
931
+ return stream[Symbol.asyncIterator]();
932
+ }
933
+ const reader = stream.getReader();
934
+ return {
935
+ async next() {
936
+ const { done, value } = await reader.read();
937
+ return { done, value };
938
+ }
939
+ };
940
+ };
941
+ const iterator = getAsyncIterator();
942
+ const createCallbackController = (originalController) => {
943
+ return {
944
+ get desiredSize() {
945
+ return originalController.desiredSize;
946
+ },
947
+ close: () => originalController.close(),
948
+ error: (e) => originalController.error(e),
949
+ enqueue: (chunk) => {
950
+ var _a, _b;
951
+ if (callbacks && chunk.type === "text-delta" && chunk.delta) {
952
+ textChunks.push(chunk.delta);
953
+ (_a = callbacks.onToken) == null ? void 0 : _a.call(callbacks, chunk.delta);
954
+ (_b = callbacks.onText) == null ? void 0 : _b.call(callbacks, chunk.delta);
955
+ }
956
+ originalController.enqueue(chunk);
957
+ }
958
+ };
959
+ };
960
+ return new ReadableStream({
961
+ async start(controller) {
962
+ var _a, _b, _c, _d;
963
+ await ((_a = callbacks == null ? void 0 : callbacks.onStart) == null ? void 0 : _a.call(callbacks));
964
+ const wrappedController = createCallbackController(controller);
965
+ controller.enqueue({ type: "start" });
966
+ try {
967
+ while (true) {
968
+ const { done, value } = await iterator.next();
969
+ if (done) break;
970
+ if (streamType === null) {
971
+ if (Array.isArray(value)) {
972
+ streamType = "langgraph";
973
+ } else if (isStreamEventsEvent(value)) {
974
+ streamType = "streamEvents";
975
+ } else {
976
+ streamType = "model";
977
+ }
978
+ }
979
+ if (streamType === "model") {
980
+ processModelChunk(
981
+ value,
982
+ modelState,
983
+ wrappedController
984
+ );
985
+ } else if (streamType === "streamEvents") {
986
+ processStreamEventsEvent(
987
+ value,
988
+ modelState,
989
+ wrappedController
990
+ );
991
+ } else {
992
+ processLangGraphEvent(
993
+ value,
994
+ langGraphState,
995
+ wrappedController
996
+ );
997
+ }
998
+ }
999
+ if (streamType === "model" || streamType === "streamEvents") {
1000
+ if (modelState.reasoningStarted) {
1001
+ controller.enqueue({
1002
+ type: "reasoning-end",
1003
+ id: (_b = modelState.reasoningMessageId) != null ? _b : modelState.messageId
1004
+ });
1005
+ }
1006
+ if (modelState.textStarted) {
1007
+ controller.enqueue({
1008
+ type: "text-end",
1009
+ id: (_c = modelState.textMessageId) != null ? _c : modelState.messageId
1010
+ });
1011
+ }
1012
+ controller.enqueue({ type: "finish" });
1013
+ } else if (streamType === "langgraph") {
1014
+ if (langGraphState.currentStep !== null) {
1015
+ controller.enqueue({ type: "finish-step" });
1016
+ }
1017
+ controller.enqueue({ type: "finish" });
1018
+ }
1019
+ await ((_d = callbacks == null ? void 0 : callbacks.onFinal) == null ? void 0 : _d.call(callbacks, textChunks.join("")));
1020
+ } catch (error) {
1021
+ controller.enqueue({
1022
+ type: "error",
1023
+ errorText: error instanceof Error ? error.message : "Unknown error"
1024
+ });
1025
+ } finally {
1026
+ controller.close();
1027
+ }
1028
+ }
1029
+ });
1030
+ }
1031
+
1032
+ // src/transport.ts
1033
+ import {
1034
+ RemoteGraph
1035
+ } from "@langchain/langgraph/remote";
1036
+ var LangSmithDeploymentTransport = class {
1037
+ constructor(options) {
1038
+ var _a;
1039
+ this.graph = new RemoteGraph({
1040
+ ...options,
1041
+ graphId: (_a = options.graphId) != null ? _a : "agent"
1042
+ });
1043
+ }
1044
+ async sendMessages(options) {
1045
+ const baseMessages = await toBaseMessages(options.messages);
1046
+ const stream = await this.graph.stream(
1047
+ { messages: baseMessages },
1048
+ { streamMode: ["values", "messages"] }
1049
+ );
1050
+ return toUIMessageStream(
1051
+ stream
1052
+ );
1053
+ }
1054
+ async reconnectToStream(_options) {
1055
+ throw new Error("Method not implemented.");
1056
+ }
1057
+ };
72
1058
  export {
1059
+ LangSmithDeploymentTransport,
1060
+ convertModelMessages,
1061
+ toBaseMessages,
73
1062
  toUIMessageStream
74
1063
  };
75
1064
  //# sourceMappingURL=index.mjs.map