@leikeduntech/leiai-js 2.7.1 → 2.9.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/build/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import Keyv from 'keyv';
2
2
 
3
- type Role = 'user' | 'assistant' | 'system' | 'function';
3
+ type Role = 'user' | 'assistant' | 'system' | 'function' | 'tool';
4
4
  type FetchFn = typeof fetch;
5
5
  type ChatGPTAPIOptions = {
6
6
  /** 模型厂商公司 **/
@@ -35,6 +35,10 @@ type SendMessageOptions = {
35
35
  abortSignal?: AbortSignal;
36
36
  completionParams?: Partial<Omit<openai.CreateChatCompletionRequest, 'messages' | 'n' | 'stream'>>;
37
37
  };
38
+ type PluginParams = {
39
+ plugin_res: object;
40
+ assistant_res: ChatMessage | any;
41
+ };
38
42
  type MessageActionType = 'next' | 'variant';
39
43
  type SendMessageBrowserOptions = {
40
44
  conversationId?: string;
@@ -51,7 +55,7 @@ interface ChatMessage {
51
55
  role?: Role;
52
56
  name?: string;
53
57
  delta?: string;
54
- detail?: openai.CreateChatCompletionResponse | CreateChatCompletionStreamResponse;
58
+ detail?: openai.CreateChatCompletionResponse | CreateChatCompletionStreamResponse | any;
55
59
  parentMessageId?: string;
56
60
  conversationId?: string;
57
61
  object?: string;
@@ -59,9 +63,11 @@ interface ChatMessage {
59
63
  sentence_id?: number;
60
64
  is_end?: boolean;
61
65
  is_truncated?: boolean;
62
- result?: string;
66
+ result?: string | object;
63
67
  need_clear_history?: boolean;
64
68
  usage?: object;
69
+ tool_call_id?: string;
70
+ content?: string | object | any;
65
71
  }
66
72
  declare class ChatGPTError extends Error {
67
73
  statusCode?: number;
@@ -226,11 +232,13 @@ declare namespace openai {
226
232
  * ]}
227
233
  */
228
234
  input?: object;
235
+ tool_call_id?: string;
229
236
  }
230
237
  const ChatCompletionRequestMessageRoleEnum: {
231
238
  readonly System: 'system';
232
239
  readonly User: 'user';
233
240
  readonly Assistant: 'assistant';
241
+ readonly Tool: 'tool';
234
242
  };
235
243
  type ChatCompletionRequestMessageRoleEnum = (typeof ChatCompletionRequestMessageRoleEnum)[keyof typeof ChatCompletionRequestMessageRoleEnum];
236
244
  /**
@@ -337,6 +345,7 @@ declare namespace openai {
337
345
  */
338
346
  user?: string;
339
347
  pluginList?: string | object;
348
+ fileList?: Array<any>;
340
349
  }
341
350
  /**
342
351
  * @type CreateChatCompletionRequestStop
@@ -458,6 +467,7 @@ declare class ChatGPTAPI {
458
467
  protected _getMessageById: GetMessageByIdFunction;
459
468
  protected _upsertMessage: UpsertMessageFunction;
460
469
  protected _messageStore: Keyv<ChatMessage>;
470
+ protected _DallE3FunData: any;
461
471
  /**
462
472
  * Creates a new client wrapper around OpenAI's chat completion API, mimicing the official ChatGPT webapp's functionality as closely as possible.
463
473
  *
@@ -475,10 +485,7 @@ declare class ChatGPTAPI {
475
485
  */
476
486
  constructor(opts: ChatGPTAPIOptions);
477
487
  pluginListMap(pluginList: any): any;
478
- DallE3Fun(): {
479
- pluginList: string;
480
- description: string;
481
- };
488
+ DallE3Fun(): any;
482
489
  /**
483
490
  * Sends a message to the OpenAI chat completions endpoint, waits for the response
484
491
  * to resolve, and returns the response.
@@ -501,7 +508,7 @@ declare class ChatGPTAPI {
501
508
  *
502
509
  * @returns The response from ChatGPT
503
510
  */
504
- sendMessage(text: string, opts?: SendMessageOptions): Promise<ChatMessage>;
511
+ sendMessage(text: string, opts: SendMessageOptions, pluginParams: PluginParams): Promise<ChatMessage>;
505
512
  get manufacturer(): string;
506
513
  set manufacturer(manufacturer: string);
507
514
  get maxModelTokens(): number;
@@ -514,7 +521,7 @@ declare class ChatGPTAPI {
514
521
  set apiKey(apiKey: string);
515
522
  get apiOrg(): string;
516
523
  set apiOrg(apiOrg: string);
517
- protected _buildMessages(text: string, opts: SendMessageOptions): Promise<{
524
+ protected _buildMessages(text: string, opts: SendMessageOptions, pluginData: ChatMessage): Promise<{
518
525
  messages: openai.ChatCompletionRequestMessage[];
519
526
  maxTokens: number;
520
527
  numTokens: number;
@@ -575,4 +582,4 @@ declare class ChatGPTUnofficialProxyAPI {
575
582
  sendMessage(text: string, opts?: SendMessageBrowserOptions): Promise<ChatMessage>;
576
583
  }
577
584
 
578
- export { ChatGPTAPI, ChatGPTAPIOptions, ChatGPTError, ChatGPTUnofficialProxyAPI, ChatMessage, ContentType, ConversationJSONBody, ConversationResponseEvent, CreateChatCompletionStreamResponse, CreateCompletionStreamResponseUsage, FetchFn, GetMessageByIdFunction, Message, MessageActionType, MessageContent, MessageMetadata, Prompt, PromptContent, Role, SendMessageBrowserOptions, SendMessageOptions, UpsertMessageFunction, openai };
585
+ export { ChatGPTAPI, ChatGPTAPIOptions, ChatGPTError, ChatGPTUnofficialProxyAPI, ChatMessage, ContentType, ConversationJSONBody, ConversationResponseEvent, CreateChatCompletionStreamResponse, CreateCompletionStreamResponseUsage, FetchFn, GetMessageByIdFunction, Message, MessageActionType, MessageContent, MessageMetadata, PluginParams, Prompt, PromptContent, Role, SendMessageBrowserOptions, SendMessageOptions, UpsertMessageFunction, openai };
package/build/index.js CHANGED
@@ -227,13 +227,16 @@ var ChatGPTAPI = class {
227
227
  }
228
228
  pluginListMap(pluginList) {
229
229
  const list = {
230
- "dall-e-3": "DallE3Fun"
230
+ "dall-e-3": {
231
+ name: "DallE3Fun",
232
+ description: "\u4F7F\u7528DALL-E3\u6A21\u578B\u6839\u636E\u7528\u6237\u63CF\u8FF0\u63D0\u793A\u7ED8\u56FE\u753B\u753B\u4F5C\u56FE"
233
+ }
231
234
  };
232
235
  return list[pluginList];
233
236
  }
234
237
  // DallE3文生图插件
235
238
  DallE3Fun() {
236
- return { pluginList: "dall-e-3", description: "\u4F7F\u7528DALL-E3\u6A21\u578B\u6839\u636E\u7528\u6237\u63CF\u8FF0\u63D0\u793A\u7ED8\u56FE\u753B\u753B\u4F5C\u56FE" };
239
+ return this._DallE3FunData;
237
240
  }
238
241
  /**
239
242
  * Sends a message to the OpenAI chat completions endpoint, waits for the response
@@ -257,7 +260,7 @@ var ChatGPTAPI = class {
257
260
  *
258
261
  * @returns The response from ChatGPT
259
262
  */
260
- async sendMessage(text, opts = {}) {
263
+ async sendMessage(text, opts = {}, pluginParams) {
261
264
  var _a;
262
265
  if (this._systemMessage === void 0 && ["openai", "azure"].indexOf((_a = this._manufacturer) == null ? void 0 : _a.toLowerCase()) > -1) {
263
266
  const currentDate = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -265,7 +268,12 @@ var ChatGPTAPI = class {
265
268
  Knowledge cutoff: 2021-09-01
266
269
  Current date: ${currentDate}`;
267
270
  }
268
- const {
271
+ let parentMsg;
272
+ if (pluginParams) {
273
+ parentMsg = await this._getMessageById(pluginParams.assistant_res.id);
274
+ opts.parentMessageId = parentMsg.id;
275
+ }
276
+ let {
269
277
  parentMessageId,
270
278
  messageId = uuidv4(),
271
279
  timeoutMs,
@@ -280,17 +288,42 @@ Current date: ${currentDate}`;
280
288
  abortController = new AbortController();
281
289
  abortSignal = abortController.signal;
282
290
  }
283
- const message = {
291
+ let message = {
284
292
  role: "user",
285
293
  id: messageId,
286
294
  conversationId,
287
295
  parentMessageId,
288
296
  text
289
297
  };
290
- const latestQuestion = message;
298
+ let latestQuestion = message, last_assistant_res_message = null, last_assistant_res = null, last_plugin_res = null;
299
+ if (pluginParams) {
300
+ last_assistant_res_message = pluginParams.assistant_res.detail.choices[0];
301
+ last_assistant_res = {
302
+ role: last_assistant_res_message.message.role,
303
+ id: parentMsg.id,
304
+ conversationId,
305
+ parentMessageId: parentMsg.parentMessageId,
306
+ text,
307
+ content: last_assistant_res_message
308
+ };
309
+ last_plugin_res = {
310
+ role: "tool",
311
+ id: messageId,
312
+ name: last_assistant_res_message.message.tool_calls[0].function.name,
313
+ conversationId,
314
+ parentMessageId: pluginParams.assistant_res.id,
315
+ text,
316
+ content: pluginParams.plugin_res,
317
+ tool_call_id: last_assistant_res_message.message.tool_calls[0].id
318
+ };
319
+ await this._upsertMessage(last_assistant_res);
320
+ latestQuestion = last_plugin_res;
321
+ this[`_${last_plugin_res.name}Data`] = pluginParams.plugin_res;
322
+ }
291
323
  const { messages, maxTokens, numTokens, errorMessage } = await this._buildMessages(
292
324
  text,
293
- opts
325
+ opts,
326
+ last_plugin_res
294
327
  );
295
328
  if (this._debug)
296
329
  console.log(`typeof errorMessage ${typeof errorMessage},numTokens:${numTokens}, _maxModelTokens:${this._maxModelTokens},errorMessage: ${errorMessage}`);
@@ -347,6 +380,8 @@ Current date: ${currentDate}`;
347
380
  }
348
381
  if (typeof completionParams.pluginList !== "undefined")
349
382
  delete completionParams.pluginList;
383
+ if (typeof completionParams.fileList !== "undefined")
384
+ delete completionParams.fileList;
350
385
  let body = {
351
386
  max_tokens: maxTokens,
352
387
  ...this._completionParams,
@@ -363,7 +398,7 @@ Current date: ${currentDate}`;
363
398
  type: "function",
364
399
  function: {
365
400
  "name": "DallE3Fun",
366
- "description": this.DallE3Fun().description,
401
+ "description": this.pluginListMap(pluginList).description,
367
402
  "parameters": {
368
403
  "type": "object",
369
404
  "properties": {
@@ -452,16 +487,12 @@ Current date: ${currentDate}`;
452
487
  signal: abortSignal,
453
488
  onMessage: (data) => {
454
489
  var _a3, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v;
455
- if (this._debug) {
456
- }
457
490
  if (data === "[DONE]") {
458
491
  result.text = result.text.trim();
459
492
  return resolve(result);
460
493
  }
461
494
  try {
462
495
  const response = JSON.parse(data);
463
- if (this._debug) {
464
- }
465
496
  if (this._manufacturer.toLowerCase() === "baidu") {
466
497
  if ((response == null ? void 0 : response.is_end) === true) {
467
498
  result.text += response.result.trim();
@@ -510,8 +541,6 @@ Current date: ${currentDate}`;
510
541
  result.text += result.delta;
511
542
  result.role = "assistant";
512
543
  if (response.choices[0].finish_reason === "tool_calls") {
513
- result.role = "function";
514
- result.name = this.pluginListMap(pluginList);
515
544
  } else if (delta.role) {
516
545
  result.role = delta.role;
517
546
  }
@@ -574,7 +603,7 @@ Current date: ${currentDate}`;
574
603
  }
575
604
  const response = await res.json();
576
605
  if (this._debug) {
577
- console.log(response);
606
+ console.log(`row data ${typeof response} : `, response, response == null ? void 0 : response.choices);
578
607
  }
579
608
  if (this._manufacturer.toLowerCase() === "aliyun") {
580
609
  if (response == null ? void 0 : response.request_id) {
@@ -633,10 +662,11 @@ Current date: ${currentDate}`;
633
662
  } catch (err) {
634
663
  }
635
664
  }
636
- return Promise.all([
665
+ const pRes = Promise.all([
637
666
  this._upsertMessage(latestQuestion),
638
667
  this._upsertMessage(message2)
639
668
  ]).then(() => message2);
669
+ return pRes;
640
670
  });
641
671
  if (timeoutMs) {
642
672
  if (abortController) {
@@ -689,8 +719,9 @@ Current date: ${currentDate}`;
689
719
  set apiOrg(apiOrg) {
690
720
  this._apiOrg = apiOrg;
691
721
  }
692
- async _buildMessages(text, opts) {
693
- const { systemMessage = this._systemMessage } = opts;
722
+ async _buildMessages(text, opts, pluginData) {
723
+ var _a;
724
+ const { systemMessage = this._systemMessage, completionParams } = opts;
694
725
  let { parentMessageId } = opts;
695
726
  let errorMessage = "";
696
727
  const userLabel = USER_LABEL_DEFAULT;
@@ -703,13 +734,45 @@ Current date: ${currentDate}`;
703
734
  content: systemMessage
704
735
  });
705
736
  }
737
+ let objText = [{ type: "text", text }];
738
+ if (completionParams.fileList && completionParams.fileList.length > 0 && completionParams.model === "gpt-4-vision-preview") {
739
+ completionParams.fileList.forEach((item) => {
740
+ objText.push({
741
+ type: "image_url",
742
+ image_url: {
743
+ url: item.imgUrl
744
+ }
745
+ });
746
+ });
747
+ if (["openai"].indexOf(this._manufacturer.toLowerCase()) > -1) {
748
+ text = objText;
749
+ }
750
+ }
706
751
  const systemMessageOffset = messages.length;
707
- const userMessage = ["baidu", "azure", "zhipu", "xunfei", "aliyun", "tencent"].indexOf(this._manufacturer.toLowerCase()) > -1 ? [{ role: "user", content: text }] : [{ role: "user", content: text, name: opts.name }];
708
- let nextMessages = text ? messages.concat(userMessage) : messages;
752
+ let userMessage = null;
753
+ if (["baidu", "azure", "zhipu", "xunfei", "aliyun", "tencent"].indexOf(this._manufacturer.toLowerCase()) > -1) {
754
+ userMessage = [{ role: "user", content: text }];
755
+ } else if (pluginData) {
756
+ userMessage = {
757
+ role: pluginData.role,
758
+ name: pluginData.name,
759
+ content: JSON.stringify(pluginData.content),
760
+ tool_call_id: pluginData.tool_call_id
761
+ };
762
+ } else {
763
+ userMessage = [{ role: "user", content: text, name: opts.name }];
764
+ }
765
+ let nextMessages = messages;
766
+ if (pluginData || text) {
767
+ nextMessages = nextMessages.concat(userMessage);
768
+ }
709
769
  let numTokens = 0;
710
770
  do {
711
771
  const prompt = nextMessages.reduce((prompt2, message) => {
712
772
  switch (message.role) {
773
+ case "tool":
774
+ return prompt2.concat([`Tool:
775
+ function call`]);
713
776
  case "system":
714
777
  return prompt2.concat([`Instructions:
715
778
  ${message.content}`]);
@@ -739,14 +802,20 @@ ${message.content}`]);
739
802
  break;
740
803
  }
741
804
  const parentMessageRole = parentMessage.role || "user";
742
- const parentMessageItem = ["baidu", "azure", "zhipu", "xunfei", "aliyun", "tencent"].indexOf(this._manufacturer.toLowerCase()) > -1 ? {
743
- role: parentMessageRole,
744
- content: parentMessage.text
745
- } : {
746
- role: parentMessageRole,
747
- content: parentMessage.text,
748
- name: parentMessage.name
749
- };
805
+ let parentMessageItem = null;
806
+ if (["baidu", "azure", "zhipu", "xunfei", "aliyun", "tencent"].indexOf(this._manufacturer.toLowerCase()) > -1) {
807
+ parentMessageItem = { role: parentMessageRole, content: parentMessage.text };
808
+ } else if (parentMessage.content && ((_a = parentMessage.content) == null ? void 0 : _a.finish_reason) === "tool_calls") {
809
+ parentMessageItem = parentMessage.content.message;
810
+ } else {
811
+ parentMessageItem = {
812
+ role: parentMessageRole,
813
+ content: parentMessage.text || parentMessage.content,
814
+ name: parentMessage.name
815
+ };
816
+ if (parentMessage.tool_call_id)
817
+ parentMessageItem.tool_call_id = parentMessage.tool_call_id;
818
+ }
750
819
  nextMessages = nextMessages.slice(0, systemMessageOffset).concat([
751
820
  parentMessageItem,
752
821
  ...nextMessages.slice(systemMessageOffset)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leikeduntech/leiai-js",
3
- "version": "2.7.1",
3
+ "version": "2.9.0",
4
4
  "author": "liuhean",
5
5
  "repository": {
6
6
  "type": "git",