@cobrowser/chatgpt 0.7.31 → 0.7.32-dev.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/dist/constants.d.ts +2 -2
- package/dist/constants.js +19 -23
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/models/ConversationHistory.d.ts +3 -3
- package/dist/models/Item.d.ts +2 -2
- package/dist/services/AssistantService/AssistantService.d.ts +3 -3
- package/dist/services/AssistantService/AssistantService.js +14 -13
- package/dist/services/BaseService/BaseService.d.ts +6 -14
- package/dist/services/BaseService/BaseService.js +7 -65
- package/dist/services/ChatService/ChatService.d.ts +1 -2
- package/dist/services/ChatService/ChatService.js +9 -14
- package/dist/services/CopilotService/CopilotService.d.ts +14 -8
- package/dist/services/CopilotService/CopilotService.js +145 -54
- package/dist/services/ResponseService/ResponseService.d.ts +37 -0
- package/dist/services/ResponseService/ResponseService.js +213 -0
- package/dist/services/TranslationService/TranslationService.d.ts +4 -4
- package/dist/services/TranslationService/TranslationService.js +11 -14
- package/package.json +4 -5
- package/dist/models/ChatGPTMessage.d.ts +0 -17
- package/dist/models/ChatGPTMessage.js +0 -9
- package/dist/models/ChatGPTResponse.d.ts +0 -8
- package/dist/models/ChatGPTResponse.js +0 -2
- package/dist/models/ChatGPTUsageTokens.d.ts +0 -6
- package/dist/models/ChatGPTUsageTokens.js +0 -2
- package/dist/models/Response.d.ts +0 -3
- package/dist/models/Response.js +0 -2
- package/dist/utils/Response.d.ts +0 -4
- package/dist/utils/Response.js +0 -11
- package/dist/utils/constants.d.ts +0 -13
- package/dist/utils/constants.js +0 -66
package/dist/constants.d.ts
CHANGED
|
@@ -6,8 +6,8 @@ export declare const MESSAGE_TYPES: {
|
|
|
6
6
|
text: string;
|
|
7
7
|
button: string;
|
|
8
8
|
};
|
|
9
|
-
export declare const DEFAULT_PROMPT = "
|
|
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";
|
|
11
11
|
export declare const LANGUAGE_DETECTION_SYSTEM_ROLE = "\n You are a language detection assistant. Your task is to analyze short text input and determine \n its language using ISO language code. Respond only in JSON format with two key-value pairs: \n - 'languageCode': the detected language's ISO code (or undefined if detection fails).\n - 'isError': a boolean value (true if detection fails, false otherwise).\n";
|
|
12
12
|
export declare const WORD_FREQUENCY_LANGUAGE_DETECTION_SYSTEM_ROLE = "\n You are a language detection assistant. Your task is to analyze the most frequently occurring words in the given text \n and determine the language based on those words. Respond only in JSON format with two key-value pairs: \n - 'languageCode': the detected language's ISO code (or undefined if detection fails).\n - 'isError': a boolean value (true if detection fails, false otherwise).\n";
|
|
13
|
-
export declare const TRANSLATION_SYSTEM_ROLE = "\n You are a translator that responds exclusively in JSON format. Your response must be a JSON object containing:\n - '
|
|
13
|
+
export declare const TRANSLATION_SYSTEM_ROLE = "\n You are a translator that responds exclusively in JSON format. Your response must be a JSON object containing:\n - 'data': it is an array of objects. Each object in the array must contain:\n - 'translated_message': The original input message before translation.\n - 'translation: The translated version of 'translated_message', ensuring it is natural, culturally appropriate, and commonly used by native speakers.\n - 'isError': a boolean value (true if translation fails, false otherwise).\n\n Ensure that 'translation' accurately represents the meaning of 'translated_message' while considering cultural nuances, usual expressions, and natural phrasing in the target language. \n Your response must follow this structure strictly.\n";
|
package/dist/constants.js
CHANGED
|
@@ -12,27 +12,26 @@ exports.MESSAGE_TYPES = {
|
|
|
12
12
|
button: 'button'
|
|
13
13
|
};
|
|
14
14
|
// Default prompt for ChatGPT
|
|
15
|
-
exports.DEFAULT_PROMPT = `
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
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.
|
|
20
19
|
|
|
21
|
-
|
|
20
|
+
You will always respond with a JSON. It will be in the format:
|
|
22
21
|
|
|
23
|
-
|
|
22
|
+
{ answer: '', suggestions: [], connectWithAgent: true or false }
|
|
24
23
|
|
|
25
|
-
|
|
24
|
+
Fields in the JSON:
|
|
26
25
|
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
Answer: It will consist of the user's query answer based on the ongoing conversation.
|
|
27
|
+
Restrict this field to 100 characters.
|
|
29
28
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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.
|
|
31
|
+
|
|
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.
|
|
36
35
|
`;
|
|
37
36
|
// Default destination language
|
|
38
37
|
exports.DESTINATION_LANGUAGE = 'English';
|
|
@@ -53,14 +52,11 @@ exports.WORD_FREQUENCY_LANGUAGE_DETECTION_SYSTEM_ROLE = `
|
|
|
53
52
|
// Message translation system role
|
|
54
53
|
exports.TRANSLATION_SYSTEM_ROLE = `
|
|
55
54
|
You are a translator that responds exclusively in JSON format. Your response must be a JSON object containing:
|
|
56
|
-
- '
|
|
57
|
-
- '
|
|
58
|
-
- 'translation: The translated version of '
|
|
55
|
+
- 'data': it is an array of objects. Each object in the array must contain:
|
|
56
|
+
- 'translated_message': The original input message before translation.
|
|
57
|
+
- 'translation: The translated version of 'translated_message', ensuring it is natural, culturally appropriate, and commonly used by native speakers.
|
|
59
58
|
- 'isError': a boolean value (true if translation fails, false otherwise).
|
|
60
59
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
Ensure that 'translation' accurately represents the meaning of 'original' while considering cultural nuances, usual expressions, and natural phrasing in the target language.
|
|
64
|
-
|
|
60
|
+
Ensure that 'translation' accurately represents the meaning of 'translated_message' while considering cultural nuances, usual expressions, and natural phrasing in the target language.
|
|
65
61
|
Your response must follow this structure strictly.
|
|
66
62
|
`;
|
package/dist/index.d.ts
CHANGED
|
@@ -2,3 +2,4 @@ export * from './services/TranslationService/TranslationService';
|
|
|
2
2
|
export * from './services/CopilotService/CopilotService';
|
|
3
3
|
export * from './services/ChatService/ChatService';
|
|
4
4
|
export * from './services/AssistantService/AssistantService';
|
|
5
|
+
export * from './services/ResponseService/ResponseService';
|
package/dist/index.js
CHANGED
|
@@ -18,3 +18,4 @@ __exportStar(require("./services/TranslationService/TranslationService"), export
|
|
|
18
18
|
__exportStar(require("./services/CopilotService/CopilotService"), exports);
|
|
19
19
|
__exportStar(require("./services/ChatService/ChatService"), exports);
|
|
20
20
|
__exportStar(require("./services/AssistantService/AssistantService"), exports);
|
|
21
|
+
__exportStar(require("./services/ResponseService/ResponseService"), exports);
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
interface ConversationHistory {
|
|
2
|
-
to: string;
|
|
3
2
|
from: string;
|
|
4
|
-
|
|
3
|
+
to: string;
|
|
5
4
|
datetime: number;
|
|
5
|
+
body: MessageBody[];
|
|
6
6
|
}
|
|
7
7
|
interface MessageBody {
|
|
8
|
-
id?: string;
|
|
9
8
|
type: string;
|
|
10
9
|
text?: string;
|
|
10
|
+
id?: string;
|
|
11
11
|
label?: string;
|
|
12
12
|
}
|
|
13
13
|
export default ConversationHistory;
|
package/dist/models/Item.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
1
|
+
import ChatGptResponse from '../../models/ChatGptResponse';
|
|
2
2
|
import BaseService from '../BaseService/BaseService';
|
|
3
|
-
import
|
|
3
|
+
import { AssistantResponseFormatOption } from 'openai/resources/beta/threads/threads';
|
|
4
4
|
export declare class AssistantService extends BaseService {
|
|
5
5
|
assistantId: string | undefined;
|
|
6
6
|
threadId: string | undefined;
|
|
@@ -22,5 +22,5 @@ export declare class AssistantService extends BaseService {
|
|
|
22
22
|
tools?: any[];
|
|
23
23
|
functionOutputs?: string;
|
|
24
24
|
definedSchema?: AssistantResponseFormatOption;
|
|
25
|
-
}): Promise<
|
|
25
|
+
}): Promise<ChatGptResponse | undefined>;
|
|
26
26
|
}
|
|
@@ -68,19 +68,20 @@ class AssistantService extends BaseService_1.default {
|
|
|
68
68
|
const openai = new openai_1.default({ apiKey: this.openaiApiKey });
|
|
69
69
|
let run;
|
|
70
70
|
if (runOptions.functionOutputs && this.runId) {
|
|
71
|
-
run = yield openai.beta.threads.runs.submitToolOutputsAndPoll(this.
|
|
71
|
+
run = yield openai.beta.threads.runs.submitToolOutputsAndPoll(this.runId, {
|
|
72
|
+
thread_id: this.threadId,
|
|
73
|
+
tool_outputs: JSON.parse(runOptions.functionOutputs)
|
|
74
|
+
});
|
|
72
75
|
}
|
|
73
76
|
else {
|
|
74
|
-
const lastThreadMessasges = yield openai.beta.threads.messages.list(this.threadId, { order: "desc", limit: 2 })
|
|
77
|
+
const lastThreadMessasges = yield openai.beta.threads.messages.list(this.threadId, { order: "desc", limit: 2 });
|
|
78
|
+
const isRepeatedMessage = lastThreadMessasges.data.find(msg => msg.content[0].type === 'text' && msg.content[0].text.value === message);
|
|
75
79
|
if (isRepeatedMessage) {
|
|
76
80
|
const runs = yield openai.beta.threads.runs.list(this.threadId, { order: "desc", limit: 1 });
|
|
77
81
|
run = runs.data[0];
|
|
78
82
|
}
|
|
79
83
|
else {
|
|
80
|
-
yield openai.beta.threads.messages.create(this.threadId, {
|
|
81
|
-
role: "user",
|
|
82
|
-
content: message
|
|
83
|
-
});
|
|
84
|
+
yield openai.beta.threads.messages.create(this.threadId, { role: "user", content: message });
|
|
84
85
|
run = yield openai.beta.threads.runs.create(this.threadId, {
|
|
85
86
|
assistant_id: (_a = this.assistantId) !== null && _a !== void 0 ? _a : '',
|
|
86
87
|
additional_instructions: runOptions.instructions,
|
|
@@ -94,16 +95,16 @@ class AssistantService extends BaseService_1.default {
|
|
|
94
95
|
}
|
|
95
96
|
while (['queued', 'in_progress', 'cancelling'].includes(run.status)) {
|
|
96
97
|
yield new Promise(resolve => setTimeout(resolve, 500));
|
|
97
|
-
run = yield openai.beta.threads.runs.retrieve(run.
|
|
98
|
+
run = yield openai.beta.threads.runs.retrieve(run.id, { thread_id: run.thread_id });
|
|
98
99
|
}
|
|
99
100
|
if (run.status === 'completed') {
|
|
100
|
-
const { data } = yield openai.beta.threads.messages.list(run.thread_id, { order: 'desc', limit: 1 })
|
|
101
|
+
const { data } = yield openai.beta.threads.messages.list(run.thread_id, { order: 'desc', limit: 1 });
|
|
102
|
+
const messages = data.flatMap((message) => message === null || message === void 0 ? void 0 : message.content.map((content) => ((content.type === 'text' && message.role === 'assistant') ? content.text : '')));
|
|
103
|
+
const assistantMessages = messages.filter(message => typeof message === 'object' && 'value' in message && typeof message.value === 'string');
|
|
101
104
|
if (assistantMessages.length) {
|
|
102
|
-
|
|
103
|
-
// we can just directly access the message here
|
|
104
|
-
const answer = assistantMessages[0].value, replaced = answer.replace(/【.*?】/g, ''), parsed = JSON.parse(replaced);
|
|
105
|
+
let answer = assistantMessages.map(message => message.value).join('\n');
|
|
105
106
|
return {
|
|
106
|
-
|
|
107
|
+
firstChoice: answer.replace(/【.*?】/g, ''),
|
|
107
108
|
threadId: run.thread_id,
|
|
108
109
|
usageTokens: run.usage,
|
|
109
110
|
};
|
|
@@ -111,7 +112,7 @@ class AssistantService extends BaseService_1.default {
|
|
|
111
112
|
}
|
|
112
113
|
if (run.status === 'requires_action') {
|
|
113
114
|
return {
|
|
114
|
-
requiredActions: run.required_action,
|
|
115
|
+
requiredActions: JSON.stringify(run.required_action),
|
|
115
116
|
threadId: run.thread_id,
|
|
116
117
|
usageTokens: run.usage,
|
|
117
118
|
};
|
|
@@ -1,38 +1,30 @@
|
|
|
1
1
|
import { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
|
|
2
|
-
import
|
|
2
|
+
import ChatGptUsageTokens from '../../models/ChatGptUsageTokens';
|
|
3
3
|
declare class BaseService {
|
|
4
|
-
readonly BASE_CHAT_COMPLETION_URL = "https://api.openai.com/v1/chat/completions";
|
|
5
4
|
request: AxiosInstance;
|
|
5
|
+
readonly BASE_CHAT_COMPLETION_URL = "https://api.openai.com/v1/chat/completions";
|
|
6
6
|
openaiApiKey: string | undefined;
|
|
7
7
|
chatGptModel: string;
|
|
8
8
|
maxNumberOfChatCompletionResult: number;
|
|
9
9
|
/**
|
|
10
|
+
*
|
|
10
11
|
* @param apiKey
|
|
11
12
|
* @param model the main chatGPT model to use
|
|
12
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
17
|
constructor(apiKey?: string | undefined, model?: string, apiUrl?: string, maxNumberOfChoices?: number);
|
|
16
|
-
/**
|
|
17
|
-
* Automatically wraps some specific async methods to return a specific sanitized
|
|
18
|
-
* and encoded JSON without any developer intervention.
|
|
19
|
-
*/
|
|
20
|
-
private processAsyncMethods;
|
|
21
|
-
/**
|
|
22
|
-
* Recursively sanitizes any value
|
|
23
|
-
*/
|
|
24
|
-
private sanitize;
|
|
25
18
|
/**
|
|
26
19
|
* Filter the response from chatGpt API and only get the first choice
|
|
27
|
-
*
|
|
28
20
|
* @param response
|
|
29
21
|
*/
|
|
30
|
-
getResponseFirstChoice(response: AxiosResponse):
|
|
22
|
+
getResponseFirstChoice(response: AxiosResponse): string | undefined;
|
|
31
23
|
/**
|
|
32
24
|
* Filter the response from chatGpt API and get the usage tokens
|
|
33
25
|
* @param response
|
|
34
26
|
*/
|
|
35
|
-
getResponseUsageTokens(response: AxiosResponse):
|
|
27
|
+
getResponseUsageTokens(response: AxiosResponse): ChatGptUsageTokens | undefined;
|
|
36
28
|
/**
|
|
37
29
|
* function to handle requests errors
|
|
38
30
|
* @param error
|
|
@@ -1,40 +1,31 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
2
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
4
|
};
|
|
14
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
6
|
const axios_1 = __importDefault(require("axios"));
|
|
16
|
-
const Response_1 = require("../../utils/Response");
|
|
17
|
-
const xss_validation_1 = require("@cobrowser/xss-validation");
|
|
18
7
|
const logger_1 = __importDefault(require("../logger"));
|
|
19
8
|
class BaseService {
|
|
20
9
|
/**
|
|
10
|
+
*
|
|
21
11
|
* @param apiKey
|
|
22
12
|
* @param model the main chatGPT model to use
|
|
23
13
|
* @param apiUrl Api url to be used to make API calls to openAI services
|
|
24
14
|
* @param maxNumberOfChoices How many chat completion choices to generate for each request.
|
|
15
|
+
*
|
|
25
16
|
*/
|
|
26
17
|
constructor(apiKey = process.env.OPEN_AI_API_KEY, model = 'gpt-4o', apiUrl, maxNumberOfChoices = 1) {
|
|
27
|
-
Object.defineProperty(this, "
|
|
18
|
+
Object.defineProperty(this, "request", {
|
|
28
19
|
enumerable: true,
|
|
29
20
|
configurable: true,
|
|
30
21
|
writable: true,
|
|
31
|
-
value:
|
|
22
|
+
value: void 0
|
|
32
23
|
});
|
|
33
|
-
Object.defineProperty(this, "
|
|
24
|
+
Object.defineProperty(this, "BASE_CHAT_COMPLETION_URL", {
|
|
34
25
|
enumerable: true,
|
|
35
26
|
configurable: true,
|
|
36
27
|
writable: true,
|
|
37
|
-
value:
|
|
28
|
+
value: 'https://api.openai.com/v1/chat/completions'
|
|
38
29
|
});
|
|
39
30
|
Object.defineProperty(this, "openaiApiKey", {
|
|
40
31
|
enumerable: true,
|
|
@@ -64,58 +55,9 @@ class BaseService {
|
|
|
64
55
|
this.openaiApiKey = apiKey;
|
|
65
56
|
this.chatGptModel = model;
|
|
66
57
|
this.maxNumberOfChatCompletionResult = maxNumberOfChoices;
|
|
67
|
-
this.processAsyncMethods();
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Automatically wraps some specific async methods to return a specific sanitized
|
|
71
|
-
* and encoded JSON without any developer intervention.
|
|
72
|
-
*/
|
|
73
|
-
processAsyncMethods() {
|
|
74
|
-
const proto = Object.getPrototypeOf(this), methodNames = Object.getOwnPropertyNames(proto);
|
|
75
|
-
for (const methodName of methodNames) {
|
|
76
|
-
const method = proto[methodName];
|
|
77
|
-
// Skip constructor, non-functions, and utility methods But include service methods
|
|
78
|
-
// like getReply, getAssistant, etc. Please note that new methods that are not final
|
|
79
|
-
// output should be skipped here.
|
|
80
|
-
if (methodName === 'constructor' ||
|
|
81
|
-
methodName === 'suggest' ||
|
|
82
|
-
typeof method !== 'function' ||
|
|
83
|
-
(methodName.startsWith('get') &&
|
|
84
|
-
!methodName.startsWith('getReply') &&
|
|
85
|
-
!methodName.startsWith('getAssist') &&
|
|
86
|
-
!methodName.startsWith('getChat')) ||
|
|
87
|
-
methodName.startsWith('handle') ||
|
|
88
|
-
methodName.includes('Sanitize') ||
|
|
89
|
-
methodName.includes('sanitize')) {
|
|
90
|
-
continue;
|
|
91
|
-
}
|
|
92
|
-
const originalMethod = method.bind(this);
|
|
93
|
-
// Replace the method with a wrapper
|
|
94
|
-
this[methodName] = (...args) => __awaiter(this, void 0, void 0, function* () {
|
|
95
|
-
try {
|
|
96
|
-
const response = Response_1.ResponseBuilder.build(yield originalMethod(...args)), sanitized = this.sanitize(response);
|
|
97
|
-
return sanitized;
|
|
98
|
-
}
|
|
99
|
-
catch (error) {
|
|
100
|
-
throw error;
|
|
101
|
-
}
|
|
102
|
-
});
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* Recursively sanitizes any value
|
|
107
|
-
*/
|
|
108
|
-
sanitize(data) {
|
|
109
|
-
if (!data) {
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
const sanitized = xss_validation_1.XSSProtector.sanitize(data), encoded = xss_validation_1.XSSProtector.encode(sanitized);
|
|
113
|
-
logger_1.default.info({ data, sanitized, encoded }, ':: Sanitized Response ::');
|
|
114
|
-
return encoded;
|
|
115
58
|
}
|
|
116
59
|
/**
|
|
117
60
|
* Filter the response from chatGpt API and only get the first choice
|
|
118
|
-
*
|
|
119
61
|
* @param response
|
|
120
62
|
*/
|
|
121
63
|
getResponseFirstChoice(response) {
|
|
@@ -123,7 +65,7 @@ class BaseService {
|
|
|
123
65
|
if ((_a = response.data.choices) === null || _a === void 0 ? void 0 : _a.length) {
|
|
124
66
|
const firstChatGptResponseMessage = response.data.choices[0].message;
|
|
125
67
|
logger_1.default.info(`First ChatGpt Message: ${firstChatGptResponseMessage.content}`);
|
|
126
|
-
return
|
|
68
|
+
return firstChatGptResponseMessage.content;
|
|
127
69
|
}
|
|
128
70
|
return undefined;
|
|
129
71
|
}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import BaseService from '../BaseService/BaseService';
|
|
2
|
-
import ChatGPTResponse from 'src/models/ChatGPTResponse';
|
|
3
2
|
import ConversationHistory from 'src/models/ConversationHistory';
|
|
4
3
|
export declare class ChatService extends BaseService {
|
|
5
4
|
#private;
|
|
6
5
|
model: string | undefined;
|
|
7
6
|
constructor(apiKey?: string, model?: string, apiUrl?: string, maxNumberOfChoices?: number);
|
|
8
|
-
ask(context: string | undefined, conversationHistory: ConversationHistory[]): Promise<
|
|
7
|
+
ask(context: string | undefined, conversationHistory: ConversationHistory[]): Promise<string | undefined>;
|
|
9
8
|
}
|
|
@@ -19,10 +19,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
19
19
|
var _ChatService_instances, _ChatService_formatConversationHistory;
|
|
20
20
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
21
|
exports.ChatService = void 0;
|
|
22
|
-
const
|
|
23
|
-
const constants_1 = require("../../utils/constants");
|
|
24
|
-
const logger_1 = __importDefault(require("../logger"));
|
|
22
|
+
const ChatGptMessage_1 = require("../../models/ChatGptMessage");
|
|
25
23
|
const BaseService_1 = __importDefault(require("../BaseService/BaseService"));
|
|
24
|
+
const logger_1 = __importDefault(require("../logger"));
|
|
25
|
+
const constants_1 = require("../../constants");
|
|
26
26
|
class ChatService extends BaseService_1.default {
|
|
27
27
|
constructor(apiKey, model, apiUrl, maxNumberOfChoices) {
|
|
28
28
|
super(apiKey, model, apiUrl, maxNumberOfChoices);
|
|
@@ -45,15 +45,10 @@ class ChatService extends BaseService_1.default {
|
|
|
45
45
|
model: this.model,
|
|
46
46
|
messages: __classPrivateFieldGet(this, _ChatService_instances, "m", _ChatService_formatConversationHistory).call(this, context, conversationHistory),
|
|
47
47
|
};
|
|
48
|
-
logger_1.default.info({
|
|
49
|
-
requestBody: JSON.stringify(requestBody)
|
|
50
|
-
}, ':: ChatService.ask :: Request Body');
|
|
48
|
+
logger_1.default.info(`:: ChatService.ask :: ${JSON.stringify(requestBody)}`);
|
|
51
49
|
try {
|
|
52
50
|
const response = yield this.request.post('', requestBody);
|
|
53
|
-
return
|
|
54
|
-
data: this.getResponseFirstChoice(response),
|
|
55
|
-
usageTokens: this.getResponseUsageTokens(response),
|
|
56
|
-
};
|
|
51
|
+
return this.getResponseFirstChoice(response);
|
|
57
52
|
}
|
|
58
53
|
catch (e) {
|
|
59
54
|
this.handleErrors(e);
|
|
@@ -66,7 +61,7 @@ exports.ChatService = ChatService;
|
|
|
66
61
|
_ChatService_instances = new WeakSet(), _ChatService_formatConversationHistory = function _ChatService_formatConversationHistory(context, conversationHistory) {
|
|
67
62
|
const formatted = [
|
|
68
63
|
{
|
|
69
|
-
role:
|
|
64
|
+
role: ChatGptMessage_1.ChatGptRole.SYSTEM,
|
|
70
65
|
content: context || constants_1.DEFAULT_PROMPT,
|
|
71
66
|
}
|
|
72
67
|
];
|
|
@@ -76,19 +71,19 @@ _ChatService_instances = new WeakSet(), _ChatService_formatConversationHistory =
|
|
|
76
71
|
for (const body of messageBody) {
|
|
77
72
|
if (body.type === constants_1.MESSAGE_TYPES.text && message.from === constants_1.MESSAGE_SENDER.visitor) {
|
|
78
73
|
formatted.push({
|
|
79
|
-
role:
|
|
74
|
+
role: ChatGptMessage_1.ChatGptRole.USER,
|
|
80
75
|
content: body.text
|
|
81
76
|
});
|
|
82
77
|
}
|
|
83
78
|
else if (body.type === constants_1.MESSAGE_TYPES.text && message.from === constants_1.MESSAGE_SENDER.chatbot) {
|
|
84
79
|
formatted.push({
|
|
85
|
-
role:
|
|
80
|
+
role: ChatGptMessage_1.ChatGptRole.ASSISTANT,
|
|
86
81
|
content: body.text
|
|
87
82
|
});
|
|
88
83
|
}
|
|
89
84
|
else if (body.type === constants_1.MESSAGE_TYPES.button && message.from === constants_1.MESSAGE_SENDER.chatbot) {
|
|
90
85
|
formatted.push({
|
|
91
|
-
role:
|
|
86
|
+
role: ChatGptMessage_1.ChatGptRole.ASSISTANT,
|
|
92
87
|
content: body.label
|
|
93
88
|
});
|
|
94
89
|
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import ChatGptResponse from '../../models/ChatGptResponse';
|
|
1
2
|
import BaseService from '../BaseService/BaseService';
|
|
2
|
-
import
|
|
3
|
+
import ChatGptMessage from '../../models/ChatGptMessage';
|
|
4
|
+
import Item from '../../models/Item';
|
|
3
5
|
export declare class CopilotService extends BaseService {
|
|
4
|
-
#private;
|
|
5
6
|
assistantId: string | undefined;
|
|
6
7
|
threadId: string | undefined;
|
|
8
|
+
conversationId: string | undefined;
|
|
7
9
|
constructor(apiKey?: string, model?: string, assistantId?: string, threadId?: string, apiUrl?: string, maxNumberOfChoices?: number);
|
|
8
10
|
/**
|
|
9
11
|
* a method to be used to suggest some quick replies for the agent based on the conversation
|
|
@@ -17,17 +19,21 @@ export declare class CopilotService extends BaseService {
|
|
|
17
19
|
* this will make it easy to ask chatGpt for quick replies
|
|
18
20
|
* @param conversation
|
|
19
21
|
*/
|
|
20
|
-
suggest(conversation: string): Promise<
|
|
22
|
+
suggest(conversation: string): Promise<ChatGptResponse | undefined>;
|
|
21
23
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* @param
|
|
24
|
+
* this will request chatGPT to recommend product or item based on the whole conversation
|
|
25
|
+
* @param conversation the whole chat conversation
|
|
26
|
+
* @param items the items to recommend from
|
|
25
27
|
*/
|
|
26
|
-
|
|
28
|
+
recommend(conversation: ChatGptMessage[], items: Item[]): Promise<string | undefined>;
|
|
27
29
|
/**
|
|
28
30
|
* Get the reply of the assistant if the assistant_id is available
|
|
29
31
|
*
|
|
30
32
|
* @param message
|
|
31
33
|
*/
|
|
32
|
-
|
|
34
|
+
getAssistantReply(message: string): Promise<ChatGptResponse | undefined>;
|
|
35
|
+
private isAssistantIdFormat;
|
|
36
|
+
private isPromptIdFormat;
|
|
37
|
+
private ensureConversation;
|
|
38
|
+
getPromptReply(message: string): Promise<ChatGptResponse | undefined>;
|
|
33
39
|
}
|