@copilotkit/shared 0.37.0 → 0.38.0-beta.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.
Files changed (80) hide show
  1. package/.turbo/turbo-build.log +73 -106
  2. package/CHANGELOG.md +6 -0
  3. package/dist/{chunk-QVD5GLKQ.mjs → chunk-2VLE6D3W.mjs} +1 -1
  4. package/dist/chunk-2VLE6D3W.mjs.map +1 -0
  5. package/dist/chunk-CIPF7PMC.mjs +80 -0
  6. package/dist/chunk-CIPF7PMC.mjs.map +1 -0
  7. package/dist/chunk-CYDWEPFL.mjs +1 -0
  8. package/dist/constants/index.d.ts +0 -2
  9. package/dist/constants/index.js +2 -9
  10. package/dist/constants/index.js.map +1 -1
  11. package/dist/constants/index.mjs +2 -6
  12. package/dist/index.d.ts +2 -6
  13. package/dist/index.js +79 -371
  14. package/dist/index.js.map +1 -1
  15. package/dist/index.mjs +11 -43
  16. package/dist/types/index.d.ts +1 -1
  17. package/dist/types/openai-assistant.d.ts +7 -46
  18. package/dist/types/openai-assistant.js.map +1 -1
  19. package/dist/utils/index.d.ts +1 -4
  20. package/dist/utils/index.js +80 -367
  21. package/dist/utils/index.js.map +1 -1
  22. package/dist/utils/index.mjs +6 -34
  23. package/dist/utils/json-schema.d.ts +30 -0
  24. package/dist/utils/json-schema.js +104 -0
  25. package/dist/utils/json-schema.js.map +1 -0
  26. package/dist/utils/json-schema.mjs +7 -0
  27. package/package.json +4 -4
  28. package/src/constants/index.ts +0 -1
  29. package/src/types/openai-assistant.ts +7 -54
  30. package/src/utils/index.ts +1 -4
  31. package/src/utils/json-schema.ts +120 -0
  32. package/dist/chunk-3ZU7SB62.mjs +0 -7
  33. package/dist/chunk-3ZU7SB62.mjs.map +0 -1
  34. package/dist/chunk-4MTSDAP6.mjs +0 -32
  35. package/dist/chunk-4MTSDAP6.mjs.map +0 -1
  36. package/dist/chunk-CBF2BIA7.mjs +0 -116
  37. package/dist/chunk-CBF2BIA7.mjs.map +0 -1
  38. package/dist/chunk-DBW3BY7E.mjs +0 -157
  39. package/dist/chunk-DBW3BY7E.mjs.map +0 -1
  40. package/dist/chunk-HW4V75UQ.mjs +0 -60
  41. package/dist/chunk-HW4V75UQ.mjs.map +0 -1
  42. package/dist/chunk-QVD5GLKQ.mjs.map +0 -1
  43. package/dist/chunk-UAPRMZEY.mjs +0 -1
  44. package/dist/constants/copilot-protocol.d.ts +0 -3
  45. package/dist/constants/copilot-protocol.js +0 -31
  46. package/dist/constants/copilot-protocol.js.map +0 -1
  47. package/dist/constants/copilot-protocol.mjs +0 -7
  48. package/dist/utils/decode-chat-completion-as-text.d.ts +0 -7
  49. package/dist/utils/decode-chat-completion-as-text.js +0 -56
  50. package/dist/utils/decode-chat-completion-as-text.js.map +0 -1
  51. package/dist/utils/decode-chat-completion-as-text.mjs +0 -7
  52. package/dist/utils/decode-chat-completion-as-text.mjs.map +0 -1
  53. package/dist/utils/decode-chat-completion.d.ts +0 -27
  54. package/dist/utils/decode-chat-completion.js +0 -140
  55. package/dist/utils/decode-chat-completion.js.map +0 -1
  56. package/dist/utils/decode-chat-completion.mjs +0 -7
  57. package/dist/utils/decode-chat-completion.mjs.map +0 -1
  58. package/dist/utils/parse-chat-completion.d.ts +0 -30
  59. package/dist/utils/parse-chat-completion.js +0 -84
  60. package/dist/utils/parse-chat-completion.js.map +0 -1
  61. package/dist/utils/parse-chat-completion.mjs +0 -7
  62. package/dist/utils/parse-chat-completion.mjs.map +0 -1
  63. package/dist/utils/utils.d.ts +0 -103
  64. package/dist/utils/utils.js +0 -189
  65. package/dist/utils/utils.js.map +0 -1
  66. package/dist/utils/utils.mjs +0 -23
  67. package/dist/utils/utils.mjs.map +0 -1
  68. package/dist/utils/utils.test.d.ts +0 -2
  69. package/dist/utils/utils.test.js +0 -9
  70. package/dist/utils/utils.test.js.map +0 -1
  71. package/dist/utils/utils.test.mjs +0 -7
  72. package/dist/utils/utils.test.mjs.map +0 -1
  73. package/src/constants/copilot-protocol.ts +0 -1
  74. package/src/utils/decode-chat-completion-as-text.ts +0 -33
  75. package/src/utils/decode-chat-completion.ts +0 -169
  76. package/src/utils/parse-chat-completion.ts +0 -112
  77. package/src/utils/utils.test.ts +0 -7
  78. package/src/utils/utils.ts +0 -298
  79. /package/dist/{chunk-UAPRMZEY.mjs.map → chunk-CYDWEPFL.mjs.map} +0 -0
  80. /package/dist/{constants/copilot-protocol.mjs.map → utils/json-schema.mjs.map} +0 -0
