@copilotkit/shared 0.2.0-alpha.3 → 0.2.0-alpha.4

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 (72) hide show
  1. package/.turbo/turbo-build.log +86 -33
  2. package/CHANGELOG.md +31 -4
  3. package/dist/chunk-4MTSDAP6.mjs +31 -0
  4. package/dist/chunk-4MTSDAP6.mjs.map +1 -0
  5. package/dist/chunk-FD6FGKYY.mjs +3 -0
  6. package/dist/chunk-GFCJUF6J.mjs +95 -0
  7. package/dist/chunk-GFCJUF6J.mjs.map +1 -0
  8. package/dist/chunk-L46AW3ET.mjs +28 -0
  9. package/dist/chunk-L46AW3ET.mjs.map +1 -0
  10. package/dist/chunk-UAPRMZEY.mjs +3 -0
  11. package/dist/chunk-W6NBBCWB.mjs +59 -0
  12. package/dist/chunk-W6NBBCWB.mjs.map +1 -0
  13. package/dist/chunk-YBHX4Y25.mjs +3 -0
  14. package/dist/chunk-YBHX4Y25.mjs.map +1 -0
  15. package/dist/index.d.ts +6 -1
  16. package/dist/index.js +345 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/index.mjs +7 -2
  19. package/dist/types/annotated-function.d.ts +24 -0
  20. package/dist/types/annotated-function.js +4 -0
  21. package/dist/types/annotated-function.js.map +1 -0
  22. package/dist/types/annotated-function.mjs +3 -0
  23. package/dist/types/annotated-function.mjs.map +1 -0
  24. package/dist/types/index.d.ts +2 -1
  25. package/dist/types/index.js +4 -0
  26. package/dist/types/index.js.map +1 -0
  27. package/dist/types/index.mjs +2 -1
  28. package/dist/types/openai-assistant.d.ts +26 -2
  29. package/dist/types/openai-assistant.js +4 -0
  30. package/dist/types/openai-assistant.js.map +1 -0
  31. package/dist/utils/annotated-function.d.ts +6 -0
  32. package/dist/utils/annotated-function.js +30 -0
  33. package/dist/utils/annotated-function.js.map +1 -0
  34. package/dist/utils/annotated-function.mjs +3 -0
  35. package/dist/utils/annotated-function.mjs.map +1 -0
  36. package/dist/utils/decode-chat-completion-as-text.d.ts +7 -0
  37. package/dist/utils/decode-chat-completion-as-text.js +33 -0
  38. package/dist/utils/decode-chat-completion-as-text.js.map +1 -0
  39. package/dist/utils/decode-chat-completion-as-text.mjs +3 -0
  40. package/dist/utils/decode-chat-completion-as-text.mjs.map +1 -0
  41. package/dist/utils/decode-chat-completion.d.ts +21 -0
  42. package/dist/utils/decode-chat-completion.js +97 -0
  43. package/dist/utils/decode-chat-completion.js.map +1 -0
  44. package/dist/utils/decode-chat-completion.mjs +3 -0
  45. package/dist/utils/decode-chat-completion.mjs.map +1 -0
  46. package/dist/utils/index.d.ts +5 -0
  47. package/dist/utils/index.js +345 -0
  48. package/dist/utils/index.js.map +1 -0
  49. package/dist/utils/index.mjs +5 -1
  50. package/dist/utils/parse-chat-completion.d.ts +17 -0
  51. package/dist/utils/parse-chat-completion.js +61 -0
  52. package/dist/utils/parse-chat-completion.js.map +1 -0
  53. package/dist/utils/parse-chat-completion.mjs +3 -0
  54. package/dist/utils/parse-chat-completion.mjs.map +1 -0
  55. package/dist/utils/utils.js +140 -0
  56. package/dist/utils/utils.js.map +1 -0
  57. package/dist/utils/utils.test.js +10 -0
  58. package/dist/utils/utils.test.js.map +1 -0
  59. package/package.json +8 -6
  60. package/src/types/annotated-function.ts +27 -0
  61. package/src/types/index.ts +1 -0
  62. package/src/types/openai-assistant.ts +31 -1
  63. package/src/utils/annotated-function.ts +33 -0
  64. package/src/utils/decode-chat-completion-as-text.ts +33 -0
  65. package/src/utils/decode-chat-completion.ts +127 -0
  66. package/src/utils/index.ts +4 -0
  67. package/src/utils/parse-chat-completion.ts +84 -0
  68. package/tsup.config.ts +1 -2
  69. package/dist/chunk-YJLRG5U3.mjs +0 -3
  70. package/dist/chunk-YPBKY4KY.mjs +0 -3
  71. /package/dist/{chunk-YJLRG5U3.mjs.map → chunk-FD6FGKYY.mjs.map} +0 -0
  72. /package/dist/{chunk-YPBKY4KY.mjs.map → chunk-UAPRMZEY.mjs.map} +0 -0
