@leikeduntech/leiai-js 4.0.4 → 4.1.1

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 (2) hide show
  1. package/build/index.js +204 -307
  2. package/package.json +1 -1
package/build/index.js CHANGED
@@ -1,3 +1,10 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
1
8
  // src/chatgpt-api.ts
2
9
  import { Spark } from "@leikeduntech/spark-nodejs";
3
10
  import Keyv from "keyv";
@@ -113,46 +120,6 @@ var uuidv4Re = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9
113
120
  function isValidUUIDv4(str) {
114
121
  return str && uuidv4Re.test(str);
115
122
  }
116
- function convertArrayToString(arr) {
117
- let result = "[";
118
- for (let i = 0; i < arr.length; i++) {
119
- const obj = arr[i];
120
- const keys = Object.keys(obj);
121
- result += "{";
122
- for (let j = 0; j < keys.length; j++) {
123
- const key = keys[j];
124
- const value = obj[key];
125
- result += '"' + key + '":' + (typeof value === "string" ? '"' + value + '"' : value) + ",";
126
- }
127
- result = result.slice(0, -1);
128
- result += "},";
129
- }
130
- result = result.slice(0, -1);
131
- result += "]";
132
- return result;
133
- }
134
- function signTencentHunyuan(bodyData, url, keyList) {
135
- const sortedObj = {};
136
- Object.keys(bodyData).sort().forEach((key) => {
137
- sortedObj[key] = bodyData[key];
138
- });
139
- let signStr = "";
140
- for (let key in sortedObj) {
141
- if (signStr) {
142
- if (typeof sortedObj[key] === "object") {
143
- signStr += `&${key}=${convertArrayToString(sortedObj[key])}`;
144
- } else {
145
- signStr += `&${key}=${sortedObj[key]}`;
146
- }
147
- } else {
148
- signStr += `${key}=${sortedObj[key]}`;
149
- }
150
- }
151
- signStr = `${url.replace("https://", "")}?${signStr}`;
152
- const hmac = CryptoJS.HmacSHA1(signStr, keyList[2]);
153
- const signBase64 = CryptoJS.enc.Base64.stringify(hmac);
154
- return signBase64;
155
- }
156
123
  function isPositiveNumber(str) {
157
124
  return /^[1-9]\d*$/.test(str);
158
125
  }
