@auipage/model 0.1.0-alpha.1 → 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/CHANGELOG CHANGED
@@ -2,8 +2,3 @@ v0.1.0:
2
2
  date:
3
3
  changes:
4
4
  - 初始化版本
5
- 1、@auipage/types 提供类型定义
6
- 2、@auipage/core 提供核心功能
7
- 3、@auipage/model 提供模型相关功能
8
- 4、@auipage/agent 提供智能体相关功能
9
- 5、@auipage/fetch 提供数据获取相关功能
@@ -0,0 +1 @@
1
+ export * from '../types/index.d.ts'
package/dist/index.js ADDED
@@ -0,0 +1,409 @@
1
+ /*! @auipage/model 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_model = {}));
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
+ exports.Model = Model;
408
+
409
+ }));
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@auipage/model",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.3",
4
4
  "description": "@auipage/model",
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,7 +30,7 @@
30
30
  },
31
31
  "homepage": "https://github.com/handless-ui/auipage#readme",
32
32
  "dependencies": {
33
- "@auipage/fetch": "^0.1.0-alpha.1",
34
- "@auipage/types": "^0.1.0-alpha.1"
33
+ "@auipage/fetch": "^0.1.0-alpha.3",
34
+ "@auipage/types": "^0.1.0-alpha.3"
35
35
  }
36
36
  }
@@ -1,4 +1,4 @@
1
- import { fetch } from "@auipage/fetch";
1
+ import { fetch } from "@auipage/fetch/src/index.js";
2
2
  import parseString from "./parseString.js";
3
3
  import handleChoices from "./streamHandler.js";
4
4