@xsai/utils-reasoning 0.2.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Moeru AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,26 @@
1
+ interface ExtractReasoningOptions {
2
+ /** @default `\n` */
3
+ separator?: string;
4
+ /** @default `false` */
5
+ startWithReasoning?: boolean;
6
+ /** @default `think` */
7
+ tagName: string;
8
+ }
9
+ interface ExtractReasoningResult {
10
+ reasoning?: string;
11
+ text: string;
12
+ }
13
+ declare const extractReasoning: (text: string, options?: ExtractReasoningOptions) => {
14
+ reasoning: string;
15
+ text: string;
16
+ };
17
+
18
+ interface ExtractReasoningStreamOptions extends ExtractReasoningOptions {
19
+ }
20
+ interface ExtractReasoningStreamResult {
21
+ reasoningStream: ReadableStream<string>;
22
+ textStream: ReadableStream<string>;
23
+ }
24
+ declare const extractReasoningStream: (stream: ReadableStream<string>, options?: ExtractReasoningStreamOptions) => ExtractReasoningStreamResult;
25
+
26
+ export { type ExtractReasoningOptions, type ExtractReasoningResult, type ExtractReasoningStreamOptions, type ExtractReasoningStreamResult, extractReasoning, extractReasoningStream };
package/dist/index.js ADDED
@@ -0,0 +1,133 @@
1
+ const extractReasoning = (text, options = {
2
+ tagName: "think"
3
+ }) => {
4
+ const startTag = `<${options.tagName}>`;
5
+ const endTag = `</${options.tagName}>`;
6
+ const separator = options.separator ?? "\n";
7
+ const fullText = options.startWithReasoning ? startTag + text : text;
8
+ const regex = new RegExp(`${startTag}(.*?)${endTag}`, "gs");
9
+ const reasonMatches = [...fullText.matchAll(regex)];
10
+ if (reasonMatches.length === 0) {
11
+ return {
12
+ reasoning: void 0,
13
+ text
14
+ };
15
+ }
16
+ const reasoning = reasonMatches.map((match) => match[1]).join(separator);
17
+ let startIndex = 0;
18
+ const texts = reasonMatches.reduce((acc, match, idx) => {
19
+ if (startIndex < match.index) {
20
+ acc.push(fullText.slice(startIndex, match.index));
21
+ }
22
+ startIndex = match.index + match[0].length;
23
+ if (idx === reasonMatches.length - 1) {
24
+ acc.push(fullText.slice(startIndex));
25
+ }
26
+ return acc;
27
+ }, []).join(separator);
28
+ return {
29
+ reasoning,
30
+ text: texts
31
+ };
32
+ };
33
+
34
+ const getPartialMatchIndex = (text, matchText) => {
35
+ if (text.length === 0 || matchText.length === 0) {
36
+ return -1;
37
+ }
38
+ const matchIndex = text.indexOf(matchText);
39
+ if (matchIndex !== -1) {
40
+ return matchIndex;
41
+ }
42
+ for (let i = Math.max(text.length - matchText.length + 1, 0); i < text.length; i++) {
43
+ if (matchText.startsWith(text.slice(i))) {
44
+ return i;
45
+ }
46
+ }
47
+ return -1;
48
+ };
49
+
50
+ const extractReasoningStream = (stream, options = {
51
+ tagName: "think"
52
+ }) => {
53
+ const startTag = `<${options.tagName}>`;
54
+ const endTag = `</${options.tagName}>`;
55
+ const separator = options.separator ?? "\n";
56
+ let reasoningStreamController;
57
+ let textStreamController;
58
+ const reasoningStream = new ReadableStream({
59
+ start(controller) {
60
+ reasoningStreamController = controller;
61
+ }
62
+ });
63
+ const textStream = new ReadableStream({
64
+ start(controller) {
65
+ textStreamController = controller;
66
+ }
67
+ });
68
+ let buffer = "";
69
+ let isFirstTextMode = true;
70
+ let isFirstReasoningMode = true;
71
+ let isReasoning = options.startWithReasoning;
72
+ let switchBlock = false;
73
+ const enqueueStream = (chunk) => {
74
+ if (chunk.length === 0) {
75
+ return;
76
+ }
77
+ const prefix = switchBlock && (isReasoning ? !isFirstReasoningMode : !isFirstTextMode) ? separator : "";
78
+ if (isReasoning) {
79
+ reasoningStreamController?.enqueue(prefix + chunk);
80
+ isFirstReasoningMode = false;
81
+ } else {
82
+ textStreamController?.enqueue(prefix + chunk);
83
+ isFirstTextMode = false;
84
+ }
85
+ switchBlock = false;
86
+ };
87
+ stream.pipeTo(
88
+ new WritableStream({
89
+ close() {
90
+ if (buffer.length > 0) {
91
+ if (isReasoning) {
92
+ reasoningStreamController?.enqueue(buffer);
93
+ } else {
94
+ textStreamController?.enqueue(buffer);
95
+ }
96
+ }
97
+ reasoningStreamController?.close();
98
+ textStreamController?.close();
99
+ },
100
+ write(chunk) {
101
+ buffer += chunk;
102
+ while (true) {
103
+ const checkTag = isReasoning ? endTag : startTag;
104
+ const idx = getPartialMatchIndex(buffer, checkTag);
105
+ if (idx === -1) {
106
+ enqueueStream(buffer);
107
+ buffer = "";
108
+ break;
109
+ }
110
+ enqueueStream(buffer.slice(0, idx));
111
+ const isFullMatch = idx + checkTag.length <= buffer.length;
112
+ if (isFullMatch) {
113
+ isReasoning = !isReasoning;
114
+ buffer = buffer.slice(idx + checkTag.length);
115
+ switchBlock = true;
116
+ } else {
117
+ buffer = buffer.slice(idx);
118
+ break;
119
+ }
120
+ }
121
+ }
122
+ })
123
+ ).catch((error) => {
124
+ reasoningStreamController?.error(error);
125
+ textStreamController?.error(error);
126
+ });
127
+ return {
128
+ reasoningStream,
129
+ textStream
130
+ };
131
+ };
132
+
133
+ export { extractReasoning, extractReasoningStream };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@xsai/utils-reasoning",
3
+ "type": "module",
4
+ "version": "0.2.0-beta.6",
5
+ "description": "extra-small AI SDK for Browser, Node.js, Deno, Bun or Edge Runtime.",
6
+ "author": "Moeru AI",
7
+ "license": "MIT",
8
+ "homepage": "https://xsai.js.org",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/moeru-ai/xsai.git",
12
+ "directory": "packages/utils-reasoning"
13
+ },
14
+ "bugs": "https://github.com/moeru-ai/xsai/issues",
15
+ "keywords": [
16
+ "xsai",
17
+ "openai",
18
+ "ai"
19
+ ],
20
+ "sideEffects": false,
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "devDependencies": {
32
+ "@xsai/generate-text": "",
33
+ "@xsai/stream-text": ""
34
+ },
35
+ "scripts": {
36
+ "build": "pkgroll",
37
+ "test": "vitest run",
38
+ "test:watch": "vitest"
39
+ },
40
+ "main": "./dist/index.js",
41
+ "types": "./dist/index.d.ts"
42
+ }