@@ -0,0 +1,140 @@
1
+ 'use strict';
2
+
3
+ // src/utils/utils.ts
4
+ var textStreamPart = {
5
+ code: "0",
6
+ name: "text",
7
+ parse: (value) => {
8
+ if (typeof value !== "string") {
9
+ throw new Error('"text" parts expect a string value.');
10
+ }
11
+ return { type: "text", value };
12
+ }
13
+ };
14
+ var functionCallStreamPart = {
15
+ code: "1",
16
+ name: "function_call",
17
+ parse: (value) => {
18
+ 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") {
19
+ throw new Error('"function_call" parts expect an object with a "function_call" property.');
20
+ }
21
+ return {
22
+ type: "function_call",
23
+ value
24
+ };
25
+ }
26
+ };
27
+ var dataStreamPart = {
28
+ code: "2",
29
+ name: "data",
30
+ parse: (value) => {
31
+ if (!Array.isArray(value)) {
32
+ throw new Error('"data" parts expect an array value.');
33
+ }
34
+ return { type: "data", value };
35
+ }
36
+ };
37
+ var errorStreamPart = {
38
+ code: "3",
39
+ name: "error",
40
+ parse: (value) => {
41
+ if (typeof value !== "string") {
42
+ throw new Error('"error" parts expect a string value.');
43
+ }
44
+ return { type: "error", value };
45
+ }
46
+ };
47
+ var assistantMessage = {
48
+ code: "4",
49
+ name: "assistant_message",
50
+ parse: (value) => {
51
+ 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(
52
+ (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"
53
+ )) {
54
+ throw new Error(
55
+ '"assistant_message" parts expect an object with an "id", "role", and "content" property.'
56
+ );
57
+ }
58
+ return {
59
+ type: "assistant_message",
60
+ value
61
+ };
62
+ }
63
+ };
64
+ var assistantControlData = {
65
+ code: "5",
66
+ name: "assistant_control_data",
67
+ parse: (value) => {
68
+ if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
69
+ throw new Error(
70
+ '"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
71
+ );
72
+ }
73
+ return {
74
+ type: "assistant_control_data",
75
+ value: {
76
+ threadId: value.threadId,
77
+ messageId: value.messageId
78
+ }
79
+ };
80
+ }
81
+ };
82
+ var streamParts = [
83
+ textStreamPart,
84
+ functionCallStreamPart,
85
+ dataStreamPart,
86
+ errorStreamPart,
87
+ assistantMessage,
88
+ assistantControlData
89
+ ];
90
+ var streamPartsByCode = {
91
+ [textStreamPart.code]: textStreamPart,
92
+ [functionCallStreamPart.code]: functionCallStreamPart,
93
+ [dataStreamPart.code]: dataStreamPart,
94
+ [errorStreamPart.code]: errorStreamPart,
95
+ [assistantMessage.code]: assistantMessage,
96
+ [assistantControlData.code]: assistantControlData
97
+ };
98
+ var StreamStringPrefixes = {
99
+ [textStreamPart.name]: textStreamPart.code,
100
+ [functionCallStreamPart.name]: functionCallStreamPart.code,
101
+ [dataStreamPart.name]: dataStreamPart.code,
102
+ [errorStreamPart.name]: errorStreamPart.code,
103
+ [assistantMessage.name]: assistantMessage.code,
104
+ [assistantControlData.name]: assistantControlData.code
105
+ };
106
+ var validCodes = streamParts.map((part) => part.code);
107
+ var parseStreamPart = (line) => {
108
+ const firstSeparatorIndex = line.indexOf(":");
109
+ if (firstSeparatorIndex === -1) {
110
+ throw new Error("Failed to parse stream string. No separator found.");
111
+ }
112
+ const prefix = line.slice(0, firstSeparatorIndex);
113
+ if (!validCodes.includes(prefix)) {
114
+ throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
115
+ }
116
+ const code = prefix;
117
+ const textValue = line.slice(firstSeparatorIndex + 1);
118
+ const jsonValue = JSON.parse(textValue);
119
+ return streamPartsByCode[code].parse(jsonValue);
120
+ };
121
+ function formatStreamPart(type, value) {
122
+ const streamPart = streamParts.find((part) => part.name === type);
123
+ if (!streamPart) {
124
+ throw new Error(`Invalid stream part type: ${type}`);
125
+ }
126
+ return `${streamPart.code}:${JSON.stringify(value)}
127
+ `;
128
+ }
129
+ var isStreamStringEqualToType = (type, value) => value.startsWith(`${StreamStringPrefixes[type]}:`) && value.endsWith("\n");
130
+ var COMPLEX_HEADER = "X-Experimental-Stream-Data";
131
+
132
+ exports.COMPLEX_HEADER = COMPLEX_HEADER;
133
+ exports.StreamStringPrefixes = StreamStringPrefixes;
134
+ exports.formatStreamPart = formatStreamPart;
135
+ exports.isStreamStringEqualToType = isStreamStringEqualToType;
136
+ exports.parseStreamPart = parseStreamPart;
137
+ exports.streamPartsByCode = streamPartsByCode;
138
+ exports.validCodes = validCodes;
139
+ //# sourceMappingURL=out.js.map
140
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/utils.ts"],"names":[],"mappings":";AAQA,IAAM,iBAAkD;AAAA,EACtD,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO,CAAC,UAAqB;AAC3B,QAAI,OAAO,UAAU,UAAU;AAC7B,YAAM,IAAI,MAAM,qCAAqC;AAAA,IACvD;AACA,WAAO,EAAE,MAAM,QAAQ,MAAM;AAAA,EAC/B;AACF;AASA,IAAM,yBAA4F;AAAA,EAChG,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO,CAAC,UAAqB;AAC3B,QACE,SAAS,QACT,OAAO,UAAU,YACjB,EAAE,mBAAmB,UACrB,OAAO,MAAM,kBAAkB,YAC/B,MAAM,iBAAiB,QACvB,EAAE,UAAU,MAAM,kBAClB,EAAE,eAAe,MAAM,kBACvB,OAAO,MAAM,cAAc,SAAS,YACpC,OAAO,MAAM,cAAc,cAAc,UACzC;AACA,YAAM,IAAI,MAAM,yEAAyE;AAAA,IAC3F;AAEA,WAAO;AAAA,MACL,MAAM;AAAA,MACN;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAA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AAK,MAAM,sBAAsB,CAAC;AACpD,QAAM,YAAuB,KAAK,MAAM,SAAS;AAEjD,SAAO,kBAAkB,IAAI,EAAE,MAAM,SAAS;AAChD;AAQO,SAAS,iBACd,MACA,OACc;AACd,QAAM,aAAa,YAAY,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI;AAEhE,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,MAAM,6BAA6B,MAAM;AAAA,EACrD;AAEA,SAAO,GAAG,WAAW,QAAQ,KAAK,UAAU,KAAK;AAAA;AACnD;AAEO,IAAM,4BAA4B,CACvC,MACA,UAEA,MAAM,WAAW,GAAG,qBAAqB,IAAI,IAAI,KAAK,MAAM,SAAS,IAAI;AAQpE,IAAM,iBAAiB","sourcesContent":["import { AssistantMessage, FunctionCall, JSONValue } from \"../types/openai-assistant\";\n\nexport interface StreamPart<CODE extends string, NAME extends string, TYPE> {\n code: CODE;\n name: NAME;\n parse: (value: JSONValue) => { type: NAME; value: TYPE };\n}\n\nconst textStreamPart: StreamPart<\"0\", \"text\", string> = {\n code: \"0\",\n name: \"text\",\n parse: (value: JSONValue) => {\n if (typeof value !== \"string\") {\n throw new Error('\"text\" parts expect a string value.');\n }\n return { type: \"text\", value };\n },\n};\n\n/**\n * This is a utility function that helps in parsing the stream parts.\n * It takes a JSONValue as input and returns an object with type and value.\n * The type is a string that represents the type of the stream part.\n * The value is the actual value of the stream part.\n * If the input value is not a string, it throws an error.\n */\nconst functionCallStreamPart: StreamPart<\"1\", \"function_call\", { function_call: FunctionCall }> = {\n code: \"1\",\n name: \"function_call\",\n parse: (value: JSONValue) => {\n if (\n value == null ||\n typeof value !== \"object\" ||\n !(\"function_call\" in value) ||\n typeof value.function_call !== \"object\" ||\n value.function_call == null ||\n !(\"name\" in value.function_call) ||\n !(\"arguments\" in value.function_call) ||\n typeof value.function_call.name !== \"string\" ||\n typeof value.function_call.arguments !== \"string\"\n ) {\n throw new Error('\"function_call\" parts expect an object with a \"function_call\" property.');\n }\n\n return {\n type: \"function_call\",\n value: value as unknown as { function_call: FunctionCall },\n };\n },\n};\n\nconst dataStreamPart: StreamPart<\"2\", \"data\", Array<JSONValue>> = {\n code: \"2\",\n name: \"data\",\n parse: (value: JSONValue) => {\n if (!Array.isArray(value)) {\n throw new Error('\"data\" parts expect an array value.');\n }\n\n return { type: \"data\", value };\n },\n};\n\nconst errorStreamPart: StreamPart<\"3\", \"error\", string> = {\n code: \"3\",\n name: \"error\",\n parse: (value: JSONValue) => {\n if (typeof value !== \"string\") {\n throw new Error('\"error\" parts expect a string value.');\n }\n return { type: \"error\", value };\n },\n};\n\nconst assistantMessage: StreamPart<\"4\", \"assistant_message\", AssistantMessage> = {\n code: \"4\",\n name: \"assistant_message\",\n parse: (value: JSONValue) => {\n if (\n value == null ||\n typeof value !== \"object\" ||\n !(\"id\" in value) ||\n !(\"role\" in value) ||\n !(\"content\" in value) ||\n typeof value.id !== \"string\" ||\n typeof value.role !== \"string\" ||\n value.role !== \"assistant\" ||\n !Array.isArray(value.content) ||\n !value.content.every(\n (item) =>\n item != null &&\n typeof item === \"object\" &&\n \"type\" in item &&\n item.type === \"text\" &&\n \"text\" in item &&\n item.text != null &&\n typeof item.text === \"object\" &&\n \"value\" in item.text &&\n typeof item.text.value === \"string\",\n )\n ) {\n throw new Error(\n '\"assistant_message\" parts expect an object with an \"id\", \"role\", and \"content\" property.',\n );\n }\n\n return {\n type: \"assistant_message\",\n value: value as AssistantMessage,\n };\n },\n};\n\nconst assistantControlData: StreamPart<\n \"5\",\n \"assistant_control_data\",\n {\n threadId: string;\n messageId: string;\n }\n> = {\n code: \"5\",\n name: \"assistant_control_data\",\n parse: (value: JSONValue) => {\n if (\n value == null ||\n typeof value !== \"object\" ||\n !(\"threadId\" in value) ||\n !(\"messageId\" in value) ||\n typeof value.threadId !== \"string\" ||\n typeof value.messageId !== \"string\"\n ) {\n throw new Error(\n '\"assistant_control_data\" parts expect an object with a \"threadId\" and \"messageId\" property.',\n );\n }\n\n return {\n type: \"assistant_control_data\",\n value: {\n threadId: value.threadId,\n messageId: value.messageId,\n },\n };\n },\n};\n\nconst streamParts = [\n textStreamPart,\n functionCallStreamPart,\n dataStreamPart,\n errorStreamPart,\n assistantMessage,\n assistantControlData,\n] as const;\n\n// union type of all stream parts\ntype StreamParts =\n | typeof textStreamPart\n | typeof functionCallStreamPart\n | typeof dataStreamPart\n | typeof errorStreamPart\n | typeof assistantMessage\n | typeof assistantControlData;\n\n/**\n * Maps the type of a stream part to its value type.\n */\ntype StreamPartValueType = {\n [P in StreamParts as P[\"name\"]]: ReturnType<P[\"parse\"]>[\"value\"];\n};\n\nexport type StreamPartType =\n | ReturnType<typeof textStreamPart.parse>\n | ReturnType<typeof functionCallStreamPart.parse>\n | ReturnType<typeof dataStreamPart.parse>\n | ReturnType<typeof errorStreamPart.parse>\n | ReturnType<typeof assistantMessage.parse>\n | ReturnType<typeof assistantControlData.parse>;\n\nexport const streamPartsByCode = {\n [textStreamPart.code]: textStreamPart,\n [functionCallStreamPart.code]: functionCallStreamPart,\n [dataStreamPart.code]: dataStreamPart,\n [errorStreamPart.code]: errorStreamPart,\n [assistantMessage.code]: assistantMessage,\n [assistantControlData.code]: assistantControlData,\n} as const;\n\n/**\n * The map of prefixes for data in the stream\n *\n * - 0: Text from the LLM response\n * - 1: (OpenAI) function_call responses\n * - 2: custom JSON added by the user using `Data`\n *\n * Example:\n * ```\n * 0:Vercel\n * 0:'s\n * 0: AI\n * 0: AI\n * 0: SDK\n * 0: is great\n * 0:!\n * 2: { \"someJson\": \"value\" }\n * 1: {\"function_call\": {\"name\": \"get_current_weather\", \"arguments\": \"{\\\\n\\\\\"location\\\\\": \\\\\"Charlottesville, Virginia\\\\\",\\\\n\\\\\"format\\\\\": \\\\\"celsius\\\\\"\\\\n}\"}}\n *```\n */\nexport const StreamStringPrefixes = {\n [textStreamPart.name]: textStreamPart.code,\n [functionCallStreamPart.name]: functionCallStreamPart.code,\n [dataStreamPart.name]: dataStreamPart.code,\n [errorStreamPart.name]: errorStreamPart.code,\n [assistantMessage.name]: assistantMessage.code,\n [assistantControlData.name]: assistantControlData.code,\n} as const;\n\nexport const validCodes = streamParts.map((part) => part.code);\n\n/**\n * Parses a stream part from a string.\n *\n * @param line The string to parse.\n * @returns The parsed stream part.\n * @throws An error if the string cannot be parsed.\n */\nexport const parseStreamPart = (line: string): StreamPartType => {\n const firstSeparatorIndex = line.indexOf(\":\");\n\n if (firstSeparatorIndex === -1) {\n throw new Error(\"Failed to parse stream string. No separator found.\");\n }\n\n const prefix = line.slice(0, firstSeparatorIndex);\n\n if (!validCodes.includes(prefix as keyof typeof streamPartsByCode)) {\n throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);\n }\n\n const code = prefix as keyof typeof streamPartsByCode;\n\n const textValue = line.slice(firstSeparatorIndex + 1);\n const jsonValue: JSONValue = JSON.parse(textValue);\n\n return streamPartsByCode[code].parse(jsonValue);\n};\n\n/**\n * Prepends a string with a prefix from the `StreamChunkPrefixes`, JSON-ifies it,\n * and appends a new line.\n *\n * It ensures type-safety for the part type and value.\n */\nexport function formatStreamPart<T extends keyof StreamPartValueType>(\n type: T,\n value: StreamPartValueType[T],\n): StreamString {\n const streamPart = streamParts.find((part) => part.name === type);\n\n if (!streamPart) {\n throw new Error(`Invalid stream part type: ${type}`);\n }\n\n return `${streamPart.code}:${JSON.stringify(value)}\\n`;\n}\n\nexport const isStreamStringEqualToType = (\n type: keyof typeof StreamStringPrefixes,\n value: string,\n): value is StreamString =>\n value.startsWith(`${StreamStringPrefixes[type]}:`) && value.endsWith(\"\\n\");\n\nexport type StreamString =\n `${typeof StreamStringPrefixes[keyof typeof StreamStringPrefixes]}:${string}\\n`;\n\n/**\n * A header sent to the client so it knows how to handle parsing the stream (as a deprecated text response or using the new prefixed protocol)\n */\nexport const COMPLEX_HEADER = \"X-Experimental-Stream-Data\";\n"]}
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ // src/utils/utils.test.ts
4
+ describe("emptyTest", () => {
5
+ it("should be truthy", () => {
6
+ expect(true).toBeTruthy();
7
+ });
8
+ });
9
+ //# sourceMappingURL=out.js.map
10
+ //# sourceMappingURL=utils.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/utils.test.ts"],"names":[],"mappings":";AAEA,SAAS,aAAa,MAAM;AAC1B,KAAG,oBAAoB,MAAM;AAC3B,WAAO,IAAI,EAAE,WAAW;AAAA,EAC1B,CAAC;AACH,CAAC","sourcesContent":["import * as utils from \"./utils\";\n\ndescribe(\"emptyTest\", () => {\n it(\"should be truthy\", () => {\n expect(true).toBeTruthy();\n });\n});\n"]}
package/package.json CHANGED
@@ -4,27 +4,29 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "0.2.0-alpha.3",
7
+ "version": "0.2.0-alpha.4",
8
8
  "sideEffects": false,