@@ -1,4 +1,4 @@
1
- export { AssistantMessage, FunctionCall, FunctionCallHandler, FunctionDefinition, JSONValue, Message, Role, ToolDefinition } from './openai-assistant.js';
1
+ export { AssistantMessage, FunctionCallHandler, FunctionCallHandlerArguments, FunctionDefinition, JSONValue, ToolDefinition } from './openai-assistant.js';
2
2
  export { AnnotatedFunction, AnnotatedFunctionArgument, AnnotatedFunctionArrayArgument, AnnotatedFunctionSimpleArgument } from './annotated-function.js';
3
3
  export { Action, MappedParameterTypes, Parameter } from './action.js';
4
4
  export { CopilotCloudConfig } from './copilot-cloud-config.js';
@@ -1,47 +1,3 @@
1
- type Role = "system" | "user" | "assistant" | "function";
2
- interface FunctionCall {
3
- /**
4
- * The arguments to call the function with, as generated by the model in JSON
5
- * format. Note that the model does not always generate valid JSON, and may
6
- * hallucinate parameters not defined by your function schema. Validate the
7
- * arguments in your code before calling your function.
8
- */
9
- arguments?: string;
10
- /**
11
- * The name of the function to call.
12
- */
13
- name?: string;
14
- /**
15
- * Temporarily add scope to the function call.
16
- */
17
- scope?: "client" | "server";
18
- }
19
- /**
20
- * Shared types between the API and UI packages.
21
- */
22
- interface Message {
23
- id: string;
24
- createdAt?: Date;
25
- content: string;
26
- ui?: string | null | undefined;
27
- role: Role;
28
- /**
29
- * If the message has a role of `function`, the `name` field is the name of the function.
30
- * Otherwise, the name field should not be set.
31
- */
32
- name?: string;
33
- /**
34
- * If the assistant role makes a function call, the `function_call` field
35
- * contains the function call name and arguments. Otherwise, the field should
36
- * not be set.
37
- */
38
- function_call?: FunctionCall;
39
- /**
40
- * Partial function call contains the function call name and arguments as they are
41
- * streamed from the model. This is used to display the function call in the UI.
42
- */
43
- partialFunctionCall?: FunctionCall;
44
- }
45
1
  interface FunctionDefinition {
46
2
  /**
47
3
  * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain
@@ -68,7 +24,12 @@ interface ToolDefinition {
68
24
  type: "function";
69
25
  function: FunctionDefinition;
70
26
  }
71
- type FunctionCallHandler = (chatMessages: Message[], functionCall: FunctionCall) => Promise<any>;
27
+ interface FunctionCallHandlerArguments {
28
+ messages: any[];
29
+ name: string;
30
+ args: any;
31
+ }
32
+ type FunctionCallHandler = (args: FunctionCallHandlerArguments) => Promise<any>;
72
33
  type AssistantMessage = {
73
34
  id: string;
74
35
  role: "assistant";
@@ -83,4 +44,4 @@ type JSONValue = null | string | number | boolean | {
83
44
  [x: string]: JSONValue;
84
45
  } | Array<JSONValue>;
85
46
 
86
- export { AssistantMessage, FunctionCall, FunctionCallHandler, FunctionDefinition, JSONValue, Message, Role, ToolDefinition };
47
+ export { AssistantMessage, FunctionCallHandler, FunctionCallHandlerArguments, FunctionDefinition, JSONValue, ToolDefinition };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types/openai-assistant.ts"],"sourcesContent":["export type Role = \"system\" | \"user\" | \"assistant\" | \"function\";\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments?: string;\n\n /**\n * The name of the function to call.\n */\n name?: string;\n\n /**\n * Temporarily add scope to the function call.\n */\n scope?: \"client\" | \"server\";\n}\n\n/**\n * Shared types between the API and UI packages.\n */\nexport interface Message {\n id: string;\n createdAt?: Date;\n content: string;\n ui?: string | null | undefined;\n role: Role;\n /**\n * If the message has a role of `function`, the `name` field is the name of the function.\n * Otherwise, the name field should not be set.\n */\n name?: string;\n /**\n * If the assistant role makes a function call, the `function_call` field\n * contains the function call name and arguments. Otherwise, the field should\n * not be set.\n */\n function_call?: FunctionCall;\n\n /**\n * Partial function call contains the function call name and arguments as they are\n * streamed from the model. This is used to display the function call in the UI.\n */\n partialFunctionCall?: FunctionCall;\n}\n\nexport interface FunctionDefinition {\n /**\n * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain\n * underscores and dashes, with a maximum length of 64.\n */\n name: string;\n /**\n * The parameters the functions accepts, described as a JSON Schema object. See the\n * [guide](/docs/guides/gpt/function-calling) for examples, and the\n * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for\n * documentation about the format.\n *\n * To describe a function that accepts no parameters, provide the value\n * `{\"type\": \"object\", \"properties\": {}}`.\n */\n parameters: Record<string, unknown>;\n /**\n * A description of what the function does, used by the model to choose when and\n * how to call the function.\n */\n description?: string;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: FunctionDefinition;\n}\n\nexport type FunctionCallHandler = (\n chatMessages: Message[],\n functionCall: FunctionCall,\n) => Promise<any>;\n\nexport type AssistantMessage = {\n id: string;\n role: \"assistant\";\n content: Array<{\n type: \"text\";\n text: {\n value: string;\n };\n }>;\n};\n\nexport type JSONValue =\n | null\n | string\n | number\n | boolean\n | { [x: string]: JSONValue }\n | Array<JSONValue>;\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../../src/types/openai-assistant.ts"],"sourcesContent":["export interface FunctionDefinition {\n /**\n * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain\n * underscores and dashes, with a maximum length of 64.\n */\n name: string;\n /**\n * The parameters the functions accepts, described as a JSON Schema object. See the\n * [guide](/docs/guides/gpt/function-calling) for examples, and the\n * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for\n * documentation about the format.\n *\n * To describe a function that accepts no parameters, provide the value\n * `{\"type\": \"object\", \"properties\": {}}`.\n */\n parameters: Record<string, unknown>;\n /**\n * A description of what the function does, used by the model to choose when and\n * how to call the function.\n */\n description?: string;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: FunctionDefinition;\n}\n\nexport interface FunctionCallHandlerArguments {\n messages: any[];\n name: string;\n args: any;\n}\n\nexport type FunctionCallHandler = (args: FunctionCallHandlerArguments) => Promise<any>;\n\nexport type AssistantMessage = {\n id: string;\n role: \"assistant\";\n content: Array<{\n type: \"text\";\n text: {\n value: string;\n };\n }>;\n};\n\nexport type JSONValue =\n | null\n | string\n | number\n | boolean\n | { [x: string]: JSONValue }\n | Array<JSONValue>;\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -1,8 +1,5 @@
1
- export { COMPLEX_HEADER, StreamPart, StreamPartType, StreamString, StreamStringPrefixes, decodeResult, encodeResult, formatStreamPart, isStreamStringEqualToType, parseStreamPart, streamPartsByCode, validCodes } from './utils.js';
2
- export { ChatCompletionChunk, ToolCallFunctionCall, ToolCallPayload, parseChatCompletion } from './parse-chat-completion.js';
3
- export { ChatCompletionContentEvent, ChatCompletionEvent, ChatCompletionFunctionEvent, ChatCompletionPartialEvent, ChatCompletionResultEvent, decodeChatCompletion } from './decode-chat-completion.js';
4
- export { decodeChatCompletionAsText } from './decode-chat-completion-as-text.js';
5
1
  export { actionToChatCompletionFunction, annotatedFunctionToAction, annotatedFunctionToChatCompletionFunction } from './annotated-function.js';
2
+ export { JSONSchema, JSONSchemaArray, JSONSchemaBoolean, JSONSchemaNumber, JSONSchemaObject, JSONSchemaString, actionParametersToJsonSchema } from './json-schema.js';
6
3
  import '../types/openai-assistant.js';
7
4
  import '../types/annotated-function.js';
8
5
  import '../types/action.js';
@@ -20,365 +20,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/utils/index.ts
21
21
  var utils_exports = {};
22
22
  __export(utils_exports, {
23
- COMPLEX_HEADER: () => COMPLEX_HEADER,
24
- StreamStringPrefixes: () => StreamStringPrefixes,
23
+ actionParametersToJsonSchema: () => actionParametersToJsonSchema,
25
24
  actionToChatCompletionFunction: () => actionToChatCompletionFunction,
26
25
  annotatedFunctionToAction: () => annotatedFunctionToAction,
27
- annotatedFunctionToChatCompletionFunction: () => annotatedFunctionToChatCompletionFunction,
28
- decodeChatCompletion: () => decodeChatCompletion,
29
- decodeChatCompletionAsText: () => decodeChatCompletionAsText,
30
- decodeResult: () => decodeResult,
31
- encodeResult: () => encodeResult,
32
- formatStreamPart: () => formatStreamPart,
33
- isStreamStringEqualToType: () => isStreamStringEqualToType,
34
- parseChatCompletion: () => parseChatCompletion,
35
- parseStreamPart: () => parseStreamPart,
36
- streamPartsByCode: () => streamPartsByCode,
37
- validCodes: () => validCodes
26
+ annotatedFunctionToChatCompletionFunction: () => annotatedFunctionToChatCompletionFunction
38
27
  });
39
28
  module.exports = __toCommonJS(utils_exports);
40
29
 
41
- // src/utils/utils.ts
42
- function encodeResult(result) {
43
- if (result === void 0) {
44
- return "";
45
- } else if (typeof result === "string") {
46
- return result;
47
- } else {
48
- return JSON.stringify(result);
49
- }
50
- }
51
- function decodeResult(result) {
52
- try {
53
- return JSON.parse(result);
54
- } catch (e) {
55
- return result;
56
- }
57
- }
58
- var textStreamPart = {
59
- code: "0",
60
- name: "text",
61
- parse: (value) => {
62
- if (typeof value !== "string") {
63
- throw new Error('"text" parts expect a string value.');
64
- }
65
- return { type: "text", value };
66
- }
67
- };
68
- var functionCallStreamPart = {
69
- code: "1",
70
- name: "function_call",
71
- parse: (value) => {
72
- if (value == null || typeof value !== "object" || !("function_call" in value) || typeof value.function_call !== "object" || value.function_call == null || !("name" in value.function_call) || !("arguments" in value.function_call) || typeof value.function_call.name !== "string" || typeof value.function_call.arguments !== "string") {
73
- throw new Error('"function_call" parts expect an object with a "function_call" property.');
74
- }
75
- return {
76
- type: "function_call",
77
- value
78
- };
79
- }
80
- };
81
- var dataStreamPart = {
82
- code: "2",
83
- name: "data",
84
- parse: (value) => {
85
- if (!Array.isArray(value)) {
86
- throw new Error('"data" parts expect an array value.');
87
- }
88
- return { type: "data", value };
89
- }
90
- };
91
- var errorStreamPart = {
92
- code: "3",
93
- name: "error",
94
- parse: (value) => {
95
- if (typeof value !== "string") {
96
- throw new Error('"error" parts expect a string value.');
97
- }
98
- return { type: "error", value };
99
- }
100
- };
101
- var assistantMessage = {
102
- code: "4",
103
- name: "assistant_message",
104
- parse: (value) => {
105
- if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every(
106
- (item) => item != null && typeof item === "object" && "type" in item && item.type === "text" && "text" in item && item.text != null && typeof item.text === "object" && "value" in item.text && typeof item.text.value === "string"
107
- )) {
108
- throw new Error(
109
- '"assistant_message" parts expect an object with an "id", "role", and "content" property.'
110
- );
111
- }
112
- return {
113
- type: "assistant_message",
114
- value
115
- };
116
- }
117
- };
118
- var assistantControlData = {
119
- code: "5",
120
- name: "assistant_control_data",
121
- parse: (value) => {
122
- if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
123
- throw new Error(
124
- '"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
125
- );
126
- }
127
- return {
128
- type: "assistant_control_data",
129
- value: {
130
- threadId: value.threadId,
131
- messageId: value.messageId
132
- }
133
- };
134
- }
135
- };
136
- var streamParts = [
137
- textStreamPart,
138
- functionCallStreamPart,
139
- dataStreamPart,
140
- errorStreamPart,
141
- assistantMessage,
142
- assistantControlData
143
- ];
144
- var streamPartsByCode = {
145
- [textStreamPart.code]: textStreamPart,
146
- [functionCallStreamPart.code]: functionCallStreamPart,
147
- [dataStreamPart.code]: dataStreamPart,
148
- [errorStreamPart.code]: errorStreamPart,
149
- [assistantMessage.code]: assistantMessage,
150
- [assistantControlData.code]: assistantControlData
151
- };
152
- var StreamStringPrefixes = {
153
- [textStreamPart.name]: textStreamPart.code,
154
- [functionCallStreamPart.name]: functionCallStreamPart.code,
155
- [dataStreamPart.name]: dataStreamPart.code,
156
- [errorStreamPart.name]: errorStreamPart.code,
157
- [assistantMessage.name]: assistantMessage.code,
158
- [assistantControlData.name]: assistantControlData.code
159
- };
160
- var validCodes = streamParts.map((part) => part.code);
161
- var parseStreamPart = (line) => {
162
- const firstSeparatorIndex = line.indexOf(":");
163
- if (firstSeparatorIndex === -1) {
164
- throw new Error("Failed to parse stream string. No separator found.");
165
- }
166
- const prefix = line.slice(0, firstSeparatorIndex);
167
- if (!validCodes.includes(prefix)) {
168
- throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
169
- }
170
- const code = prefix;
171
- const textValue = line.slice(firstSeparatorIndex + 1);
172
- const jsonValue = JSON.parse(textValue);
173
- return streamPartsByCode[code].parse(jsonValue);
174
- };
175
- function formatStreamPart(type, value) {
176
- const streamPart = streamParts.find((part) => part.name === type);
177
- if (!streamPart) {
178
- throw new Error(`Invalid stream part type: ${type}`);
179
- }
180
- return `${streamPart.code}:${JSON.stringify(value)}
181
- `;
182
- }
183
- var isStreamStringEqualToType = (type, value) => value.startsWith(`${StreamStringPrefixes[type]}:`) && value.endsWith("\n");
184
- var COMPLEX_HEADER = "X-Experimental-Stream-Data";
185
-
186
- // src/utils/parse-chat-completion.ts
187
- function parseChatCompletion(stream) {
188
- const reader = stream.getReader();
189
- let buffer = new Uint8Array();
190
- async function cleanup(controller) {
191
- if (controller) {
192
- try {
193
- controller.close();
194
- } catch (_) {
195
- }
196
- }
197
- if (reader) {
198
- try {
199
- await reader.cancel();
200
- } catch (_) {
201
- }
202
- }
203
- }
204
- return new ReadableStream({
205
- async pull(controller) {
206
- while (true) {
207
- try {
208
- const { done, value } = await reader.read();
209
- if (done) {
210
- await cleanup(controller);
211
- return;
212
- }
213
- const newBuffer = new Uint8Array(buffer.length + value.length);
214
- newBuffer.set(buffer);
215
- newBuffer.set(value, buffer.length);
216
- buffer = newBuffer;
217
- const valueString = new TextDecoder("utf-8").decode(buffer);
218
- const lines = valueString.split("\n").filter((line) => line.trim() !== "");
219
- buffer = !valueString.endsWith("\n") ? new TextEncoder().encode(lines.pop() || "") : new Uint8Array();
220
- for (const line of lines) {
221
- const cleanedLine = line.replace(/^data: /, "");
222
- if (cleanedLine === "[DONE]") {
223
- await cleanup(controller);
224
- return;
225
- }
226
- const json = JSON.parse(cleanedLine);
227
- controller.enqueue(json);
228
- }
229
- } catch (error) {
230
- controller.error(error);
231
- await cleanup(controller);
232
- return;
233
- }
234
- }
235
- },
236
- cancel() {
237
- reader.cancel();
238
- }
239
- });
240
- }
241
-
242
- // src/utils/decode-chat-completion.ts
243
- function decodeChatCompletion(stream) {
244
- const reader = stream.getReader();
245
- let mode = null;
246
- let functionCallName = "";
247
- let functionCallArguments = "";
248
- let functionCallScope = "client";
249
- async function cleanup(controller) {
250
- if (controller) {
251
- try {
252
- controller.close();
253
- } catch (_) {
254
- }
255
- }
256
- if (reader) {
257
- try {
258
- await reader.cancel();
259
- } catch (_) {
260
- }
261
- }
262
- }
263
- return new ReadableStream({
264
- async pull(controller) {
265
- var _a, _b, _c, _d, _e, _f;
266
- const flushFunctionCall = () => {
267
- let args = null;
268
- try {
269
- args = JSON.parse(functionCallArguments);
270
- } catch (error) {
271
- cleanup(controller);
272
- controller.error(error);
273
- return false;
274
- }
275
- controller.enqueue({
276
- type: "function",
277
- name: functionCallName,
278
- arguments: args,
279
- scope: functionCallScope
280
- });
281
- mode = null;
282
- functionCallName = "";
283
- functionCallArguments = "";
284
- return true;
285
- };
286
- while (true) {
287
- try {
288
- const { done, value } = await reader.read();
289
- if (done) {
290
- if ((mode == null ? void 0 : mode.type) === "function") {
291
- flushFunctionCall();
292
- }
293
- await cleanup(controller);
294
- return;
295
- }
296
- if ((mode == null ? void 0 : mode.type) === "function" && (!((_b = (_a = value.choices[0].delta.tool_calls) == null ? void 0 : _a[0]) == null ? void 0 : _b.function) || ((_d = (_c = value.choices[0].delta.tool_calls) == null ? void 0 : _c[0]) == null ? void 0 : _d.function.name))) {
297
- if (!flushFunctionCall()) {
298
- return;
299
- }
300
- }
301
- const maybeFunctionCall = (_f = (_e = value.choices[0].delta.tool_calls) == null ? void 0 : _e[0]) == null ? void 0 : _f.function;
302
- if (maybeFunctionCall) {
303
- mode = { type: "function", function: maybeFunctionCall };
304
- } else {
305
- mode = { type: "message" };
306
- }
307
- if (mode.type === "message") {
308
- if (value.choices[0].delta.role === "function") {
309
- controller.enqueue({
310
- type: "result",
311
- content: value.choices[0].delta.content,
312
- name: value.choices[0].delta.name
313
- });
314
- } else if (value.choices[0].delta.content) {
315
- controller.enqueue({
316
- type: "content",
317
- content: value.choices[0].delta.content
318
- });
319
- }
320
- continue;
321
- } else if (mode.type === "function") {
322
- const maybeFunctionCallName = mode.function.name;
323
- if (maybeFunctionCallName) {
324
- functionCallName = maybeFunctionCallName;
325
- }
326
- const maybeFunctionCallArguments = mode.function.arguments;
327
- if (maybeFunctionCallArguments) {
328
- functionCallArguments += maybeFunctionCallArguments;
329
- }
330
- const maybeFunctionCallScope = mode.function.scope;
331
- if (maybeFunctionCallScope) {
332
- functionCallScope = maybeFunctionCallScope;
333
- }
334
- controller.enqueue({
335
- type: "partial",
336
- name: functionCallName,
337
- arguments: functionCallArguments
338
- });
339
- continue;
340
- }
341
- } catch (error) {
342
- controller.error(error);
343
- await cleanup(controller);
344
- return;
345
- }
346
- }
347
- },
348
- cancel() {
349
- reader.cancel();
350
- }
351
- });
352
- }
353
-
354
- // src/utils/decode-chat-completion-as-text.ts
355
- function decodeChatCompletionAsText(stream) {
356
- const reader = stream.getReader();
357
- return new ReadableStream({
358
- async pull(controller) {
359
- while (true) {
360
- try {
361
- const { done, value } = await reader.read();
362
- if (done) {
363
- controller.close();
364
- return;
365
- }
366
- if (value.type === "content") {
367
- controller.enqueue(value.content);
368
- continue;
369
- }
370
- } catch (error) {
371
- controller.error(error);
372
- return;
373
- }
374
- }
375
- },
376
- cancel() {
377
- reader.cancel();
378
- }
379
- });
380
- }
381
-
382
30
  // src/utils/annotated-function.ts
