@ai-sdk/langchain 3.0.0-beta.18 → 3.0.0-beta.180

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
@@ -1,38 +1,18 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- LangSmithDeploymentTransport: () => LangSmithDeploymentTransport,
24
- convertModelMessages: () => convertModelMessages,
25
- toBaseMessages: () => toBaseMessages,
26
- toUIMessageStream: () => toUIMessageStream
27
- });
28
- module.exports = __toCommonJS(index_exports);
29
-
30
1
  // src/adapter.ts
31
- var import_messages2 = require("@langchain/core/messages");
32
- var import_ai = require("ai");
2
+ import {
3
+ SystemMessage
4
+ } from "@langchain/core/messages";
5
+ import {
6
+ convertToModelMessages
7
+ } from "ai";
33
8
 
34
9
  // src/utils.ts
35
- var import_messages = require("@langchain/core/messages");
10
+ import {
11
+ AIMessage,
12
+ HumanMessage,
13
+ ToolMessage,
14
+ AIMessageChunk
15
+ } from "@langchain/core/messages";
36
16
  function parseLangGraphEvent(event) {
37
17
  return event.length === 3 ? [event[1], event[2]] : [event[0], event[1]];
38
18
  }
@@ -54,14 +34,14 @@ function convertToolResultPart(block) {
54
34
  }
55
35
  return "";
56
36
  })();
57
- return new import_messages.ToolMessage({
37
+ return new ToolMessage({
58
38
  tool_call_id: block.toolCallId,
59
39
  content
60
40
  });
61
41
  }
62
42
  function convertAssistantContent(content) {
63
43
  if (typeof content === "string") {
64
- return new import_messages.AIMessage({ content });
44
+ return new AIMessage({ content });
65
45
  }
66
46
  const textParts = [];
67
47
  const toolCalls = [];
@@ -76,19 +56,19 @@ function convertAssistantContent(content) {
76
56
  });
77
57
  }
78
58
  }