9
9
  "main": "./dist/index.js",
10
10
  "module": "./dist/index.mjs",
11
- "exports": "./dist/index.mjs",
11
+ "exports": {
12
+ ".": "./dist/index.js"
13
+ },
12
14
  "types": "./dist/index.d.ts",
13
15
  "license": "MIT",
14
16
  "peerDependencies": {},
15
17
  "devDependencies": {
16
18
  "@types/jest": "^29.5.4",
17
19
  "eslint": "^7.32.0",
20
+ "eslint-config-custom": "0.3.0-alpha.4",
18
21
  "jest": "^29.6.4",
19
22
  "ts-jest": "^29.1.1",
23
+ "tsconfig": "0.7.0-alpha.4",
20
24
  "tsup": "^6.7.0",
21
- "typescript": "^5.1.3",
22
- "eslint-config-custom": "0.2.0",
23
- "tsconfig": "0.6.0"
25
+ "typescript": "^5.1.3"
24
26
  },
25
27
  "dependencies": {},
26
28
  "scripts": {
27
- "build": "tsup --treeshake",
29
+ "build": "tsup --treeshake --clean",
28
30
  "dev": "tsup --watch --no-splitting",
29
31
  "test": "jest",
30
32
  "check-types": "tsc --noEmit",
@@ -0,0 +1,27 @@
1
+ export interface AnnotatedFunctionSimpleArgument {
2
+ name: string;
3
+ type: "string" | "number" | "boolean" | "object"; // Add or change types according to your needs.
4
+ description: string;
5
+ required: boolean;
6
+ }
7
+
8
+ export interface AnnotatedFunctionArrayArgument {
9
+ name: string;
10
+ type: "array";
11
+ items: {
12
+ type: string;
13
+ };
14
+ description: string;
15
+ required: boolean;
16
+ }
17
+
18
+ export type AnnotatedFunctionArgument =
19
+ | AnnotatedFunctionSimpleArgument
20
+ | AnnotatedFunctionArrayArgument;
21
+
22
+ export interface AnnotatedFunction<Inputs extends any[]> {
23
+ name: string;
24
+ description: string;
25
+ argumentAnnotations: AnnotatedFunctionArgument[];
26
+ implementation: (...args: Inputs) => Promise<void>;
27
+ }
@@ -1 +1,2 @@
1
1
  export * from "./openai-assistant";
2
+ export * from "./annotated-function";
@@ -1,3 +1,5 @@
1
+ export type Role = "system" | "user" | "assistant" | "function";
2
+
1
3
  export interface FunctionCall {
2
4
  /**
3
5
  * The arguments to call the function with, as generated by the model in JSON
@@ -21,7 +23,7 @@ export interface Message {
21
23
  createdAt?: Date;
22
24
  content: string;
23
25
  ui?: string | null | undefined;
24
- role: "system" | "user" | "assistant" | "function";
26
+ role: Role;
25
27
  /**
26
28
  * If the message has a role of `function`, the `name` field is the name of the function.
27
29
  * Otherwise, the name field should not be set.
@@ -35,6 +37,34 @@ export interface Message {
35
37
  function_call?: string | FunctionCall;
36
38
  }
37
39
 
40
+ export interface Function {
41
+ /**
42
+ * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain
43
+ * underscores and dashes, with a maximum length of 64.
44
+ */
45
+ name: string;
46
+ /**
47
+ * The parameters the functions accepts, described as a JSON Schema object. See the
48
+ * [guide](/docs/guides/gpt/function-calling) for examples, and the
49
+ * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for
50
+ * documentation about the format.
51
+ *
52
+ * To describe a function that accepts no parameters, provide the value
53
+ * `{"type": "object", "properties": {}}`.
54
+ */
55
+ parameters: Record<string, unknown>;
56
+ /**
57
+ * A description of what the function does, used by the model to choose when and
58
+ * how to call the function.
59
+ */
60
+ description?: string;
61
+ }
62
+
63
+ export type FunctionCallHandler = (
64
+ chatMessages: Message[],
65
+ functionCall: FunctionCall,
66
+ ) => Promise<void>;
67
+
38
68
  export type AssistantMessage = {
39
69
  id: string;
40
70
  role: "assistant";
@@ -0,0 +1,33 @@
1
+ import { AnnotatedFunction, Function } from "../types";
2
+
3
+ export function annotatedFunctionToChatCompletionFunction(
4
+ annotatedFunction: AnnotatedFunction<any[]>,
5
+ ): Function {
6
+ // Create the parameters object based on the argumentAnnotations
7
+ let parameters: { [key: string]: any } = {};
8
+ for (let arg of annotatedFunction.argumentAnnotations) {
9
+ // isolate the args we should forward inline
10
+ let { name, required, ...forwardedArgs } = arg;
11
+ parameters[arg.name] = forwardedArgs;
12
+ }
13
+
14
+ let requiredParameterNames: string[] = [];
15
+ for (let arg of annotatedFunction.argumentAnnotations) {
16
+ if (arg.required) {
17
+ requiredParameterNames.push(arg.name);
18
+ }
19
+ }
20
+
21
+ // Create the ChatCompletionFunctions object
22
+ let chatCompletionFunction: Function = {
23
+ name: annotatedFunction.name,
24
+ description: annotatedFunction.description,
25
+ parameters: {
26
+ type: "object",
27
+ properties: parameters,
28
+ required: requiredParameterNames,
29
+ },
30
+ };
31
+
32
+ return chatCompletionFunction;
33
+ }
@@ -0,0 +1,33 @@
1
+ import { ChatCompletionEvent } from "./decode-chat-completion";
2
+
3
+ export function decodeChatCompletionAsText(
4
+ stream: ReadableStream<ChatCompletionEvent>,
5
+ ): ReadableStream<string> {
6
+ const reader = stream.getReader();
7
+
8
+ return new ReadableStream<string>({
9
+ async pull(controller) {
10
+ while (true) {
11
+ try {
12
+ const { done, value } = await reader.read();
13
+
14
+ if (done) {
15
+ controller.close();
16
+ return;
17
+ }
18
+
19
+ if (value.type === "content") {
20
+ controller.enqueue(value.content);
21
+ continue;
22
+ }
23
+ } catch (error) {
24
+ controller.error(error);
25
+ return;
26
+ }
27
+ }
28
+ },
29
+ cancel() {
30
+ reader.cancel();
31
+ },
32
+ });
33
+ }
@@ -0,0 +1,127 @@
1
+ import { ChatCompletionChunk } from "./parse-chat-completion";
2
+
3
+ export interface ChatCompletionContentEvent {
4
+ type: "content";
5
+ content: string;
6
+ }
7
+
8
+ export interface ChatCompletionPartialEvent {
9
+ type: "partial";
10
+ name: string;
11
+ arguments: string;
12
+ }
13
+
14
+ export interface ChatCompletionFunctionEvent {
15
+ type: "function";
16
+ name: string;
17
+ arguments: any;
18
+ }
19
+
20
+ export type ChatCompletionEvent =
21
+ | ChatCompletionContentEvent
22
+ | ChatCompletionPartialEvent
23
+ | ChatCompletionFunctionEvent;
24
+
25
+ export function decodeChatCompletion(
26
+ stream: ReadableStream<ChatCompletionChunk>,
27
+ ): ReadableStream<ChatCompletionEvent> {
28
+ const reader = stream.getReader();
29
+
30
+ let mode: "function" | "message" | null = null;
31
+ let functionCallName: string = "";
32
+ let functionCallArguments: string = "";
33
+
34
+ async function cleanup(controller?: ReadableStreamDefaultController<any>) {
35
+ if (controller) {
36
+ try {
37
+ controller.close();
38
+ } catch (_) {}
39
+ }
40
+ if (reader) {
41
+ try {
42
+ await reader.cancel();
43
+ } catch (_) {}
44
+ }
45
+ }
46
+
47
+ return new ReadableStream<ChatCompletionEvent>({
48
+ async pull(controller) {
49
+ const flushFunctionCall = (): boolean => {
50
+ let args: any = null;
51
+ try {
52
+ args = JSON.parse(functionCallArguments);
53
+ } catch (error) {
54
+ cleanup(controller);
55
+ controller.error(error);
56
+ return false;
57
+ }
58
+ controller.enqueue({
59
+ type: "function",
60
+ name: functionCallName,
61
+ arguments: args,
62
+ });
63
+
64
+ mode = null;
65
+ functionCallName = "";
66
+ functionCallArguments = "";
67
+ return true;
68
+ };
69
+
70
+ while (true) {
71
+ try {
72
+ const { done, value } = await reader.read();
73
+
74
+ if (done) {
75
+ if (mode === "function") {
76
+ flushFunctionCall();
77
+ }
78
+ await cleanup(controller);
79
+ return;
80
+ }
81
+
82
+ // In case we are in a function call but the next message is not a function call, flush it.
83
+ if (mode === "function" && !value.choices[0].delta.function_call) {
84
+ if (!flushFunctionCall()) {
85
+ return;
86
+ }
87
+ }
88
+
89
+ mode = value.choices[0].delta.function_call ? "function" : "message";
90
+
91
+ // if we get a message, emit the content and continue;
92
+ if (mode === "message") {
93
+ if (value.choices[0].delta.content) {
94
+ controller.enqueue({
95
+ type: "content",
96
+ content: value.choices[0].delta.content,
97
+ });
98
+ }
99
+ continue;
100
+ }
101
+ // if we get a function call, buffer the name and arguments, then emit a partial event.
102
+ else if (mode === "function") {
103
+ if (value.choices[0].delta.function_call!.name) {
104
+ functionCallName = value.choices[0].delta.function_call!.name!;
105
+ }
106
+ if (value.choices[0].delta.function_call!.arguments) {
107
+ functionCallArguments += value.choices[0].delta.function_call!.arguments!;
108
+ }
109
+ controller.enqueue({
110
+ type: "partial",
111
+ name: functionCallName,
112
+ arguments: functionCallArguments,
113
+ });
114
+ continue;
115
+ }
116
+ } catch (error) {
117
+ controller.error(error);
118
+ await cleanup(controller);
119
+ return;
120
+ }
121
+ }
122
+ },
123
+ cancel() {
124
+ reader.cancel();
125
+ },
126
+ });
127
+ }
@@ -1 +1,5 @@
1
1
  export * from "./utils";
2
+ export * from "./parse-chat-completion";
3
+ export * from "./decode-chat-completion";
4
+ export * from "./decode-chat-completion-as-text";
5
+ export * from "./annotated-function";
@@ -0,0 +1,84 @@
1
+ import { Role } from "../types/openai-assistant";
2
+
3
+ export interface ChatCompletionChunk {
4
+ choices: {
5
+ delta: {
6
+ role: Role;
7
+ content?: string | null;
8
+ function_call?: {
9
+ name?: string;
10
+ arguments?: string;
11
+ };
12
+ };
13
+ }[];
14
+ }
15
+
16
+ // TODO:
17
+ // it's possible that unicode characters could be split across chunks
18
+ // make sure to properly handle that
19
+ export function parseChatCompletion(
20
+ stream: ReadableStream<Uint8Array>,
21
+ ): ReadableStream<ChatCompletionChunk> {
22
+ const reader = stream.getReader();
23
+ let buffer = new Uint8Array();
24
+
25
+ async function cleanup(controller?: ReadableStreamDefaultController<any>) {
26
+ if (controller) {
27
+ try {
28
+ controller.close();
29
+ } catch (_) {}
30
+ }
31
+ if (reader) {
32
+ try {
33
+ await reader.cancel();
34
+ } catch (_) {}
35
+ }
36
+ }
37
+
38
+ return new ReadableStream<ChatCompletionChunk>({
39
+ async pull(controller) {
40
+ while (true) {
41
+ try {
42
+ const { done, value } = await reader.read();
43
+
44
+ if (done) {
45
+ await cleanup(controller);
46
+ return;
47
+ }
48
+
49
+ const newBuffer = new Uint8Array(buffer.length + value.length);
50
+ newBuffer.set(buffer);
51
+ newBuffer.set(value, buffer.length);
52
+ buffer = newBuffer;
53
+
54
+ const valueString = new TextDecoder("utf-8").decode(buffer);
55
+ const lines = valueString.split("\n").filter((line) => line.trim() !== "");
56
+
57
+ // If the last line isn't complete, keep it in the buffer for next time
58
+ buffer = !valueString.endsWith("\n")
59
+ ? new TextEncoder().encode(lines.pop() || "")
60
+ : new Uint8Array();
61
+
62
+ for (const line of lines) {
63
+ const cleanedLine = line.replace(/^data: /, "");
64
+
65
+ if (cleanedLine === "[DONE]") {
66
+ await cleanup(controller);
67
+ return;
68
+ }
69
+
70
+ const json = JSON.parse(cleanedLine);
71
+ controller.enqueue(json);
72
+ }
73
+ } catch (error) {
74
+ controller.error(error);
75
+ await cleanup(controller);
76
+ return;
77
+ }
78
+ }
79
+ },
80
+ cancel() {
81
+ reader.cancel();
82
+ },
83
+ });
84
+ }
package/tsup.config.ts CHANGED
@@ -2,10 +2,9 @@ import { defineConfig, Options } from "tsup";
2
2
 
3
3
  export default defineConfig((options: Options) => ({
4
4
  entry: ["src/**/*.{ts,tsx}"],
5
- format: ["esm"],
5
+ format: ["esm", "cjs"],
6
6
  dts: true,
7
7
  minify: false,
8
- clean: true,
9
8
  external: [],
10
9
  sourcemap: true,
11
10
  exclude: [
@@ -1,3 +0,0 @@
1
-
2
- //# sourceMappingURL=out.js.map
3
- //# sourceMappingURL=chunk-YJLRG5U3.mjs.map
@@ -1,3 +0,0 @@
1
-
2
- //# sourceMappingURL=out.js.map
3
- //# sourceMappingURL=chunk-YPBKY4KY.mjs.map