@vectorx/ai-sdk 0.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.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ ### 小程序/智能体 ai sdk
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Agent = exports.AiSdkEnv = void 0;
13
+ var AiSdkEnv;
14
+ (function (AiSdkEnv) {
15
+ AiSdkEnv["Cloud"] = "cloud";
16
+ AiSdkEnv["MiniProgram"] = "miniprogram";
17
+ })(AiSdkEnv || (exports.AiSdkEnv = AiSdkEnv = {}));
18
+ class Agent {
19
+ constructor(req, baseUrl, options) {
20
+ this.req = req;
21
+ this.baseUrl = baseUrl;
22
+ this.options = options;
23
+ }
24
+ sendMessage(props) {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const fetchHeaders = {
27
+ "Content-Type": "application/json",
28
+ Accept: "text/event-stream",
29
+ };
30
+ const response = yield this.req.fetch({
31
+ method: "post",
32
+ headers: Object.assign({}, fetchHeaders),
33
+ body: props,
34
+ url: `${this.baseUrl}/v1/aiagent/agents/${this.options.agentId}/send-message`,
35
+ stream: true,
36
+ });
37
+ return response;
38
+ });
39
+ }
40
+ getHistoryMessages(props) {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ const response = yield this.req.get({
43
+ method: "GET",
44
+ url: `${this.baseUrl}/v1/aiagent/agents/${this.options.agentId}/messages`,
45
+ data: props,
46
+ });
47
+ return response.data;
48
+ });
49
+ }
50
+ getAgentInfo() {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ const response = yield this.req.get({
53
+ method: "GET",
54
+ url: `${this.baseUrl}/v1/aiagent/agents/${this.options.agentId}/info`,
55
+ });
56
+ return response.data;
57
+ });
58
+ }
59
+ getConversations() {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ const response = yield this.req.get({
62
+ method: "GET",
63
+ url: `${this.baseUrl}/v1/aiagent/agents/${this.options.agentId}/conversations`,
64
+ });
65
+ return response.data;
66
+ });
67
+ }
68
+ }
69
+ exports.Agent = Agent;
package/lib/ai.js ADDED
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.AI = void 0;
46
+ const agent_1 = require("./agent");
47
+ const index_1 = require("./index");
48
+ const models = __importStar(require("./models"));
49
+ const utils_1 = require("./utils");
50
+ class AI {
51
+ constructor(request, baseUrl, env) {
52
+ this.modelSubUrl = "conversation/chat";
53
+ this.modelRequest = (options) => __awaiter(this, void 0, void 0, function* () {
54
+ const fetchHeaders = {
55
+ "Content-Type": "application/json",
56
+ };
57
+ options.stream && Object.assign(fetchHeaders, { Accept: "text/event-stream" });
58
+ const { data: responseData, header } = (yield this.request.fetch({
59
+ method: "post",
60
+ headers: Object.assign({}, fetchHeaders),
61
+ body: JSON.stringify(options),
62
+ url: `${this.baseUrl}/${this.modelSubUrl}`,
63
+ stream: options.stream,
64
+ }));
65
+ return (0, utils_1.handleResponseData)(responseData, header);
66
+ });
67
+ this.baseUrl = baseUrl;
68
+ this.request = request;
69
+ this.env = env;
70
+ }
71
+ createModel(model) {
72
+ if (this.env === index_1.AiSdkEnv.MiniProgram) {
73
+ console.warn(`[${index_1.AiSdkEnv.MiniProgram}] is not supported for model creation`);
74
+ return null;
75
+ }
76
+ const simpleModel = new models.DefaultSimpleModel(this.modelRequest, model);
77
+ const reactModel = new models.ReactModel(simpleModel);
78
+ return reactModel;
79
+ }
80
+ createAgent(options) {
81
+ if (this.env === index_1.AiSdkEnv.Cloud) {
82
+ console.warn(`[${index_1.AiSdkEnv.Cloud}] is not supported for \`Agent\` creation !`);
83
+ return null;
84
+ }
85
+ return new agent_1.Agent(this.request, this.baseUrl, options);
86
+ }
87
+ registerFunctionTool(functionTool) {
88
+ if (models.toolMap.has(functionTool.name)) {
89
+ console.warn(`AI function tool ${functionTool.name} already exists and will be overwritten!`);
90
+ }
91
+ models.toolMap.set(functionTool.name, functionTool.fn);
92
+ }
93
+ }
94
+ exports.AI = AI;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createParser = void 0;
4
+ var parse_1 = require("./parse");
5
+ Object.defineProperty(exports, "createParser", { enumerable: true, get: function () { return parse_1.createParser; } });
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createParser = createParser;
4
+ function createParser(onParse) {
5
+ let isFirstChunk;
6
+ let buffer;
7
+ let startingPosition;
8
+ let startingFieldLength;
9
+ let eventId;
10
+ let eventName;
11
+ let data;
12
+ reset();
13
+ return { feed, reset };
14
+ function reset() {
15
+ isFirstChunk = true;
16
+ buffer = "";
17
+ startingPosition = 0;
18
+ startingFieldLength = -1;
19
+ eventId = undefined;
20
+ eventName = undefined;
21
+ data = "";
22
+ }
23
+ function feed(chunk) {
24
+ buffer = buffer ? buffer + chunk : chunk;
25
+ if (isFirstChunk && hasBom(buffer)) {
26
+ buffer = buffer.slice(BOM.length);
27
+ }
28
+ isFirstChunk = false;
29
+ const { length } = buffer;
30
+ let position = 0;
31
+ let discardTrailingNewline = false;
32
+ while (position < length) {
33
+ if (discardTrailingNewline) {
34
+ if (buffer[position] === "\n") {
35
+ position += 1;
36
+ }
37
+ discardTrailingNewline = false;
38
+ }
39
+ let lineLength = -1;
40
+ let fieldLength = startingFieldLength;
41
+ let character;
42
+ for (let index = startingPosition; lineLength < 0 && index < length; index++) {
43
+ character = buffer[index];
44
+ if (character === ":" && fieldLength < 0) {
45
+ fieldLength = index - position;
46
+ }
47
+ else if (character === "\r") {
48
+ discardTrailingNewline = true;
49
+ lineLength = index - position;
50
+ }
51
+ else if (character === "\n") {
52
+ lineLength = index - position;
53
+ }
54
+ }
55
+ if (lineLength < 0) {
56
+ startingPosition = length - position;
57
+ startingFieldLength = fieldLength;
58
+ break;
59
+ }
60
+ else {
61
+ startingPosition = 0;
62
+ startingFieldLength = -1;
63
+ }
64
+ parseEventStreamLine(buffer, position, fieldLength, lineLength);
65
+ position += lineLength + 1;
66
+ }
67
+ if (position === length) {
68
+ buffer = "";
69
+ }
70
+ else if (position > 0) {
71
+ buffer = buffer.slice(position);
72
+ }
73
+ }
74
+ function parseEventStreamLine(lineBuffer, index, fieldLength, lineLength) {
75
+ if (lineLength === 0) {
76
+ if (data.length > 0) {
77
+ onParse({
78
+ type: "event",
79
+ id: eventId,
80
+ event: eventName || undefined,
81
+ data: data.slice(0, -1),
82
+ });
83
+ data = "";
84
+ eventId = undefined;
85
+ }
86
+ eventName = undefined;
87
+ return;
88
+ }
89
+ const noValue = fieldLength < 0;
90
+ const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength));
91
+ let step = 0;
92
+ if (noValue) {
93
+ step = lineLength;
94
+ }
95
+ else if (lineBuffer[index + fieldLength + 1] === " ") {
96
+ step = fieldLength + 2;
97
+ }
98
+ else {
99
+ step = fieldLength + 1;
100
+ }
101
+ const position = index + step;
102
+ const valueLength = lineLength - step;
103
+ const value = lineBuffer.slice(position, position + valueLength).toString();
104
+ if (field === "data") {
105
+ data += value ? `${value}\n` : "\n";
106
+ }
107
+ else if (field === "event") {
108
+ eventName = value;
109
+ }
110
+ else if (field === "id" && !value.includes("\u0000")) {
111
+ eventId = value;
112
+ }
113
+ else if (field === "retry") {
114
+ const retry = Number.parseInt(value, 10);
115
+ if (!Number.isNaN(retry)) {
116
+ onParse({ type: "reconnect-interval", value: retry });
117
+ }
118
+ }
119
+ }
120
+ }
121
+ const BOM = [239, 187, 191];
122
+ function hasBom(buffer) {
123
+ return BOM.every((charCode, index) => buffer.charCodeAt(index) === charCode);
124
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventSourceParserStream = void 0;
4
+ const parse_1 = require("./parse");
5
+ class EventSourceParserStream extends TransformStream {
6
+ constructor() {
7
+ let parser;
8
+ super({
9
+ start(controller) {
10
+ parser = (0, parse_1.createParser)((event) => {
11
+ if (event.type === "event") {
12
+ controller.enqueue(event);
13
+ }
14
+ });
15
+ },
16
+ transform(chunk) {
17
+ parser.feed(chunk);
18
+ },
19
+ });
20
+ }
21
+ }
22
+ exports.EventSourceParserStream = EventSourceParserStream;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/lib/index.js ADDED
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
36
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.IAgentEnv = exports.AiSdkEnv = exports.AI = exports.models = void 0;
40
+ exports.createAi = createAi;
41
+ const agent_1 = require("./agent");
42
+ Object.defineProperty(exports, "AiSdkEnv", { enumerable: true, get: function () { return agent_1.AiSdkEnv; } });
43
+ const ai_1 = require("./ai");
44
+ Object.defineProperty(exports, "AI", { enumerable: true, get: function () { return ai_1.AI; } });
45
+ const models = __importStar(require("./models"));
46
+ exports.models = models;
47
+ const types_1 = require("./types");
48
+ Object.defineProperty(exports, "IAgentEnv", { enumerable: true, get: function () { return types_1.IAgentEnv; } });
49
+ function createAi({ getBaseUrl, request, env = agent_1.AiSdkEnv.Cloud }) {
50
+ if (getBaseUrl == null || typeof getBaseUrl !== "function") {
51
+ throw new Error("`getBaseUrl` is required!");
52
+ }
53
+ return new ai_1.AI(request, getBaseUrl(), env);
54
+ }
55
+ __exportStar(require("./types"), exports);
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DefaultSimpleModel = exports.SimpleChatModel = void 0;
13
+ const stream_1 = require("../stream");
14
+ class SimpleChatModel {
15
+ }
16
+ exports.SimpleChatModel = SimpleChatModel;
17
+ const defaultOptions = {
18
+ max_tokens: 1000,
19
+ temperature: 0.7,
20
+ top_p: 1,
21
+ frequency_penalty: 0,
22
+ presence_penalty: 0,
23
+ stream: true,
24
+ platform_tools: [],
25
+ knowledge_base: [],
26
+ enable_thinking: false,
27
+ enable_search: false,
28
+ };
29
+ class DefaultSimpleModel {
30
+ constructor(req, modelName) {
31
+ this.req = req;
32
+ this.modelName = modelName;
33
+ }
34
+ doGenerate(data, options) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ data.model = this.modelName;
37
+ const res = yield this.req(Object.assign(Object.assign(Object.assign(Object.assign({}, defaultOptions), data), (options || {})), { stream: false }));
38
+ return Object.assign(Object.assign({}, res), { rawResponse: res });
39
+ });
40
+ }
41
+ doStream(data, options) {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ data.model = this.modelName;
44
+ const _stream = yield this.req(Object.assign(Object.assign(Object.assign(Object.assign({}, defaultOptions), data), (options || {})), { stream: true }));
45
+ const stream = (0, stream_1.toPolyfillReadable)(_stream);
46
+ const standardStream = (0, stream_1.intoStandardStream)(stream);
47
+ return (0, stream_1.createAsyncIterable)(standardStream);
48
+ });
49
+ }
50
+ }
51
+ exports.DefaultSimpleModel = DefaultSimpleModel;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toolMap = exports.ReactModel = exports.DefaultSimpleModel = exports.modelName = exports.ModelName = void 0;
4
+ const default_1 = require("./default");
5
+ Object.defineProperty(exports, "DefaultSimpleModel", { enumerable: true, get: function () { return default_1.DefaultSimpleModel; } });
6
+ const react_1 = require("./react");
7
+ Object.defineProperty(exports, "ReactModel", { enumerable: true, get: function () { return react_1.ReactModel; } });
8
+ var ModelName;
9
+ (function (ModelName) {
10
+ ModelName["DeepSeekR1"] = "deepseek-r1";
11
+ ModelName["DeepSeekV3"] = "deepseek-v3";
12
+ ModelName["QwenMax"] = "qwen-max";
13
+ ModelName["QwenLong"] = "qwen-long";
14
+ ModelName["QwenPlus"] = "qwen-plus";
15
+ ModelName["QwenTurbo"] = "qwen-turbo";
16
+ ModelName["QwenVlOcr"] = "qwen-vl-ocr";
17
+ ModelName["Wanx21T2iTurbo"] = "wanx2.1-t2i-turbo";
18
+ })(ModelName || (exports.ModelName = ModelName = {}));
19
+ exports.modelName = {
20
+ [ModelName.DeepSeekR1]: "deepseek-r1",
21
+ [ModelName.DeepSeekV3]: "deepseek-v3",
22
+ [ModelName.QwenMax]: "qwen-max",
23
+ [ModelName.QwenLong]: "qwen-long",
24
+ [ModelName.QwenPlus]: "qwen-plus",
25
+ [ModelName.QwenTurbo]: "qwen-turbo",
26
+ [ModelName.QwenVlOcr]: "qwen-vl-ocr",
27
+ };
28
+ const toolMap = new Map();
29
+ exports.toolMap = toolMap;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SimpleChatModel = void 0;
4
+ class SimpleChatModel {
5
+ }
6
+ exports.SimpleChatModel = SimpleChatModel;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ReactModel = void 0;
13
+ class ReactModel {
14
+ constructor(model) {
15
+ this.model = model;
16
+ }
17
+ generateText(_input, options) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ return this.model.doGenerate(_input, options);
20
+ });
21
+ }
22
+ streamText(_input, options) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ return this.model.doStream(_input, options);
25
+ });
26
+ }
27
+ }
28
+ exports.ReactModel = ReactModel;
package/lib/stream.js ADDED
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.TextDecoderStream = exports.toPolyfillReadable = exports.createEventSourceParserTransformStream = exports.TransformStream = exports.ReadableStream = void 0;
13
+ exports.createAsyncIterable = createAsyncIterable;
14
+ exports.intoStandardStream = intoStandardStream;
15
+ exports.createPromise = createPromise;
16
+ exports.isToolCallAssistantMessage = isToolCallAssistantMessage;
17
+ exports.functionToolToModelTool = functionToolToModelTool;
18
+ const web_streams_adapter_1 = require("@mattiasbuelens/web-streams-adapter");
19
+ const text_encoding_shim_1 = require("text-encoding-shim");
20
+ const web_streams_polyfill_1 = require("web-streams-polyfill");
21
+ const eventsource_parser_1 = require("./eventsource_parser");
22
+ exports.ReadableStream = web_streams_polyfill_1.ReadableStream;
23
+ exports.TransformStream = web_streams_polyfill_1.TransformStream;
24
+ const createEventSourceParserTransformStream = () => {
25
+ let parser;
26
+ return new exports.TransformStream({
27
+ start(controller) {
28
+ parser = (0, eventsource_parser_1.createParser)((event) => {
29
+ if (event.type === "event") {
30
+ controller.enqueue(event);
31
+ }
32
+ });
33
+ },
34
+ transform(chunk) {
35
+ parser.feed(chunk);
36
+ },
37
+ });
38
+ };
39
+ exports.createEventSourceParserTransformStream = createEventSourceParserTransformStream;
40
+ exports.toPolyfillReadable = (0, web_streams_adapter_1.createReadableStreamWrapper)(exports.ReadableStream);
41
+ class TextDecoderStream {
42
+ constructor(encoding = "utf-8", options = {}) {
43
+ this.transform = new exports.TransformStream({
44
+ transform: (chunk, controller) => {
45
+ const value = this.handle.decode(new Uint8Array(chunk), { stream: true });
46
+ if (value) {
47
+ controller.enqueue(value);
48
+ }
49
+ },
50
+ flush: (controller) => {
51
+ const value = this.handle.decode();
52
+ if (value) {
53
+ controller.enqueue(value);
54
+ }
55
+ controller.terminate();
56
+ },
57
+ });
58
+ this.handle = new text_encoding_shim_1.TextDecoder(encoding, options);
59
+ }
60
+ get encoding() {
61
+ return this.handle.encoding;
62
+ }
63
+ get fatal() {
64
+ return this.handle.fatal;
65
+ }
66
+ get ignoreBOM() {
67
+ return this.handle.ignoreBOM;
68
+ }
69
+ get readable() {
70
+ return this.transform.readable;
71
+ }
72
+ get writable() {
73
+ return this.transform.writable;
74
+ }
75
+ get [Symbol.toStringTag]() {
76
+ return "TextDecoderStream";
77
+ }
78
+ }
79
+ exports.TextDecoderStream = TextDecoderStream;
80
+ function createAsyncIterable(stream) {
81
+ const _stream = stream;
82
+ _stream[Symbol.asyncIterator] = () => {
83
+ const reader = stream.getReader();
84
+ return {
85
+ next() {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ const { done, value } = yield reader.read();
88
+ return done ? { done: true, value: undefined } : { done: false, value };
89
+ });
90
+ },
91
+ };
92
+ };
93
+ return _stream;
94
+ }
95
+ function intoStandardStream(stream) {
96
+ return createAsyncIterable(stream
97
+ .pipeThrough(new TextDecoderStream())
98
+ .pipeThrough((0, exports.createEventSourceParserTransformStream)())
99
+ .pipeThrough(new exports.TransformStream({
100
+ transform(chunk, controller) {
101
+ try {
102
+ const data = JSON.parse(chunk.data);
103
+ controller.enqueue(data);
104
+ }
105
+ catch (e) {
106
+ if (chunk.data !== "[DONE]") {
107
+ console.warn("Error when transforming event source data to json", e, chunk);
108
+ }
109
+ else {
110
+ controller.terminate();
111
+ }
112
+ }
113
+ },
114
+ })));
115
+ }
116
+ function createPromise() {
117
+ let res;
118
+ let rej;
119
+ const promise = new Promise((resolve, reject) => {
120
+ res = resolve;
121
+ rej = reject;
122
+ });
123
+ return { promise, res, rej };
124
+ }
125
+ function isToolCallAssistantMessage(message) {
126
+ var _a;
127
+ return message.role === "assistant" && "tool_calls" in message && ((_a = message.tool_calls) === null || _a === void 0 ? void 0 : _a[0]) != null;
128
+ }
129
+ function functionToolToModelTool(tool) {
130
+ return {
131
+ type: "function",
132
+ function: {
133
+ description: tool.description,
134
+ name: tool.name,
135
+ parameters: tool.parameters,
136
+ },
137
+ };
138
+ }
package/lib/types.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IAgentEnv = exports.SimpleChatModel = void 0;
4
+ class SimpleChatModel {
5
+ }
6
+ exports.SimpleChatModel = SimpleChatModel;
7
+ var IAgentEnv;
8
+ (function (IAgentEnv) {
9
+ IAgentEnv["Production"] = "production";
10
+ IAgentEnv["Development"] = "development";
11
+ })(IAgentEnv || (exports.IAgentEnv = IAgentEnv = {}));
package/lib/utils.js ADDED
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.handleResponseData = handleResponseData;
13
+ const GO_TO_AI_TEXT = "请检查调用方式,或前往云开发 AI+ 首页查看文档:https://tcb.cloud.tencent.com/dev#/ai";
14
+ function handleResponseData(responseData, header) {
15
+ return __awaiter(this, void 0, void 0, function* () {
16
+ var _a, _b;
17
+ if (typeof responseData === "object" && responseData && "then" in responseData) {
18
+ const json = (yield responseData);
19
+ if (typeof json === "object" && json && "code" in json && json.code !== 0) {
20
+ throw new Error(`小红书 ModelRequest 请求出错,错误码:${json.code},错误信息:${json.message}\n${GO_TO_AI_TEXT}\n${JSON.stringify(json, null, 2)}`);
21
+ }
22
+ return responseData;
23
+ }
24
+ if ((_b = (_a = header === null || header === void 0 ? void 0 : header.get) === null || _a === void 0 ? void 0 : _a.call(header, "content-type")) === null || _b === void 0 ? void 0 : _b.includes("application/json")) {
25
+ const json = yield readableStream2JsonObject(responseData);
26
+ if (typeof json === "object" && json && "code" in json && json.code !== 0) {
27
+ throw new Error(`小红书 ModelRequest 请求出错,错误码:${json.code},错误信息:${json.message}\n${GO_TO_AI_TEXT}\n${JSON.stringify(json, null, 2)}`);
28
+ }
29
+ }
30
+ return responseData;
31
+ });
32
+ }
33
+ function readableStream2JsonObject(stream) {
34
+ return __awaiter(this, void 0, void 0, function* () {
35
+ const reader = stream.getReader();
36
+ const decoder = new TextDecoder();
37
+ let result = "";
38
+ while (true) {
39
+ const { done, value } = yield reader.read();
40
+ if (done)
41
+ break;
42
+ result += decoder.decode(value);
43
+ }
44
+ return JSON.parse(result);
45
+ });
46
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@vectorx/ai-sdk",
3
+ "version": "0.1.0",
4
+ "description": "Cloud AI SDK",
5
+ "main": "lib/index.js",
6
+ "types": "types/index.d.ts",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "lib",
10
+ "types",
11
+ "README.md"
12
+ ],
13
+ "keywords": [
14
+ "ai",
15
+ "sdk",
16
+ "cloud",
17
+ "sdk"
18
+ ],
19
+ "author": "",
20
+ "license": "ISC",
21
+ "engines": {
22
+ "node": ">=18.0.0"
23
+ },
24
+ "dependencies": {
25
+ "@vectorx/ai-types": "0.1.0",
26
+ "@vectorx/agent-runtime": "0.1.0",
27
+ "@mattiasbuelens/web-streams-adapter": "^0.1.0",
28
+ "text-encoding-shim": "^1.0.5",
29
+ "web-streams-polyfill": "^4.1.0",
30
+ "zod": "^3.24.2"
31
+ },
32
+ "devDependencies": {
33
+ "@types/jest": "^29.5.12",
34
+ "@types/node": "^20.11.24",
35
+ "@typescript-eslint/eslint-plugin": "^7.1.0",
36
+ "@typescript-eslint/parser": "^7.1.0",
37
+ "eslint": "^8.57.0",
38
+ "jest": "^29.7.0",
39
+ "openai": "^4.103.0",
40
+ "ts-node-dev": "^2.0.0",
41
+ "typescript": "^5.3.3"
42
+ },
43
+ "scripts": {
44
+ "dev": "tsc -w",
45
+ "build": "rimraf lib types && tsc",
46
+ "lint": "eslint 'src/**/*.ts'",
47
+ "fix": "eslint 'src/**/*.ts' --fix"
48
+ },
49
+ "readme": "### 小程序/智能体 ai sdk "
50
+ }
@@ -0,0 +1,17 @@
1
+ import type { GetAgentInfoResponse, GetConversationsResponse, GetHistoryMessagesParams, GetHistoryMessagesResponse, SendMessageInput } from "@vectorx/agent-runtime";
2
+ import type { IAbstractRequest } from "@vectorx/ai-types";
3
+ import type { IAgent, IAgentOptions } from "../types";
4
+ export declare enum AiSdkEnv {
5
+ Cloud = "cloud",
6
+ MiniProgram = "miniprogram"
7
+ }
8
+ export declare class Agent implements IAgent {
9
+ private readonly req;
10
+ private readonly baseUrl;
11
+ private readonly options;
12
+ constructor(req: IAbstractRequest, baseUrl: string, options: IAgentOptions);
13
+ sendMessage(props: SendMessageInput): Promise<any>;
14
+ getHistoryMessages(props: GetHistoryMessagesParams): Promise<GetHistoryMessagesResponse>;
15
+ getAgentInfo(): Promise<GetAgentInfoResponse>;
16
+ getConversations(): Promise<GetConversationsResponse>;
17
+ }
package/types/ai.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { IAbstractRequest } from "@vectorx/ai-types";
2
+ import { Agent } from "./agent";
3
+ import { AiSdkEnv } from "./index";
4
+ import * as models from "./models";
5
+ import type * as types from "./types";
6
+ declare class AI {
7
+ baseUrl: string;
8
+ request: IAbstractRequest;
9
+ modelSubUrl: string;
10
+ env: AiSdkEnv;
11
+ constructor(request: IAbstractRequest, baseUrl: string, env: AiSdkEnv);
12
+ createModel(model: models.ModelName): models.ReactModel;
13
+ modelRequest: (options: types.ModelRequestOptions) => Promise<any>;
14
+ createAgent(options: types.IAgentOptions): Agent;
15
+ registerFunctionTool(functionTool: types.FunctionTool): void;
16
+ }
17
+ export { AI };
@@ -0,0 +1,2 @@
1
+ export type { EventSourceParser, ParsedEvent, ReconnectInterval, ParseEvent, EventSourceParseCallback, } from "./types";
2
+ export { createParser } from "./parse";
@@ -0,0 +1,2 @@
1
+ import type { EventSourceParseCallback, EventSourceParser } from "./types";
2
+ export declare function createParser(onParse: EventSourceParseCallback): EventSourceParser;
@@ -0,0 +1,5 @@
1
+ import type { ParsedEvent } from "./types";
2
+ export declare class EventSourceParserStream extends TransformStream<string, ParsedEvent> {
3
+ constructor();
4
+ }
5
+ export type { ParsedEvent } from "./types";
@@ -0,0 +1,16 @@
1
+ export interface EventSourceParser {
2
+ feed(chunk: string): void;
3
+ reset(): void;
4
+ }
5
+ export interface ParsedEvent {
6
+ type: "event";
7
+ event?: string;
8
+ id?: string;
9
+ data: string;
10
+ }
11
+ export interface ReconnectInterval {
12
+ type: "reconnect-interval";
13
+ value: number;
14
+ }
15
+ export type ParseEvent = ParsedEvent | ReconnectInterval;
16
+ export type EventSourceParseCallback = (event: ParseEvent) => void;
@@ -0,0 +1,13 @@
1
+ import type { IAbstractRequest } from "@vectorx/ai-types";
2
+ import { AiSdkEnv } from "./agent";
3
+ import { AI } from "./ai";
4
+ import * as models from "./models";
5
+ import { IAgentEnv } from "./types";
6
+ interface ICreateAi {
7
+ getBaseUrl: () => string;
8
+ request: IAbstractRequest;
9
+ env?: AiSdkEnv;
10
+ }
11
+ declare function createAi({ getBaseUrl, request, env }: ICreateAi): AI;
12
+ export * from "./types";
13
+ export { createAi, models, AI, AiSdkEnv, IAgentEnv };
@@ -0,0 +1,13 @@
1
+ import type { DoGenerateOutput, DoStreamOutput, ModelReq, ModelRequestOptions, ReqOptions } from "../types";
2
+ import type { ModelName } from "./index";
3
+ export declare abstract class SimpleChatModel {
4
+ abstract doGenerate(data: ModelRequestOptions, options?: ReqOptions): Promise<DoGenerateOutput>;
5
+ abstract doStream(data: ModelRequestOptions, options?: ReqOptions): Promise<DoStreamOutput>;
6
+ }
7
+ export declare class DefaultSimpleModel implements SimpleChatModel {
8
+ private req;
9
+ modelName: ModelName;
10
+ constructor(req: ModelReq, modelName: ModelName);
11
+ doGenerate(data: ModelRequestOptions, options?: ReqOptions): Promise<DoGenerateOutput>;
12
+ doStream(data: ModelRequestOptions, options?: ReqOptions): Promise<DoStreamOutput>;
13
+ }
@@ -0,0 +1,23 @@
1
+ import { DefaultSimpleModel } from "./default";
2
+ import { ReactModel } from "./react";
3
+ export declare enum ModelName {
4
+ DeepSeekR1 = "deepseek-r1",
5
+ DeepSeekV3 = "deepseek-v3",
6
+ QwenMax = "qwen-max",
7
+ QwenLong = "qwen-long",
8
+ QwenPlus = "qwen-plus",
9
+ QwenTurbo = "qwen-turbo",
10
+ QwenVlOcr = "qwen-vl-ocr",
11
+ Wanx21T2iTurbo = "wanx2.1-t2i-turbo"
12
+ }
13
+ export declare const modelName: {
14
+ "deepseek-r1": string;
15
+ "deepseek-v3": string;
16
+ "qwen-max": string;
17
+ "qwen-long": string;
18
+ "qwen-plus": string;
19
+ "qwen-turbo": string;
20
+ "qwen-vl-ocr": string;
21
+ };
22
+ declare const toolMap: Map<string, Function>;
23
+ export { DefaultSimpleModel, ReactModel, toolMap };
@@ -0,0 +1,131 @@
1
+ export declare abstract class SimpleChatModel {
2
+ abstract doGenerate(data: ModelRequestOptions, options?: ReqOptions): Promise<DoGenerateOutput>;
3
+ abstract doStream(data: ModelRequestOptions, options?: ReqOptions): Promise<DoStreamOutput>;
4
+ }
5
+ export interface ModelRequestOptions {
6
+ model: string;
7
+ max_tokens?: number;
8
+ temperature?: number;
9
+ top_p?: number;
10
+ n?: number;
11
+ conversation_id?: string;
12
+ frequency_penalty?: number;
13
+ presence_penalty?: number;
14
+ stream?: boolean;
15
+ platform_tools?: Array<{
16
+ plantform_tool_id: string;
17
+ payload: any;
18
+ }>;
19
+ historys?: Array<{
20
+ role: string;
21
+ content: string;
22
+ }>;
23
+ knowledge_base?: Array<{
24
+ knowledge_base_id: string;
25
+ search_mode?: "vector" | "full_text" | "hybrid";
26
+ limit?: number;
27
+ score_threshold?: number;
28
+ }>;
29
+ db_base?: any[];
30
+ enable_thinking?: boolean;
31
+ enable_search?: boolean;
32
+ }
33
+ type RawResponse = {
34
+ rawResponse?: any;
35
+ };
36
+ export type DoGenerateOutput = BaseDoGenerateOutput & RawResponse;
37
+ export type DoStreamOutput = AsyncIterableReadableStream<BaseDoStreamOutputChunk & RawResponse>;
38
+ export type ChatModelConstructor = typeof SimpleChatModel;
39
+ export type AsyncIterableReadableStream<T> = ReadableStream<T> & {
40
+ [Symbol.asyncIterator]: () => {
41
+ next(): Promise<IteratorResult<T>>;
42
+ };
43
+ };
44
+ export interface IModelReqInput {
45
+ url: string;
46
+ headers?: Record<string, string>;
47
+ data?: Object;
48
+ stream?: boolean;
49
+ timeout?: number;
50
+ }
51
+ export type ModelReq = <T extends IModelReqInput>(props: T) => T["stream"] extends true ? Promise<ReadableStream<Uint8Array>> : Promise<Object>;
52
+ export interface IAgentReqInput {
53
+ url: string;
54
+ method: string;
55
+ headers?: Record<string, string>;
56
+ data?: Object;
57
+ stream?: boolean;
58
+ timeout?: number;
59
+ }
60
+ export interface ReqOptions {
61
+ timeout?: number;
62
+ }
63
+ export type AgentReq = <T extends IAgentReqInput>(props: T) => T["stream"] extends true ? Promise<ReadableStream<Uint8Array>> : Promise<Object>;
64
+ export type UserMessage = {
65
+ role: "user";
66
+ content: string;
67
+ };
68
+ export type SystemMessage = {
69
+ role: "system";
70
+ content: string;
71
+ };
72
+ export type AssistantMessage = PlainAssistantMessage | ToolCallAssistantMessage;
73
+ export type PlainAssistantMessage = {
74
+ role: "assistant";
75
+ content: string;
76
+ };
77
+ export type ToolCallAssistantMessage = {
78
+ role: "assistant";
79
+ tool_calls: Array<ToolCall>;
80
+ content?: string;
81
+ };
82
+ export type ToolMessage = {
83
+ role: "tool";
84
+ tool_call_id: string;
85
+ content: string;
86
+ };
87
+ export type ChatModelMessage = UserMessage | SystemMessage | AssistantMessage | ToolMessage;
88
+ export type FunctionTool = {
89
+ name: string;
90
+ description: string;
91
+ fn: CallableFunction;
92
+ parameters: object;
93
+ };
94
+ export type ModelTool = {
95
+ type: string;
96
+ function: ModelToolFunction;
97
+ };
98
+ export type ModelToolFunction = {
99
+ name: string;
100
+ description: string;
101
+ parameters: object;
102
+ };
103
+ export type ToolCall = {
104
+ id: string;
105
+ type: string;
106
+ function: {
107
+ name: string;
108
+ arguments: string;
109
+ };
110
+ };
111
+ type FinishReason = "tool_calls" | (string & {});
112
+ export type Usage = {
113
+ completion_tokens: number;
114
+ prompt_tokens: number;
115
+ total_tokens: number;
116
+ };
117
+ export interface BaseDoGenerateOutput {
118
+ choices?: Array<{
119
+ finish_reason?: FinishReason;
120
+ message?: ChatModelMessage;
121
+ }>;
122
+ usage?: Usage;
123
+ }
124
+ export interface BaseDoStreamOutputChunk {
125
+ choices?: Array<{
126
+ finish_reason?: FinishReason;
127
+ delta?: ChatModelMessage;
128
+ }>;
129
+ usage?: Usage;
130
+ }
131
+ export {};
@@ -0,0 +1,7 @@
1
+ import type { DoGenerateOutput, DoStreamOutput, ModelRequestOptions, ReqOptions, SimpleChatModel } from "../types";
2
+ export declare class ReactModel {
3
+ private model;
4
+ constructor(model: SimpleChatModel);
5
+ generateText(_input: ModelRequestOptions, options?: ReqOptions): Promise<DoGenerateOutput>;
6
+ streamText(_input: ModelRequestOptions, options?: ReqOptions): Promise<DoStreamOutput>;
7
+ }
@@ -0,0 +1,54 @@
1
+ import { type ParsedEvent } from "./eventsource_parser";
2
+ import type { BaseDoGenerateOutput, BaseDoStreamOutputChunk, ChatModelMessage, ModelTool, SimpleChatModel, ToolCallAssistantMessage } from "./types";
3
+ export type FunctionTool = {
4
+ name: string;
5
+ description: string;
6
+ fn: CallableFunction;
7
+ parameters: object;
8
+ };
9
+ type RawResponse = {
10
+ rawResponse?: any;
11
+ };
12
+ export type DoGenerateOutput = BaseDoGenerateOutput & RawResponse;
13
+ export type DoStreamOutput = AsyncIterableReadableStream<BaseDoStreamOutputChunk & RawResponse>;
14
+ export type ChatModelConstructor = typeof SimpleChatModel;
15
+ export type AsyncIterableReadableStream<T> = ReadableStream<T> & {
16
+ [Symbol.asyncIterator]: () => {
17
+ next(): Promise<IteratorResult<T>>;
18
+ };
19
+ };
20
+ export declare const ReadableStream: {
21
+ prototype: ReadableStream;
22
+ new (underlyingSource: UnderlyingByteSource, strategy?: {
23
+ highWaterMark?: number;
24
+ }): ReadableStream<Uint8Array>;
25
+ new <R = any>(underlyingSource: UnderlyingDefaultSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
26
+ new <R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
27
+ };
28
+ export declare const TransformStream: {
29
+ prototype: TransformStream;
30
+ new <I = any, O = any>(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>): TransformStream<I, O>;
31
+ };
32
+ export declare const createEventSourceParserTransformStream: () => TransformStream<string, ParsedEvent>;
33
+ export declare const toPolyfillReadable: import("@mattiasbuelens/web-streams-adapter").ReadableStreamWrapper;
34
+ export declare class TextDecoderStream {
35
+ private handle;
36
+ private transform;
37
+ constructor(encoding?: string, options?: TextDecoderOptions);
38
+ get encoding(): string;
39
+ get fatal(): boolean;
40
+ get ignoreBOM(): boolean;
41
+ get readable(): ReadableStream<any>;
42
+ get writable(): WritableStream<any>;
43
+ get [Symbol.toStringTag](): string;
44
+ }
45
+ export declare function createAsyncIterable<T>(stream: ReadableStream<T>): AsyncIterableReadableStream<T>;
46
+ export declare function intoStandardStream<T>(stream: ReadableStream<Uint8Array>): ReadableStream<T>;
47
+ export declare function createPromise<T = unknown>(): {
48
+ promise: Promise<T>;
49
+ res: (value: T | PromiseLike<T>) => void;
50
+ rej: (reason?: any) => void;
51
+ };
52
+ export declare function isToolCallAssistantMessage(message: ChatModelMessage): message is ToolCallAssistantMessage;
53
+ export declare function functionToolToModelTool(tool: FunctionTool): ModelTool;
54
+ export {};
@@ -0,0 +1,159 @@
1
+ import type { GetAgentInfoResponse, GetConversationsResponse, GetHistoryMessagesParams, GetHistoryMessagesResponse, SendMessageInput } from "@vectorx/agent-runtime";
2
+ import type { ModelName } from "./models";
3
+ export type { GetAgentInfoResponse, GetConversationsResponse, GetHistoryMessagesParams, GetHistoryMessagesResponse, SendMessageInput, };
4
+ type RawResponse = {
5
+ rawResponse?: any;
6
+ };
7
+ export type DoGenerateOutput = BaseDoGenerateOutput & RawResponse;
8
+ export type DoStreamOutput = AsyncIterableReadableStream<BaseDoStreamOutputChunk & RawResponse>;
9
+ export type ChatModelConstructor = typeof SimpleChatModel;
10
+ export type AsyncIterableReadableStream<T> = ReadableStream<T> & {
11
+ [Symbol.asyncIterator]: () => {
12
+ next(): Promise<IteratorResult<T>>;
13
+ };
14
+ };
15
+ export declare abstract class SimpleChatModel {
16
+ abstract doGenerate(data: ModelRequestOptions, options?: ReqOptions): Promise<DoGenerateOutput>;
17
+ abstract doStream(data: ModelRequestOptions, options?: ReqOptions): Promise<DoStreamOutput>;
18
+ }
19
+ export interface ModelRequestOptions {
20
+ model: ModelName;
21
+ max_tokens?: number;
22
+ temperature?: number;
23
+ top_p?: number;
24
+ n?: number;
25
+ conversation_id?: string;
26
+ frequency_penalty?: number;
27
+ presence_penalty?: number;
28
+ stream?: boolean;
29
+ platform_tools?: Array<{
30
+ plantform_tool_id: string;
31
+ payload: any;
32
+ }>;
33
+ messages?: Array<{
34
+ role: string;
35
+ content: string;
36
+ }>;
37
+ knowledge_base?: Array<{
38
+ knowledge_base_id: string;
39
+ search_mode?: "vector" | "full_text" | "hybrid";
40
+ limit?: number;
41
+ score_threshold?: number;
42
+ }>;
43
+ db_base?: any[];
44
+ enable_thinking?: boolean;
45
+ enable_search?: boolean;
46
+ }
47
+ export type ModelReq = <T extends ModelRequestOptions>(props: T) => T["stream"] extends true ? Promise<ReadableStream<Uint8Array>> : Promise<Object>;
48
+ export interface IAgentReqInput {
49
+ url: string;
50
+ method: string;
51
+ headers?: Record<string, string>;
52
+ data?: Object;
53
+ stream?: boolean;
54
+ timeout?: number;
55
+ }
56
+ export interface ReqOptions {
57
+ timeout?: number;
58
+ }
59
+ export type AgentReq = <T extends IAgentReqInput>(props: T) => T["stream"] extends true ? Promise<ReadableStream<Uint8Array>> : Promise<Object>;
60
+ export type UserMessage = {
61
+ role: "user";
62
+ content: string;
63
+ };
64
+ export type SystemMessage = {
65
+ role: "system";
66
+ content: string;
67
+ };
68
+ export type AssistantMessage = PlainAssistantMessage | ToolCallAssistantMessage;
69
+ export type PlainAssistantMessage = {
70
+ role: "assistant";
71
+ content: string;
72
+ };
73
+ export type ToolCallAssistantMessage = {
74
+ role: "assistant";
75
+ tool_calls: Array<ToolCall>;
76
+ content?: string;
77
+ };
78
+ export type ToolMessage = {
79
+ role: "tool";
80
+ tool_call_id: string;
81
+ content: string;
82
+ };
83
+ export type ChatModelMessage = UserMessage | SystemMessage | AssistantMessage | ToolMessage;
84
+ export type FunctionTool = {
85
+ name: string;
86
+ description: string;
87
+ fn: CallableFunction;
88
+ parameters: object;
89
+ };
90
+ export type ModelTool = {
91
+ type: string;
92
+ function: ModelToolFunction;
93
+ };
94
+ export type ModelToolFunction = {
95
+ name: string;
96
+ description: string;
97
+ parameters: object;
98
+ };
99
+ export type ToolCall = {
100
+ id: string;
101
+ type: string;
102
+ function: {
103
+ name: string;
104
+ arguments: string;
105
+ };
106
+ };
107
+ export interface BaseDoGenerateOutput extends ChatCompletion {
108
+ }
109
+ export interface BaseDoStreamOutputChunk extends ChatCompletion {
110
+ }
111
+ export interface ChatCompletion {
112
+ id: string;
113
+ log_id: string;
114
+ object: string;
115
+ error: string;
116
+ code: number;
117
+ created: number;
118
+ model: string;
119
+ choices: Choice[];
120
+ usage: Usage;
121
+ }
122
+ export type MessageType = "answer" | "function_call" | "function_call_response" | "knowledge_base_search" | "knowledge_base_search_response";
123
+ export interface Choice {
124
+ index: number;
125
+ message: {
126
+ id: string;
127
+ role: string;
128
+ type: MessageType;
129
+ reasoning_content?: string;
130
+ content?: string;
131
+ knowledge_retrieval?: any[];
132
+ db_operations?: any[];
133
+ search_results?: any[];
134
+ };
135
+ finish_reason: string;
136
+ }
137
+ interface Usage {
138
+ prompt_tokens: number;
139
+ completion_tokens: number;
140
+ knowledge_tokens: number;
141
+ reasoning_tokens: number;
142
+ total_tokens: number;
143
+ }
144
+ export interface IAgent {
145
+ sendMessage(input: SendMessageInput): Promise<any>;
146
+ getHistoryMessages?(input: GetHistoryMessagesParams): Promise<GetHistoryMessagesResponse>;
147
+ getAgentInfo?(): Promise<GetAgentInfoResponse>;
148
+ getConversations?(): Promise<GetConversationsResponse>;
149
+ }
150
+ export declare enum IAgentEnv {
151
+ Production = "production",
152
+ Development = "development"
153
+ }
154
+ export interface IAgentOptions {
155
+ agentId: string;
156
+ accessToken: string;
157
+ version?: string;
158
+ env: IAgentEnv;
159
+ }
@@ -0,0 +1 @@
1
+ export declare function handleResponseData(responseData: Promise<unknown> | ReadableStream<Uint8Array>, header?: Headers): Promise<unknown>;