@assistant-ui/react 0.5.35 → 0.5.37

Sign up to get free protection for your applications and to get access to all the features.
@@ -165,6 +165,74 @@ var toLanguageModelTools = (tools) => {
165
165
  }));
166
166
  };
167
167
 
168
+ // src/runtimes/edge/streams/assistantEncoderStream.ts
169
+ function assistantEncoderStream() {
170
+ const toolCalls = /* @__PURE__ */ new Set();
171
+ return new TransformStream({
172
+ transform(chunk, controller) {
173
+ const chunkType = chunk.type;
174
+ switch (chunkType) {
175
+ case "text-delta": {
176
+ controller.enqueue({
177
+ type: "0" /* TextDelta */,
178
+ value: chunk.textDelta
179
+ });
180
+ break;
181
+ }
182
+ case "tool-call-delta": {
183
+ if (!toolCalls.has(chunk.toolCallId)) {
184
+ toolCalls.add(chunk.toolCallId);
185
+ controller.enqueue({
186
+ type: "1" /* ToolCallBegin */,
187
+ value: {
188
+ id: chunk.toolCallId,
189
+ name: chunk.toolName
190
+ }
191
+ });
192
+ }
193
+ controller.enqueue({
194
+ type: "2" /* ToolCallArgsTextDelta */,
195
+ value: chunk.argsTextDelta
196
+ });
197
+ break;
198
+ }
199
+ // ignore
200
+ case "tool-call":
201
+ break;
202
+ case "tool-result": {
203
+ controller.enqueue({
204
+ type: "3" /* ToolCallResult */,
205
+ value: {
206
+ id: chunk.toolCallId,
207
+ result: chunk.result
208
+ }
209
+ });
210
+ break;
211
+ }
212
+ case "finish": {
213
+ const { type, ...rest } = chunk;
214
+ controller.enqueue({
215
+ type: "F" /* Finish */,
216
+ value: rest
217
+ });
218
+ break;
219
+ }
220
+ case "error": {
221
+ controller.enqueue({
222
+ type: "E" /* Error */,
223
+ value: chunk.error
224
+ });
225
+ break;
226
+ }
227
+ default: {
228
+ const unhandledType = chunkType;
229
+ throw new Error(`Unhandled chunk type: ${unhandledType}`);
230
+ }
231
+ }
232
+ }
233
+ });
234
+ }
235
+
168
236
  // src/types/ModelConfigTypes.ts
169
237
 
