@auipage/agent 0.1.0-alpha.2 → 0.1.0-alpha.3
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/dist/index.d.ts +1 -0
- package/dist/index.js +582 -0
- package/dist/package.json +3 -0
- package/package.json +5 -5
- package/src/index.js +1 -1
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '../types/index.d.ts'
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
/*! @auipage/agent v0.1.0-alpha.3 */
|
|
2
|
+
(function (global, factory) {
|
|
3
|
+
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
|
4
|
+
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
|
5
|
+
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.auipage_agent = {}));
|
|
6
|
+
})(this, (function (exports) { 'use strict';
|
|
7
|
+
|
|
8
|
+
// 极简 EventEmitter:on / off / emit,供 Response 复用
|
|
9
|
+
class Emitter {
|
|
10
|
+
constructor() {
|
|
11
|
+
this._events = Object.create(null);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
on(event, listener) {
|
|
15
|
+
if (typeof listener !== 'function') return this;
|
|
16
|
+
const list = this._events[event] || (this._events[event] = []);
|
|
17
|
+
list.push(listener);
|
|
18
|
+
return this;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
off(event, listener) {
|
|
22
|
+
const list = this._events[event];
|
|
23
|
+
if (!list) return this;
|
|
24
|
+
const idx = list.indexOf(listener);
|
|
25
|
+
if (idx >= 0) list.splice(idx, 1);
|
|
26
|
+
if (list.length === 0) delete this._events[event];
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
emit(event, ...args) {
|
|
31
|
+
const list = this._events[event];
|
|
32
|
+
if (!list || list.length === 0) return false;
|
|
33
|
+
// 复制一份再触发,避免 off 回调过程中影响本次派发
|
|
34
|
+
for (const fn of list.slice()) {
|
|
35
|
+
try {
|
|
36
|
+
fn.apply(null, args);
|
|
37
|
+
} catch (e) {
|
|
38
|
+
// 单个监听器异常不影响其它监听器
|
|
39
|
+
// 用 queueMicrotask 抛到全局,避免污染 emit 调用栈
|
|
40
|
+
queueMicrotask(() => { throw e; });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
|
|
48
|
+
|
|
49
|
+
class Response extends Emitter {
|
|
50
|
+
constructor() {
|
|
51
|
+
super();
|
|
52
|
+
this.status = 0;
|
|
53
|
+
this.headers = {};
|
|
54
|
+
this.ok = false;
|
|
55
|
+
this._done = false; // 标记是否已经 end/error,防止重复触发
|
|
56
|
+
this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
|
|
57
|
+
this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
|
|
61
|
+
_push(type, payload) {
|
|
62
|
+
if (this._done && type !== 'error') return;
|
|
63
|
+
|
|
64
|
+
// SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
|
|
65
|
+
if (type === 'data' && this._sseMode) {
|
|
66
|
+
this._sseBuffer += payload;
|
|
67
|
+
|
|
68
|
+
// 按 \n\n 分割出完整事件,最后一段可能不完整
|
|
69
|
+
const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
|
|
70
|
+
this._sseBuffer = parts.pop();
|
|
71
|
+
|
|
72
|
+
for (const part of parts) {
|
|
73
|
+
const payload = this._extractSSEData(part);
|
|
74
|
+
if (payload !== null) {
|
|
75
|
+
this.emit('data', payload);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (type === 'end') {
|
|
82
|
+
// SSE 模式下,flush 缓冲区残留
|
|
83
|
+
if (this._sseMode && this._sseBuffer.trim()) {
|
|
84
|
+
const payload = this._extractSSEData(this._sseBuffer);
|
|
85
|
+
if (payload !== null) {
|
|
86
|
+
this.emit('data', payload);
|
|
87
|
+
}
|
|
88
|
+
this._sseBuffer = '';
|
|
89
|
+
}
|
|
90
|
+
this._done = true;
|
|
91
|
+
}
|
|
92
|
+
if (type === 'error') this._done = true;
|
|
93
|
+
|
|
94
|
+
this.emit(type, payload);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
|
|
98
|
+
_extractSSEData(raw) {
|
|
99
|
+
const dataLines = [];
|
|
100
|
+
for (const line of raw.split('\n')) {
|
|
101
|
+
if (line.startsWith('data:')) {
|
|
102
|
+
dataLines.push(line.replace(/^data:\s*/, ''));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (dataLines.length === 0) return null;
|
|
106
|
+
return dataLines.join('\n');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// fetch 工厂:注入 adapter,返回对外的 fetch 函数
|
|
111
|
+
|
|
112
|
+
function createFetch(adapter) {
|
|
113
|
+
return function fetch(options) {
|
|
114
|
+
// 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
if (!options || !options.url) {
|
|
117
|
+
reject(new Error('fetch: options.url is required'));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const response = new Response();
|
|
122
|
+
|
|
123
|
+
// adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
|
|
124
|
+
// 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
|
|
125
|
+
queueMicrotask(() => resolve(response));
|
|
126
|
+
|
|
127
|
+
adapter(options, {
|
|
128
|
+
onResponse(meta) {
|
|
129
|
+
if (meta && typeof meta.status === 'number') {
|
|
130
|
+
response.status = meta.status;
|
|
131
|
+
response.ok = meta.status >= 200 && meta.status < 300;
|
|
132
|
+
}
|
|
133
|
+
if (meta && meta.headers) {
|
|
134
|
+
response.headers = meta.headers;
|
|
135
|
+
|
|
136
|
+
// 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
|
|
137
|
+
const contentType =
|
|
138
|
+
(typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
|
|
139
|
+
meta.headers['content-type'] ||
|
|
140
|
+
'';
|
|
141
|
+
if (contentType.includes('text/event-stream')) {
|
|
142
|
+
response._sseMode = true;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
onData(chunk) {
|
|
147
|
+
response._push('data', chunk);
|
|
148
|
+
},
|
|
149
|
+
onEnd() {
|
|
150
|
+
response._push('end');
|
|
151
|
+
},
|
|
152
|
+
onError(err) {
|
|
153
|
+
// 错误同时通过 error 事件 和 catch 暴露,避免遗漏
|
|
154
|
+
response._push('error', err);
|
|
155
|
+
reject(err);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// 浏览器环境适配器:基于原生 fetch + ReadableStream
|
|
163
|
+
// adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
|
|
164
|
+
function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
165
|
+
const { url, method = 'GET', headers = {}, body } = options;
|
|
166
|
+
|
|
167
|
+
if (typeof fetch !== 'function') {
|
|
168
|
+
onError(new Error('Global fetch is not available in this environment'));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
fetch(url, { method, headers, body })
|
|
173
|
+
.then(async (res) => {
|
|
174
|
+
if (typeof onResponse === 'function') {
|
|
175
|
+
onResponse({
|
|
176
|
+
status: res.status || 0,
|
|
177
|
+
headers: res.headers || {}
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// 没有 body(例如 204)直接结束
|
|
182
|
+
if (!res.body) {
|
|
183
|
+
onEnd();
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const reader = res.body.getReader();
|
|
188
|
+
const decoder = new TextDecoder('utf-8');
|
|
189
|
+
|
|
190
|
+
// 循环读取流直到 done
|
|
191
|
+
// 用 async IIFE 形式启动,错误统一走 onError
|
|
192
|
+
(async () => {
|
|
193
|
+
try {
|
|
194
|
+
// eslint-disable-next-line no-constant-condition
|
|
195
|
+
while (true) {
|
|
196
|
+
const { value, done } = await reader.read();
|
|
197
|
+
if (done) {
|
|
198
|
+
onEnd();
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
// value 是 Uint8Array,解码为字符串
|
|
202
|
+
onData(decoder.decode(value, { stream: true }));
|
|
203
|
+
}
|
|
204
|
+
} catch (err) {
|
|
205
|
+
onError(err);
|
|
206
|
+
}
|
|
207
|
+
})();
|
|
208
|
+
})
|
|
209
|
+
.catch((err) => onError(err));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Node 环境适配器:基于 http / https,天然流式输出
|
|
213
|
+
// adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
|
|
214
|
+
// 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
|
|
215
|
+
// 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
|
|
216
|
+
async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
217
|
+
const [{ default: http }, { default: https }, { URL }] = await Promise.all([
|
|
218
|
+
import('http'),
|
|
219
|
+
import('https'),
|
|
220
|
+
import('url')
|
|
221
|
+
]);
|
|
222
|
+
|
|
223
|
+
const { url, method = 'GET', headers = {}, body } = options;
|
|
224
|
+
|
|
225
|
+
let parsed;
|
|
226
|
+
try {
|
|
227
|
+
parsed = new URL(url);
|
|
228
|
+
} catch (e) {
|
|
229
|
+
onError(e);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const isHttps = parsed.protocol === 'https:';
|
|
234
|
+
const lib = isHttps ? https : http;
|
|
235
|
+
|
|
236
|
+
const reqOptions = {
|
|
237
|
+
method,
|
|
238
|
+
hostname: parsed.hostname,
|
|
239
|
+
port: parsed.port || (isHttps ? 443 : 80),
|
|
240
|
+
path: parsed.pathname + parsed.search,
|
|
241
|
+
headers
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
const req = lib.request(reqOptions, (res) => {
|
|
245
|
+
// 把 status / headers 同步给 Response(若上游关心)
|
|
246
|
+
if (typeof onResponse === 'function') {
|
|
247
|
+
onResponse({
|
|
248
|
+
status: res.statusCode || 0,
|
|
249
|
+
headers: res.headers || {}
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
res.setEncoding('utf8');
|
|
254
|
+
res.on('data', (chunk) => onData(chunk));
|
|
255
|
+
res.on('end', () => onEnd());
|
|
256
|
+
res.on('error', (err) => onError(err));
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
req.on('error', (err) => onError(err));
|
|
260
|
+
|
|
261
|
+
if (body != null) {
|
|
262
|
+
req.write(body);
|
|
263
|
+
}
|
|
264
|
+
req.end();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// 入口:环境判断 + 选择 adapter,构造并导出 fetch
|
|
268
|
+
|
|
269
|
+
// 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
|
|
270
|
+
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
|
|
271
|
+
|
|
272
|
+
const adapter = isBrowser ? browserAdapter : nodeAdapter;
|
|
273
|
+
|
|
274
|
+
const fetch$1 = createFetch(adapter);
|
|
275
|
+
|
|
276
|
+
// 字符串转JSON
|
|
277
|
+
// 适配LLM返回数据格式
|
|
278
|
+
function parseString (value) {
|
|
279
|
+
value = value.trim().replace(/^data: /, "").replace(/data: \[DONE\]$/, "");
|
|
280
|
+
|
|
281
|
+
if (/\r{0,1}\n\r{0,1}\ndata: /.test(value)) {
|
|
282
|
+
return JSON.parse("[" + (value.split(/\r{0,1}\n\r{0,1}\ndata: /)).join(",") + "]");
|
|
283
|
+
} else if (value === "[DONE]") {
|
|
284
|
+
return [];
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
let result = JSON.parse(value);
|
|
288
|
+
if (result.error) throw result.error;
|
|
289
|
+
|
|
290
|
+
return result;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// 解析 LLM 返回的推理内容(reasoning / reasoning_content)
|
|
294
|
+
// 将 <think>...</think> 形式的内容从 delta.content 中剥离出来
|
|
295
|
+
function parseReasoning(reasoning, content) {
|
|
296
|
+
if (!/<\/think>/.test(reasoning)) return reasoning;
|
|
297
|
+
|
|
298
|
+
const parts = reasoning.split("</think>");
|
|
299
|
+
const thinkPart = parts[0].replace("<think>", "");
|
|
300
|
+
return {
|
|
301
|
+
reasoning: thinkPart,
|
|
302
|
+
content: thinkPart[1] + (content || "")
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
|
|
307
|
+
// 返回累积的 { content, tool_calls }
|
|
308
|
+
function handleChoices(choices, { logback, thinkback }, state) {
|
|
309
|
+
for (let i = 0; i < choices.length; i++) {
|
|
310
|
+
const delta = choices[i].delta;
|
|
311
|
+
|
|
312
|
+
// 推理内容
|
|
313
|
+
let reasoning = delta.reasoning || delta.reasoning_content;
|
|
314
|
+
if (reasoning) {
|
|
315
|
+
const parsed = parseReasoning(reasoning, delta.content);
|
|
316
|
+
if (typeof parsed === "object") {
|
|
317
|
+
reasoning = parsed.reasoning;
|
|
318
|
+
delta.content = parsed.content;
|
|
319
|
+
}
|
|
320
|
+
if (thinkback) thinkback(reasoning);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// 正文内容
|
|
324
|
+
if (delta.content) {
|
|
325
|
+
if (logback) logback(delta.content);
|
|
326
|
+
state.content += delta.content;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// 工具调用
|
|
330
|
+
if (delta.tool_calls) {
|
|
331
|
+
for (const toolCall of delta.tool_calls) {
|
|
332
|
+
if (toolCall.id) {
|
|
333
|
+
state.tool_calls.push(toolCall);
|
|
334
|
+
} else {
|
|
335
|
+
state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function completions(params, logback, thinkback) {
|
|
343
|
+
return new Promise((resolve, reject) => {
|
|
344
|
+
|
|
345
|
+
const state = { content: "", tool_calls: [] };
|
|
346
|
+
const callbacks = { logback, thinkback };
|
|
347
|
+
|
|
348
|
+
let buffer = "";
|
|
349
|
+
|
|
350
|
+
fetch$1({
|
|
351
|
+
url: `${this.baseURL}/chat/completions`,
|
|
352
|
+
method: "POST",
|
|
353
|
+
headers: {
|
|
354
|
+
"Authorization": `Bearer ${this.apiKey}`,
|
|
355
|
+
"Content-Type": "application/json",
|
|
356
|
+
},
|
|
357
|
+
body: JSON.stringify({
|
|
358
|
+
model: this.model,
|
|
359
|
+
messages: params.messages,
|
|
360
|
+
tools: params.tools ? params.tools.map(tool => tool.description) : [],
|
|
361
|
+
stream: params.stream,
|
|
362
|
+
})
|
|
363
|
+
}).then(res => {
|
|
364
|
+
|
|
365
|
+
// 数据流
|
|
366
|
+
res.on("data", chunk => {
|
|
367
|
+
if (params.stream) {
|
|
368
|
+
const parsed = parseString(chunk.toString());
|
|
369
|
+
if (Array.isArray(parsed)) {
|
|
370
|
+
for (const item of parsed) {
|
|
371
|
+
handleChoices(item.choices, callbacks, state);
|
|
372
|
+
}
|
|
373
|
+
} else {
|
|
374
|
+
handleChoices(parsed.choices, callbacks, state);
|
|
375
|
+
}
|
|
376
|
+
} else {
|
|
377
|
+
buffer += chunk;
|
|
378
|
+
}
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
// 结束
|
|
382
|
+
res.on("end", () => {
|
|
383
|
+
if (!params.stream) {
|
|
384
|
+
handleChoices(
|
|
385
|
+
[{ delta: parseString(buffer).choices[0].message }],
|
|
386
|
+
callbacks,
|
|
387
|
+
state
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
resolve({ content: state.content, tool_calls: state.tool_calls });
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
res.on("error", err => reject(err));
|
|
394
|
+
}).catch(err => reject(err));
|
|
395
|
+
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function Model(fields) {
|
|
400
|
+
this.model = fields.model;
|
|
401
|
+
this.apiKey = fields.apiKey;
|
|
402
|
+
this.baseURL = fields.baseURL;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
Model.prototype.completions = completions;
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* 根据模型返回的 tool_calls,依次在 _this.tools 中查找匹配的工具并执行,
|
|
409
|
+
* 返回与 tool_calls 等长的结果数组(同步值/异步值都会被规范化)。
|
|
410
|
+
*
|
|
411
|
+
* @param {Object} _this Agent 实例
|
|
412
|
+
* @param {Array} tool_calls 模型返回的工具调用列表
|
|
413
|
+
* @returns {Promise<Array>} 每个工具的执行结果,未匹配到的槽位会被填入错误说明字符串
|
|
414
|
+
*/
|
|
415
|
+
function callFuns(_this, tool_calls) {
|
|
416
|
+
|
|
417
|
+
const tasks = tool_calls.map(call => {
|
|
418
|
+
const tool = _this.tools.find(
|
|
419
|
+
t => t.description.function.name === call.function.name
|
|
420
|
+
);
|
|
421
|
+
|
|
422
|
+
if (!tool) {
|
|
423
|
+
return Promise.resolve("工具" + call.function.name + "不存在");
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
let result;
|
|
427
|
+
try {
|
|
428
|
+
result = tool.execute(JSON.parse(call.function.arguments));
|
|
429
|
+
} catch (e) {
|
|
430
|
+
return Promise.resolve("参数解析失败:" + e);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
if (result instanceof Promise) {
|
|
434
|
+
// 工具内部报错也不要阻断对话,转成字符串继续往下走
|
|
435
|
+
return result.catch(e => "运行出错:" + e);
|
|
436
|
+
}
|
|
437
|
+
return Promise.resolve(result);
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
return Promise.all(tasks);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* 把一次工具调用的执行结果转成 tool 消息。
|
|
445
|
+
*/
|
|
446
|
+
function toToolMessage(call, value) {
|
|
447
|
+
return {
|
|
448
|
+
role: "tool",
|
|
449
|
+
tool_call_id: call.id,
|
|
450
|
+
tool_name: call.function.name,
|
|
451
|
+
content: typeof value === "string" ? value : (JSON.stringify(value) + "")
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* 把模型响应按 role 追加到 messages,返回是否还有工具调用需要下一轮处理。
|
|
457
|
+
*/
|
|
458
|
+
function appendAssistantMessage(messages, result) {
|
|
459
|
+
if (result.content) {
|
|
460
|
+
messages.push({ role: "assistant", content: result.content });
|
|
461
|
+
}
|
|
462
|
+
if (result.tool_calls && result.tool_calls.length > 0) {
|
|
463
|
+
messages.push({ role: "assistant", tool_calls: result.tool_calls });
|
|
464
|
+
return true;
|
|
465
|
+
}
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* 执行模型对话循环:
|
|
471
|
+
* 1. 调用模型获取响应
|
|
472
|
+
* 2. 若返回工具调用,依次执行工具并将结果追加到 messages,继续循环
|
|
473
|
+
* 3. 否则将最终内容 resolve 给调用方
|
|
474
|
+
*/
|
|
475
|
+
async function runConversation(_this, messages, logback, thinkback) {
|
|
476
|
+
|
|
477
|
+
while (true) {
|
|
478
|
+
const result = await _this.model.completions({
|
|
479
|
+
messages,
|
|
480
|
+
tools: _this.tools,
|
|
481
|
+
stream: _this.stream,
|
|
482
|
+
}, logback, thinkback);
|
|
483
|
+
|
|
484
|
+
const hasToolCalls = appendAssistantMessage(messages, result);
|
|
485
|
+
|
|
486
|
+
if (!hasToolCalls) {
|
|
487
|
+
return result.content;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
const toolResults = await callFuns(_this, result.tool_calls);
|
|
491
|
+
|
|
492
|
+
result.tool_calls.forEach((call, i) => {
|
|
493
|
+
messages.push(toToolMessage(call, toolResults[i]));
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function initOption(setOption, defaultOption) {
|
|
499
|
+
for (const key in setOption) {
|
|
500
|
+
defaultOption[key] = setOption[key];
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
return defaultOption;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function CreateTool(ms) {
|
|
507
|
+
this.ms = ms;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
CreateTool.prototype.create = function ({ description, execute }) {
|
|
511
|
+
let _this = this;
|
|
512
|
+
return {
|
|
513
|
+
description,
|
|
514
|
+
execute: async function (args) {
|
|
515
|
+
let toolInfo = {
|
|
516
|
+
type: "tool-call",
|
|
517
|
+
status: "pending",
|
|
518
|
+
id: Date.now().toString()+"_"+Math.random().toString(36).substring(2).toUpperCase(),
|
|
519
|
+
name: description.function.name,
|
|
520
|
+
caller: execute ? "backend" : "frontend",
|
|
521
|
+
args
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
// 后端工具调用
|
|
525
|
+
if (execute) {
|
|
526
|
+
_this.ms.send(toolInfo); // 开始调用工具
|
|
527
|
+
|
|
528
|
+
let result, status;
|
|
529
|
+
try {
|
|
530
|
+
result = await execute(args);
|
|
531
|
+
status = "success"; // 调用成功
|
|
532
|
+
} catch (error) {
|
|
533
|
+
result = error;
|
|
534
|
+
status = "error"; // 调用失败
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
_this.ms.send(initOption({ // 结束调用工具
|
|
538
|
+
status,
|
|
539
|
+
result
|
|
540
|
+
}, toolInfo));
|
|
541
|
+
|
|
542
|
+
return result;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// 前端工具调用
|
|
546
|
+
else {
|
|
547
|
+
let _resolve = null;
|
|
548
|
+
globalThis[toolInfo.id] = function (result) {
|
|
549
|
+
_resolve(result);
|
|
550
|
+
delete globalThis[toolInfo.id];
|
|
551
|
+
};
|
|
552
|
+
|
|
553
|
+
_this.ms.send(toolInfo); // 开始调用工具
|
|
554
|
+
|
|
555
|
+
return new Promise((resolve, reject) => {
|
|
556
|
+
_resolve = resolve;
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
};
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
function Agent(option) {
|
|
564
|
+
this.model = new Model(option.model);
|
|
565
|
+
this.tools = option.tools || [];
|
|
566
|
+
this.systemPrompt = option.systemPrompt || "";
|
|
567
|
+
this.stream = option.stream || false;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
Agent.prototype.generate = function (messages, logback, thinkback) {
|
|
571
|
+
if (this.systemPrompt) messages.unshift({
|
|
572
|
+
role: "system",
|
|
573
|
+
content: this.systemPrompt
|
|
574
|
+
});
|
|
575
|
+
|
|
576
|
+
return runConversation(this, messages, logback, thinkback);
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
exports.Agent = Agent;
|
|
580
|
+
exports.CreateTool = CreateTool;
|
|
581
|
+
|
|
582
|
+
}));
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auipage/agent",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.3",
|
|
4
4
|
"description": "@auipage/agent",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
7
7
|
"typings": "types/index.d.ts",
|
|
8
8
|
"sideEffects": false,
|
|
9
9
|
"scripts": {
|
|
10
|
-
"prepublishOnly": "node ../../swap-pkg.js --mode=publish",
|
|
11
|
-
"postpublish": "node ../../swap-pkg.js --mode=restore"
|
|
10
|
+
"prepublishOnly": "node ../../scripts/swap-pkg.js --mode=publish",
|
|
11
|
+
"postpublish": "node ../../scripts/swap-pkg.js --mode=restore"
|
|
12
12
|
},
|
|
13
13
|
"repository": {
|
|
14
14
|
"type": "git",
|
|
@@ -30,8 +30,8 @@
|
|
|
30
30
|
},
|
|
31
31
|
"homepage": "https://github.com/handless-ui/auipage#readme",
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@auipage/model": "^0.1.0-alpha.
|
|
34
|
-
"@auipage/types": "^0.1.0-alpha.
|
|
33
|
+
"@auipage/model": "^0.1.0-alpha.3",
|
|
34
|
+
"@auipage/types": "^0.1.0-alpha.3",
|
|
35
35
|
"oipage": "^2.1.0"
|
|
36
36
|
}
|
|
37
37
|
}
|
package/src/index.js
CHANGED