@ai-sdk/langchain 2.0.0-beta.99 → 2.0.0

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,778 @@ 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);
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("");
46
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 convertUserContent(content) {
82
+ if (typeof content === "string") {
83
+ return new import_messages.HumanMessage({ content });
84
+ }
85
+ const textParts = content.filter(
86
+ (part) => part.type === "text"
87
+ ).map((part) => part.text);
88
+ return new import_messages.HumanMessage({ content: textParts.join("") });
89
+ }
90
+ function isToolResultPart(item) {
91
+ return item != null && typeof item === "object" && "type" in item && item.type === "tool-result";
92
+ }
93
+ function processModelChunk(chunk, state, controller) {
94
+ if (chunk.id) {
95
+ state.messageId = chunk.id;
96
+ }
97
+ const reasoning = extractReasoningFromContentBlocks(chunk) || extractReasoningFromValuesMessage(chunk);
98
+ if (reasoning) {
99
+ if (!state.reasoningStarted) {
100
+ controller.enqueue({ type: "reasoning-start", id: state.messageId });
101
+ state.reasoningStarted = true;
102
+ state.started = true;
103
+ }
104
+ controller.enqueue({
105
+ type: "reasoning-delta",
106
+ delta: reasoning,
107
+ id: state.messageId
108
+ });
109
+ }
110
+ const text = typeof chunk.content === "string" ? chunk.content : Array.isArray(chunk.content) ? chunk.content.filter(
111
+ (c) => typeof c === "object" && c !== null && "type" in c && c.type === "text"
112
+ ).map((c) => c.text).join("") : "";
113
+ if (text) {
114
+ if (state.reasoningStarted && !state.textStarted) {
115
+ controller.enqueue({ type: "reasoning-end", id: state.messageId });
116
+ state.reasoningStarted = false;
117
+ }
118
+ if (!state.textStarted) {
119
+ controller.enqueue({ type: "text-start", id: state.messageId });
120
+ state.textStarted = true;
121
+ state.started = true;
122
+ }
123
+ controller.enqueue({
124
+ type: "text-delta",
125
+ delta: text,
126
+ id: state.messageId
127
+ });
128
+ }
129
+ }
130
+ function isPlainMessageObject(msg) {
131
+ if (msg == null || typeof msg !== "object") return false;
132
+ return typeof msg._getType !== "function";
133
+ }
134
+ function getMessageId(msg) {
135
+ if (msg == null || typeof msg !== "object") return void 0;
136
+ const msgObj = msg;
137
+ if (typeof msgObj.id === "string") {
138
+ return msgObj.id;
139
+ }
140
+ if (msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object") {
141
+ const kwargs = msgObj.kwargs;
142
+ if (typeof kwargs.id === "string") {
143
+ return kwargs.id;
144
+ }
145
+ }
146
+ return void 0;
147
+ }
148
+ function isAIMessageChunk(msg) {
149
+ if (import_messages.AIMessageChunk.isInstance(msg)) return true;
150
+ if (isPlainMessageObject(msg)) {
151
+ const obj = msg;
152
+ if ("type" in obj && obj.type === "ai") return true;
153
+ if (obj.type === "constructor" && Array.isArray(obj.id) && (obj.id.includes("AIMessageChunk") || obj.id.includes("AIMessage"))) {
154
+ return true;
155
+ }
156
+ }
157
+ return false;
158
+ }
159
+ function isToolMessageType(msg) {
160
+ if (import_messages.ToolMessage.isInstance(msg)) return true;
161
+ if (isPlainMessageObject(msg)) {
162
+ const obj = msg;
163
+ if ("type" in obj && obj.type === "tool") return true;
164
+ if (obj.type === "constructor" && Array.isArray(obj.id) && obj.id.includes("ToolMessage")) {
165
+ return true;
166
+ }
167
+ }
168
+ return false;
169
+ }
170
+ function getMessageText(msg) {
171
+ var _a;
172
+ if (import_messages.AIMessageChunk.isInstance(msg)) {
173
+ return (_a = msg.text) != null ? _a : "";
174
+ }
175
+ if (msg == null || typeof msg !== "object") return "";
176
+ const msgObj = msg;
177
+ const dataSource = msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
178
+ if ("content" in dataSource) {
179
+ const content = dataSource.content;
180
+ if (typeof content === "string") {
181
+ return content;
182
+ }
183
+ if (Array.isArray(content)) {
184
+ return content.filter(
185
+ (block) => block != null && typeof block === "object" && block.type === "text" && typeof block.text === "string"
186
+ ).map((block) => block.text).join("");
187
+ }
188
+ return "";
189
+ }
190
+ return "";
191
+ }
192
+ function isReasoningContentBlock(obj) {
193
+ return obj != null && typeof obj === "object" && "type" in obj && obj.type === "reasoning" && "reasoning" in obj && typeof obj.reasoning === "string";
194
+ }
195
+ function isThinkingContentBlock(obj) {
196
+ return obj != null && typeof obj === "object" && "type" in obj && obj.type === "thinking" && "thinking" in obj && typeof obj.thinking === "string";
197
+ }
198
+ function isGPT5ReasoningOutput(obj) {
199
+ return obj != null && typeof obj === "object" && "type" in obj && obj.type === "reasoning" && "summary" in obj && Array.isArray(obj.summary);
200
+ }
201
+ function extractReasoningId(msg) {
202
+ var _a;
203
+ if (msg == null || typeof msg !== "object") return void 0;
204
+ const msgObj = msg;
205
+ const kwargs = msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
206
+ const additionalKwargs = kwargs.additional_kwargs;
207
+ if ((_a = additionalKwargs == null ? void 0 : additionalKwargs.reasoning) == null ? void 0 : _a.id) {
208
+ return additionalKwargs.reasoning.id;
209
+ }
210
+ const responseMetadata = kwargs.response_metadata;
211
+ if (responseMetadata && Array.isArray(responseMetadata.output)) {
212
+ for (const item of responseMetadata.output) {
213
+ if (isGPT5ReasoningOutput(item)) {
214
+ return item.id;
215
+ }
216
+ }
217
+ }
218
+ return void 0;
219
+ }
220
+ function extractReasoningFromContentBlocks(msg) {
221
+ if (msg == null || typeof msg !== "object") return void 0;
222
+ const msgObj = msg;
223
+ const kwargs = msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
224
+ const contentBlocks = kwargs.contentBlocks;
225
+ if (Array.isArray(contentBlocks)) {
226
+ const reasoningParts = [];
227
+ for (const block of contentBlocks) {
228
+ if (isReasoningContentBlock(block)) {
229
+ reasoningParts.push(block.reasoning);
230
+ } else if (isThinkingContentBlock(block)) {
231
+ reasoningParts.push(block.thinking);
232
+ }
233
+ }
234
+ if (reasoningParts.length > 0) {
235
+ return reasoningParts.join("");
236
+ }
237
+ }
238
+ const additionalKwargs = kwargs.additional_kwargs;
239
+ if ((additionalKwargs == null ? void 0 : additionalKwargs.reasoning) && Array.isArray(additionalKwargs.reasoning.summary)) {
240
+ const reasoningParts = [];
241
+ for (const summaryItem of additionalKwargs.reasoning.summary) {
242
+ if (typeof summaryItem === "object" && summaryItem !== null && "text" in summaryItem && typeof summaryItem.text === "string") {
243
+ reasoningParts.push(summaryItem.text);
244
+ }
245
+ }
246
+ if (reasoningParts.length > 0) {
247
+ return reasoningParts.join("");
248
+ }
249
+ }
250
+ return void 0;
251
+ }
252
+ function extractReasoningFromValuesMessage(msg) {
253
+ if (msg == null || typeof msg !== "object") return void 0;
254
+ const msgObj = msg;
255
+ const kwargs = msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
256
+ const responseMetadata = kwargs.response_metadata;
257
+ if (responseMetadata && Array.isArray(responseMetadata.output)) {
258
+ const reasoningParts = [];
259
+ for (const item of responseMetadata.output) {
260
+ if (isGPT5ReasoningOutput(item)) {
261
+ for (const summaryItem of item.summary) {
262
+ if (typeof summaryItem === "object" && summaryItem !== null) {
263
+ const text = summaryItem.text;
264
+ if (typeof text === "string" && text) {
265
+ reasoningParts.push(text);
266
+ }
267
+ }
268
+ }
269
+ }
270
+ }
271
+ if (reasoningParts.length > 0) {
272
+ return reasoningParts.join("");
273
+ }
274
+ }
275
+ const additionalKwargs = kwargs.additional_kwargs;
276
+ if ((additionalKwargs == null ? void 0 : additionalKwargs.reasoning) && Array.isArray(additionalKwargs.reasoning.summary)) {
277
+ const reasoningParts = [];
278
+ for (const summaryItem of additionalKwargs.reasoning.summary) {
279
+ if (typeof summaryItem === "object" && summaryItem !== null && "text" in summaryItem && typeof summaryItem.text === "string") {
280
+ reasoningParts.push(summaryItem.text);
281
+ }
282
+ }
283
+ if (reasoningParts.length > 0) {
284
+ return reasoningParts.join("");
285
+ }
286
+ }
287
+ return void 0;
288
+ }
289
+ function isImageGenerationOutput(obj) {
290
+ return obj != null && typeof obj === "object" && "type" in obj && obj.type === "image_generation_call";
291
+ }
292
+ function extractImageOutputs(additionalKwargs) {
293
+ if (!additionalKwargs) return [];
294
+ const toolOutputs = additionalKwargs.tool_outputs;
295
+ if (!Array.isArray(toolOutputs)) return [];
296
+ return toolOutputs.filter(isImageGenerationOutput);
297
+ }
298
+ function processLangGraphEvent(event, state, controller) {
299
+ 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;
300
+ const {
301
+ messageSeen,
302
+ messageConcat,
303
+ emittedToolCalls,
304
+ emittedImages,
305
+ emittedReasoningIds,
306
+ messageReasoningIds,
307
+ toolCallInfoByIndex,
308
+ emittedToolCallsByKey
309
+ } = state;
310
+ const [type, data] = event.length === 3 ? event.slice(1) : event;
311
+ switch (type) {
312
+ case "custom": {
313
+ let customTypeName = "custom";
314
+ let partId;
315
+ if (data != null && typeof data === "object" && !Array.isArray(data)) {
316
+ const dataObj = data;
317
+ if (typeof dataObj.type === "string" && dataObj.type) {
318
+ customTypeName = dataObj.type;
319
+ }
320
+ if (typeof dataObj.id === "string" && dataObj.id) {
321
+ partId = dataObj.id;
322
+ }
323
+ }
324
+ controller.enqueue({
325
+ type: `data-${customTypeName}`,
326
+ id: partId,
327
+ transient: partId == null,
328
+ data
329
+ });
330
+ break;
331
+ }
332
+ case "messages": {
333
+ const [rawMsg, metadata] = data;
334
+ const msg = rawMsg;
335
+ const msgId = getMessageId(msg);
336
+ if (!msgId) return;
337
+ const langgraphStep = typeof (metadata == null ? void 0 : metadata.langgraph_step) === "number" ? metadata.langgraph_step : null;
338
+ if (langgraphStep !== null && langgraphStep !== state.currentStep) {
339
+ if (state.currentStep !== null) {
340
+ controller.enqueue({ type: "finish-step" });
341
+ }
342
+ controller.enqueue({ type: "start-step" });
343
+ state.currentStep = langgraphStep;
344
+ }
345
+ if (import_messages.AIMessageChunk.isInstance(msg)) {
346
+ if (messageConcat[msgId]) {
347
+ messageConcat[msgId] = messageConcat[msgId].concat(
348
+ msg
349
+ );
350
+ } else {
351
+ messageConcat[msgId] = msg;
352
+ }
353
+ }
354
+ if (isAIMessageChunk(msg)) {
355
+ const concatChunk = messageConcat[msgId];
356
+ const msgObj = msg;
357
+ const dataSource = msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
358
+ const additionalKwargs = dataSource.additional_kwargs;
359
+ const imageOutputs = extractImageOutputs(additionalKwargs);
360
+ for (const imageOutput of imageOutputs) {
361
+ if (imageOutput.result && !emittedImages.has(imageOutput.id)) {
362
+ emittedImages.add(imageOutput.id);
363
+ const mediaType = `image/${imageOutput.output_format || "png"}`;
364
+ controller.enqueue({
365
+ type: "file",
366
+ mediaType,
367
+ url: `data:${mediaType};base64,${imageOutput.result}`
368
+ });
369
+ }
370
+ }
371
+ const toolCallChunks = dataSource.tool_call_chunks;
372
+ if (toolCallChunks == null ? void 0 : toolCallChunks.length) {
373
+ for (const toolCallChunk of toolCallChunks) {
374
+ const idx = (_a = toolCallChunk.index) != null ? _a : 0;
375
+ if (toolCallChunk.id) {
376
+ (_b = toolCallInfoByIndex[msgId]) != null ? _b : toolCallInfoByIndex[msgId] = {};
377
+ toolCallInfoByIndex[msgId][idx] = {
378
+ id: toolCallChunk.id,
379
+ name: toolCallChunk.name || ((_d = (_c = concatChunk == null ? void 0 : concatChunk.tool_call_chunks) == null ? void 0 : _c[idx]) == null ? void 0 : _d.name) || "unknown"
380
+ };
381
+ }
382
+ 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);
383
+ if (!toolCallId) {
384
+ continue;
385
+ }
386
+ 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";
387
+ if (!((_n = (_m = messageSeen[msgId]) == null ? void 0 : _m.tool) == null ? void 0 : _n[toolCallId])) {
388
+ controller.enqueue({
389
+ type: "tool-input-start",
390
+ toolCallId,
391
+ toolName,
392
+ dynamic: true
393
+ });
394
+ (_o = messageSeen[msgId]) != null ? _o : messageSeen[msgId] = {};
395
+ (_q = (_p = messageSeen[msgId]).tool) != null ? _q : _p.tool = {};
396
+ messageSeen[msgId].tool[toolCallId] = true;
397
+ emittedToolCalls.add(toolCallId);
398
+ }
399
+ if (toolCallChunk.args) {
400
+ controller.enqueue({
401
+ type: "tool-input-delta",
402
+ toolCallId,
403
+ inputTextDelta: toolCallChunk.args
404
+ });
405
+ }
406
+ }
58
407
  return;
59
408
  }
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
409
+ const chunkReasoningId = extractReasoningId(msg);
410
+ if (chunkReasoningId) {
411
+ if (!messageReasoningIds[msgId]) {
412
+ messageReasoningIds[msgId] = chunkReasoningId;
413
+ }
414
+ emittedReasoningIds.add(chunkReasoningId);
415
+ }
416
+ const reasoning = extractReasoningFromContentBlocks(msg);
417
+ if (reasoning) {
418
+ const reasoningId = (_s = (_r = messageReasoningIds[msgId]) != null ? _r : chunkReasoningId) != null ? _s : msgId;
419
+ if (!((_t = messageSeen[msgId]) == null ? void 0 : _t.reasoning)) {
420
+ controller.enqueue({ type: "reasoning-start", id: msgId });
421
+ (_u = messageSeen[msgId]) != null ? _u : messageSeen[msgId] = {};
422
+ messageSeen[msgId].reasoning = true;
423
+ }
424
+ controller.enqueue({
425
+ type: "reasoning-delta",
426
+ delta: reasoning,
427
+ id: msgId
428
+ });
429
+ emittedReasoningIds.add(reasoningId);
430
+ }
431
+ const text = getMessageText(msg);
432
+ if (text) {
433
+ if (!((_v = messageSeen[msgId]) == null ? void 0 : _v.text)) {
434
+ controller.enqueue({ type: "text-start", id: msgId });
435
+ (_w = messageSeen[msgId]) != null ? _w : messageSeen[msgId] = {};
436
+ messageSeen[msgId].text = true;
437
+ }
438
+ controller.enqueue({
439
+ type: "text-delta",
440
+ delta: text,
441
+ id: msgId
442
+ });
443
+ }
444
+ } else if (isToolMessageType(msg)) {
445
+ const msgObj = msg;
446
+ const dataSource = msgObj.type === "constructor" && msgObj.kwargs && typeof msgObj.kwargs === "object" ? msgObj.kwargs : msgObj;
447
+ const toolCallId = dataSource.tool_call_id;
448
+ const status = dataSource.status;
449
+ if (toolCallId) {
450
+ if (status === "error") {
451
+ controller.enqueue({
452
+ type: "tool-output-error",
453
+ toolCallId,
454
+ errorText: typeof dataSource.content === "string" ? dataSource.content : "Tool execution failed"
455
+ });
456
+ } else {
457
+ controller.enqueue({
458
+ type: "tool-output-available",
459
+ toolCallId,
460
+ output: dataSource.content
461
+ });
462
+ }
463
+ }
464
+ }
465
+ return;
466
+ }
467
+ case "values": {
468
+ for (const [id, seen] of Object.entries(messageSeen)) {
469
+ if (seen.text) controller.enqueue({ type: "text-end", id });
470
+ if (seen.tool) {
471
+ for (const [toolCallId, toolCallSeen] of Object.entries(seen.tool)) {
472
+ const concatMsg = messageConcat[id];
473
+ const toolCall = (_x = concatMsg == null ? void 0 : concatMsg.tool_calls) == null ? void 0 : _x.find(
474
+ (call) => call.id === toolCallId
65
475
  );
476
+ if (toolCallSeen && toolCall) {
477
+ emittedToolCalls.add(toolCallId);
478
+ const toolCallKey = `${toolCall.name}:${JSON.stringify(toolCall.args)}`;
479
+ emittedToolCallsByKey.set(toolCallKey, toolCallId);
480
+ controller.enqueue({
481
+ type: "tool-input-available",
482
+ toolCallId,
483
+ toolName: toolCall.name,
484
+ input: toolCall.args,
485
+ dynamic: true
486
+ });
487
+ }
66
488
  }
67
- return;
68
489
  }
69
- forwardAIMessageChunk(value, controller);
490
+ if (seen.reasoning) {
491
+ controller.enqueue({ type: "reasoning-end", id });
492
+ }
493
+ delete messageSeen[id];
494
+ delete messageConcat[id];
495
+ delete messageReasoningIds[id];
70
496
  }
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" });
497
+ if (data != null && typeof data === "object" && "messages" in data) {
498
+ const messages = data.messages;
499
+ if (Array.isArray(messages)) {
500
+ for (const msg of messages) {
501
+ if (!msg || typeof msg !== "object") continue;
502
+ const msgId = getMessageId(msg);
503
+ if (!msgId) continue;
504
+ let toolCalls;
505
+ if (import_messages.AIMessageChunk.isInstance(msg) || import_messages.AIMessage.isInstance(msg)) {
506
+ toolCalls = msg.tool_calls;
507
+ } else if (isPlainMessageObject(msg)) {
508
+ const obj = msg;
509
+ const isSerializedFormat = obj.type === "constructor" && Array.isArray(obj.id) && (obj.id.includes("AIMessageChunk") || obj.id.includes("AIMessage"));
510
+ const dataSource = isSerializedFormat ? obj.kwargs : obj;
511
+ if (obj.type === "ai" || isSerializedFormat) {
512
+ if (Array.isArray(dataSource == null ? void 0 : dataSource.tool_calls)) {
513
+ toolCalls = dataSource.tool_calls;
514
+ } else if (
515
+ /**
516
+ * Fall back to additional_kwargs.tool_calls (OpenAI format)
517
+ */
518
+ (dataSource == null ? void 0 : dataSource.additional_kwargs) && typeof dataSource.additional_kwargs === "object"
519
+ ) {
520
+ const additionalKwargs = dataSource.additional_kwargs;
521
+ if (Array.isArray(additionalKwargs.tool_calls)) {
522
+ toolCalls = additionalKwargs.tool_calls.map((tc, idx) => {
523
+ const functionData = tc.function;
524
+ let args;
525
+ try {
526
+ args = (functionData == null ? void 0 : functionData.arguments) ? JSON.parse(functionData.arguments) : {};
527
+ } catch (e) {
528
+ args = {};
529
+ }
530
+ return {
531
+ id: tc.id || `call_${idx}`,
532
+ name: (functionData == null ? void 0 : functionData.name) || "unknown",
533
+ args
534
+ };
535
+ });
536
+ }
537
+ }
538
+ }
539
+ }
540
+ if (toolCalls && toolCalls.length > 0) {
541
+ for (const toolCall of toolCalls) {
542
+ if (toolCall.id && !emittedToolCalls.has(toolCall.id)) {
543
+ emittedToolCalls.add(toolCall.id);
544
+ const toolCallKey = `${toolCall.name}:${JSON.stringify(toolCall.args)}`;
545
+ emittedToolCallsByKey.set(toolCallKey, toolCall.id);
546
+ controller.enqueue({
547
+ type: "tool-input-start",
548
+ toolCallId: toolCall.id,
549
+ toolName: toolCall.name,
550
+ dynamic: true
551
+ });
552
+ controller.enqueue({
553
+ type: "tool-input-available",
554
+ toolCallId: toolCall.id,
555
+ toolName: toolCall.name,
556
+ input: toolCall.args,
557
+ dynamic: true
558
+ });
559
+ }
560
+ }
561
+ }
562
+ const reasoningId = extractReasoningId(msg);
563
+ const wasStreamedThisRequest = !!messageSeen[msgId];
564
+ const hasToolCalls = toolCalls && toolCalls.length > 0;
565
+ const shouldEmitReasoning = reasoningId && !emittedReasoningIds.has(reasoningId) && (wasStreamedThisRequest || !hasToolCalls);
566
+ if (shouldEmitReasoning) {
567
+ const reasoning = extractReasoningFromValuesMessage(msg);
568
+ if (reasoning) {
569
+ controller.enqueue({ type: "reasoning-start", id: msgId });
570
+ controller.enqueue({
571
+ type: "reasoning-delta",
572
+ delta: reasoning,
573
+ id: msgId
574
+ });
575
+ controller.enqueue({ type: "reasoning-end", id: msgId });
576
+ emittedReasoningIds.add(reasoningId);
577
+ }
578
+ }
579
+ }
580
+ }
581
+ }
582
+ if (data != null && typeof data === "object") {
583
+ const interrupt = data.__interrupt__;
584
+ if (Array.isArray(interrupt) && interrupt.length > 0) {
585
+ for (const interruptItem of interrupt) {
586
+ const interruptValue = interruptItem == null ? void 0 : interruptItem.value;
587
+ if (!interruptValue) continue;
588
+ const actionRequests = interruptValue.actionRequests || interruptValue.action_requests;
589
+ if (!Array.isArray(actionRequests)) continue;
590
+ for (const actionRequest of actionRequests) {
591
+ const toolName = actionRequest.name;
592
+ const input = actionRequest.args || actionRequest.arguments;
593
+ const toolCallKey = `${toolName}:${JSON.stringify(input)}`;
594
+ const toolCallId = emittedToolCallsByKey.get(toolCallKey) || actionRequest.id || `hitl-${toolName}-${Date.now()}`;
595
+ if (!emittedToolCalls.has(toolCallId)) {
596
+ emittedToolCalls.add(toolCallId);
597
+ emittedToolCallsByKey.set(toolCallKey, toolCallId);
598
+ controller.enqueue({
599
+ type: "tool-input-start",
600
+ toolCallId,
601
+ toolName,
602
+ dynamic: true
603
+ });
604
+ controller.enqueue({
605
+ type: "tool-input-available",
606
+ toolCallId,
607
+ toolName,
608
+ input,
609
+ dynamic: true
610
+ });
611
+ }
612
+ controller.enqueue({
613
+ type: "tool-approval-request",
614
+ approvalId: toolCallId,
615
+ toolCallId
616
+ });
617
+ }
618
+ }
619
+ }
82
620
  }
83
- })
84
- );
621
+ break;
622
+ }
623
+ }
624
+ }
625
+
626
+ // src/adapter.ts
627
+ async function toBaseMessages(messages) {
628
+ const modelMessages = await (0, import_ai.convertToModelMessages)(messages);
629
+ return convertModelMessages(modelMessages);
85
630
  }
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);
631
+ function convertModelMessages(modelMessages) {
632
+ const result = [];
633
+ for (const message of modelMessages) {
634
+ switch (message.role) {
635
+ case "tool": {
636
+ for (const item of message.content) {
637
+ if (isToolResultPart(item)) {
638
+ result.push(convertToolResultPart(item));
639
+ }
640
+ }
641
+ break;
642
+ }
643
+ case "assistant": {
644
+ result.push(convertAssistantContent(message.content));
645
+ break;
646
+ }
647
+ case "system": {
648
+ result.push(new import_messages2.SystemMessage({ content: message.content }));
649
+ break;
650
+ }
651
+ case "user": {
652
+ result.push(convertUserContent(message.content));
653
+ break;
94
654
  }
95
655
  }
96
656
  }
657
+ return result;
658
+ }
659
+ function toUIMessageStream(stream, callbacks) {
660
+ const textChunks = [];
661
+ const modelState = {
662
+ started: false,
663
+ messageId: "langchain-msg-1",
664
+ reasoningStarted: false,
665
+ textStarted: false
666
+ };
667
+ const langGraphState = {
668
+ messageSeen: {},
669
+ messageConcat: {},
670
+ emittedToolCalls: /* @__PURE__ */ new Set(),
671
+ emittedImages: /* @__PURE__ */ new Set(),
672
+ emittedReasoningIds: /* @__PURE__ */ new Set(),
673
+ messageReasoningIds: {},
674
+ toolCallInfoByIndex: {},
675
+ currentStep: null,
676
+ emittedToolCallsByKey: /* @__PURE__ */ new Map()
677
+ };
678
+ let streamType = null;
679
+ const getAsyncIterator = () => {
680
+ if (Symbol.asyncIterator in stream) {
681
+ return stream[Symbol.asyncIterator]();
682
+ }
683
+ const reader = stream.getReader();
684
+ return {
685
+ async next() {
686
+ const { done, value } = await reader.read();
687
+ return { done, value };
688
+ }
689
+ };
690
+ };
691
+ const iterator = getAsyncIterator();
692
+ const createCallbackController = (originalController) => {
693
+ return {
694
+ get desiredSize() {
695
+ return originalController.desiredSize;
696
+ },
697
+ close: () => originalController.close(),
698
+ error: (e) => originalController.error(e),
699
+ enqueue: (chunk) => {
700
+ var _a, _b;
701
+ if (callbacks && chunk.type === "text-delta" && chunk.delta) {
702
+ textChunks.push(chunk.delta);
703
+ (_a = callbacks.onToken) == null ? void 0 : _a.call(callbacks, chunk.delta);
704
+ (_b = callbacks.onText) == null ? void 0 : _b.call(callbacks, chunk.delta);
705
+ }
706
+ originalController.enqueue(chunk);
707
+ }
708
+ };
709
+ };
710
+ return new ReadableStream({
711
+ async start(controller) {
712
+ var _a, _b;
713
+ await ((_a = callbacks == null ? void 0 : callbacks.onStart) == null ? void 0 : _a.call(callbacks));
714
+ const wrappedController = createCallbackController(controller);
715
+ controller.enqueue({ type: "start" });
716
+ try {
717
+ while (true) {
718
+ const { done, value } = await iterator.next();
719
+ if (done) break;
720
+ if (streamType === null) {
721
+ if (Array.isArray(value)) {
722
+ streamType = "langgraph";
723
+ } else {
724
+ streamType = "model";
725
+ }
726
+ }
727
+ if (streamType === "model") {
728
+ processModelChunk(
729
+ value,
730
+ modelState,
731
+ wrappedController
732
+ );
733
+ } else {
734
+ processLangGraphEvent(
735
+ value,
736
+ langGraphState,
737
+ wrappedController
738
+ );
739
+ }
740
+ }
741
+ if (streamType === "model") {
742
+ if (modelState.reasoningStarted) {
743
+ controller.enqueue({
744
+ type: "reasoning-end",
745
+ id: modelState.messageId
746
+ });
747
+ }
748
+ if (modelState.textStarted) {
749
+ controller.enqueue({ type: "text-end", id: modelState.messageId });
750
+ }
751
+ controller.enqueue({ type: "finish" });
752
+ }
753
+ await ((_b = callbacks == null ? void 0 : callbacks.onFinal) == null ? void 0 : _b.call(callbacks, textChunks.join("")));
754
+ } catch (error) {
755
+ controller.enqueue({
756
+ type: "error",
757
+ errorText: error instanceof Error ? error.message : "Unknown error"
758
+ });
759
+ } finally {
760
+ controller.close();
761
+ }
762
+ }
763
+ });
97
764
  }
765
+
766
+ // src/transport.ts
767
+ var import_remote = require("@langchain/langgraph/remote");
768
+ var LangSmithDeploymentTransport = class {
769
+ constructor(options) {
770
+ var _a;
771
+ this.graph = new import_remote.RemoteGraph({
772
+ ...options,
773
+ graphId: (_a = options.graphId) != null ? _a : "agent"
774
+ });
775
+ }
776
+ async sendMessages(options) {
777
+ const baseMessages = await toBaseMessages(options.messages);
778
+ const stream = await this.graph.stream(
779
+ { messages: baseMessages },
780
+ { streamMode: ["values", "messages"] }
781
+ );
782
+ return toUIMessageStream(
783
+ stream
784
+ );
785
+ }
786
+ async reconnectToStream(_options) {
787
+ throw new Error("Method not implemented.");
788
+ }
789
+ };
98
790
  // Annotate the CommonJS export names for ESM import in node:
99
791
  0 && (module.exports = {
792
+ LangSmithDeploymentTransport,
793
+ convertModelMessages,
794
+ toBaseMessages,
100
795
  toUIMessageStream
101
796
  });
102
797
  //# sourceMappingURL=index.js.map