@cobrowser/chatgpt 0.7.2 → 0.7.4

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.
@@ -6,5 +6,5 @@ export declare const MESSAGE_TYPES: {
6
6
  text: string;
7
7
  button: string;
8
8
  };
9
- export declare const DEFAULT_PROMPT = "You are a helpful assistant. Your role is to address visitor queries related to the ongoing conversation and the last message received. Please ensure that responses remain within the ongoing conversation. Politely decline any user queries that is not present in the ongoing conversation. \n\nYou will always respond with a JSON. It will be in the format: \n\n{ answer: '', suggestions: [], connectWithAgent: true or false }\n\nFields in the JSON:\n\nAnswer: It will consist of the user's query answer based on the ongoing conversation. Restrict this field to 100 characters.\n\nSuggestions: Request 2 suggestions from user's perspective that he can ask. It should be an array of strings. Restrict each suggestion to 50 characters.\n \nConnectWithAgent: It is a boolean. It should be set to true if the user's query is not found in the ongoing conversation. Politely tell the user to talk to a real agent. Also when it is true, do not provide any suggestions.\n";
9
+ export declare const DEFAULT_PROMPT = "You are a helpful assistant. Your role is to address visitor \nqueries related to the ongoing conversation and the last message received. Please ensure \nthat responses remain within the ongoing conversation. Politely decline any user queries \nthat is not present in the ongoing conversation. \n\nYou will always respond with a JSON. It will be in the format: \n\n{ answer: '', suggestions: [], connectWithAgent: true or false }\n\nFields in the JSON:\n\nAnswer: It will consist of the user's query answer based on the ongoing conversation. \nRestrict this field to 100 characters.\n\nSuggestions: Request 2 suggestions from user's perspective that he can ask. \nIt should be an array of strings. Restrict each suggestion to 50 characters.\n \nConnectWithAgent: It is a boolean. It should be set to true if the user's query is \nnot found in the ongoing conversation. Politely tell the user to talk to a real agent. \nAlso when it is true, do not provide any suggestions.\n";
10
10
  export declare const DESTINATION_LANGUAGE = "English";
package/dist/constants.js CHANGED
@@ -12,7 +12,10 @@ exports.MESSAGE_TYPES = {
12
12
  button: 'button'
13
13
  };
14
14
  // Default prompt for ChatGPT
15
- exports.DEFAULT_PROMPT = `You are a helpful assistant. Your role is to address visitor queries related to the ongoing conversation and the last message received. Please ensure that responses remain within the ongoing conversation. Politely decline any user queries that is not present in the ongoing conversation.
15
+ exports.DEFAULT_PROMPT = `You are a helpful assistant. Your role is to address visitor
16
+ queries related to the ongoing conversation and the last message received. Please ensure
17
+ that responses remain within the ongoing conversation. Politely decline any user queries
18
+ that is not present in the ongoing conversation.
16
19
 
17
20
  You will always respond with a JSON. It will be in the format:
18
21
 
@@ -20,11 +23,15 @@ You will always respond with a JSON. It will be in the format:
20
23
 
21
24
  Fields in the JSON:
22
25
 
23
- Answer: It will consist of the user's query answer based on the ongoing conversation. Restrict this field to 100 characters.
26
+ Answer: It will consist of the user's query answer based on the ongoing conversation.
27
+ Restrict this field to 100 characters.
24
28
 
25
- Suggestions: Request 2 suggestions from user's perspective that he can ask. It should be an array of strings. Restrict each suggestion to 50 characters.
29
+ Suggestions: Request 2 suggestions from user's perspective that he can ask.
30
+ It should be an array of strings. Restrict each suggestion to 50 characters.
26
31
 
