@ai-sdk-tool/parser 3.0.0 → 3.1.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.
@@ -1309,7 +1309,7 @@ function parse2(text, optsOrReviver) {
1309
1309
  return parseWithTransform(text, options);
1310
1310
  }
1311
1311
 
1312
- // src/core/protocols/json-mix-protocol.ts
1312
+ // src/core/protocols/json-protocol.ts
1313
1313
  function processToolCallJson(toolCallJson, fullMatch, processedElements, options) {
1314
1314
  var _a, _b;
1315
1315
  try {
@@ -1369,7 +1369,6 @@ function flushBuffer(state, controller, toolCallStart) {
1369
1369
  controller.enqueue({
1370
1370
  type: "text-delta",
1371
1371
  id: state.currentTextId,
1372
- textDelta: deltaContent,
1373
1372
  delta: deltaContent
1374
1373
  });
1375
1374
  state.buffer = "";
@@ -1402,7 +1401,6 @@ function emitIncompleteToolCall(state, controller, toolCallStart) {
1402
1401
  controller.enqueue({
1403
1402
  type: "text-delta",
1404
1403
  id: errorId,
1405
- textDelta: errorContent,
1406
1404
  delta: errorContent
1407
1405
  });
1408
1406
  controller.enqueue({
@@ -1435,7 +1433,6 @@ function publishText(text, state, controller) {
1435
1433
  controller.enqueue({
1436
1434
  type: "text-delta",
1437
1435
  id: state.currentTextId,
1438
- textDelta: text,
1439
1436
  delta: text
1440
1437
  });
1441
1438
  }
@@ -1468,7 +1465,6 @@ function emitToolCall(context) {
1468
1465
  controller.enqueue({
1469
1466
  type: "text-delta",
1470
1467
  id: errorId,
1471
- textDelta: errorContent,
1472
1468
  delta: errorContent
1473
1469
  });
1474
1470
  controller.enqueue({
@@ -1528,19 +1524,15 @@ function handlePartialTag(state, controller, toolCallStart) {
1528
1524
  state.buffer = "";
1529
1525
  }
1530
1526
  }
1531
- var jsonMixProtocol = ({
1527
+ var jsonProtocol = ({
1532
1528
  toolCallStart = "<tool_call>",
1533
- toolCallEnd = "</tool_call>",
1534
- toolResponseStart = "<tool_response>",
1535
- toolResponseEnd = "</tool_response>"
1529
+ toolCallEnd = "</tool_call>"
1536
1530
  } = {}) => ({
1537
- formatTools({ tools, toolSystemPromptTemplate }) {
1538
- const toolsForPrompt = (tools || []).filter((tool) => tool.type === "function").map((tool) => ({
1539
- name: tool.name,
1540
- description: tool.type === "function" && typeof tool.description === "string" ? tool.description : void 0,
1541
- parameters: tool.inputSchema
1542
- }));
1543
- return toolSystemPromptTemplate(JSON.stringify(toolsForPrompt));
1531
+ formatTools({
1532
+ tools,
1533
+ toolSystemPromptTemplate
1534
+ }) {
1535
+ return toolSystemPromptTemplate(tools || []);
1544
1536
  },
1545
1537
  formatToolCall(toolCall) {
1546
1538
  let args = {};
@@ -1554,13 +1546,10 @@ var jsonMixProtocol = ({
1554
1546
  arguments: args
1555
1547
  })}${toolCallEnd}`;
1556
1548
  },
1557
- formatToolResponse(toolResult) {
1558
- return `${toolResponseStart}${JSON.stringify({
1559
- toolName: toolResult.toolName,
1560
- result: toolResult.result
1561
- })}${toolResponseEnd}`;
1562
- },
1563
- parseGeneratedText({ text, options }) {
1549
+ parseGeneratedText({
1550
+ text,
1551
+ options
1552
+ }) {
1564
1553
  const startEsc = escapeRegExp2(toolCallStart);
1565
1554
  const endEsc = escapeRegExp2(toolCallEnd);
1566
1555
  const toolCallRegex = new RegExp(
@@ -1586,7 +1575,9 @@ var jsonMixProtocol = ({
1586
1575
  }
1587
1576
  return processedElements;
1588
1577
  },
1589
- createStreamParser({ options }) {
1578
+ createStreamParser({
1579
+ options
1580
+ }) {
1590
1581
  const state = {
1591
1582
  isInsideToolCall: false,
1592
1583
  buffer: "",
@@ -1596,7 +1587,7 @@ var jsonMixProtocol = ({
1596
1587
  };
1597
1588
  return new TransformStream({
1598
1589
  transform(chunk, controller) {
1599
- var _a, _b;
1590
+ var _a;
1600
1591
  if (chunk.type === "finish") {
1601
1592
  handleFinishChunk(state, controller, toolCallStart, chunk);
1602
1593
  return;
@@ -1605,7 +1596,7 @@ var jsonMixProtocol = ({
1605
1596
  controller.enqueue(chunk);
1606
1597
  return;
1607
1598
  }
1608
- const textContent = (_b = (_a = chunk.textDelta) != null ? _a : chunk.delta) != null ? _b : "";
1599
+ const textContent = (_a = chunk.delta) != null ? _a : "";
1609
1600
  state.buffer += textContent;
1610
1601
  processBufferTags({
1611
1602
  state,
@@ -1632,7 +1623,12 @@ var jsonMixProtocol = ({
1632
1623
  }
1633
1624
  });
1634
1625
 
1635
- // src/core/protocols/morph-xml-protocol.ts
1626
+ // src/core/protocols/protocol-interface.ts
1627
+ function isTCMProtocolFactory(protocol) {
1628
+ return typeof protocol === "function";
1629
+ }
1630
+
1631
+ // src/core/protocols/xml-protocol.ts
1636
1632
  var import_rxml2 = require("@ai-sdk-tool/rxml");
1637
1633
  var defaultPipelineConfig2 = defaultPipelineConfig;
1638
1634
  var NAME_CHAR_RE2 = /[A-Za-z0-9_:-]/;
@@ -1967,7 +1963,6 @@ function createFlushTextHandler(getCurrentTextId, setCurrentTextId, getHasEmitte
1967
1963
  controller.enqueue({
1968
1964
  type: "text-delta",
1969
1965
  id: getCurrentTextId(),
1970
- textDelta: content,
1971
1966
  delta: content
1972
1967
  });
1973
1968
  }
@@ -2129,7 +2124,7 @@ function createProcessBufferHandler(getBuffer, setBuffer, getCurrentToolCall, se
2129
2124
  }
2130
2125
  };
2131
2126
  }
2132
- var morphXmlProtocol = (protocolOptions) => {
2127
+ var xmlProtocol = (protocolOptions) => {
2133
2128
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2134
2129
  let pipelineConfig = protocolOptions == null ? void 0 : protocolOptions.pipeline;
2135
2130
  const maxReparses = protocolOptions == null ? void 0 : protocolOptions.maxReparses;
@@ -2169,12 +2164,7 @@ var morphXmlProtocol = (protocolOptions) => {
2169
2164
  }
2170
2165
  return {
2171
2166
  formatTools({ tools, toolSystemPromptTemplate }) {
2172
- const toolsForPrompt = (tools || []).map((tool) => ({
2173
- name: tool.name,
2174
- description: tool.description,
2175
- parameters: (0, import_rxml2.unwrapJsonSchema)(tool.inputSchema)
2176
- }));
2177
- return toolSystemPromptTemplate(JSON.stringify(toolsForPrompt));
2167
+ return toolSystemPromptTemplate(tools || []);
2178
2168
  },
2179
2169
  formatToolCall(toolCall) {
2180
2170
  let args = {};
@@ -2188,21 +2178,6 @@ var morphXmlProtocol = (protocolOptions) => {
2188
2178
  format: false
2189
2179
  });
2190
2180
  },
2191
- formatToolResponse(toolResult) {
2192
- let result = toolResult.result;
2193
- if (result && typeof result === "object" && "type" in result && result.type === "json" && "value" in result) {
2194
- result = result.value;
2195
- }
2196
- const xml = (0, import_rxml2.stringify)(
2197
- "tool_response",
2198
- {
2199
- tool_name: toolResult.toolName,
2200
- result
2201
- },
2202
- { declaration: false }
2203
- );
2204
- return xml;
2205
- },
2206
2181
  parseGeneratedText({ text, tools, options }) {
2207
2182
  const toolNames = tools.map((t) => t.name).filter(Boolean);
2208
2183
  if (toolNames.length === 0) {
@@ -2271,7 +2246,7 @@ var morphXmlProtocol = (protocolOptions) => {
2271
2246
  );
2272
2247
  return new TransformStream({
2273
2248
  transform(chunk, controller) {
2274
- var _a2, _b2;
2249
+ var _a2;
2275
2250
  if (chunk.type !== "text-delta") {
2276
2251
  if (buffer) {
2277
2252
  flushText(controller, buffer);
@@ -2280,7 +2255,7 @@ var morphXmlProtocol = (protocolOptions) => {
2280
2255
  controller.enqueue(chunk);
2281
2256
  return;
2282
2257
  }
2283
- const textContent = (_b2 = (_a2 = chunk.textDelta) != null ? _a2 : chunk.delta) != null ? _b2 : "";
2258
+ const textContent = (_a2 = chunk.delta) != null ? _a2 : "";
2284
2259
  buffer += textContent;
2285
2260
  processBuffer(controller);
2286
2261
  },
@@ -2315,13 +2290,7 @@ var morphXmlProtocol = (protocolOptions) => {
2315
2290
  };
2316
2291
  };
2317
2292
 
2318
- // src/core/protocols/tool-call-protocol.ts
2319
- function isProtocolFactory(protocol) {
2320
- return typeof protocol === "function";
2321
- }
2322
-
2323
- // src/core/protocols/yaml-xml-protocol.ts
2324
- var import_rxml3 = require("@ai-sdk-tool/rxml");
2293
+ // src/core/protocols/yaml-protocol.ts
2325
2294
  var import_yaml = __toESM(require("yaml"), 1);
2326
2295
  var NAME_CHAR_RE3 = /[A-Za-z0-9_:-]/;
2327
2296
  var WHITESPACE_REGEX4 = /\s/;
@@ -2542,7 +2511,6 @@ function createFlushTextHandler2(getCurrentTextId, setCurrentTextId, getHasEmitt
2542
2511
  controller.enqueue({
2543
2512
  type: "text-delta",
2544
2513
  id: getCurrentTextId(),
2545
- textDelta: content,
2546
2514
  delta: content
2547
2515
  });
2548
2516
  }
@@ -2590,15 +2558,10 @@ function findEarliestToolTag2(buffer, toolNames) {
2590
2558
  tagLength: bestTagLength
2591
2559
  };
2592
2560
  }
2593
- var yamlXmlProtocol = (_protocolOptions) => {
2561
+ var yamlProtocol = (_protocolOptions) => {
2594
2562
  return {
2595
2563
  formatTools({ tools, toolSystemPromptTemplate }) {
2596
- const toolsForPrompt = (tools || []).map((tool) => ({
2597
- name: tool.name,
2598
- description: tool.description,
2599
- parameters: (0, import_rxml3.unwrapJsonSchema)(tool.inputSchema)
2600
- }));
2601
- return toolSystemPromptTemplate(JSON.stringify(toolsForPrompt));
2564
+ return toolSystemPromptTemplate(tools || []);
2602
2565
  },
2603
2566
  formatToolCall(toolCall) {
2604
2567
  let args = {};
@@ -2611,21 +2574,6 @@ var yamlXmlProtocol = (_protocolOptions) => {
2611
2574
  return `<${toolCall.toolName}>
2612
2575
  ${yamlContent}</${toolCall.toolName}>`;
2613
2576
  },
2614
- formatToolResponse(toolResult) {
2615
- let result = toolResult.result;
2616
- if (result && typeof result === "object" && "type" in result && result.type === "json" && "value" in result) {
2617
- result = result.value;
2618
- }
2619
- const xml = (0, import_rxml3.stringify)(
2620
- "tool_response",
2621
- {
2622
- tool_name: toolResult.toolName,
2623
- result
2624
- },
2625
- { declaration: false }
2626
- );
2627
- return xml;
2628
- },
2629
2577
  parseGeneratedText({ text, tools, options }) {
2630
2578
  const toolNames = tools.map((t) => t.name).filter(Boolean);
2631
2579
  if (toolNames.length === 0) {
@@ -2739,7 +2687,7 @@ ${yamlContent}</${toolCall.toolName}>`;
2739
2687
  };
2740
2688
  return new TransformStream({
2741
2689
  transform(chunk, controller) {
2742
- var _a, _b;
2690
+ var _a;
2743
2691
  if (chunk.type !== "text-delta") {
2744
2692
  if (buffer) {
2745
2693
  flushText(controller, buffer);
@@ -2748,7 +2696,7 @@ ${yamlContent}</${toolCall.toolName}>`;
2748
2696
  controller.enqueue(chunk);
2749
2697
  return;
2750
2698
  }
2751
- const textContent = (_b = (_a = chunk.textDelta) != null ? _a : chunk.delta) != null ? _b : "";
2699
+ const textContent = (_a = chunk.delta) != null ? _a : "";
2752
2700
  buffer += textContent;
2753
2701
  processBuffer(controller);
2754
2702
  },
@@ -2784,44 +2732,6 @@ ${yamlContent}</${toolCall.toolName}>`;
2784
2732
  }
2785
2733
  };
2786
2734
  };
2787
- function orchestratorSystemPromptTemplate(tools, includeMultilineExample = true) {
2788
- const multilineExample = includeMultilineExample ? `
2789
-
2790
- For multiline values, use YAML's literal block syntax:
2791
- <write_file>
2792
- file_path: /tmp/example.txt
2793
- contents: |
2794
- First line
2795
- Second line
2796
- Third line
2797
- </write_file>` : "";
2798
- return `# Tools
2799
-
2800
- You may call one or more functions to assist with the user query.
2801
-
2802
- You are provided with function signatures within <tools></tools> XML tags:
2803
- <tools>${tools}</tools>
2804
-
2805
- # Format
2806
-
2807
- Use exactly one XML element whose tag name is the function name.
2808
- Inside the XML element, specify parameters using YAML syntax (key: value pairs).
2809
-
2810
- # Example
2811
- <get_weather>
2812
- location: New York
2813
- unit: celsius
2814
- </get_weather>${multilineExample}
2815
-
2816
- # Rules
2817
- - Parameter names and values must follow the schema exactly.
2818
- - Use proper YAML syntax for values (strings, numbers, booleans, arrays, objects).
2819
- - Each required parameter must appear once.
2820
- - Do not add functions or parameters not in the schema.
2821
- - After calling a tool, you will receive a response. Use this result to answer the user.
2822
- - Do NOT ask clarifying questions. Use reasonable defaults for optional parameters.
2823
- - If a task requires multiple function calls, make ALL of them at once.`;
2824
- }
2825
2735
 
2826
2736
  // src/core/utils/dynamic-tool-schema.ts
2827
2737
  function createDynamicIfThenElseSchema(tools) {
@@ -2925,9 +2835,9 @@ function isToolCallContent(content) {
2925
2835
  (typeof content.input === "string" || typeof content.input === "object");
2926
2836
  }
2927
2837
 
2928
- // src/v6/generate-handler.ts
2838
+ // src/generate-handler.ts
2929
2839
  var import_provider_utils = require("@ai-sdk/provider-utils");
2930
- var import_rxml4 = require("@ai-sdk-tool/rxml");
2840
+ var import_rxml3 = require("@ai-sdk-tool/rxml");
2931
2841
  function parseToolChoiceJson(text, providerOptions) {
2932
2842
  var _a;
2933
2843
  try {
@@ -3090,80 +3000,207 @@ function fixToolCallWithSchema(part, tools) {
3090
3000
  args = tc.input;
3091
3001
  }
3092
3002
  const schema = (_a = tools.find((t) => t.name === tc.toolName)) == null ? void 0 : _a.inputSchema;
3093
- const coerced = (0, import_rxml4.coerceBySchema)(args, schema);
3003
+ const coerced = (0, import_rxml3.coerceBySchema)(args, schema);
3094
3004
  return {
3095
3005
  ...part,
3096
3006
  input: JSON.stringify(coerced != null ? coerced : {})
3097
3007
  };
3098
3008
  }
3099
3009
 
3100
- // src/v6/stream-handler.ts
3101
- var import_provider_utils2 = require("@ai-sdk/provider-utils");
3102
- function mapCorePartToV3(part) {
3103
- switch (part.type) {
3104
- case "text-delta":
3105
- return {
3106
- type: "text-delta",
3107
- id: part.id || (0, import_provider_utils2.generateId)(),
3108
- delta: part.textDelta
3109
- };
3110
- case "tool-call":
3111
- return {
3112
- type: "tool-call",
3113
- toolCallId: part.toolCallId,
3114
- toolName: part.toolName,
3115
- input: part.input
3116
- };
3117
- case "tool-call-delta":
3118
- return {
3119
- type: "tool-call-delta",
3120
- toolCallId: part.toolCallId,
3121
- toolName: part.toolName,
3122
- argsTextDelta: part.argsTextDelta
3123
- };
3124
- case "finish":
3125
- return {
3126
- type: "finish",
3127
- finishReason: part.finishReason,
3128
- usage: part.usage
3129
- };
3130
- case "error":
3131
- return {
3132
- type: "error",
3133
- error: part.error
3134
- };
3135
- default:
3136
- return part;
3010
+ // src/core/prompts/hermes-system-prompt.ts
3011
+ function hermesSystemPromptTemplate(tools) {
3012
+ const toolsJson = JSON.stringify(tools);
3013
+ return `You are a function calling AI model.
3014
+ You are provided with function signatures within <tools></tools> XML tags.
3015
+ You may call one or more functions to assist with the user query.
3016
+ Don't make assumptions about what values to plug into functions.
3017
+ Here are the available tools: <tools>${toolsJson}</tools>
3018
+ Use the following pydantic model json schema for each tool call you will make: {"title": "FunctionCall", "type": "object", "properties": {"arguments": {"title": "Arguments", "type": "object"}, "name": {"title": "Name", "type": "string"}}, "required": ["arguments", "name"]}
3019
+ For each function call return a json object with function name and arguments within <tool_call></tool_call> XML tags as follows:
3020
+ <tool_call>
3021
+ {"name": "<function-name>", "arguments": <args-dict>}
3022
+ </tool_call>`;
3023
+ }
3024
+
3025
+ // src/core/prompts/tool-response.ts
3026
+ function unwrapToolResult(result) {
3027
+ var _a, _b;
3028
+ switch (result.type) {
3029
+ case "text":
3030
+ return (_a = result.value) != null ? _a : "";
3031
+ case "json":
3032
+ return result.value;
3033
+ case "execution-denied": {
3034
+ const reason = result.reason;
3035
+ return reason ? `[Execution Denied: ${reason}]` : "[Execution Denied]";
3036
+ }
3037
+ case "error-text":
3038
+ return `[Error: ${(_b = result.value) != null ? _b : ""}]`;
3039
+ case "error-json":
3040
+ return `[Error: ${JSON.stringify(result.value)}]`;
3041
+ case "content": {
3042
+ return result.value.map((part) => {
3043
+ var _a2;
3044
+ const contentPart = part;
3045
+ switch (contentPart.type) {
3046
+ case "text":
3047
+ return (_a2 = contentPart.text) != null ? _a2 : "";
3048
+ case "image-data":
3049
+ return `[Image: ${contentPart.mediaType}]`;
3050
+ case "image-url":
3051
+ return `[Image URL: ${contentPart.url}]`;
3052
+ case "image-file-id": {
3053
+ const fileId = contentPart.fileId;
3054
+ const displayId = typeof fileId === "string" ? fileId : JSON.stringify(fileId);
3055
+ return `[Image ID: ${displayId}]`;
3056
+ }
3057
+ case "file-data": {
3058
+ const filePart = contentPart;
3059
+ if (filePart.filename) {
3060
+ return `[File: ${filePart.filename} (${filePart.mediaType})]`;
3061
+ }
3062
+ return `[File: ${filePart.mediaType}]`;
3063
+ }
3064
+ case "file-url":
3065
+ return `[File URL: ${contentPart.url}]`;
3066
+ case "file-id": {
3067
+ const fileId = contentPart.fileId;
3068
+ const displayId = typeof fileId === "string" ? fileId : JSON.stringify(fileId);
3069
+ return `[File ID: ${displayId}]`;
3070
+ }
3071
+ case "media":
3072
+ return `[Media: ${contentPart.mediaType}]`;
3073
+ case "custom":
3074
+ return "[Custom content]";
3075
+ default:
3076
+ return "[Unknown content]";
3077
+ }
3078
+ }).join("\n");
3079
+ }
3080
+ default: {
3081
+ const _exhaustive = result;
3082
+ return _exhaustive;
3083
+ }
3137
3084
  }
3138
3085
  }
3139
- function mapV3PartToCore(part) {
3140
- const p = part;
3141
- switch (p.type) {
3142
- case "text-delta":
3143
- return {
3144
- type: "text-delta",
3145
- id: p.id,
3146
- textDelta: p.delta || p.textDelta || ""
3147
- };
3148
- case "tool-call":
3149
- return {
3150
- type: "tool-call",
3151
- toolCallId: p.toolCallId,
3152
- toolName: p.toolName,
3153
- input: p.input
3154
- };
3155
- case "finish": {
3156
- const finishReason = p.finishReason;
3157
- return {
3158
- type: "finish",
3159
- finishReason: (typeof finishReason === "object" ? finishReason == null ? void 0 : finishReason.unified : finishReason) || "stop",
3160
- usage: p.usage
3161
- };
3086
+ function formatToolResponseAsJsonInXml(toolResult) {
3087
+ const unwrappedResult = unwrapToolResult(toolResult.output);
3088
+ return `<tool_response>${JSON.stringify({
3089
+ toolName: toolResult.toolName,
3090
+ result: unwrappedResult
3091
+ })}</tool_response>`;
3092
+ }
3093
+ function formatToolResponseAsXml(toolResult) {
3094
+ const unwrappedResult = unwrapToolResult(toolResult.output);
3095
+ const toolNameXml = `<tool_name>${toolResult.toolName}</tool_name>`;
3096
+ const resultLines = formatXmlNode("result", unwrappedResult, 1);
3097
+ return [
3098
+ "<tool_response>",
3099
+ ` ${toolNameXml}`,
3100
+ ...resultLines,
3101
+ "</tool_response>"
3102
+ ].join("\n");
3103
+ }
3104
+ function formatXmlNode(tagName, value, depth) {
3105
+ const indent = " ".repeat(depth);
3106
+ if (value === null || value === void 0) {
3107
+ return [`${indent}<${tagName}></${tagName}>`];
3108
+ }
3109
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
3110
+ return [`${indent}<${tagName}>${String(value)}</${tagName}>`];
3111
+ }
3112
+ if (Array.isArray(value)) {
3113
+ if (value.length === 0) {
3114
+ return [`${indent}<${tagName}></${tagName}>`];
3162
3115
  }
3163
- default:
3164
- return p;
3116
+ const lines2 = [`${indent}<${tagName}>`];
3117
+ for (const item of value) {
3118
+ lines2.push(...formatXmlNode("item", item, depth + 1));
3119
+ }
3120
+ lines2.push(`${indent}</${tagName}>`);
3121
+ return lines2;
3122
+ }
3123
+ const entries = Object.entries(value);
3124
+ if (entries.length === 0) {
3125
+ return [`${indent}<${tagName}></${tagName}>`];
3165
3126
  }
3127
+ const lines = [`${indent}<${tagName}>`];
3128
+ for (const [key, entryValue] of entries) {
3129
+ lines.push(...formatXmlNode(key, entryValue, depth + 1));
3130
+ }
3131
+ lines.push(`${indent}</${tagName}>`);
3132
+ return lines;
3133
+ }
3134
+
3135
+ // src/core/prompts/xml-system-prompt.ts
3136
+ function xmlSystemPromptTemplate(tools) {
3137
+ const toolsJson = JSON.stringify(tools);
3138
+ return `# Tools
3139
+
3140
+ You may call one or more functions to assist with the user query.
3141
+
3142
+ You are provided with function signatures within <tools></tools> XML tags:
3143
+ <tools>${toolsJson}</tools>
3144
+
3145
+ # Rules
3146
+ - Use exactly one XML element whose tag name is the function name.
3147
+ - Put each parameter as a child element.
3148
+ - Values must follow the schema exactly (numbers, arrays, objects, enums \u2192 copy as-is).
3149
+ - Do not add or remove functions or parameters.
3150
+ - Each required parameter must appear once.
3151
+ - Output nothing before or after the function call.
3152
+ - After calling a tool, you will receive a response in the format: <tool_response><tool_name>NAME</tool_name><result>RESULT</result></tool_response>. Use this result to answer the user.
3153
+
3154
+ # Example
3155
+ <get_weather>
3156
+ <location>New York</location>
3157
+ <unit>celsius</unit>
3158
+ </get_weather>`;
3159
+ }
3160
+
3161
+ // src/core/prompts/yaml-system-prompt.ts
3162
+ function yamlSystemPromptTemplate(tools, includeMultilineExample = true) {
3163
+ const toolsJson = JSON.stringify(tools);
3164
+ const multilineExample = includeMultilineExample ? `
3165
+
3166
+ For multiline values, use YAML's literal block syntax:
3167
+ <write_file>
3168
+ file_path: /tmp/example.txt
3169
+ contents: |
3170
+ First line
3171
+ Second line
3172
+ Third line
3173
+ </write_file>` : "";
3174
+ return `# Tools
3175
+
3176
+ You may call one or more functions to assist with the user query.
3177
+
3178
+ You are provided with function signatures within <tools></tools> XML tags:
3179
+ <tools>${toolsJson}</tools>
3180
+
3181
+ # Format
3182
+
3183
+ Use exactly one XML element whose tag name is the function name.
3184
+ Inside the XML element, specify parameters using YAML syntax (key: value pairs).
3185
+
3186
+ # Example
3187
+ <get_weather>
3188
+ location: New York
3189
+ unit: celsius
3190
+ </get_weather>${multilineExample}
3191
+
3192
+ # Rules
3193
+ - Parameter names and values must follow the schema exactly.
3194
+ - Use proper YAML syntax for values (strings, numbers, booleans, arrays, objects).
3195
+ - Each required parameter must appear once.
3196
+ - Do not add functions or parameters not in the schema.
3197
+ - After calling a tool, you will receive a response. Use this result to answer the user.
3198
+ - Do NOT ask clarifying questions. Use reasonable defaults for optional parameters.
3199
+ - If a task requires multiple function calls, make ALL of them at once.`;
3166
3200
  }
3201
+
3202
+ // src/stream-handler.ts
3203
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
3167
3204
  async function wrapStream({
3168
3205
  protocol,
3169
3206
  doStream,
@@ -3187,23 +3224,24 @@ async function wrapStream({
3187
3224
  ...((_c = params.providerOptions) == null ? void 0 : _c.toolCallMiddleware) || {}
3188
3225
  };
3189
3226
  const coreStream = stream.pipeThrough(
3190
- new TransformStream({
3191
- transform(part, controller) {
3192
- if (debugLevel === "stream") {
3193
- logRawChunk(part);
3227
+ new TransformStream(
3228
+ {
3229
+ transform(part, controller) {
3230
+ if (debugLevel === "stream") {
3231
+ logRawChunk(part);
3232
+ }
3233
+ controller.enqueue(part);
3194
3234
  }
3195
- controller.enqueue(mapV3PartToCore(part));
3196
3235
  }
3197
- })
3236
+ )
3198
3237
  ).pipeThrough(protocol.createStreamParser({ tools, options }));
3199
3238
  const v3Stream = coreStream.pipeThrough(
3200
3239
  new TransformStream({
3201
3240
  transform(part, controller) {
3202
- const v3Part = mapCorePartToV3(part);
3203
3241
  if (debugLevel === "stream") {
3204
- logParsedChunk(v3Part);
3242
+ logParsedChunk(part);
3205
3243
  }
3206
- controller.enqueue(v3Part);
3244
+ controller.enqueue(part);
3207
3245
  }
3208
3246
  })
3209
3247
  );
@@ -3260,7 +3298,7 @@ async function toolChoiceStream({
3260
3298
  };
3261
3299
  }
3262
3300
 
3263
- // src/v6/transform-handler.ts
3301
+ // src/transform-handler.ts
3264
3302
  function buildFinalPrompt(systemPrompt, processedPrompt, placement) {
3265
3303
  const systemIndex = processedPrompt.findIndex((m) => m.role === "system");
3266
3304
  if (systemIndex !== -1) {
@@ -3403,10 +3441,11 @@ function transformParams({
3403
3441
  params,
3404
3442
  protocol,
3405
3443
  toolSystemPromptTemplate,
3444
+ toolResponsePromptTemplate,
3406
3445
  placement = "first"
3407
3446
  }) {
3408
- var _a, _b, _c, _d, _e;
3409
- const resolvedProtocol = isProtocolFactory(protocol) ? protocol() : protocol;
3447
+ var _a, _b, _c, _d;
3448
+ const resolvedProtocol = isTCMProtocolFactory(protocol) ? protocol() : protocol;
3410
3449
  const functionTools = ((_a = params.tools) != null ? _a : []).filter(
3411
3450
  (t) => t.type === "function"
3412
3451
  );
@@ -3414,9 +3453,18 @@ function transformParams({
3414
3453
  tools: functionTools,
3415
3454
  toolSystemPromptTemplate
3416
3455
  });
3456
+ let normalizedPrompt;
3457
+ if (Array.isArray(params.prompt)) {
3458
+ normalizedPrompt = params.prompt;
3459
+ } else if (params.prompt) {
3460
+ normalizedPrompt = [params.prompt];
3461
+ } else {
3462
+ normalizedPrompt = [];
3463
+ }
3417
3464
  const processedPrompt = convertToolPrompt(
3418
- (_b = params.prompt) != null ? _b : [],
3465
+ normalizedPrompt,
3419
3466
  resolvedProtocol,
3467
+ toolResponsePromptTemplate,
3420
3468
  extractOnErrorOption(params.providerOptions)
3421
3469
  );
3422
3470
  const finalPrompt = buildFinalPrompt(
@@ -3429,15 +3477,15 @@ function transformParams({
3429
3477
  finalPrompt,
3430
3478
  functionTools
3431
3479
  );
3432
- if (((_c = params.toolChoice) == null ? void 0 : _c.type) === "none") {
3480
+ if (((_b = params.toolChoice) == null ? void 0 : _b.type) === "none") {
3433
3481
  throw new Error(
3434
3482
  "The 'none' toolChoice type is not supported by this middleware. Please use 'auto', 'required', or specify a tool name."
3435
3483
  );
3436
3484
  }
3437
- if (((_d = params.toolChoice) == null ? void 0 : _d.type) === "tool") {
3485
+ if (((_c = params.toolChoice) == null ? void 0 : _c.type) === "tool") {
3438
3486
  return handleToolChoiceTool(params, baseReturnParams);
3439
3487
  }
3440
- if (((_e = params.toolChoice) == null ? void 0 : _e.type) === "required") {
3488
+ if (((_d = params.toolChoice) == null ? void 0 : _d.type) === "required") {
3441
3489
  return handleToolChoiceRequired(params, baseReturnParams, functionTools);
3442
3490
  }
3443
3491
  return baseReturnParams;
@@ -3476,25 +3524,28 @@ function processAssistantContent(content, resolvedProtocol, providerOptions) {
3476
3524
  }
3477
3525
  ] : newContent;
3478
3526
  }
3479
- function processToolMessage(content, resolvedProtocol) {
3527
+ function formatApprovalResponse(part) {
3528
+ const status = part.approved ? "Approved" : "Denied";
3529
+ const reason = part.reason ? `: ${part.reason}` : "";
3530
+ return `[Tool Approval ${status}${reason}]`;
3531
+ }
3532
+ function processToolMessage(toolResults, approvalResponses, toolResponsePromptTemplate) {
3533
+ const resultTexts = toolResults.map((toolResult) => {
3534
+ return toolResponsePromptTemplate(toolResult);
3535
+ });
3536
+ const approvalTexts = approvalResponses.map(formatApprovalResponse);
3537
+ const allTexts = [...resultTexts, ...approvalTexts];
3480
3538
  return {
3481
3539
  role: "user",
3482
3540
  content: [
3483
3541
  {
3484
3542
  type: "text",
3485
- text: content.map((toolResult) => {
3486
- var _a, _b;
3487
- const tr = toolResult;
3488
- return resolvedProtocol.formatToolResponse({
3489
- ...toolResult,
3490
- result: (_b = (_a = tr.result) != null ? _a : tr.content) != null ? _b : tr.output
3491
- });
3492
- }).join("\n")
3543
+ text: allTexts.join("\n")
3493
3544
  }
3494
3545
  ]
3495
3546
  };
3496
3547
  }
3497
- function processMessage(message, resolvedProtocol, providerOptions) {
3548
+ function processMessage(message, resolvedProtocol, providerOptions, toolResponsePromptTemplate) {
3498
3549
  if (message.role === "assistant") {
3499
3550
  const condensedContent = processAssistantContent(
3500
3551
  message.content,
@@ -3507,10 +3558,23 @@ function processMessage(message, resolvedProtocol, providerOptions) {
3507
3558
  };
3508
3559
  }
3509
3560
  if (message.role === "tool") {
3510
- const toolResultParts = message.content.filter(
3561
+ const toolContent = message.content;
3562
+ const toolResultParts = toolContent.filter(
3511
3563
  (part) => part.type === "tool-result"
3512
3564
  );
3513
- return processToolMessage(toolResultParts, resolvedProtocol);
3565
+ const approvalResponseParts = toolContent.filter(
3566
+ (part) => part.type === "tool-approval-response"
3567
+ );
3568
+ if (!toolResponsePromptTemplate) {
3569
+ throw new Error(
3570
+ 'toolResponsePromptTemplate is required when processing messages with role "tool". This parameter is optional for other roles but is required here so tool-result content can be converted into a prompt. Ensure your middleware or transform configuration passes a toolResponsePromptTemplate when tool message processing is enabled.'
3571
+ );
3572
+ }
3573
+ return processToolMessage(
3574
+ toolResultParts,
3575
+ approvalResponseParts,
3576
+ toolResponsePromptTemplate
3577
+ );
3514
3578
  }
3515
3579
  return message;
3516
3580
  }
@@ -3573,22 +3637,28 @@ ${currentContent}` }]
3573
3637
  }
3574
3638
  return processedPrompt;
3575
3639
  }
3576
- function convertToolPrompt(prompt, resolvedProtocol, providerOptions) {
3640
+ function convertToolPrompt(prompt, resolvedProtocol, toolResponsePromptTemplate, providerOptions) {
3577
3641
  let processedPrompt = prompt.map(
3578
- (message) => processMessage(message, resolvedProtocol, providerOptions)
3642
+ (message) => processMessage(
3643
+ message,
3644
+ resolvedProtocol,
3645
+ providerOptions,
3646
+ toolResponsePromptTemplate
3647
+ )
3579
3648
  );
3580
3649
  processedPrompt = condenseTextContent(processedPrompt);
3581
3650
  processedPrompt = mergeConsecutiveUserMessages(processedPrompt);
3582
3651
  return processedPrompt;
3583
3652
  }
3584
3653
 
3585
- // src/v6/tool-call-middleware.ts
3654
+ // src/tool-call-middleware.ts
3586
3655
  function createToolMiddleware({
3587
3656
  protocol,
3588
3657
  toolSystemPromptTemplate,
3658
+ toolResponsePromptTemplate,
3589
3659
  placement = "last"
3590
3660
  }) {
3591
- const resolvedProtocol = isProtocolFactory(protocol) ? protocol() : protocol;
3661
+ const resolvedProtocol = isTCMProtocolFactory(protocol) ? protocol() : protocol;
3592
3662
  return {
3593
3663
  specificationVersion: "v3",
3594
3664
  wrapStream: ({ doStream, doGenerate, params }) => {
@@ -3613,85 +3683,38 @@ function createToolMiddleware({
3613
3683
  transformParams: async ({ params }) => transformParams({
3614
3684
  protocol: resolvedProtocol,
3615
3685
  toolSystemPromptTemplate,
3686
+ toolResponsePromptTemplate,
3616
3687
  placement,
3617
3688
  params
3618
3689
  })
3619
3690
  };
3620
3691
  }
3621
3692
 
3622
- // src/v6/index.ts
3623
- var gemmaToolMiddleware = createToolMiddleware({
3624
- protocol: jsonMixProtocol({
3625
- toolCallStart: "```tool_call\n",
3626
- toolCallEnd: "\n```",
3627
- toolResponseStart: "```tool_response\n",
3628
- toolResponseEnd: "\n```"
3629
- }),
3630
- toolSystemPromptTemplate(tools) {
3631
- return `You have access to functions. If you decide to invoke any of the function(s),
3632
- you MUST put it in the format of markdown code fence block with the language name of tool_call , e.g.
3633
- \`\`\`tool_call
3634
- {'name': <function-name>, 'arguments': <args-dict>}
3635
- \`\`\`
3636
- You SHOULD NOT include any other text in the response if you call a function
3637
- ${tools}`;
3638
- }
3639
- });
3693
+ // src/preconfigured-middleware.ts
3640
3694
  var hermesToolMiddleware = createToolMiddleware({
3641
- protocol: jsonMixProtocol,
3642
- toolSystemPromptTemplate(tools) {
3643
- return `You are a function calling AI model.
3644
- You are provided with function signatures within <tools></tools> XML tags.
3645
- You may call one or more functions to assist with the user query.
3646
- Don't make assumptions about what values to plug into functions.
3647
- Here are the available tools: <tools>${tools}</tools>
3648
- Use the following pydantic model json schema for each tool call you will make: {"title": "FunctionCall", "type": "object", "properties": {"arguments": {"title": "Arguments", "type": "object"}, "name": {"title": "Name", "type": "string"}}, "required": ["arguments", "name"]}
3649
- For each function call return a json object with function name and arguments within <tool_call></tool_call> XML tags as follows:
3650
- <tool_call>
3651
- {"name": "<function-name>", "arguments": <args-dict>}
3652
- </tool_call>`;
3653
- }
3695
+ protocol: jsonProtocol({}),
3696
+ toolSystemPromptTemplate: hermesSystemPromptTemplate,
3697
+ toolResponsePromptTemplate: formatToolResponseAsJsonInXml
3654
3698
  });
3655
- var morphXmlToolMiddleware = createToolMiddleware({
3656
- protocol: morphXmlProtocol,
3657
- placement: "first",
3658
- toolSystemPromptTemplate(tools) {
3659
- return `# Tools
3660
-
3661
- You may call one or more functions to assist with the user query.
3662
-
3663
- You are provided with function signatures within <tools></tools> XML tags:
3664
- <tools>${tools}</tools>
3665
-
3666
- # Rules
3667
- - Use exactly one XML element whose tag name is the function name.
3668
- - Put each parameter as a child element.
3669
- - Values must follow the schema exactly (numbers, arrays, objects, enums \u2192 copy as-is).
3670
- - Do not add or remove functions or parameters.
3671
- - Each required parameter must appear once.
3672
- - Output nothing before or after the function call.
3673
- - After calling a tool, you will receive a response in the format: <tool_response><tool_name>NAME</tool_name><result>RESULT</result></tool_response>. Use this result to answer the user.
3674
-
3675
- # Example
3676
- <get_weather>
3677
- <location>New York</location>
3678
- <unit>celsius</unit>
3679
- </get_weather>`;
3680
- }
3699
+ var xmlToolMiddleware = createToolMiddleware({
3700
+ protocol: xmlProtocol({}),
3701
+ toolSystemPromptTemplate: xmlSystemPromptTemplate,
3702
+ toolResponsePromptTemplate: formatToolResponseAsXml
3681
3703
  });
3682
- var orchestratorToolMiddleware = createToolMiddleware({
3683
- protocol: yamlXmlProtocol(),
3684
- placement: "first",
3685
- toolSystemPromptTemplate: orchestratorSystemPromptTemplate
3704
+ var yamlToolMiddleware = createToolMiddleware({
3705
+ protocol: yamlProtocol({}),
3706
+ toolSystemPromptTemplate: yamlSystemPromptTemplate,
3707
+ toolResponsePromptTemplate: formatToolResponseAsXml
3686
3708
  });
3687
3709
 
3688
3710
  // src/community/sijawara.ts
3689
3711
  var sijawaraDetailedXmlToolMiddleware = createToolMiddleware({
3690
- protocol: morphXmlProtocol,
3712
+ protocol: xmlProtocol,
3691
3713
  toolSystemPromptTemplate(tools) {
3714
+ const toolsJson = JSON.stringify(tools);
3692
3715
  return `You have access to callable functions (tools).
3693
3716
  Tool list/context:
3694
- ${tools}
3717
+ ${toolsJson}
3695
3718
 
3696
3719
  ===============================
3697
3720
  TOOL CALLING FORMAT
@@ -3743,11 +3766,12 @@ var sijawaraDetailedXmlToolMiddleware = createToolMiddleware({
3743
3766
  }
3744
3767
  });
3745
3768
  var sijawaraConciseXmlToolMiddleware = createToolMiddleware({
3746
- protocol: morphXmlProtocol,
3769
+ protocol: xmlProtocol,
3747
3770
  toolSystemPromptTemplate(tools) {
3771
+ const toolsJson = JSON.stringify(tools);
3748
3772
  return `You have access to callable functions (tools).
3749
3773
  Tool list/context:
3750
- ${tools}
3774
+ ${toolsJson}
3751
3775
 
3752
3776
  STRICT CALLING RULES:
3753
3777
  - Use the XML-like format for tool calls: