@ai-sdk/langchain 3.0.0-beta.9 → 3.0.0-beta.91

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