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