27
- ConnectWithAgent: It is a boolean. It should be set to true if the user's query is not found in the ongoing conversation. Politely tell the user to talk to a real agent. Also when it is true, do not provide any suggestions.
32
+ ConnectWithAgent: It is a boolean. It should be set to true if the user's query is
33
+ not found in the ongoing conversation. Politely tell the user to talk to a real agent.
34
+ Also when it is true, do not provide any suggestions.
28
35
  `;
29
36
  // Default destination language
30
37
  exports.DESTINATION_LANGUAGE = 'English';
@@ -5,6 +5,9 @@ export declare enum ChatGptRole {
5
5
  }
6
6
  export interface ChatGptRequestBody {
7
7
  model: string;
8
+ response_format?: {
9
+ type: string;
10
+ };
8
11
  messages: ChatGptMessage[];
9
12
  }
10
13
  interface ChatGptMessage {
@@ -0,0 +1,6 @@
1
+ import ChatGptUsageTokens from './ChatGptUsageTokens';
2
+ interface ChatGptResponse {
3
+ firstChoice?: string;
4
+ usageTokens?: ChatGptUsageTokens;
5
+ }
6
+ export default ChatGptResponse;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,6 @@
1
+ interface ChatGptUsageTokens {
2
+ prompt_tokens: Number;
3
+ completion_tokens: Number;
4
+ total_tokens: Number;
5
+ }
6
+ export default ChatGptUsageTokens;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,4 +1,5 @@
1
1
  import { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
2
+ import ChatGptUsageTokens from '../../models/ChatGptUsageTokens';
2
3
  declare class BaseService {
3
4
  request: AxiosInstance;
4
5
  readonly BASE_CHAT_COMPLETION_URL = "https://api.openai.com/v1/chat/completions";
@@ -6,16 +7,23 @@ declare class BaseService {
6
7
  maxNumberOfChatCompletionResult: number;
7
8
  /**
8
9
  *
9
- * @param apiUrl Api url to be used to make API calls to openAI services
10
+ * @param apiKey
10
11
  * @param model the main chatGPT model to use
12
+ * @param apiUrl Api url to be used to make API calls to openAI services
11
13
  * @param maxNumberOfChoices How many chat completion choices to generate for each request.
14
+ *
12
15
  */
13
- constructor(apiUrl?: string, model?: string, maxNumberOfChoices?: number, apiKey?: string | undefined);
16
+ constructor(apiKey?: string | undefined, model?: string, apiUrl?: string, maxNumberOfChoices?: number);
14
17
  /**
15
18
  * Filter the response from chatGpt API and only get the first choice
16
19
  * @param response
17
20
  */
18
21
  getResponseFirstChoice(response: AxiosResponse): string | undefined;
22
+ /**
23
+ * Filter the response from chatGpt API and get the usage tokens
24
+ * @param response
25
+ */
26
+ getResponseUsageTokens(response: AxiosResponse): ChatGptUsageTokens | undefined;
19
27
  /**
20
28
  * function to handle requests errors
21
29
  * @param error
@@ -8,11 +8,13 @@ const logger_1 = __importDefault(require("../logger"));
8
8
  class BaseService {
9
9
  /**
10
10
  *
11
- * @param apiUrl Api url to be used to make API calls to openAI services
11
+ * @param apiKey
12
12
  * @param model the main chatGPT model to use
13
+ * @param apiUrl Api url to be used to make API calls to openAI services
13
14
  * @param maxNumberOfChoices How many chat completion choices to generate for each request.
15
+ *
14
16
  */
15
- constructor(apiUrl, model = 'gpt-3.5-turbo', maxNumberOfChoices = 1, apiKey = process.env.OPEN_AI_API_KEY) {
17
+ constructor(apiKey = process.env.OPEN_AI_API_KEY, model = 'gpt-3.5-turbo', apiUrl, maxNumberOfChoices = 1) {
16
18
  Object.defineProperty(this, "request", {
17
19
  enumerable: true,
18
20
  configurable: true,
@@ -60,6 +62,19 @@ class BaseService {
60
62
  }
61
63
  return undefined;
62
64
  }
65
+ /**
66
+ * Filter the response from chatGpt API and get the usage tokens
67
+ * @param response
68
+ */
69
+ getResponseUsageTokens(response) {
70
+ var _a;
71
+ if ((_a = response.data) === null || _a === void 0 ? void 0 : _a.usage) {
72
+ const usage = response.data.usage;
73
+ logger_1.default.info(`ChatGpt response usage tokens: ${JSON.stringify(usage)}`);
74
+ return usage;
75
+ }
76
+ return undefined;
77
+ }
63
78
  /**
64
79
  * function to handle requests errors
65
80
  * @param error
@@ -3,6 +3,6 @@ import ConversationHistory from 'src/models/ConversationHistory';
3
3
  export declare class ChatService extends BaseService {
4
4
  #private;
5
5
  model: string | undefined;
6
- constructor(apiUrl?: string, model?: string, maxNumberOfChoices?: number, apiKey?: string);
6
+ constructor(apiKey?: string, model?: string, apiUrl?: string, maxNumberOfChoices?: number);
7
7
  ask(context: string | undefined, conversationHistory: ConversationHistory[]): Promise<string | undefined>;
8
8
  }
@@ -24,8 +24,8 @@ const BaseService_1 = __importDefault(require("../BaseService/BaseService"));
24
24
  const logger_1 = __importDefault(require("../logger"));
25
25
  const constants_1 = require("../../constants");
26
26
  class ChatService extends BaseService_1.default {
27
- constructor(apiUrl, model, maxNumberOfChoices, apiKey) {
28
- super(apiUrl, model, maxNumberOfChoices, apiKey);
27
+ constructor(apiKey, model, apiUrl, maxNumberOfChoices) {
28
+ super(apiKey, model, apiUrl, maxNumberOfChoices);
29
29
  _ChatService_instances.add(this);
30
30
  Object.defineProperty(this, "model", {
31
31
  enumerable: true,
@@ -1,8 +1,9 @@
1
+ import ChatGptResponse from '../../models/ChatGptResponse';
1
2
  import BaseService from '../BaseService/BaseService';
2
3
  import ChatGptMessage from '../../models/ChatGptMessage';
3
4
  import Item from '../../models/Item';
4
5
  export declare class CopilotService extends BaseService {
5
- constructor(apiUrl?: string, model?: string, maxNumberOfChoices?: number, apiKey?: string);
6
+ constructor(apiKey?: string, model?: string, apiUrl?: string, maxNumberOfChoices?: number);
6
7
  /**
7
8
  * a method to be used to suggest some quick replies for the agent based on the conversation
8
9
  * will be added as a single string in the format
@@ -15,7 +16,7 @@ export declare class CopilotService extends BaseService {
15
16
  * this will make it easy to ask chatGpt for quick replies
16
17
  * @param conversation
17
18
  */
18
- suggest(conversation: string): Promise<string | undefined>;
19
+ suggest(conversation: string): Promise<ChatGptResponse | undefined>;
19
20
  /**
20
21
  * this will request chatGPT to recommend product or item based on the whole conversation
21
22
  * @param conversation the whole chat conversation
@@ -17,8 +17,8 @@ const BaseService_1 = __importDefault(require("../BaseService/BaseService"));
17
17
  const logger_1 = __importDefault(require("../logger"));
18
18
  const ChatGptMessage_1 = require("../../models/ChatGptMessage");
19
19
  class CopilotService extends BaseService_1.default {
20
- constructor(apiUrl, model, maxNumberOfChoices, apiKey) {
21
- super(apiUrl, model, maxNumberOfChoices, apiKey);
20
+ constructor(apiKey, model, apiUrl, maxNumberOfChoices) {
21
+ super(apiKey, model, apiUrl, maxNumberOfChoices);
22
22
  }
23
23
  /**
24
24
  * a method to be used to suggest some quick replies for the agent based on the conversation
@@ -41,19 +41,21 @@ class CopilotService extends BaseService_1.default {
41
41
  try {
42
42
  // main prompt used to instruct chatGPT to suggest some quick replies
43
43
  const mainPrompt = `Propose some quick replies for the agent to be used on the following conversation