@@ -248,6 +215,7 @@ var ChatGPTAPI = class {
248
215
  * @returns The response from ChatGPT
249
216
  */
250
217
  async sendMessage(text, opts = {}, pluginParams) {
218
+ var _a, _b, _c, _d, _e, _f, _g, _h;
251
219
  let parentMsg;
252
220
  if (pluginParams) {
253
221
  parentMsg = await this._getMessageById(pluginParams.assistant_res.id);
@@ -279,8 +247,42 @@ var ChatGPTAPI = class {
279
247
  let latestQuestion = message, last_assistant_res_message = null, last_assistant_res = null, last_plugin_res = null;
280
248
  if (pluginParams) {
281
249
  last_assistant_res_message = pluginParams.assistant_res.detail.choices[0];
250
+ let toolCalls = ((_a = last_assistant_res_message == null ? void 0 : last_assistant_res_message.message) == null ? void 0 : _a.tool_calls) || [];
251
+ if (!toolCalls || toolCalls.length === 0) {
252
+ toolCalls = ((_b = last_assistant_res_message == null ? void 0 : last_assistant_res_message.delta) == null ? void 0 : _b.tool_calls) || [];
253
+ }
254
+ if (!toolCalls || toolCalls.length === 0) {
255
+ toolCalls = ((_f = (_e = (_d = (_c = pluginParams.assistant_res.detail) == null ? void 0 : _c.choices) == null ? void 0 : _d[0]) == null ? void 0 : _e.delta) == null ? void 0 : _f.tool_calls) || [];
256
+ }
257
+ if ((!toolCalls || toolCalls.length === 0) && pluginParams.plugin_res && Array.isArray(pluginParams.plugin_res) && pluginParams.plugin_res.length > 0) {
258
+ const firstPluginRes = pluginParams.plugin_res[0];
259
+ if (firstPluginRes == null ? void 0 : firstPluginRes.skill) {
260
+ toolCalls = [{
261
+ id: `call_${Date.now()}`,
262
+ type: "function",
263
+ function: {
264
+ name: firstPluginRes.skill,
265
+ arguments: "{}"
266
+ },
267
+ index: 0
268
+ }];
269
+ }
270
+ }
271
+ if (!toolCalls || toolCalls.length === 0) {
272
+ throw new Error("\u65E0\u6CD5\u4ECE assistant_res \u4E2D\u83B7\u53D6 tool_calls\uFF0C\u8BF7\u786E\u4FDD assistant_res.detail.choices[0].message.tool_calls \u6216 delta.tool_calls \u5B58\u5728");
273
+ }
274
+ if (!last_assistant_res_message.message) {
275
+ last_assistant_res_message.message = {
276
+ role: ((_g = last_assistant_res_message.message) == null ? void 0 : _g.role) || "assistant",
277
+ tool_calls: toolCalls
278
+ };
279
+ } else {
280
+ if (!last_assistant_res_message.message.tool_calls || last_assistant_res_message.message.tool_calls.length === 0) {
281
+ last_assistant_res_message.message.tool_calls = toolCalls;
282
+ }
283
+ }
282
284
  last_assistant_res = {
283
- role: last_assistant_res_message.message.role,
285
+ role: last_assistant_res_message.message.role || "assistant",
284
286
  id: parentMsg.id,
285
287
  conversationId,
286
288
  parentMessageId: parentMsg.parentMessageId,
@@ -291,15 +293,23 @@ var ChatGPTAPI = class {
291
293
  if (this._manufacturer.toLowerCase() === "azure") {
292
294
  r = "function";
293
295
  }
296
+ let pluginContent = pluginParams.plugin_res;
297
+ if (Array.isArray(pluginContent) && pluginContent.length > 0) {
298
+ pluginContent = ((_h = pluginContent[0]) == null ? void 0 : _h.result) || pluginContent[0] || pluginContent;
299
+ }
300
+ if (typeof pluginContent !== "string") {
301
+ pluginContent = JSON.stringify(pluginContent);
302
+ }
294
303
  last_plugin_res = {
295
304
  role: r,
296
305
  id: messageId,
297
- name: last_assistant_res_message.message.tool_calls[0].function.name,
306
+ name: toolCalls[0].function.name,
298
307
  conversationId,
299
308
  parentMessageId: pluginParams.assistant_res.id,
300
309
  text,
301
- content: pluginParams.plugin_res,
302
- tool_call_id: last_assistant_res_message.message.tool_calls[0].id
310
+ // ChatMessage.content 类型是 object,这里显式转为 any 以兼容字符串内容
311
+ content: pluginContent,
312
+ tool_call_id: toolCalls[0].id
303
313
  };
304
314
  await this._upsertMessage(last_assistant_res);
305
315
  latestQuestion = last_plugin_res;
@@ -332,7 +342,7 @@ var ChatGPTAPI = class {
332
342
  };
333
343
  const responseP = new Promise(
334
344
  async (resolve, reject) => {
335
- var _a, _b, _c, _d, _e, _f, _g, _h;
345
+ var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
336
346
  let url = `${this._apiBaseUrl}/chat/completions`;
337
347
  const headers = {
338
348
  "Content-Type": "application/json",
@@ -373,74 +383,7 @@ var ChatGPTAPI = class {
373
383
  delete body.max_tokens;
374
384
  }
375
385
  if (typeof body.plugins !== void 0) delete body.plugins;
376
- if (["openai", "azure"].indexOf(this._manufacturer.toLowerCase()) > -1) {
377
- if (body.tools && Array.isArray(body.tools) && body.tools.length > 0) {
378
- if (this._manufacturer.toLowerCase() === "azure") {
379
- body.functions = body.tools.map((tool) => {
380
- if (tool.type === "function" && tool.function) {
381
- return tool.function;
382
- }
383
- return tool;
384
- });
385
- delete body.tools;
386
- if (body.tool_choice) {
387
- if (typeof body.tool_choice === "string") {
388
- body.function_call = body.tool_choice === "none" ? "none" : "auto";
389
- } else if (body.tool_choice && typeof body.tool_choice === "object" && body.tool_choice.function) {
390
- body.function_call = { name: body.tool_choice.function.name };
391
- }
392
- delete body.tool_choice;
393
- }
394
- }
395
- }
396
- }
397
- if (["openai", "azure"].indexOf(this._manufacturer.toLowerCase()) === -1) {
398
- if (body.tools) delete body.tools;
399
- if (body.tool_choice) delete body.tool_choice;
400
- if (body.functions) delete body.functions;
401
- if (body.function_call) delete body.function_call;
402
- if (body.parallel_tool_calls) delete body.parallel_tool_calls;
403
- }
404
- if (this._manufacturer.toLowerCase() === "aliyun") {
405
- body = Object.assign(body, {
406
- parameters: { result_format: "message" },
407
- input: { messages }
408
- });
409
- delete body.messages;
410
- } else if (this._manufacturer.toLowerCase() === "zhipu") {
411
- if (completionParams.model === "glm-4") {
412
- } else {
413
- delete body.messages;
414
- body = Object.assign(body, { prompt: messages });
415
- }
416
- } else if (this._manufacturer.toLowerCase() === "tencent") {
417
- url = this._apiBaseUrl;
418
- const timestamp = Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3) + 1;
419
- const keyList = this._apiKey.split(".");
420
- body = Object.assign(body, {
421
- app_id: parseInt(keyList[0]),
422
- secret_id: keyList[1],
423
- timestamp,
424
- expired: timestamp + 24 * 60 * 60,
425
- stream: stream ? 1 : 0
426
- });
427
- delete body.model;
428
- delete body.max_tokens;
429
- headers["Authorization"] = signTencentHunyuan(body, url, keyList);
430
- } else if (this._manufacturer.toLowerCase() === "chatdoc") {
431
- let query = messages.splice(messages.length - 1, 1);
432
- body = Object.assign(body, {
433
- upload_id: (_a = completionParams == null ? void 0 : completionParams.extParams) == null ? void 0 : _a.upload_id,
434
- question: (_b = query[0]) == null ? void 0 : _b.content,
435
- history: messages
436
- });
437
- if (body.extParams) delete body.extParams;
438
- if (body.model) delete body.model;
439
- if (body.max_tokens) delete body.max_tokens;
440
- if (body.temperature) delete body.temperature;
441
- if (body.messages) delete body.messages;
442
- }
443
- if (this._apiOrg && this._manufacturer.toLowerCase() === "openai") {
386
+ if (this._apiOrg) {
444
387
  headers["OpenAI-Organization"] = this._apiOrg;
445
388
  }
446
389
  if (this._debug) {
@@ -453,6 +396,32 @@ var ChatGPTAPI = class {
453
396
  typeof messages
454
397
  );
455
398
  }
399
+ if (pluginParams) {
400
+ const debugLog = {
401
+ location: "chatgpt-api.ts:430",
402
+ message: "Second sendMessage with pluginParams",
403
+ data: {
404
+ manufacturer: this._manufacturer,
405
+ messagesLength: messages.length,
406
+ messages: JSON.stringify(messages).substring(0, 2e3),
407
+ hasPluginRes: !!(pluginParams == null ? void 0 : pluginParams.plugin_res),
408
+ pluginResPreview: JSON.stringify(pluginParams == null ? void 0 : pluginParams.plugin_res).substring(0, 500),
409
+ bodyMessagesLength: (_a2 = body.messages) == null ? void 0 : _a2.length,
410
+ bodyMessages: JSON.stringify(body.messages).substring(0, 2e3),
411
+ stream,
412
+ url
413
+ },
414
+ timestamp: Date.now(),
415
+ sessionId: "debug-session",
416
+ runId: "run19",
417
+ hypothesisId: "T"
418
+ };
419
+ try {
420
+ const fs = __require("fs");
421
+ fs.appendFileSync("/Volumes/softdev2/gpt-project/LeiAI-Web-H5/.cursor/debug.log", JSON.stringify(debugLog) + "\n");
422
+ } catch (e) {
423
+ }
424
+ }
456
425
  if (this._manufacturer.toLowerCase() === "xunfei") {
457
426
  const self = this;
458
427
  const keyList = this._apiKey.split(".");
@@ -504,8 +473,30 @@ var ChatGPTAPI = class {
504
473
  body: JSON.stringify(body),
505
474
  signal: abortSignal,
506
475
  onMessage: (data) => {
507
- var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B;
476
+ var _a3, _b3, _c3, _d3, _e3, _f3, _g3, _h2, _i;
508
477
  if (data === "[DONE]") {
478
+ if (pluginParams) {
479
+ const debugLog = {
480
+ location: "chatgpt-api.ts:520",
481
+ message: "Second sendMessage stream DONE",
482
+ data: {
483
+ manufacturer: this._manufacturer,
484
+ finalTextLength: result.text.length,
485
+ finalTextPreview: result.text.substring(0, 500),
486
+ hasDetail: !!result.detail,
487
+ resultKeys: Object.keys(result || {})
488
+ },
489
+ timestamp: Date.now(),
490
+ sessionId: "debug-session",
491
+ runId: "run19",
492
+ hypothesisId: "T"
493
+ };
494
+ try {
495
+ const fs = __require("fs");
496
+ fs.appendFileSync("/Volumes/softdev2/gpt-project/LeiAI-Web-H5/.cursor/debug.log", JSON.stringify(debugLog) + "\n");
497
+ } catch (e) {
498
+ }
499
+ }
509
500
  result.text = result.text.trim();
510
501
  return resolve(result);
511
502
  }
@@ -518,134 +509,80 @@ var ChatGPTAPI = class {
518
509
  response == null ? void 0 : response.choices
519
510
  );
520
511
  }
521
- if (this._manufacturer.toLowerCase() === "baidu") {
522
- if ((response == null ? void 0 : response.is_end) === true) {
523
- result.text += response.result.trim();
524
- result.detail = response;
525
- return resolve(result);
526
- }
527
- } else if (this._manufacturer.toLowerCase() === "azure") {
528
- if (((_a2 = response.choices[0]) == null ? void 0 : _a2.finish_reason) === "stop") {
529
- result.text = result.text.trim();
530
- return resolve(result);
531
- }
532
- } else if (this._manufacturer.toLowerCase() === "aliyun") {
533
- if (["stop", "length"].indexOf(
534
- (_c2 = (_b2 = response == null ? void 0 : response.output) == null ? void 0 : _b2.choices[0]) == null ? void 0 : _c2.finish_reason
535
- ) > -1) {
536
- result.text = (_f2 = (_e2 = (_d2 = response == null ? void 0 : response.output) == null ? void 0 : _d2.choices[0]) == null ? void 0 : _e2.message) == null ? void 0 : _f2.content.trim();
537
- return resolve(result);
538
- }
539
- } else if (this._manufacturer.toLowerCase() === "zhipu") {
540
- if (completionParams.model === "glm-4") {
541
- const gelResponse = JSON.parse(response.data);
542
- if (((_h2 = (_g2 = gelResponse == null ? void 0 : gelResponse.choices) == null ? void 0 : _g2[0]) == null ? void 0 : _h2.finish_reason) === "stop") {
543
- result.text = result.text.trim();
544
- return resolve(result);
545
- }
546
- } else {
547
- if ((response == null ? void 0 : response.event) === "finish") {
548
- result.text += response == null ? void 0 : response.data.trim();
549
- return resolve(result);
550
- }
551
- }
552
- } else if (this._manufacturer.toLowerCase() === "tencent") {
553
- if (((_i = response.choices[0]) == null ? void 0 : _i.finish_reason) === "stop") {
554
- result.text += (_k = (_j = response == null ? void 0 : response.choices[0]) == null ? void 0 : _j.delta) == null ? void 0 : _k.content.trim();
555
- return resolve(result);
556
- }
557
- } else if (this._manufacturer.toLowerCase() === "chatdoc") {
558
- result.id = `chatdoc-${Math.floor(
559
- Math.random() * 1e7
560
- )}${(/* @__PURE__ */ new Date()).getTime()}`;
561
- if (response == null ? void 0 : response.source_info) {
562
- result.text += response == null ? void 0 : response.answer;
563
- return resolve(result);
564
- }
565
- }
566
- if (this._manufacturer.toLowerCase() === "aliyun") {
567
- if (response == null ? void 0 : response.request_id) {
568
- result.id = response.request_id;
569
- }
570
- } else {
571
- if (response == null ? void 0 : response.id) {
572
- result.id = response.id;
573
- }
574
- }
575
- if (((_l = response.choices) == null ? void 0 : _l.length) && ["openai", "azure", "tencent", "anthropic"].indexOf(
576
- this._manufacturer.toLowerCase()
577
- ) > -1) {
512
+ if (((_a3 = response.choices) == null ? void 0 : _a3.length) && ((_b3 = response.choices[0]) == null ? void 0 : _b3.delta) !== void 0) {
578
513
  const delta = response.choices[0].delta;
514
+ const finishReason = response.choices[0].finish_reason;
579
515
  result.delta = "";
580
- if (response.choices[0].finish_reason === "tool_calls") {
516
+ if (finishReason === "tool_calls") {
581
517
  result.delta = text;
582
518
  } else if (delta.content) {
583
519
  result.delta = delta.content;
584
520
  }
585
- if (delta == null ? void 0 : delta.content) result.text += result.delta;
521
+ if (delta == null ? void 0 : delta.content) {
522
+ result.text += result.delta;
523
+ }
586
524
  result.role = "assistant";
587
- if (response.choices[0].finish_reason === "tool_calls") {
588
- } else if (delta.role) {
525
+ if (finishReason !== "tool_calls" && delta.role) {
589
526
  result.role = delta.role;
590
527
  }
591
528
  result.detail = response;
592
- onProgress == null ? void 0 : onProgress(result);
593
- } else if ((response == null ? void 0 : response.result) && this._manufacturer.toLowerCase() === "baidu") {
594
- result.delta = response.result;
595
- if (response == null ? void 0 : response.result) result.text += response.result;
596
- result.role = "assistant";
597
- result.detail = response;
598
- onProgress == null ? void 0 : onProgress(result);
599
- } else if ((response == null ? void 0 : response.output) && this._manufacturer.toLowerCase() === "aliyun") {
600
- response.usage = Object.assign(response.usage, {
601
- prompt_tokens: (_m = response.usage) == null ? void 0 : _m.input_tokens,
602
- completion_tokens: (_n = response.usage) == null ? void 0 : _n.output_tokens,
603
- total_tokens: ((_o = response.usage) == null ? void 0 : _o.input_tokens) + ((_p = response.usage) == null ? void 0 : _p.output_tokens)
604
- });
605
- result.delta = "";
606
- if ((_s = (_r = (_q = response == null ? void 0 : response.output) == null ? void 0 : _q.choices[0]) == null ? void 0 : _r.message) == null ? void 0 : _s.content)
607
- result.text = (_v = (_u = (_t = response == null ? void 0 : response.output) == null ? void 0 : _t.choices[0]) == null ? void 0 : _u.message) == null ? void 0 : _v.content;
608
- result.role = "assistant";
609
- result.detail = response;
610
- onProgress == null ? void 0 : onProgress(result);
611
- } else if ((response == null ? void 0 : response.data) && this._manufacturer.toLowerCase() === "zhipu") {
612
- if (completionParams.model === "glm-4") {
613
- const glmResponse = JSON.parse(response.data);
614
- if (((_x = (_w = glmResponse == null ? void 0 : glmResponse.choices) == null ? void 0 : _w[0]) == null ? void 0 : _x.finish_reason) === "stop") {
615
- response.usage = glmResponse.usage;
616
- }
617
- let data2 = (_z = (_y = glmResponse == null ? void 0 : glmResponse.choices) == null ? void 0 : _y[0]) == null ? void 0 : _z.delta.content;
618
- result.delta = data2;
619
- if (data2) {
620
- result.text += data2;
621
- }
622
- result.role = "assistant";
623
- result.detail = response;
624
- onProgress == null ? void 0 : onProgress(result);
625
- } else {
626
- if (response.event === "finish") {
627
- if ((_A = response == null ? void 0 : response.meta) == null ? void 0 : _A.usage) {
628
- response.usage = (_B = response == null ? void 0 : response.meta) == null ? void 0 : _B.usage;
629
- } else {
630
- response.usage = {
631
- prompt_tokens: 1,
632
- completion_tokens: 1,
633
- total_tokens: 2
634
- };
635
- }
529
+ if (response == null ? void 0 : response.id) {
530
+ result.id = response.id;
531
+ }
532
+ if (pluginParams) {
533
+ const debugLog = {
534
+ location: "chatgpt-api.ts:570",
535
+ message: "Second sendMessage onMessage (streaming)",
536
+ data: {
537
+ manufacturer: this._manufacturer,
538
+ hasDelta: !!delta,
539
+ deltaContent: delta == null ? void 0 : delta.content,
540
+ deltaContentLength: (_c3 = delta == null ? void 0 : delta.content) == null ? void 0 : _c3.length,
541
+ finishReason,
542
+ resultTextLength: result.text.length,
543
+ resultTextPreview: result.text.substring(0, 200),
544
+ responseChoicesLength: (_d3 = response.choices) == null ? void 0 : _d3.length
545
+ },
546
+ timestamp: Date.now(),
547
+ sessionId: "debug-session",
548
+ runId: "run19",
549
+ hypothesisId: "T"
550
+ };
551
+ try {
552
+ const fs = __require("fs");
553
+ fs.appendFileSync("/Volumes/softdev2/gpt-project/LeiAI-Web-H5/.cursor/debug.log", JSON.stringify(debugLog) + "\n");
554
+ } catch (e) {
636
555
  }
637
- result.delta = response.data;
638
- if (response == null ? void 0 : response.data) result.text += response == null ? void 0 : response.data;
639
- result.role = "assistant";
640
- result.detail = response;
641
- onProgress == null ? void 0 : onProgress(result);
642
556
  }
643
- } else if ((response == null ? void 0 : response.answer) && this._manufacturer.toLowerCase() === "chatdoc") {
644
- result.delta = response.answer;
645
- if (response == null ? void 0 : response.answer) result.text += response.answer;
646
- result.role = "assistant";
647
- result.detail = response;
648
557
  onProgress == null ? void 0 : onProgress(result);
558
+ if (finishReason === "stop" || finishReason === "length") {
559
+ result.text = result.text.trim();
560
+ return resolve(result);
561
+ }
562
+ } else {
563
+ if (pluginParams) {
564
+ const debugLog = {
565
+ location: "chatgpt-api.ts:605",
566
+ message: "Second sendMessage onMessage (unexpected format)",
567
+ data: {
568
+ manufacturer: this._manufacturer,
569
+ responseStructure: JSON.stringify(response).substring(0, 1e3),
570
+ hasChoices: !!response.choices,
571
+ choicesLength: (_e3 = response.choices) == null ? void 0 : _e3.length,
572
+ firstChoiceDelta: (_g3 = (_f3 = response.choices) == null ? void 0 : _f3[0]) == null ? void 0 : _g3.delta,
573
+ firstChoiceFinishReason: (_i = (_h2 = response.choices) == null ? void 0 : _h2[0]) == null ? void 0 : _i.finish_reason
574
+ },
575
+ timestamp: Date.now(),
576
+ sessionId: "debug-session",
577
+ runId: "run19",
578
+ hypothesisId: "T"
579
+ };
580
+ try {
581
+ const fs = __require("fs");
582
+ fs.appendFileSync("/Volumes/softdev2/gpt-project/LeiAI-Web-H5/.cursor/debug.log", JSON.stringify(debugLog) + "\n");
583
+ } catch (e) {
584
+ }
585
+ }
649
586
  }
650
587
  } catch (err) {
651
588
  console.warn(
@@ -682,35 +619,21 @@ var ChatGPTAPI = class {
682
619
  console.log(
683
620
  `row data ${typeof response} : `,
684
621
  response,
685
- (response == null ? void 0 : response.choices) && ((_c = response == null ? void 0 : response.choices[0]) == null ? void 0 : _c.message)
622
+ (response == null ? void 0 : response.choices) && ((_b2 = response == null ? void 0 : response.choices[0]) == null ? void 0 : _b2.message)
686
623
  );
687
624
  }
688
- if (this._manufacturer.toLowerCase() === "aliyun") {
689
- if (response == null ? void 0 : response.request_id) {
690
- result.id = response.request_id;
691
- }
692
- } else {
693
- if (response == null ? void 0 : response.id) {
694
- result.id = response.id;
695
- }
625
+ if (response == null ? void 0 : response.id) {
626
+ result.id = response.id;
696
627
  }
697
- if (((_d = response == null ? void 0 : response.choices) == null ? void 0 : _d.length) && ["openai", "azure"].indexOf(this._manufacturer.toLowerCase()) > -1) {
628
+ if (((_c2 = response == null ? void 0 : response.choices) == null ? void 0 : _c2.length) && ((_d2 = response.choices[0]) == null ? void 0 : _d2.message)) {
698
629
  const message2 = response.choices[0].message;
699
- result.text = message2.content;
700
- if (message2.role) {
701
- result.role = message2.role;
702
- }
703
- } else if ((response == null ? void 0 : response.result) && this._manufacturer.toLowerCase() === "baidu") {
704
- result.text = response.result;
705
- result.role = "assistant";
706
- } else if (((_e = response == null ? void 0 : response.output) == null ? void 0 : _e.text) && this._manufacturer.toLowerCase() === "aliyun") {
707
- result.text = (_f = response == null ? void 0 : response.output) == null ? void 0 : _f.text;
708
- result.role = "assistant";
630
+ result.text = message2.content || "";
631
+ result.role = message2.role || "assistant";
709
632
  } else {
710
633
  const res2 = response;
711
634
  return reject(
712
635
  new Error(
713
- `${this._manufacturer} error: ${((_g = res2 == null ? void 0 : res2.detail) == null ? void 0 : _g.message) || ((_h = res2 == null ? void 0 : res2.detail) == null ? void 0 : _h.error_msg) || (res2 == null ? void 0 : res2.detail) || "unknown"}`
636
+ `API error: ${((_e2 = res2 == null ? void 0 : res2.detail) == null ? void 0 : _e2.message) || ((_f2 = res2 == null ? void 0 : res2.detail) == null ? void 0 : _f2.error_msg) || ((_g2 = res2 == null ? void 0 : res2.error) == null ? void 0 : _g2.message) || (res2 == null ? void 0 : res2.detail) || "unknown"}`
714
637
  )
715
638
  );
716
639
  }
@@ -725,7 +648,7 @@ var ChatGPTAPI = class {
725
648
  }
726
649
  }
727
650
  ).then(async (message2) => {
728
- var _a, _b, _c, _d, _e;
651
+ var _a2, _b2, _c2, _d2, _e2;
729
652
  if (this._debug) console.log("\u8DDF\u8E2A7", JSON.stringify(message2));
730
653
  if (message2.detail) {
731
654
  if (!message2.detail.usage) {
@@ -733,7 +656,7 @@ var ChatGPTAPI = class {
733
656
  const promptTokens = numTokens;
734
657
  let completionTokens = 0;
735
658
  if (["baidu", "aliyun"].indexOf(this._manufacturer.toLowerCase()) > -1) {
736
- completionTokens = (_b = (_a = message2.detail) == null ? void 0 : _a.usage) == null ? void 0 : _b.total_tokens;
659
+ completionTokens = (_b2 = (_a2 = message2.detail) == null ? void 0 : _a2.usage) == null ? void 0 : _b2.total_tokens;
737
660
  } else {
738
661
  completionTokens = await this._getTokenCount(message2.text);
739
662
  }
@@ -747,7 +670,7 @@ var ChatGPTAPI = class {
747
670
  }
748
671
  }
749
672
  if (this._manufacturer.toLowerCase() === "azure") {
750
- if (((_d = (_c = message2.detail) == null ? void 0 : _c.choices[0]) == null ? void 0 : _d.finish_reason) === "function_call") {
673
+ if (((_d2 = (_c2 = message2.detail) == null ? void 0 : _c2.choices[0]) == null ? void 0 : _d2.finish_reason) === "function_call") {
751
674
  message2.detail.choices[0].finish_reason = "tool_calls";
752
675
  message2.detail.choices[0].message = {
753
676
  role: message2.detail.choices[0].message.role,
@@ -755,7 +678,7 @@ var ChatGPTAPI = class {
755
678
  {
756
679
  id: `call_${uuidv4()}`,
757
680
  type: "function",
758
- function: (_e = message2.detail.choices[0].message) == null ? void 0 : _e.function_call
681
+ function: (_e2 = message2.detail.choices[0].message) == null ? void 0 : _e2.function_call
759
682
  }
760
683
  ]
761
684
  };
@@ -824,7 +747,7 @@ var ChatGPTAPI = class {
824
747
  this._apiOrg = apiOrg;
825
748
  }
826
749
  async _buildMessages(text, opts, pluginData) {
827
- var _a, _b;
750
+ var _a;
828
751
  const { systemMessage = this._systemMessage, completionParams } = opts;
829
752
  let { parentMessageId, contextRestriction } = opts;
830
753
  let errorMessage = "";
@@ -856,59 +779,55 @@ var ChatGPTAPI = class {
856
779
  }
857
780
  const systemMessageOffset = messages.length;
858
781
  let userMessage = null;
859
- if ([
860
- "baidu",
861
- "zhipu",
862
- "xunfei",
863
- "aliyun",
864
- "tencent",
865
- "chatdoc",
866
- "anthropic"
867
- ].indexOf(this._manufacturer.toLowerCase()) > -1) {
868
- userMessage = [{ role: "user", content: text }];
869
- } else if (pluginData) {
782
+ if (pluginData) {
783
+ let pluginContent = pluginData.content;
784
+ if (typeof pluginContent !== "string") {
785
+ pluginContent = JSON.stringify(pluginContent);
786
+ }
870
787
  userMessage = {
871
- role: pluginData.role,
788
+ role: pluginData.role || "tool",
872
789
  name: pluginData.name,
873
- content: JSON.stringify(pluginData.content),
790
+ content: pluginContent,
874
791
  tool_call_id: pluginData.tool_call_id
875
792
  };
876
- if (["azure"].indexOf(this._manufacturer.toLowerCase()) > -1) {
877
- delete userMessage.tool_call_id;
878
- }
879
793
  } else {
880
794
  userMessage = [{ role: "user", content: text, name: opts.name }];
881
795
  }
882
796
  let nextMessages = messages;
883
797
  if (pluginData || text) {
884
- nextMessages = nextMessages.concat(userMessage);
798
+ if (Array.isArray(userMessage)) {
799
+ nextMessages = nextMessages.concat(userMessage);
800
+ } else {
801
+ nextMessages = nextMessages.concat([userMessage]);
802
+ }
885
803
  }
886
804
  let numTokens = 0;
887
805
  do {
888
806
  const prompt = nextMessages.reduce((prompt2, message) => {
807
+ const content = typeof message === "object" && message.content !== void 0 ? typeof message.content === "string" ? message.content : JSON.stringify(message.content) : typeof message === "string" ? message : JSON.stringify(message);
889
808
  switch (message.role) {
890
809
  case "tool":
891
810
  return prompt2.concat([`Tool:
892
811
  function call`]);
893
812
  case "system":
894
813
  return prompt2.concat([`Instructions:
895
- ${message.content}`]);
814
+ ${content}`]);
896
815
  case "user":
897
816
  return prompt2.concat([`${userLabel}:
898
- ${message.content}`]);
817
+ ${content}`]);
899
818
  default:
900
819
  return prompt2.concat([`${assistantLabel}:
901
- ${message.content}`]);
820
+ ${content}`]);
902
821
  }
903
822
  }, []).join("\n\n");
904
823
  const nextNumTokensEstimate = await this._getTokenCount(prompt);
905
824
  const isValidPrompt = nextNumTokensEstimate <= maxNumTokens;
906
- if (prompt && !isValidPrompt && ["openai", "azure"].indexOf(this._manufacturer.toLowerCase()) > -1) {
825
+ if (prompt && !isValidPrompt) {
907
826
  break;
908
827
  }
909
828
  messages = nextMessages;
910
829
  numTokens = nextNumTokensEstimate;
911
- if (!isValidPrompt && ["openai", "azure"].indexOf(this._manufacturer.toLowerCase()) > -1) {
830
+ if (!isValidPrompt) {
912
831
  break;
913
832
  }
914
833
  if (!parentMessageId) {
@@ -920,29 +839,8 @@ ${message.content}`]);
920
839
  }
921
840
  const parentMessageRole = parentMessage.role || "user";
922
841
  let parentMessageItem = null;
923
- if ([
924
- "baidu",
925
- "zhipu",
926
- "xunfei",
927
- "aliyun",
928
- "tencent",
929
- "chatdoc",
930
- "anthropic"
931
- ].indexOf(this._manufacturer.toLowerCase()) > -1) {
932
- parentMessageItem = {
933
- role: parentMessageRole,
934
- content: parentMessage.text
935
- };
936
- } else if (parentMessage.content && ((_a = parentMessage.content) == null ? void 0 : _a.finish_reason) === "tool_calls") {
937
- if (["azure"].indexOf(this._manufacturer.toLowerCase()) > -1) {
938
- parentMessageItem = Object.assign(parentMessage.content.message, {
939
- function_call: (_b = parentMessage.content.message.tool_calls[0]) == null ? void 0 : _b.function,
940
- content: parentMessage.text || parentMessage.content
941
- });
942
- delete parentMessage.content.message.tool_calls;
943
- } else {
944
- parentMessageItem = parentMessage.content.message;
945
- }
842
+ if (parentMessage.content && ((_a = parentMessage.content) == null ? void 0 : _a.finish_reason) === "tool_calls") {
843
+ parentMessageItem = parentMessage.content.message;
946
844
  } else {
947
845
  parentMessageItem = {
948
846
  role: parentMessageRole,
@@ -958,14 +856,13 @@ ${message.content}`]);
958
856
  } while (true);
959
857
  let maxTokens = this._maxModelTokens;
960
858
  if (isPositiveNumber(maxTokens)) {
961
- if (["openai", "azure"].indexOf(this._manufacturer.toLowerCase()) > -1) {
962
- maxTokens = Math.max(
963
- 1,
964
- Math.min(this._maxModelTokens - numTokens, this._maxResponseTokens)
965
- );
966
- } else if (numTokens > this._maxModelTokens) {
859
+ maxTokens = Math.max(
860
+ 1,
861
+ Math.min(this._maxModelTokens - numTokens, this._maxResponseTokens)
862
+ );
863
+ if (numTokens > this._maxModelTokens) {
967
864
  maxTokens = this._maxModelTokens;
968
- errorMessage = `${this._manufacturer}\uFF1A\u5F53\u524D\u63D0\u95EE\u4E0A\u4E0B\u6587\u5185\u5BB9\u957F\u5EA6${numTokens}tokns\u8D85\u957F\uFF0C\u8BE5\u6A21\u578B\u6700\u5927\u63D0\u95EE\u957F\u5EA6\u4E3A${this._maxModelTokens}tokens\uFF0C\u8BF7\u5207\u6362\u5176\u4ED6\u589E\u5F3AAI\u6A21\u578B\u6216\u51CF\u5C11\u5B57\u6570\u6216\u8005\u5173\u95ED\u4E0A\u4E0B\u6587\u5386\u53F2\u63D0\u9AD8\u5355\u6B21\u63D0\u95EE\u957F\u5EA6\uFF01`;
865
+ errorMessage = `\u5F53\u524D\u63D0\u95EE\u4E0A\u4E0B\u6587\u5185\u5BB9\u957F\u5EA6${numTokens}tokens\u8D85\u957F\uFF0C\u8BE5\u6A21\u578B\u6700\u5927\u63D0\u95EE\u957F\u5EA6\u4E3A${this._maxModelTokens}tokens\uFF0C\u8BF7\u5207\u6362\u5176\u4ED6\u589E\u5F3AAI\u6A21\u578B\u6216\u51CF\u5C11\u5B57\u6570\u6216\u8005\u5173\u95ED\u4E0A\u4E0B\u6587\u5386\u53F2\u63D0\u9AD8\u5355\u6B21\u63D0\u95EE\u957F\u5EA6\uFF01`;
969
866
  }
970
867
  }
971
868
  return { messages, maxTokens, numTokens, errorMessage, objText };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leikeduntech/leiai-js",
3
- "version": "4.0.4",
3
+ "version": "4.1.1",
4
4
  "author": "liuhean",
5
5
  "repository": {
6
6
  "type": "git",