383
31
  function annotatedFunctionToChatCompletionFunction(annotatedFunction) {
384
32
  let parameters = {};
@@ -535,22 +183,87 @@ function annotatedFunctionToAction(annotatedFunction) {
535
183
  }
536
184
  };
537
185
  }
186
+
187
+ // src/utils/json-schema.ts
188
+ function actionParametersToJsonSchema(actionParameters) {
189
+ let parameters = {};
190
+ for (let parameter of actionParameters || []) {
191
+ parameters[parameter.name] = convertAttribute2(parameter);
192
+ }
193
+ let requiredParameterNames = [];
194
+ for (let arg of actionParameters || []) {
195
+ if (arg.required !== false) {
196
+ requiredParameterNames.push(arg.name);
197
+ }
198
+ }
199
+ return {
200
+ type: "object",
201
+ properties: parameters,
202
+ required: requiredParameterNames
203
+ };
204
+ }
205
+ function convertAttribute2(attribute) {
206
+ var _a, _b, _c;
207
+ switch (attribute.type) {
208
+ case "string":
209
+ return {
210
+ type: "string",
211
+ description: attribute.description,
212
+ ...attribute.enum && { enum: attribute.enum }
213
+ };
214
+ case "number":
215
+ case "boolean":
216
+ return {
217
+ type: attribute.type,
218
+ description: attribute.description
219
+ };
220
+ case "object":
221
+ case "object[]":
222
+ const properties = (_a = attribute.attributes) == null ? void 0 : _a.reduce(
223
+ (acc, attr) => {
224
+ acc[attr.name] = convertAttribute2(attr);
225
+ return acc;
226
+ },
227
+ {}
228
+ );
229
+ const required = (_b = attribute.attributes) == null ? void 0 : _b.filter((attr) => attr.required !== false).map((attr) => attr.name);
230
+ if (attribute.type === "object[]") {
231
+ return {
232
+ type: "array",
233
+ items: {
234
+ type: "object",
235
+ ...properties && { properties },
236
+ ...required && required.length > 0 && { required }
237
+ },
238
+ description: attribute.description
239
+ };
240
+ }
241
+ return {
242
+ type: "object",
243
+ description: attribute.description,
244
+ ...properties && { properties },
245
+ ...required && required.length > 0 && { required }
246
+ };
247
+ default:
248
+ if ((_c = attribute.type) == null ? void 0 : _c.endsWith("[]")) {
249
+ const itemType = attribute.type.slice(0, -2);
250
+ return {
251
+ type: "array",
252
+ items: { type: itemType },
253
+ description: attribute.description
254
+ };
255
+ }
256
+ return {
257
+ type: "string",
258
+ description: attribute.description
259
+ };
260
+ }
261
+ }
538
262
  // Annotate the CommonJS export names for ESM import in node:
539
263
  0 && (module.exports = {
540
- COMPLEX_HEADER,
541
- StreamStringPrefixes,
264
+ actionParametersToJsonSchema,
542
265
  actionToChatCompletionFunction,
543
266
  annotatedFunctionToAction,
544
- annotatedFunctionToChatCompletionFunction,
545
- decodeChatCompletion,
546
- decodeChatCompletionAsText,
547
- decodeResult,
548
- encodeResult,
549
- formatStreamPart,
550
- isStreamStringEqualToType,
551
- parseChatCompletion,
552
- parseStreamPart,
553
- streamPartsByCode,
554
- validCodes
267
+ annotatedFunctionToChatCompletionFunction
555
268
  });
556
269
  //# sourceMappingURL=index.js.map