44
- display your response as unordered list:-\n${conversation}`;
44
+ display your response as unordered list:-\n${conversation}`,
45
45
  // main prompt will be the whole conversation as string
46
- const mainPromptMessage = {
46
+ mainPromptMessage = {
47
47
  role: ChatGptMessage_1.ChatGptRole.USER,
48
48
  content: mainPrompt,
49
- };
49
+ },
50
50
  // the body we need to send to the request
51
- const requestBody = {
51
+ requestBody = {
52
52
  model: this.chatGptModel,
53
53
  messages: [mainPromptMessage],
54
+ }, response = yield this.request.post('', requestBody);
55
+ return {
56
+ firstChoice: this.getResponseFirstChoice(response),
57
+ usageTokens: this.getResponseUsageTokens(response),
54
58
  };
55
- const response = yield this.request.post('', requestBody);
56
- return this.getResponseFirstChoice(response);
57
59
  }
58
60
  catch (e) {
59
61
  this.handleErrors(e);
@@ -74,18 +76,17 @@ class CopilotService extends BaseService_1.default {
74
76
  }
75
77
  try {
76
78
  // main prompt used to instruct chatGPT to recommend products
77
- const mainPrompt = `we have this list of Items: ${JSON.stringify(items)}, what to recommend for you`;
79
+ const mainPrompt = `we have this list of Items: ${JSON.stringify(items)}, what to recommend for you`,
78
80
  // main prompt will be the first message of the whole conversation
79
- const firstMessage = {
81
+ firstMessage = {
80
82
  role: ChatGptMessage_1.ChatGptRole.ASSISTANT,
81
83
  content: mainPrompt,
82
- };
84
+ },
83
85
  // the body we need to send to the request
84
- const requestBody = {
86
+ requestBody = {
85
87
  model: this.chatGptModel,
86
88
  messages: [firstMessage, ...conversation],
87
- };
88
- const response = yield this.request.post('', requestBody);
89
+ }, response = yield this.request.post('', requestBody);
89
90
  return this.getResponseFirstChoice(response);
90
91
  }
91
92
  catch (e) {
@@ -1,11 +1,16 @@
1
+ import ChatGptResponse from '../../models/ChatGptResponse';
1
2
  import BaseService from '../BaseService/BaseService';
2
3
  export declare class TranslationService extends BaseService {
3
- constructor(apiUrl?: string, model?: string, maxNumberOfChoices?: number, apiKey?: string);
4
+ SYSTEM_ROLE_MESSAGE: string;
5
+ FIND_TEXT_LANGUAGE_SYSTEM_ROLE: string;
6
+ constructor(apiKey?: string, model?: string, apiUrl?: string, maxNumberOfChoices?: number);
4
7
  /**
5
8
  * request the chatGpt Api to translate a specific test to a desired language
6
9
  * @param text the text to translate
7
10
  * @param toLanguage the desired language to translate to ( English is the default )
8
11
  * @param fromLanguage if we want to specify the language of the text, we can use this ( optional)
9
12
  */
10
- translate(text: string, toLanguage?: string, fromLanguage?: string): Promise<string | undefined>;
13
+ translate(text: string, toLanguage?: string, fromLanguage?: string): Promise<ChatGptResponse | undefined>;
14
+ findTextLanguage(text: string): Promise<ChatGptResponse | undefined>;
15
+ getFindTextLanguagePromptMessage(text: string): string;
11
16
  }
@@ -18,8 +18,26 @@ const BaseService_1 = __importDefault(require("../BaseService/BaseService"));
18
18
  const logger_1 = __importDefault(require("../logger"));
19
19
  const constants_1 = require("../../constants");
20
20
  class TranslationService extends BaseService_1.default {
21
- constructor(apiUrl, model, maxNumberOfChoices, apiKey) {
22
- super(apiUrl, model, maxNumberOfChoices, apiKey);
21
+ constructor(apiKey, model, apiUrl, maxNumberOfChoices) {
22
+ super(apiKey, model, apiUrl, maxNumberOfChoices);
23
+ Object.defineProperty(this, "SYSTEM_ROLE_MESSAGE", {
24
+ enumerable: true,
25
+ configurable: true,
26
+ writable: true,
27
+ value: 'You are a translator that provides a response in JSON format only. '
28
+ + 'The response should be a JSON object with a boolean called \'error\' and \'data,\''
29
+ + ' which is an array of objects. Each object in the array will contain a \'translation\' property, '
30
+ + 'holding the translation of the message, and a \'translated_message\' property, '
31
+ + 'which will contain the original message before being translated.'
32
+ + ' Additionally, the \'translation\' property will hold the translation of the \'translated_message\' property.'
33
+ });
34
+ Object.defineProperty(this, "FIND_TEXT_LANGUAGE_SYSTEM_ROLE", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: 'You are a translator that provides a response in JSON format only—a JSON that contains'
39
+ + ' \'languageCode\' and \'isError\' if you cannot detect the language.'
40
+ });
23
41
  }
24
42
  /**
25
43
  * request the chatGpt Api to translate a specific test to a desired language
@@ -39,14 +57,24 @@ class TranslationService extends BaseService_1.default {
39
57
  // the body we need to send to the request
40
58
  requestBody = {
41
59
  model: this.chatGptModel,
42
- messages: [{
60
+ response_format: { type: 'json_object' },
61
+ messages: [
62
+ {
63
+ role: ChatGptMessage_1.ChatGptRole.SYSTEM,
64
+ content: this.SYSTEM_ROLE_MESSAGE,
65
+ },
66
+ {
43
67
  role: ChatGptMessage_1.ChatGptRole.USER,
44
68
  content: translateText,
45
- }],
69
+ },
70
+ ],
46
71
  };
47
72
  try {
48
73
  const response = yield this.request.post('', requestBody);
49
- return this.getResponseFirstChoice(response);
74
+ return {
75
+ firstChoice: this.getResponseFirstChoice(response),
76
+ usageTokens: this.getResponseUsageTokens(response),
77
+ };
50
78
  }
51
79
  catch (e) {
52
80
  this.handleErrors(e);
@@ -54,5 +82,45 @@ class TranslationService extends BaseService_1.default {
54
82
  }
55
83
  });
56
84
  }
85
+ findTextLanguage(text) {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ if (!text) {
88
+ logger_1.default.error('translation text should be provided');
89
+ return Promise.reject(new Error('text must be provided'));
90
+ }
91
+ // instruction on what to do with the text
92
+ const translateText = this.getFindTextLanguagePromptMessage(text),
93
+ // the body we need to send to the request
94
+ requestBody = {
95
+ model: this.chatGptModel,
96
+ response_format: { type: 'json_object' },
97
+ messages: [
98
+ {
99
+ role: ChatGptMessage_1.ChatGptRole.SYSTEM,
100
+ content: this.FIND_TEXT_LANGUAGE_SYSTEM_ROLE,
101
+ },
102
+ {
103
+ role: ChatGptMessage_1.ChatGptRole.USER,
104
+ content: translateText,
105
+ }
106
+ ],
107
+ };
108
+ try {
109
+ const response = yield this.request.post('', requestBody);
110
+ return {
111
+ firstChoice: this.getResponseFirstChoice(response),
112
+ usageTokens: this.getResponseUsageTokens(response),
113
+ };
114
+ }
115
+ catch (e) {
116
+ this.handleErrors(e);
117
+ return Promise.reject(e);
118
+ }
119
+ });
120
+ }
121
+ getFindTextLanguagePromptMessage(text) {
122
+ return `In which language is this text in '${text}'? The response should be {'languageCode': 'language_code_here', 'isError': 'true or false based on whether you did find the language code or not'}.
123
+ Other responses or explanations are not allowed.`;
124
+ }
57
125
  }
58
126
  exports.TranslationService = TranslationService;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cobrowser/chatgpt",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
4
4
  "description": "chatgpt services to connect our projects with chatgpt api",
5
5
  "keywords": [
6
6
  "chatgpt",
@@ -38,5 +38,5 @@
38
38
  "bugs": {
39
39
  "url": "https://bitbucket.org/cobrowser/cb_utils/issues"
40
40
  },
41
- "gitHead": "0429dead571677c56bd9e618d6e3ec91acf3d4f3"
41
+ "gitHead": "e71a58b5be231da26741a5ded6e51db3b86aa419"
42
42
  }