170
238
  var LanguageModelV1CallSettingsSchema = _zod.z.object({
@@ -220,39 +288,145 @@ ${config.system}`;
220
288
  }, {});
221
289
  };
222
290
 
223
- // src/runtimes/edge/streams/utils/PipeableTransformStream.ts
224
- var PipeableTransformStream = class extends TransformStream {
225
- constructor(transform) {
226
- super();
227
- const readable = transform(super.readable);
228
- Object.defineProperty(this, "readable", {
229
- value: readable,
230
- writable: false
231
- });
232
- }
233
- };
291
+ // src/runtimes/edge/EdgeRuntimeRequestOptions.ts
234
292
 
235
- // src/runtimes/edge/streams/utils/streamPartEncoderStream.ts
236
- function encodeStreamPart({
237
- type,
238
- value
239
- }) {
240
- return `${type}:${JSON.stringify(value)}
241
- `;
242
- }
243
- function streamPartEncoderStream() {
244
- const encodeStream = new TransformStream({
293
+ var LanguageModelV1FunctionToolSchema = _zod.z.object({
294
+ type: _zod.z.literal("function"),
295
+ name: _zod.z.string(),
296
+ description: _zod.z.string().optional(),
297
+ parameters: _zod.z.custom(
298
+ (val) => typeof val === "object" && val !== null
299
+ )
300
+ });
301
+ var TextContentPartSchema = _zod.z.object({
302
+ type: _zod.z.literal("text"),
303
+ text: _zod.z.string()
304
+ });
305
+ var ImageContentPartSchema = _zod.z.object({
306
+ type: _zod.z.literal("image"),
307
+ image: _zod.z.string()
308
+ });
309
+ var CoreToolCallContentPartSchema = _zod.z.object({
310
+ type: _zod.z.literal("tool-call"),
311
+ toolCallId: _zod.z.string(),
312
+ toolName: _zod.z.string(),
313
+ args: _zod.z.record(_zod.z.unknown()),
314
+ result: _zod.z.unknown().optional(),
315
+ isError: _zod.z.boolean().optional()
316
+ });
317
+ var CoreUserMessageSchema = _zod.z.object({
318
+ role: _zod.z.literal("user"),
319
+ content: _zod.z.array(
320
+ _zod.z.discriminatedUnion("type", [
321
+ TextContentPartSchema,
322
+ ImageContentPartSchema
323
+ ])
324
+ ).min(1)
325
+ });
326
+ var CoreAssistantMessageSchema = _zod.z.object({
327
+ role: _zod.z.literal("assistant"),
328
+ content: _zod.z.array(
329
+ _zod.z.discriminatedUnion("type", [
330
+ TextContentPartSchema,
331
+ CoreToolCallContentPartSchema
332
+ ])
333
+ ).min(1)
334
+ });
335
+ var CoreSystemMessageSchema = _zod.z.object({
336
+ role: _zod.z.literal("system"),
337
+ content: _zod.z.tuple([TextContentPartSchema])
338
+ });
339
+ var CoreMessageSchema = _zod.z.discriminatedUnion("role", [
340
+ CoreSystemMessageSchema,
341
+ CoreUserMessageSchema,
342
+ CoreAssistantMessageSchema
343
+ ]);
344
+ var EdgeRuntimeRequestOptionsSchema = _zod.z.object({
345
+ system: _zod.z.string().optional(),
346
+ messages: _zod.z.array(CoreMessageSchema).min(1),
347
+ tools: _zod.z.array(LanguageModelV1FunctionToolSchema).optional()
348
+ }).merge(LanguageModelV1CallSettingsSchema).merge(LanguageModelConfigSchema);
349
+
350
+ // src/runtimes/edge/streams/toolResultStream.ts
351
+
352
+ var _securejsonparse = require('secure-json-parse'); var _securejsonparse2 = _interopRequireDefault(_securejsonparse);
353
+ function toolResultStream(tools, abortSignal) {
354
+ const toolCallExecutions = /* @__PURE__ */ new Map();
355
+ return new TransformStream({
245
356
  transform(chunk, controller) {
246
- controller.enqueue(encodeStreamPart(chunk));
357
+ controller.enqueue(chunk);
358
+ const chunkType = chunk.type;
359
+ switch (chunkType) {
360
+ case "tool-call": {
361
+ const { toolCallId, toolCallType, toolName, args: argsText } = chunk;
362
+ const tool = _optionalChain([tools, 'optionalAccess', _3 => _3[toolName]]);
363
+ if (!tool || !tool.execute) return;
364
+ const args = _securejsonparse2.default.parse(argsText);
365
+ if (tool.parameters instanceof _zod.z.ZodType) {
366
+ const result = tool.parameters.safeParse(args);
367
+ if (!result.success) {
368
+ controller.enqueue({
369
+ type: "tool-result",
370
+ toolCallType,
371
+ toolCallId,
372
+ toolName,
373
+ result: "Function parameter validation failed. " + JSON.stringify(result.error.issues),
374
+ isError: true
375
+ });
376
+ return;
377
+ } else {
378
+ toolCallExecutions.set(
379
+ toolCallId,
380
+ (async () => {
381
+ if (!tool.execute) return;
382
+ try {
383
+ const result2 = await tool.execute(args, { abortSignal });
384
+ controller.enqueue({
385
+ type: "tool-result",
386
+ toolCallType,
387
+ toolCallId,
388
+ toolName,
389
+ result: result2
390
+ });
391
+ } catch (error) {
392
+ controller.enqueue({
393
+ type: "tool-result",
394
+ toolCallType,
395
+ toolCallId,
396
+ toolName,
397
+ result: "Error: " + error,
398
+ isError: true
399
+ });
400
+ } finally {
401
+ toolCallExecutions.delete(toolCallId);
402
+ }
403
+ })()
404
+ );
405
+ }
406
+ }
407
+ break;
408
+ }
409
+ // ignore other parts
410
+ case "text-delta":
411
+ case "tool-call-delta":
412
+ case "tool-result":
413
+ case "finish":
414
+ case "error":
415
+ break;
416
+ default: {
417
+ const unhandledType = chunkType;
418
+ throw new Error(`Unhandled chunk type: ${unhandledType}`);
419
+ }
420
+ }
421
+ },
422
+ async flush() {
423
+ await Promise.all(toolCallExecutions.values());
247
424
  }
248
425
  });
249
- return new PipeableTransformStream((readable) => {
250
- return readable.pipeThrough(encodeStream).pipeThrough(new TextEncoderStream());
251
- });
252
426
  }
253
427
 
254
428
  // src/runtimes/edge/partial-json/parse-partial-json.ts
255
- var _securejsonparse = require('secure-json-parse'); var _securejsonparse2 = _interopRequireDefault(_securejsonparse);
429
+
256
430
 
257
431
  // src/runtimes/edge/partial-json/fix-json.ts
258
432
  function fixJson(input) {
@@ -576,10 +750,10 @@ function fixJson(input) {
576
750
  var parsePartialJson = (json) => {
577
751
  try {
578
752
  return _securejsonparse2.default.parse(json);
579
- } catch (e) {
753
+ } catch (e2) {
580
754
  try {
581
755
  return _securejsonparse2.default.parse(fixJson(json));
582
- } catch (e2) {
756
+ } catch (e3) {
583
757
  return void 0;
584
758
  }
585
759
  }
@@ -655,8 +829,8 @@ function runResultStream() {
655
829
  }
656
830
  var appendOrUpdateText = (message, textDelta) => {
657
831
  let contentParts = _nullishCoalesce(message.content, () => ( []));
658
- let contentPart = _optionalChain([message, 'access', _3 => _3.content, 'optionalAccess', _4 => _4.at, 'call', _5 => _5(-1)]);
659
- if (_optionalChain([contentPart, 'optionalAccess', _6 => _6.type]) !== "text") {
832
+ let contentPart = _optionalChain([message, 'access', _4 => _4.content, 'optionalAccess', _5 => _5.at, 'call', _6 => _6(-1)]);
833
+ if (_optionalChain([contentPart, 'optionalAccess', _7 => _7.type]) !== "text") {
660
834
  contentPart = { type: "text", text: textDelta };
661
835
  } else {
662
836
  contentParts = contentParts.slice(0, -1);
@@ -669,8 +843,8 @@ var appendOrUpdateText = (message, textDelta) => {
669
843
  };
670
844
  var appendOrUpdateToolCall = (message, toolCallId, toolName, argsText) => {
671
845
  let contentParts = _nullishCoalesce(message.content, () => ( []));
672
- let contentPart = _optionalChain([message, 'access', _7 => _7.content, 'optionalAccess', _8 => _8.at, 'call', _9 => _9(-1)]);
673
- if (_optionalChain([contentPart, 'optionalAccess', _10 => _10.type]) !== "tool-call" || contentPart.toolCallId !== toolCallId) {
846
+ let contentPart = _optionalChain([message, 'access', _8 => _8.content, 'optionalAccess', _9 => _9.at, 'call', _10 => _10(-1)]);
847
+ if (_optionalChain([contentPart, 'optionalAccess', _11 => _11.type]) !== "tool-call" || contentPart.toolCallId !== toolCallId) {
674
848
  contentPart = {
675
849
  type: "tool-call",
676
850
  toolCallId,
@@ -693,7 +867,7 @@ var appendOrUpdateToolCall = (message, toolCallId, toolName, argsText) => {
693
867
  };
694
868
  var appendOrUpdateToolResult = (message, toolCallId, toolName, result) => {
695
869
  let found = false;
696
- const newContentParts = _optionalChain([message, 'access', _11 => _11.content, 'optionalAccess', _12 => _12.map, 'call', _13 => _13((part) => {
870
+ const newContentParts = _optionalChain([message, 'access', _12 => _12.content, 'optionalAccess', _13 => _13.map, 'call', _14 => _14((part) => {
697
871
  if (part.type !== "tool-call" || part.toolCallId !== toolCallId)
698
872
  return part;
699
873
  found = true;
@@ -723,7 +897,7 @@ var appendOrUpdateFinish = (message, chunk) => {
723
897
  metadata: {
724
898
  ...message.metadata,
725
899
  roundtrips: [
726
- ..._nullishCoalesce(_optionalChain([message, 'access', _14 => _14.metadata, 'optionalAccess', _15 => _15.roundtrips]), () => ( [])),
900
+ ..._nullishCoalesce(_optionalChain([message, 'access', _15 => _15.metadata, 'optionalAccess', _16 => _16.roundtrips]), () => ( [])),
727
901
  {
728
902
  logprobs: rest.logprobs,
729
903
  usage: rest.usage
@@ -760,83 +934,181 @@ var appendOrUpdateCancel = (message) => {
760
934
  };
761
935
  };
762
936
 
763
- // src/runtimes/edge/streams/toolResultStream.ts
764
-
937
+ // src/runtimes/edge/streams/utils/PipeableTransformStream.ts
938
+ var PipeableTransformStream = class extends TransformStream {
939
+ constructor(transform) {
940
+ super();
941
+ const readable = transform(super.readable);
942
+ Object.defineProperty(this, "readable", {
943
+ value: readable,
944
+ writable: false
945
+ });
946
+ }
947
+ };
765
948
 
766
- function toolResultStream(tools, abortSignal) {
767
- const toolCallExecutions = /* @__PURE__ */ new Map();
768
- return new TransformStream({
949
+ // src/runtimes/edge/streams/utils/streamPartEncoderStream.ts
950
+ function encodeStreamPart({
951
+ type,
952
+ value
953
+ }) {
954
+ return `${type}:${JSON.stringify(value)}
955
+ `;
956
+ }
957
+ function streamPartEncoderStream() {
958
+ const encodeStream = new TransformStream({
769
959
  transform(chunk, controller) {
770
- controller.enqueue(chunk);
771
- const chunkType = chunk.type;
772
- switch (chunkType) {
773
- case "tool-call": {
774
- const { toolCallId, toolCallType, toolName, args: argsText } = chunk;
775
- const tool = _optionalChain([tools, 'optionalAccess', _16 => _16[toolName]]);
776
- if (!tool || !tool.execute) return;
777
- const args = _securejsonparse2.default.parse(argsText);
778
- if (tool.parameters instanceof _zod.z.ZodType) {
779
- const result = tool.parameters.safeParse(args);
780
- if (!result.success) {
781
- controller.enqueue({
782
- type: "tool-result",
783
- toolCallType,
784
- toolCallId,
785
- toolName,
786
- result: "Function parameter validation failed. " + JSON.stringify(result.error.issues),
787
- isError: true
788
- });
960
+ controller.enqueue(encodeStreamPart(chunk));
961
+ }
962
+ });
963
+ return new PipeableTransformStream((readable) => {
964
+ return readable.pipeThrough(encodeStream).pipeThrough(new TextEncoderStream());
965
+ });
966
+ }
967
+
968
+ // src/runtimes/edge/createEdgeRuntimeAPI.ts
969
+ var voidStream = () => {
970
+ return new WritableStream({
971
+ abort(reason) {
972
+ console.error("Server stream processing aborted:", reason);
973
+ }
974
+ });
975
+ };
976
+ var getEdgeRuntimeStream = async ({
977
+ abortSignal,
978
+ requestData: unsafeRequest,
979
+ options: {
980
+ model: modelOrCreator,
981
+ system: serverSystem,
982
+ tools: serverTools = {},
983
+ toolChoice,
984
+ onFinish,
985
+ ...unsafeSettings
986
+ }
987
+ }) => {
988
+ const settings = LanguageModelV1CallSettingsSchema.parse(unsafeSettings);
989
+ const lmServerTools = toLanguageModelTools(serverTools);
990
+ const hasServerTools = Object.values(serverTools).some((v) => !!v.execute);
991
+ const {
992
+ system: clientSystem,
993
+ tools: clientTools = [],
994
+ messages,
995
+ apiKey,
996
+ baseUrl,
997
+ modelName,
998
+ ...callSettings
999
+ } = EdgeRuntimeRequestOptionsSchema.parse(unsafeRequest);
1000
+ const systemMessages = [];
1001
+ if (serverSystem) systemMessages.push(serverSystem);
1002
+ if (clientSystem) systemMessages.push(clientSystem);
1003
+ const system = systemMessages.join("\n\n");
1004
+ for (const clientTool of clientTools) {
1005
+ if (_optionalChain([serverTools, 'optionalAccess', _17 => _17[clientTool.name]])) {
1006
+ throw new Error(
1007
+ `Tool ${clientTool.name} was defined in both the client and server tools. This is not allowed.`
1008
+ );
1009
+ }
1010
+ }
1011
+ let model;
1012
+ model = typeof modelOrCreator === "function" ? await modelOrCreator({ apiKey, baseUrl, modelName }) : modelOrCreator;
1013
+ let stream;
1014
+ const streamResult = await streamMessage({
1015
+ ...settings,
1016
+ ...callSettings,
1017
+ model,
1018
+ abortSignal,
1019
+ ...!!system ? { system } : void 0,
1020
+ messages,
1021
+ tools: lmServerTools.concat(clientTools),
1022
+ ...toolChoice ? { toolChoice } : void 0
1023
+ });
1024
+ stream = streamResult.stream;
1025
+ const canExecuteTools = hasServerTools && _optionalChain([toolChoice, 'optionalAccess', _18 => _18.type]) !== "none";
1026
+ if (canExecuteTools) {
1027
+ stream = stream.pipeThrough(toolResultStream(serverTools, abortSignal));
1028
+ }
1029
+ if (canExecuteTools || onFinish) {
1030
+ const tees = stream.tee();
1031
+ stream = tees[0];
1032
+ let serverStream = tees[1];
1033
+ if (onFinish) {
1034
+ let lastChunk;
1035
+ serverStream = serverStream.pipeThrough(runResultStream()).pipeThrough(
1036
+ new TransformStream({
1037
+ transform(chunk) {
1038
+ lastChunk = chunk;
1039
+ },
1040
+ flush() {
1041
+ if (!_optionalChain([lastChunk, 'optionalAccess', _19 => _19.status]) || lastChunk.status.type === "running")
789
1042
  return;
790
- } else {
791
- toolCallExecutions.set(
792
- toolCallId,
793
- (async () => {
794
- if (!tool.execute) return;
795
- try {
796
- const result2 = await tool.execute(args, { abortSignal });
797
- controller.enqueue({
798
- type: "tool-result",
799
- toolCallType,
800
- toolCallId,
801
- toolName,
802
- result: result2
803
- });
804
- } catch (error) {
805
- controller.enqueue({
806
- type: "tool-result",
807
- toolCallType,
808
- toolCallId,
809
- toolName,
810
- result: "Error: " + error,
811
- isError: true
812
- });
813
- } finally {
814
- toolCallExecutions.delete(toolCallId);
815
- }
816
- })()
817
- );
818
- }
1043
+ const resultingMessages = [
1044
+ ...messages,
1045
+ toCoreMessage({
1046
+ role: "assistant",
1047
+ content: lastChunk.content
1048
+ })
1049
+ ];
1050
+ onFinish({
1051
+ messages: resultingMessages,
1052
+ metadata: {
1053
+ roundtrips: _optionalChain([lastChunk, 'access', _20 => _20.metadata, 'optionalAccess', _21 => _21.roundtrips])
1054
+ }
1055
+ });
819
1056
  }
820
- break;
821
- }
822
- // ignore other parts
823
- case "text-delta":
824
- case "tool-call-delta":
825
- case "tool-result":
826
- case "finish":
827
- case "error":
828
- break;
829
- default: {
830
- const unhandledType = chunkType;
831
- throw new Error(`Unhandled chunk type: ${unhandledType}`);
832
- }
1057
+ })
1058
+ );
1059
+ }
1060
+ serverStream.pipeTo(voidStream()).catch((e) => {
1061
+ console.error("Server stream processing error:", e);
1062
+ });
1063
+ }
1064
+ return stream;
1065
+ };
1066
+ var getEdgeRuntimeResponse = async (options) => {
1067
+ const stream = await getEdgeRuntimeStream(options);
1068
+ return new Response(
1069
+ stream.pipeThrough(assistantEncoderStream()).pipeThrough(streamPartEncoderStream()),
1070
+ {
1071
+ headers: {
1072
+ "Content-Type": "text/plain; charset=utf-8"
833
1073
  }
834
- },
835
- async flush() {
836
- await Promise.all(toolCallExecutions.values());
837
1074
  }
1075
+ );
1076
+ };
1077
+ var createEdgeRuntimeAPI = (options) => ({
1078
+ POST: async (request) => getEdgeRuntimeResponse({
1079
+ abortSignal: request.signal,
1080
+ requestData: await request.json(),
1081
+ options
1082
+ })
1083
+ });
1084
+ async function streamMessage({
1085
+ model,
1086
+ system,
1087
+ messages,
1088
+ tools,
1089
+ toolChoice,
1090
+ ...options
1091
+ }) {
1092
+ return model.doStream({
1093
+ inputFormat: "messages",
1094
+ mode: {
1095
+ type: "regular",
1096
+ ...tools ? { tools } : void 0,
1097
+ ...toolChoice ? { toolChoice } : void 0
1098
+ },
1099
+ prompt: convertToLanguageModelPrompt(system, messages),
1100
+ ...options
838
1101
  });
839
1102
  }
1103
+ function convertToLanguageModelPrompt(system, messages) {
1104
+ const languageModelMessages = [];
1105
+ if (system != null) {
1106
+ languageModelMessages.push({ role: "system", content: system });
1107
+ }
1108
+ languageModelMessages.push(...toLanguageModelMessages(messages));
1109
+ return languageModelMessages;
1110
+ }
1111
+
840
1112
 
841
1113
 
842
1114
 
@@ -850,5 +1122,5 @@ function toolResultStream(tools, abortSignal) {
850
1122
 
851
1123
 
852
1124
 
853
- exports.LanguageModelV1CallSettingsSchema = LanguageModelV1CallSettingsSchema; exports.LanguageModelConfigSchema = LanguageModelConfigSchema; exports.mergeModelConfigs = mergeModelConfigs; exports.toLanguageModelMessages = toLanguageModelMessages; exports.toCoreMessages = toCoreMessages; exports.toCoreMessage = toCoreMessage; exports.toLanguageModelTools = toLanguageModelTools; exports.PipeableTransformStream = PipeableTransformStream; exports.streamPartEncoderStream = streamPartEncoderStream; exports.runResultStream = runResultStream; exports.toolResultStream = toolResultStream;
854
- //# sourceMappingURL=chunk-JKRONBQK.js.map
1125
+ exports.mergeModelConfigs = mergeModelConfigs; exports.toLanguageModelMessages = toLanguageModelMessages; exports.toCoreMessages = toCoreMessages; exports.toCoreMessage = toCoreMessage; exports.toLanguageModelTools = toLanguageModelTools; exports.PipeableTransformStream = PipeableTransformStream; exports.streamPartEncoderStream = streamPartEncoderStream; exports.runResultStream = runResultStream; exports.toolResultStream = toolResultStream; exports.getEdgeRuntimeStream = getEdgeRuntimeStream; exports.getEdgeRuntimeResponse = getEdgeRuntimeResponse; exports.createEdgeRuntimeAPI = createEdgeRuntimeAPI;
1126
+ //# sourceMappingURL=chunk-BQ3MRWUV.js.map