79
- return new import_messages.AIMessage({
59
+ return new AIMessage({
80
60
  content: textParts.join(""),
81
61
  tool_calls: toolCalls.length > 0 ? toolCalls : void 0
82
62
  });
83
63
  }
84
64
  function getDefaultFilename(mediaType, prefix = "file") {
85
- const ext = mediaType.split("/")[1] || "bin";
86
- return `${prefix}.${ext}`;
65
+ const fileExtension = mediaType.split("/")[1] || "bin";
66
+ return `${prefix}.${fileExtension}`;
87
67
  }
88
68
  function convertUserContent(content) {
89
69
  var _a;
90
70
  if (typeof content === "string") {
91
- return new import_messages.HumanMessage({ content });
71
+ return new HumanMessage({ content });
92
72
  }
93
73
  const contentBlocks = [];
94
74
  for (const part of content) {
@@ -129,7 +109,29 @@ function convertUserContent(content) {
129
109
  });
130
110
  }
131
111
  } else if (part.type === "file") {
132
- const filePart = part;
112
+ const rawFilePart = part;
113
+ const normalizedData = (() => {
114
+ const data = rawFilePart.data;
115
+ if (typeof data === "object" && data !== null && !(data instanceof URL) && !(data instanceof Uint8Array) && !(data instanceof ArrayBuffer) && "type" in data) {
116
+ switch (data.type) {
117
+ case "data":
118
+ return data.data;
119
+ case "url":
120
+ return data.url;
121
+ case "text":
122
+ return data.text;
123
+ default:
124
+ return "";
125
+ }
126
+ }
127
+ return data;
128
+ })();
129
+ const filePart = {
130
+ type: "file",
131
+ data: normalizedData,
132
+ mediaType: rawFilePart.mediaType,
133
+ filename: rawFilePart.filename
134
+ };
133
135
  const isImage = (_a = filePart.mediaType) == null ? void 0 : _a.startsWith("image/");
134
136
  if (isImage) {
135
137
  if (filePart.data instanceof URL) {
@@ -215,11 +217,11 @@ function convertUserContent(content) {
215
217
  }
216
218
  }
217
219
  if (contentBlocks.every((block) => block.type === "text")) {
218
- return new import_messages.HumanMessage({
220
+ return new HumanMessage({
219
221
  content: contentBlocks.map((block) => block.text).join("")
220
222
  });
221
223
  }
222
- return new import_messages.HumanMessage({ content: contentBlocks });
224
+ return new HumanMessage({ content: contentBlocks });
223
225
  }
224
226
  function isToolResultPart(item) {
225
227
  return item != null && typeof item === "object" && "type" in item && item.type === "tool-result";
@@ -229,6 +231,9 @@ function processModelChunk(chunk, state, controller) {
229
231
  if (!state.emittedImages) {
230
232
  state.emittedImages = /* @__PURE__ */ new Set();
231
233
  }
234
+ if (!state.emittedSourceIds) {
235
+ state.emittedSourceIds = /* @__PURE__ */ new Set();
236
+ }
232
237
  if (chunk.id) {
233
238
  state.messageId = chunk.id;
234
239
  }
@@ -284,6 +289,15 @@ function processModelChunk(chunk, state, controller) {
284
289
  id: (_c = state.textMessageId) != null ? _c : state.messageId
285
290
  });
286
291
  }
292
+ const citations = extractCitationsFromContentBlocks(chunk);
293
+ if (citations.length > 0) {
294
+ emitSourceChunks(
295
+ citations,
296
+ state.messageId,
297
+ state.emittedSourceIds,
298
+ controller
299
+ );
300
+ }
287
301
  }
288
302
  function isPlainMessageObject(msg) {
289
303
  if (msg == null || typeof msg !== "object") return false;
@@ -304,22 +318,24 @@ function getMessageId(msg) {
304
318
  return void 0;
305
319
  }
306
320
  function isAIMessageChunk(msg) {
307
- if (import_messages.AIMessageChunk.isInstance(msg)) return true;
321
+ if (AIMessageChunk.isInstance(msg)) return true;
308
322
  if (isPlainMessageObject(msg)) {
309
- const obj = msg;
310
- if ("type" in obj && obj.type === "ai") return true;
311
- if (obj.type === "constructor" && Array.isArray(obj.id) && (obj.id.includes("AIMessageChunk") || obj.id.includes("AIMessage"))) {
323
+ const messageRecord = msg;
324
+ if ("type" in messageRecord && (messageRecord.type === "ai" || messageRecord.type === "AIMessageChunk")) {
325
+ return true;
326
+ }
327
+ if (messageRecord.type === "constructor" && Array.isArray(messageRecord.id) && (messageRecord.id.includes("AIMessageChunk") || messageRecord.id.includes("AIMessage"))) {
312
328
  return true;
313
329
  }
314
330
  }
315
331
  return false;
316
332
  }
317
333
  function isToolMessageType(msg) {
318
- if (import_messages.ToolMessage.isInstance(msg)) return true;
334
+ if (ToolMessage.isInstance(msg)) return true;
319
335
  if (isPlainMessageObject(msg)) {
320
- const obj = msg;
321
- if ("type" in obj && obj.type === "tool") return true;
322
- if (obj.type === "constructor" && Array.isArray(obj.id) && obj.id.includes("ToolMessage")) {
336
+ const messageRecord = msg;
337
+ if ("type" in messageRecord && messageRecord.type === "tool") return true;
338
+ if (messageRecord.type === "constructor" && Array.isArray(messageRecord.id) && messageRecord.id.includes("ToolMessage")) {
323
339
  return true;
324
340
  }
325
341
  }
@@ -327,7 +343,7 @@ function isToolMessageType(msg) {
327
343
  }
328
344
  function getMessageText(msg) {
329
345
  var _a;
330
- if (import_messages.AIMessageChunk.isInstance(msg)) {
346
+ if (AIMessageChunk.isInstance(msg)) {
331
347
  return (_a = msg.text) != null ? _a : "";
332
348
  }
333
349
  if (msg == null || typeof msg !== "object") return "";
@@ -444,6 +460,85 @@ function extractReasoningFromValuesMessage(msg) {
444
460
  }
445
461
  return void 0;
446
462
  }
463
+ function isCitationContentBlock(obj) {
464
+ return obj != null && typeof obj === "object" && "type" in obj && obj.type === "citation";
465
+ }
466
+ function extractCitationsFromContentBlocks(msg) {
467
+ if (msg == null || typeof msg !== "object") return [];
468
+ const msgObj = msg;
469
+ const kwargs = msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
470
+ const contentBlocks = kwargs.contentBlocks;
471
+ const content = kwargs.content;
472
+ const blockSources = Array.isArray(contentBlocks) ? contentBlocks : Array.isArray(content) ? content : [];
473
+ const citations = [];
474
+ for (const block of blockSources) {
475
+ if (block == null || typeof block !== "object") continue;
476
+ const annotations = block.annotations;
477
+ if (!Array.isArray(annotations)) continue;
478
+ for (const annotation of annotations) {
479
+ if (!isCitationContentBlock(annotation)) continue;
480
+ citations.push({
481
+ url: annotation.url,
482
+ title: annotation.title,
483
+ source: annotation.source,
484
+ citedText: annotation.citedText,
485
+ startIndex: annotation.startIndex,
486
+ endIndex: annotation.endIndex
487
+ });
488
+ }
489
+ }
490
+ return citations;
491
+ }
492
+ function buildSourceProviderMetadata(citation) {
493
+ const langchain = {};
494
+ if (typeof citation.citedText === "string") {
495
+ langchain.citedText = citation.citedText;
496
+ }
497
+ if (typeof citation.startIndex === "number") {
498
+ langchain.startIndex = citation.startIndex;
499
+ }
500
+ if (typeof citation.endIndex === "number") {
501
+ langchain.endIndex = citation.endIndex;
502
+ }
503
+ if (typeof citation.source === "string") {
504
+ langchain.source = citation.source;
505
+ }
506
+ if (Object.keys(langchain).length === 0) {
507
+ return void 0;
508
+ }
509
+ return { langchain };
510
+ }
511
+ function emitSourceChunks(citations, messageId, emittedSourceIds, controller) {
512
+ var _a, _b, _c, _d;
513
+ for (const citation of citations) {
514
+ if (citation.url) {
515
+ if (emittedSourceIds.has(citation.url)) continue;
516
+ emittedSourceIds.add(citation.url);
517
+ const providerMetadata2 = buildSourceProviderMetadata(citation);
518
+ controller.enqueue({
519
+ type: "source-url",
520
+ sourceId: citation.url,
521
+ url: citation.url,
522
+ ...citation.title ? { title: citation.title } : {},
523
+ ...providerMetadata2 ? { providerMetadata: providerMetadata2 } : {}
524
+ });
525
+ continue;
526
+ }
527
+ const title = (_a = citation.title) != null ? _a : citation.source;
528
+ if (!title) continue;
529
+ const sourceId = `${messageId}:${title}:${(_b = citation.citedText) != null ? _b : ""}:${(_c = citation.startIndex) != null ? _c : ""}:${(_d = citation.endIndex) != null ? _d : ""}`;
530
+ if (emittedSourceIds.has(sourceId)) continue;
531
+ emittedSourceIds.add(sourceId);
532
+ const providerMetadata = buildSourceProviderMetadata(citation);
533
+ controller.enqueue({
534
+ type: "source-document",
535
+ sourceId,
536
+ mediaType: "text/plain",
537
+ title,
538
+ ...providerMetadata ? { providerMetadata } : {}
539
+ });
540
+ }
541
+ }
447
542
  function isImageGenerationOutput(obj) {
448
543
  return obj != null && typeof obj === "object" && "type" in obj && obj.type === "image_generation_call";
449
544
  }
@@ -453,8 +548,34 @@ function extractImageOutputs(additionalKwargs) {
453
548
  if (!Array.isArray(toolOutputs)) return [];
454
549
  return toolOutputs.filter(isImageGenerationOutput);
455
550
  }
551
+ function formatToolError(error) {
552
+ if (error instanceof Error) return error.message;
553
+ if (typeof error === "string") return error;
554
+ try {
555
+ const serialized = JSON.stringify(error);
556
+ return serialized != null ? serialized : String(error);
557
+ } catch (e) {
558
+ return String(error);
559
+ }
560
+ }
561
+ function getOrCreateMessageSeen(messageSeen, msgId) {
562
+ let seen = messageSeen.get(msgId);
563
+ if (!seen) {
564
+ seen = {};
565
+ messageSeen.set(msgId, seen);
566
+ }
567
+ return seen;
568
+ }
569
+ function getOrCreateToolCallInfoByIndex(toolCallInfoByIndex, msgId) {
570
+ let toolCallInfo = toolCallInfoByIndex.get(msgId);
571
+ if (!toolCallInfo) {
572
+ toolCallInfo = /* @__PURE__ */ new Map();
573
+ toolCallInfoByIndex.set(msgId, toolCallInfo);
574
+ }
575
+ return toolCallInfo;
576
+ }
456
577
  function processLangGraphEvent(event, state, controller) {
457
- 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;
578
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
458
579
  const {
459
580
  messageSeen,
460
581
  messageConcat,
@@ -463,7 +584,8 @@ function processLangGraphEvent(event, state, controller) {
463
584
  emittedReasoningIds,
464
585
  messageReasoningIds,
465
586
  toolCallInfoByIndex,
466
- emittedToolCallsByKey
587
+ emittedToolCallsByKey,
588
+ emittedToolInputs
467
589
  } = state;
468
590
  const [type, data] = parseLangGraphEvent(event);
469
591
  switch (type) {
@@ -495,22 +617,35 @@ function processLangGraphEvent(event, state, controller) {
495
617
  const langgraphStep = typeof (metadata == null ? void 0 : metadata.langgraph_step) === "number" ? metadata.langgraph_step : null;
496
618
  if (langgraphStep !== null && langgraphStep !== state.currentStep) {
497
619
  if (state.currentStep !== null) {
620
+ for (const [id, seen] of messageSeen) {
621
+ if (seen.text) {
622
+ controller.enqueue({ type: "text-end", id });
623
+ }
624
+ if (seen.reasoning) {
625
+ controller.enqueue({ type: "reasoning-end", id });
626
+ }
627
+ messageSeen.delete(id);
628
+ messageConcat.delete(id);
629
+ messageReasoningIds.delete(id);
630
+ }
498
631
  controller.enqueue({ type: "finish-step" });
499
632
  }
500
633
  controller.enqueue({ type: "start-step" });
501
634
  state.currentStep = langgraphStep;
502
635
  }
503
- if (import_messages.AIMessageChunk.isInstance(msg)) {
504
- if (messageConcat[msgId]) {
505
- messageConcat[msgId] = messageConcat[msgId].concat(
506
- msg
636
+ if (AIMessageChunk.isInstance(msg)) {
637
+ const existingMessage = messageConcat.get(msgId);
638
+ if (existingMessage) {
639
+ messageConcat.set(
640
+ msgId,
641
+ existingMessage.concat(msg)
507
642
  );
508
643
  } else {
509
- messageConcat[msgId] = msg;
644
+ messageConcat.set(msgId, msg);
510
645
  }
511
646
  }
512
647
  if (isAIMessageChunk(msg)) {
513
- const concatChunk = messageConcat[msgId];
648
+ const concatChunk = messageConcat.get(msgId);
514
649
  const msgObj = msg;
515
650
  const dataSource = msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
516
651
  const additionalKwargs = dataSource.additional_kwargs;
@@ -529,30 +664,36 @@ function processLangGraphEvent(event, state, controller) {
529
664
  const toolCallChunks = dataSource.tool_call_chunks;
530
665
  if (toolCallChunks == null ? void 0 : toolCallChunks.length) {
531
666
  for (const toolCallChunk of toolCallChunks) {
532
- const idx = (_a = toolCallChunk.index) != null ? _a : 0;
667
+ const toolCallIndex = (_a = toolCallChunk.index) != null ? _a : 0;
533
668
  if (toolCallChunk.id) {
534
- (_b = toolCallInfoByIndex[msgId]) != null ? _b : toolCallInfoByIndex[msgId] = {};
535
- toolCallInfoByIndex[msgId][idx] = {
536
- id: toolCallChunk.id,
537
- name: toolCallChunk.name || ((_d = (_c = concatChunk == null ? void 0 : concatChunk.tool_call_chunks) == null ? void 0 : _c[idx]) == null ? void 0 : _d.name) || "unknown"
538
- };
669
+ getOrCreateToolCallInfoByIndex(toolCallInfoByIndex, msgId).set(
670
+ toolCallIndex,
671
+ {
672
+ id: toolCallChunk.id,
673
+ name: toolCallChunk.name || ((_c = (_b = concatChunk == null ? void 0 : concatChunk.tool_call_chunks) == null ? void 0 : _b[toolCallIndex]) == null ? void 0 : _c.name) || "unknown"
674
+ }
675
+ );
539
676
  }
540
- 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);
677
+ const storedToolCallInfo = (_d = toolCallInfoByIndex.get(msgId)) == null ? void 0 : _d.get(toolCallIndex);
678
+ const toolCallId = toolCallChunk.id || (storedToolCallInfo == null ? void 0 : storedToolCallInfo.id) || ((_f = (_e = concatChunk == null ? void 0 : concatChunk.tool_call_chunks) == null ? void 0 : _e[toolCallIndex]) == null ? void 0 : _f.id);
541
679
  if (!toolCallId) {
542
680
  continue;
543
681
  }
544
- 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";
545
- if (!((_n = (_m = messageSeen[msgId]) == null ? void 0 : _m.tool) == null ? void 0 : _n[toolCallId])) {
546
- controller.enqueue({
547
- type: "tool-input-start",
548
- toolCallId,
549
- toolName,
550
- dynamic: true
551
- });
552
- (_o = messageSeen[msgId]) != null ? _o : messageSeen[msgId] = {};
553
- (_q = (_p = messageSeen[msgId]).tool) != null ? _q : _p.tool = {};
554
- messageSeen[msgId].tool[toolCallId] = true;
555
- emittedToolCalls.add(toolCallId);
682
+ const toolName = toolCallChunk.name || (storedToolCallInfo == null ? void 0 : storedToolCallInfo.name) || ((_h = (_g = concatChunk == null ? void 0 : concatChunk.tool_call_chunks) == null ? void 0 : _g[toolCallIndex]) == null ? void 0 : _h.name) || "unknown";
683
+ const seen = messageSeen.get(msgId);
684
+ if (!((_i = seen == null ? void 0 : seen.tool) == null ? void 0 : _i.has(toolCallId))) {
685
+ const updatedSeen = getOrCreateMessageSeen(messageSeen, msgId);
686
+ (_j = updatedSeen.tool) != null ? _j : updatedSeen.tool = /* @__PURE__ */ new Set();
687
+ updatedSeen.tool.add(toolCallId);
688
+ if (!emittedToolCalls.has(toolCallId)) {
689
+ emittedToolCalls.add(toolCallId);
690
+ controller.enqueue({
691
+ type: "tool-input-start",
692
+ toolCallId,
693
+ toolName,
694
+ dynamic: true
695
+ });
696
+ }
556
697
  }
557
698
  if (toolCallChunk.args) {
558
699
  controller.enqueue({
@@ -566,18 +707,18 @@ function processLangGraphEvent(event, state, controller) {
566
707
  }
567
708
  const chunkReasoningId = extractReasoningId(msg);
568
709
  if (chunkReasoningId) {
569
- if (!messageReasoningIds[msgId]) {
570
- messageReasoningIds[msgId] = chunkReasoningId;
710
+ if (!messageReasoningIds.has(msgId)) {
711
+ messageReasoningIds.set(msgId, chunkReasoningId);
571
712
  }
572
713
  emittedReasoningIds.add(chunkReasoningId);
573
714
  }
574
715
  const reasoning = extractReasoningFromContentBlocks(msg);
575
716
  if (reasoning) {
576
- const reasoningId = (_s = (_r = messageReasoningIds[msgId]) != null ? _r : chunkReasoningId) != null ? _s : msgId;
577
- if (!((_t = messageSeen[msgId]) == null ? void 0 : _t.reasoning)) {
717
+ const reasoningId = (_l = (_k = messageReasoningIds.get(msgId)) != null ? _k : chunkReasoningId) != null ? _l : msgId;
718
+ const seen = messageSeen.get(msgId);
719
+ if (!(seen == null ? void 0 : seen.reasoning)) {
578
720
  controller.enqueue({ type: "reasoning-start", id: msgId });
579
- (_u = messageSeen[msgId]) != null ? _u : messageSeen[msgId] = {};
580
- messageSeen[msgId].reasoning = true;
721
+ getOrCreateMessageSeen(messageSeen, msgId).reasoning = true;
581
722
  }
582
723
  controller.enqueue({
583
724
  type: "reasoning-delta",
@@ -588,10 +729,10 @@ function processLangGraphEvent(event, state, controller) {
588
729
  }
589
730
  const text = getMessageText(msg);
590
731
  if (text) {
591
- if (!((_v = messageSeen[msgId]) == null ? void 0 : _v.text)) {
732
+ const seen = messageSeen.get(msgId);
733
+ if (!(seen == null ? void 0 : seen.text)) {
592
734
  controller.enqueue({ type: "text-start", id: msgId });
593
- (_w = messageSeen[msgId]) != null ? _w : messageSeen[msgId] = {};
594
- messageSeen[msgId].text = true;
735
+ getOrCreateMessageSeen(messageSeen, msgId).text = true;
595
736
  }
596
737
  controller.enqueue({
597
738
  type: "text-delta",
@@ -599,6 +740,15 @@ function processLangGraphEvent(event, state, controller) {
599
740
  id: msgId
600
741
  });
601
742
  }
743
+ const citations = extractCitationsFromContentBlocks(msg);
744
+ if (citations.length > 0) {
745
+ emitSourceChunks(
746
+ citations,
747
+ msgId,
748
+ state.emittedSourceIds,
749
+ controller
750
+ );
751
+ }
602
752
  } else if (isToolMessageType(msg)) {
603
753
  const msgObj = msg;
604
754
  const dataSource = msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
@@ -622,35 +772,105 @@ function processLangGraphEvent(event, state, controller) {
622
772
  }
623
773
  return;
624
774
  }
775
+ case "tools": {
776
+ if (data == null || typeof data !== "object" || Array.isArray(data)) {
777
+ return;
778
+ }
779
+ const payload = data;
780
+ const toolCallId = typeof payload.toolCallId === "string" ? payload.toolCallId : void 0;
781
+ const toolName = typeof payload.name === "string" ? payload.name : "unknown";
782
+ if (!toolCallId) return;
783
+ const ensureToolInputLifecycle = () => {
784
+ if (!emittedToolCalls.has(toolCallId)) {
785
+ emittedToolCalls.add(toolCallId);
786
+ controller.enqueue({
787
+ type: "tool-input-start",
788
+ toolCallId,
789
+ toolName,
790
+ dynamic: true
791
+ });
792
+ }
793
+ if (!emittedToolInputs.has(toolCallId)) {
794
+ emittedToolInputs.add(toolCallId);
795
+ controller.enqueue({
796
+ type: "tool-input-available",
797
+ toolCallId,
798
+ toolName,
799
+ input: payload.input,
800
+ dynamic: true
801
+ });
802
+ }
803
+ };
804
+ switch (payload.event) {
805
+ case "on_tool_start": {
806
+ const toolCallKey = `${toolName}:${JSON.stringify(payload.input)}`;
807
+ emittedToolCallsByKey.set(toolCallKey, toolCallId);
808
+ ensureToolInputLifecycle();
809
+ break;
810
+ }
811
+ case "on_tool_event": {
812
+ ensureToolInputLifecycle();
813
+ controller.enqueue({
814
+ type: "tool-output-available",
815
+ toolCallId,
816
+ output: payload.data,
817
+ preliminary: true
818
+ });
819
+ break;
820
+ }
821
+ case "on_tool_end": {
822
+ ensureToolInputLifecycle();
823
+ controller.enqueue({
824
+ type: "tool-output-available",
825
+ toolCallId,
826
+ output: payload.output
827
+ });
828
+ break;
829
+ }
830
+ case "on_tool_error": {
831
+ ensureToolInputLifecycle();
832
+ controller.enqueue({
833
+ type: "tool-output-error",
834
+ toolCallId,
835
+ errorText: formatToolError(payload.error)
836
+ });
837
+ break;
838
+ }
839
+ }
840
+ return;
841
+ }
625
842
  case "values": {
626
- for (const [id, seen] of Object.entries(messageSeen)) {
843
+ for (const [id, seen] of messageSeen) {
627
844
  if (seen.text) controller.enqueue({ type: "text-end", id });
628
845
  if (seen.tool) {
629
- for (const [toolCallId, toolCallSeen] of Object.entries(seen.tool)) {
630
- const concatMsg = messageConcat[id];
631
- const toolCall = (_x = concatMsg == null ? void 0 : concatMsg.tool_calls) == null ? void 0 : _x.find(
846
+ for (const toolCallId of seen.tool) {
847
+ const concatMsg = messageConcat.get(id);
848
+ const toolCall = (_m = concatMsg == null ? void 0 : concatMsg.tool_calls) == null ? void 0 : _m.find(
632
849
  (call) => call.id === toolCallId
633
850
  );
634
- if (toolCallSeen && toolCall) {
851
+ if (toolCall) {
635
852
  emittedToolCalls.add(toolCallId);
636
853
  const toolCallKey = `${toolCall.name}:${JSON.stringify(toolCall.args)}`;
637
854
  emittedToolCallsByKey.set(toolCallKey, toolCallId);
638
- controller.enqueue({
639
- type: "tool-input-available",
640
- toolCallId,
641
- toolName: toolCall.name,
642
- input: toolCall.args,
643
- dynamic: true
644
- });
855
+ if (!emittedToolInputs.has(toolCallId)) {
856
+ emittedToolInputs.add(toolCallId);
857
+ controller.enqueue({
858
+ type: "tool-input-available",
859
+ toolCallId,
860
+ toolName: toolCall.name,
861
+ input: toolCall.args,
862
+ dynamic: true
863
+ });
864
+ }
645
865
  }
646
866
  }
647
867
  }
648
868
  if (seen.reasoning) {
649
869
  controller.enqueue({ type: "reasoning-end", id });
650
870
  }
651
- delete messageSeen[id];
652
- delete messageConcat[id];
653
- delete messageReasoningIds[id];
871
+ messageSeen.delete(id);
872
+ messageConcat.delete(id);
873
+ messageReasoningIds.delete(id);
654
874
  }
655
875
  if (data != null && typeof data === "object" && "messages" in data) {
656
876
  const messages = data.messages;
@@ -672,13 +892,13 @@ function processLangGraphEvent(event, state, controller) {
672
892
  const msgId = getMessageId(msg);
673
893
  if (!msgId) continue;
674
894
  let toolCalls;
675
- if (import_messages.AIMessageChunk.isInstance(msg) || import_messages.AIMessage.isInstance(msg)) {
895
+ if (AIMessageChunk.isInstance(msg) || AIMessage.isInstance(msg)) {
676
896
  toolCalls = msg.tool_calls;
677
897
  } else if (isPlainMessageObject(msg)) {
678
- const obj = msg;
679
- const isSerializedFormat = obj.type === "constructor" && Array.isArray(obj.id) && (obj.id.includes("AIMessageChunk") || obj.id.includes("AIMessage"));
680
- const dataSource = isSerializedFormat ? obj.kwargs : obj;
681
- if (obj.type === "ai" || isSerializedFormat) {
898
+ const messageRecord = msg;
899
+ const isSerializedFormat = messageRecord.type === "constructor" && Array.isArray(messageRecord.id) && (messageRecord.id.includes("AIMessageChunk") || messageRecord.id.includes("AIMessage"));
900
+ const dataSource = isSerializedFormat ? messageRecord.kwargs : messageRecord;
901
+ if (messageRecord.type === "ai" || messageRecord.type === "AIMessageChunk" || isSerializedFormat) {
682
902
  if (Array.isArray(dataSource == null ? void 0 : dataSource.tool_calls)) {
683
903
  toolCalls = dataSource.tool_calls;
684
904
  } else if (
@@ -719,6 +939,7 @@ function processLangGraphEvent(event, state, controller) {
719
939
  toolName: toolCall.name,
720
940
  dynamic: true
721
941
  });
942
+ emittedToolInputs.add(toolCall.id);
722
943
  controller.enqueue({
723
944
  type: "tool-input-available",
724
945
  toolCallId: toolCall.id,
@@ -726,11 +947,14 @@ function processLangGraphEvent(event, state, controller) {
726
947
  input: toolCall.args,
727
948
  dynamic: true
728
949
  });
950
+ } else if (toolCall.id && emittedToolCalls.has(toolCall.id)) {
951
+ const toolCallKey = `${toolCall.name}:${JSON.stringify(toolCall.args)}`;
952
+ emittedToolCallsByKey.set(toolCallKey, toolCall.id);
729
953
  }
730
954
  }
731
955
  }
732
956
  const reasoningId = extractReasoningId(msg);
733
- const wasStreamedThisRequest = !!messageSeen[msgId];
957
+ const wasStreamedThisRequest = messageSeen.has(msgId);
734
958
  const hasToolCalls = toolCalls && toolCalls.length > 0;
735
959
  const shouldEmitReasoning = reasoningId && !emittedReasoningIds.has(reasoningId) && (wasStreamedThisRequest || !hasToolCalls);
736
960
  if (shouldEmitReasoning) {
@@ -746,6 +970,15 @@ function processLangGraphEvent(event, state, controller) {
746
970
  emittedReasoningIds.add(reasoningId);
747
971
  }
748
972
  }
973
+ const valuesCitations = extractCitationsFromContentBlocks(msg);
974
+ if (valuesCitations.length > 0) {
975
+ emitSourceChunks(
976
+ valuesCitations,
977
+ msgId,
978
+ state.emittedSourceIds,
979
+ controller
980
+ );
981
+ }
749
982
  }
750
983
  }
751
984
  }
@@ -771,6 +1004,7 @@ function processLangGraphEvent(event, state, controller) {
771
1004
  toolName,
772
1005
  dynamic: true
773
1006
  });
1007
+ emittedToolInputs.add(toolCallId);
774
1008
  controller.enqueue({
775
1009
  type: "tool-input-available",
776
1010
  toolCallId,
@@ -795,7 +1029,7 @@ function processLangGraphEvent(event, state, controller) {
795
1029
 
796
1030
  // src/adapter.ts
797
1031
  async function toBaseMessages(messages) {
798
- const modelMessages = await (0, import_ai.convertToModelMessages)(messages);
1032
+ const modelMessages = await convertToModelMessages(messages);
799
1033
  return convertModelMessages(modelMessages);
800
1034
  }
801
1035
  function convertModelMessages(modelMessages) {
@@ -815,7 +1049,7 @@ function convertModelMessages(modelMessages) {
815
1049
  break;
816
1050
  }
817
1051
  case "system": {
818
- result.push(new import_messages2.SystemMessage({ content: message.content }));
1052
+ result.push(new SystemMessage({ content: message.content }));
819
1053
  break;
820
1054
  }
821
1055
  case "user": {
@@ -841,6 +1075,22 @@ function processStreamEventsEvent(event, state, controller) {
841
1075
  if (!event.data) return;
842
1076
  switch (event.event) {
843
1077
  case "on_chat_model_start": {
1078
+ if (state.reasoningStarted) {
1079
+ controller.enqueue({
1080
+ type: "reasoning-end",
1081
+ id: state.reasoningMessageId != null ? state.reasoningMessageId : state.messageId
1082
+ });
1083
+ state.reasoningStarted = false;
1084
+ state.reasoningMessageId = null;
1085
+ }
1086
+ if (state.textStarted) {
1087
+ controller.enqueue({
1088
+ type: "text-end",
1089
+ id: state.textMessageId != null ? state.textMessageId : state.messageId
1090
+ });
1091
+ state.textStarted = false;
1092
+ state.textMessageId = null;
1093
+ }
844
1094
  const runId = event.run_id || event.data.run_id;
845
1095
  if (runId) {
846
1096
  state.messageId = runId;
@@ -895,6 +1145,15 @@ function processStreamEventsEvent(event, state, controller) {
895
1145
  id: (_c = state.textMessageId) != null ? _c : state.messageId
896
1146
  });
897
1147
  }
1148
+ const citations = extractCitationsFromContentBlocks(chunk);
1149
+ if (citations.length > 0) {
1150
+ emitSourceChunks(
1151
+ citations,
1152
+ state.messageId,
1153
+ state.emittedSourceIds,
1154
+ controller
1155
+ );
1156
+ }
898
1157
  }
899
1158
  break;
900
1159
  }
@@ -942,18 +1201,21 @@ function toUIMessageStream(stream, callbacks) {
942
1201
  /** Track the ID used for text-start to ensure text-end uses the same ID */
943
1202
  textMessageId: null,
944
1203
  /** Track the ID used for reasoning-start to ensure reasoning-end uses the same ID */
945
- reasoningMessageId: null
1204
+ reasoningMessageId: null,
1205
+ emittedSourceIds: /* @__PURE__ */ new Set()
946
1206
  };
947
1207
  const langGraphState = {
948
- messageSeen: {},
949
- messageConcat: {},
1208
+ messageSeen: /* @__PURE__ */ new Map(),
1209
+ messageConcat: /* @__PURE__ */ new Map(),
950
1210
  emittedToolCalls: /* @__PURE__ */ new Set(),
1211
+ emittedToolInputs: /* @__PURE__ */ new Set(),
951
1212
  emittedImages: /* @__PURE__ */ new Set(),
952
1213
  emittedReasoningIds: /* @__PURE__ */ new Set(),
953
- messageReasoningIds: {},
954
- toolCallInfoByIndex: {},
1214
+ messageReasoningIds: /* @__PURE__ */ new Map(),
1215
+ toolCallInfoByIndex: /* @__PURE__ */ new Map(),
955
1216
  currentStep: null,
956
- emittedToolCallsByKey: /* @__PURE__ */ new Map()
1217
+ emittedToolCallsByKey: /* @__PURE__ */ new Map(),
1218
+ emittedSourceIds: /* @__PURE__ */ new Set()
957
1219
  };
958
1220
  let streamType = null;
959
1221
  const getAsyncIterator = () => {
@@ -1046,6 +1308,14 @@ function toUIMessageStream(stream, callbacks) {
1046
1308
  }
1047
1309
  controller.enqueue({ type: "finish" });
1048
1310
  } else if (streamType === "langgraph") {
1311
+ for (const [id, seen] of langGraphState.messageSeen) {
1312
+ if (seen.text) {
1313
+ controller.enqueue({ type: "text-end", id });
1314
+ }
1315
+ if (seen.reasoning) {
1316
+ controller.enqueue({ type: "reasoning-end", id });
1317
+ }
1318
+ }
1049
1319
  if (langGraphState.currentStep !== null) {
1050
1320
  controller.enqueue({ type: "finish-step" });
1051
1321
  }
@@ -1073,11 +1343,13 @@ function toUIMessageStream(stream, callbacks) {
1073
1343
  }
1074
1344
 
1075
1345
  // src/transport.ts
1076
- var import_remote = require("@langchain/langgraph/remote");
1346
+ import {
1347
+ RemoteGraph
1348
+ } from "@langchain/langgraph/remote";
1077
1349
  var LangSmithDeploymentTransport = class {
1078
1350
  constructor(options) {
1079
1351
  var _a;
1080
- this.graph = new import_remote.RemoteGraph({
1352
+ this.graph = new RemoteGraph({
1081
1353
  ...options,
1082
1354
  graphId: (_a = options.graphId) != null ? _a : "agent"
1083
1355
  });
@@ -1096,11 +1368,10 @@ var LangSmithDeploymentTransport = class {
1096
1368
  throw new Error("Method not implemented.");
1097
1369
  }
1098
1370
  };
1099
- // Annotate the CommonJS export names for ESM import in node:
1100
- 0 && (module.exports = {
1371
+ export {
1101
1372
  LangSmithDeploymentTransport,
1102
1373
  convertModelMessages,
1103
1374
  toBaseMessages,
1104
1375
  toUIMessageStream
1105
- });
1376
+ };
1106
1377
  //# sourceMappingURL=index.js.map