@cobrowser/chatgpt 0.7.35-dev.1 → 0.7.36
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/index.d.ts +0 -1
- package/dist/index.js +0 -1
- package/dist/services/AssistantService/AssistantService.js +2 -5
- package/dist/services/BaseService/BaseService.d.ts +1 -1
- package/dist/services/BaseService/BaseService.js +6 -9
- package/dist/services/CopilotService/CopilotService.d.ts +0 -4
- package/dist/services/CopilotService/CopilotService.js +3 -82
- package/dist/services/TranslationService/TranslationService.d.ts +5 -4
- package/dist/services/TranslationService/TranslationService.js +12 -8
- package/dist/utils/constants.d.ts +3 -1
- package/dist/utils/constants.js +28 -13
- package/package.json +3 -3
- package/dist/services/ResponseService/ResponseService.d.ts +0 -34
- package/dist/services/ResponseService/ResponseService.js +0 -193
package/dist/index.d.ts
CHANGED
|
@@ -2,4 +2,3 @@ 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,4 +18,3 @@ __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);
|
|
@@ -68,10 +68,7 @@ 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.runId, {
|
|
72
|
-
thread_id: this.threadId,
|
|
73
|
-
tool_outputs: JSON.parse(runOptions.functionOutputs)
|
|
74
|
-
});
|
|
71
|
+
run = yield openai.beta.threads.runs.submitToolOutputsAndPoll(this.threadId, this.runId, { tool_outputs: JSON.parse(runOptions.functionOutputs) });
|
|
75
72
|
}
|
|
76
73
|
else {
|
|
77
74
|
const lastThreadMessasges = yield openai.beta.threads.messages.list(this.threadId, { order: "desc", limit: 2 }), isRepeatedMessage = lastThreadMessasges.data.find(msg => msg.content[0].type === 'text' && msg.content[0].text.value === message);
|
|
@@ -97,7 +94,7 @@ class AssistantService extends BaseService_1.default {
|
|
|
97
94
|
}
|
|
98
95
|
while (['queued', 'in_progress', 'cancelling'].includes(run.status)) {
|
|
99
96
|
yield new Promise(resolve => setTimeout(resolve, 500));
|
|
100
|
-
run = yield openai.beta.threads.runs.retrieve(run.
|
|
97
|
+
run = yield openai.beta.threads.runs.retrieve(run.thread_id, run.id);
|
|
101
98
|
}
|
|
102
99
|
if (run.status === 'completed') {
|
|
103
100
|
const { data } = yield openai.beta.threads.messages.list(run.thread_id, { order: 'desc', limit: 1 }), messages = data.flatMap((message) => message === null || message === void 0 ? void 0 : message.content.map((content) => ((content.type === 'text' && message.role === 'assistant') ? content.text : ''))), assistantMessages = messages.filter(message => typeof message === 'object' && 'value' in message && typeof message.value === 'string');
|
|
@@ -4,7 +4,7 @@ declare class BaseService {
|
|
|
4
4
|
readonly BASE_CHAT_COMPLETION_URL = "https://api.openai.com/v1/chat/completions";
|
|
5
5
|
request: AxiosInstance;
|
|
6
6
|
openaiApiKey: string | undefined;
|
|
7
|
-
|
|
7
|
+
chatGPTModel: string;
|
|
8
8
|
maxNumberOfChatCompletionResult: number;
|
|
9
9
|
/**
|
|
10
10
|
* @param apiKey
|
|
@@ -15,6 +15,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
15
15
|
const axios_1 = __importDefault(require("axios"));
|
|
16
16
|
const Response_1 = require("../../utils/Response");
|
|
17
17
|
const xss_validation_1 = require("@cobrowser/xss-validation");
|
|
18
|
+
const constants_1 = require("../../utils/constants");
|
|
18
19
|
const logger_1 = __importDefault(require("../logger"));
|
|
19
20
|
class BaseService {
|
|
20
21
|
/**
|
|
@@ -23,7 +24,7 @@ class BaseService {
|
|
|
23
24
|
* @param apiUrl Api url to be used to make API calls to openAI services
|
|
24
25
|
* @param maxNumberOfChoices How many chat completion choices to generate for each request.
|
|
25
26
|
*/
|
|
26
|
-
constructor(apiKey = process.env.OPEN_AI_API_KEY, model =
|
|
27
|
+
constructor(apiKey = process.env.OPEN_AI_API_KEY, model = constants_1.DEFAULT_MODEL, apiUrl, maxNumberOfChoices = 1) {
|
|
27
28
|
Object.defineProperty(this, "BASE_CHAT_COMPLETION_URL", {
|
|
28
29
|
enumerable: true,
|
|
29
30
|
configurable: true,
|
|
@@ -42,7 +43,7 @@ class BaseService {
|
|
|
42
43
|
writable: true,
|
|
43
44
|
value: void 0
|
|
44
45
|
});
|
|
45
|
-
Object.defineProperty(this, "
|
|
46
|
+
Object.defineProperty(this, "chatGPTModel", {
|
|
46
47
|
enumerable: true,
|
|
47
48
|
configurable: true,
|
|
48
49
|
writable: true,
|
|
@@ -62,7 +63,7 @@ class BaseService {
|
|
|
62
63
|
},
|
|
63
64
|
});
|
|
64
65
|
this.openaiApiKey = apiKey;
|
|
65
|
-
this.
|
|
66
|
+
this.chatGPTModel = model;
|
|
66
67
|
this.maxNumberOfChatCompletionResult = maxNumberOfChoices;
|
|
67
68
|
this.processAsyncMethods();
|
|
68
69
|
}
|
|
@@ -83,14 +84,10 @@ class BaseService {
|
|
|
83
84
|
(methodName.startsWith('get') &&
|
|
84
85
|
!methodName.startsWith('getReply') &&
|
|
85
86
|
!methodName.startsWith('getAssist') &&
|
|
86
|
-
!methodName.startsWith('getChat')
|
|
87
|
-
!methodName.startsWith('getPrompt')) ||
|
|
87
|
+
!methodName.startsWith('getChat')) ||
|
|
88
88
|
methodName.startsWith('handle') ||
|
|
89
89
|
methodName.includes('Sanitize') ||
|
|
90
|
-
methodName.includes('sanitize')
|
|
91
|
-
methodName.includes('createConversation') ||
|
|
92
|
-
methodName.includes('isAssistantIdFormat') ||
|
|
93
|
-
methodName.includes('isPromptIdFormat')) {
|
|
90
|
+
methodName.includes('sanitize')) {
|
|
94
91
|
continue;
|
|
95
92
|
}
|
|
96
93
|
const originalMethod = method.bind(this);
|
|
@@ -4,7 +4,6 @@ export declare class CopilotService extends BaseService {
|
|
|
4
4
|
#private;
|
|
5
5
|
assistantId: string | undefined;
|
|
6
6
|
threadId: string | undefined;
|
|
7
|
-
conversationId: string | undefined;
|
|
8
7
|
constructor(apiKey?: string, model?: string, assistantId?: string, threadId?: string, apiUrl?: string, maxNumberOfChoices?: number);
|
|
9
8
|
/**
|
|
10
9
|
* a method to be used to suggest some quick replies for the agent based on the conversation
|
|
@@ -31,7 +30,4 @@ export declare class CopilotService extends BaseService {
|
|
|
31
30
|
* @param message
|
|
32
31
|
*/
|
|
33
32
|
getAssistantSuggestions(conversation: string): Promise<ChatGPTResponse | undefined>;
|
|
34
|
-
private isAssistantIdFormat;
|
|
35
|
-
private isPromptIdFormat;
|
|
36
|
-
getPromptSuggestions(message: string): Promise<ChatGPTResponse | undefined>;
|
|
37
33
|
}
|
|
@@ -39,12 +39,6 @@ class CopilotService extends BaseService_1.default {
|
|
|
39
39
|
writable: true,
|
|
40
40
|
value: void 0
|
|
41
41
|
});
|
|
42
|
-
Object.defineProperty(this, "conversationId", {
|
|
43
|
-
enumerable: true,
|
|
44
|
-
configurable: true,
|
|
45
|
-
writable: true,
|
|
46
|
-
value: void 0
|
|
47
|
-
});
|
|
48
42
|
this.assistantId = assistantId;
|
|
49
43
|
this.threadId = threadId;
|
|
50
44
|
}
|
|
@@ -68,19 +62,7 @@ class CopilotService extends BaseService_1.default {
|
|
|
68
62
|
}
|
|
69
63
|
try {
|
|
70
64
|
if (this.assistantId) {
|
|
71
|
-
|
|
72
|
-
// as we are doing with the other approach
|
|
73
|
-
const conversationArray = conversation.split('\n');
|
|
74
|
-
const lastCustomerMessage = conversationArray.reverse().find(e => e.includes('customer:'));
|
|
75
|
-
if (!lastCustomerMessage) {
|
|
76
|
-
logger_1.default.error('last customer message not found');
|
|
77
|
-
return Promise.reject(new Error('last customer message not found'));
|
|
78
|
-
}
|
|
79
|
-
// Route based on id shape: asst_* => Assistant API, prompt_* => Responses API
|
|
80
|
-
if (yield this.isAssistantIdFormat(this.assistantId)) {
|
|
81
|
-
return yield this.getAssistantSuggestions(conversation);
|
|
82
|
-
}
|
|
83
|
-
return yield this.getPromptSuggestions(lastCustomerMessage);
|
|
65
|
+
return yield this.getAssistantSuggestions(conversation);
|
|
84
66
|
}
|
|
85
67
|
return yield this.getChatCompletionSuggestions(conversation);
|
|
86
68
|
}
|
|
@@ -108,7 +90,7 @@ class CopilotService extends BaseService_1.default {
|
|
|
108
90
|
},
|
|
109
91
|
// the body we need to send to the request
|
|
110
92
|
requestBody = {
|
|
111
|
-
model: this.
|
|
93
|
+
model: this.chatGPTModel,
|
|
112
94
|
messages: [mainPromptMessage],
|
|
113
95
|
}, response = yield this.request.post('', requestBody);
|
|
114
96
|
return {
|
|
@@ -150,7 +132,7 @@ class CopilotService extends BaseService_1.default {
|
|
|
150
132
|
}
|
|
151
133
|
while (['queued', 'in_progress', 'cancelling'].includes(run.status)) {
|
|
152
134
|
yield new Promise(resolve => setTimeout(resolve, 500));
|
|
153
|
-
run = yield openai.beta.threads.runs.retrieve(run.
|
|
135
|
+
run = yield openai.beta.threads.runs.retrieve(run.thread_id, run.id);
|
|
154
136
|
}
|
|
155
137
|
if (run.status === 'completed') {
|
|
156
138
|
const { data } = yield openai.beta.threads.messages.list(run.thread_id, { order: 'desc', limit: 1 }), messages = data.flatMap((message) => message === null || message === void 0 ? void 0 : message.content.map((content) => ((content.type === 'text' && message.role === 'assistant') ? content.text : ''))), assistantMessages = messages.filter(message => typeof message === 'object' && 'value' in message && typeof message.value === 'string');
|
|
@@ -166,67 +148,6 @@ class CopilotService extends BaseService_1.default {
|
|
|
166
148
|
return undefined;
|
|
167
149
|
});
|
|
168
150
|
}
|
|
169
|
-
isAssistantIdFormat(id) {
|
|
170
|
-
return !!id && /^asst_[A-Za-z0-9]+$/.test(id);
|
|
171
|
-
}
|
|
172
|
-
isPromptIdFormat(id) {
|
|
173
|
-
return !!id && /^pmpt_[A-Za-z0-9]+$/.test(id);
|
|
174
|
-
}
|
|
175
|
-
getPromptSuggestions(message) {
|
|
176
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
|
|
177
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
178
|
-
const openai = new openai_1.default({ apiKey: this.openaiApiKey });
|
|
179
|
-
let conversationId = this.conversationId;
|
|
180
|
-
if (!conversationId) {
|
|
181
|
-
const conv = yield openai.conversations.create();
|
|
182
|
-
conversationId = conv.id;
|
|
183
|
-
}
|
|
184
|
-
const request = {
|
|
185
|
-
//model: this.chatGptModel || 'gpt-4o-mini',
|
|
186
|
-
input: message,
|
|
187
|
-
store: true,
|
|
188
|
-
conversation: { id: conversationId },
|
|
189
|
-
include: ['file_search_call.results'],
|
|
190
|
-
};
|
|
191
|
-
if (this.assistantId && (yield this.isPromptIdFormat(this.assistantId))) {
|
|
192
|
-
request.prompt = { id: this.assistantId };
|
|
193
|
-
}
|
|
194
|
-
const response = yield openai.responses.create(request);
|
|
195
|
-
response.output.forEach((item, index) => {
|
|
196
|
-
});
|
|
197
|
-
if ((_a = response.conversation) === null || _a === void 0 ? void 0 : _a.id) {
|
|
198
|
-
this.conversationId = response.conversation.id;
|
|
199
|
-
}
|
|
200
|
-
// Sometimes if the prompt needs a file search, the output will be an array of messages
|
|
201
|
-
// which includes multiple messages (some of them are not useful for the user, but the last one is)
|
|
202
|
-
const output = response.output || [];
|
|
203
|
-
const assistantMessages = output.filter((item) => item.type === 'message' && item.role === 'assistant');
|
|
204
|
-
if (assistantMessages.length) {
|
|
205
|
-
const text = assistantMessages.flatMap((m) => { var _a, _b; return ((_b = (_a = m.content) === null || _a === void 0 ? void 0 : _a.filter((c) => c.type === 'output_text')) === null || _b === void 0 ? void 0 : _b.map((c) => c.text)) || []; });
|
|
206
|
-
return {
|
|
207
|
-
data: [text.pop()],
|
|
208
|
-
threadId: this.conversationId,
|
|
209
|
-
usageTokens: {
|
|
210
|
-
prompt_tokens: Number((_c = ((_b = response.usage) === null || _b === void 0 ? void 0 : _b.prompt_tokens)) !== null && _c !== void 0 ? _c : 0),
|
|
211
|
-
completion_tokens: Number((_e = ((_d = response.usage) === null || _d === void 0 ? void 0 : _d.completion_tokens)) !== null && _e !== void 0 ? _e : 0),
|
|
212
|
-
total_tokens: Number((_g = ((_f = response.usage) === null || _f === void 0 ? void 0 : _f.total_tokens)) !== null && _g !== void 0 ? _g : 0),
|
|
213
|
-
},
|
|
214
|
-
};
|
|
215
|
-
}
|
|
216
|
-
if (response.output_text) {
|
|
217
|
-
return {
|
|
218
|
-
data: [response.output_text],
|
|
219
|
-
threadId: this.conversationId,
|
|
220
|
-
usageTokens: {
|
|
221
|
-
prompt_tokens: Number((_j = ((_h = response.usage) === null || _h === void 0 ? void 0 : _h.prompt_tokens)) !== null && _j !== void 0 ? _j : 0),
|
|
222
|
-
completion_tokens: Number((_l = ((_k = response.usage) === null || _k === void 0 ? void 0 : _k.completion_tokens)) !== null && _l !== void 0 ? _l : 0),
|
|
223
|
-
total_tokens: Number((_o = ((_m = response.usage) === null || _m === void 0 ? void 0 : _m.total_tokens)) !== null && _o !== void 0 ? _o : 0),
|
|
224
|
-
},
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
|
-
return undefined;
|
|
228
|
-
});
|
|
229
|
-
}
|
|
230
151
|
}
|
|
231
152
|
exports.CopilotService = CopilotService;
|
|
232
153
|
_CopilotService_instances = new WeakSet(), _CopilotService_processSuggestions = function _CopilotService_processSuggestions(suggestions) {
|
|
@@ -5,11 +5,12 @@ export declare class TranslationService extends BaseService {
|
|
|
5
5
|
/**
|
|
6
6
|
* Request the ChatGPT API to translate a specific test to a desired language
|
|
7
7
|
*
|
|
8
|
-
* @param text
|
|
9
|
-
* @param toLanguage
|
|
10
|
-
* @param fromLanguage
|
|
8
|
+
* @param text the text to translate
|
|
9
|
+
* @param toLanguage the desired language to translate to ( English is the default )
|
|
10
|
+
* @param fromLanguage if we want to specify the language of the text, we can use this (optional)
|
|
11
|
+
* @param additionalInstructions additional instructions set by Manager or use default (optional)
|
|
11
12
|
*/
|
|
12
|
-
translate(text: string, toLanguage?: string, fromLanguage?: string): Promise<ChatGPTResponse | undefined>;
|
|
13
|
+
translate(text: string, toLanguage?: string, fromLanguage?: string, additionalInstructions?: string): Promise<ChatGPTResponse | undefined>;
|
|
13
14
|
/**
|
|
14
15
|
* Detects the ISO language code of a text
|
|
15
16
|
*
|
|
@@ -24,11 +24,12 @@ class TranslationService extends BaseService_1.default {
|
|
|
24
24
|
/**
|
|
25
25
|
* Request the ChatGPT API to translate a specific test to a desired language
|
|
26
26
|
*
|
|
27
|
-
* @param text
|
|
28
|
-
* @param toLanguage
|
|
29
|
-
* @param fromLanguage
|
|
27
|
+
* @param text the text to translate
|
|
28
|
+
* @param toLanguage the desired language to translate to ( English is the default )
|
|
29
|
+
* @param fromLanguage if we want to specify the language of the text, we can use this (optional)
|
|
30
|
+
* @param additionalInstructions additional instructions set by Manager or use default (optional)
|
|
30
31
|
*/
|
|
31
|
-
translate(text, toLanguage = constants_1.DESTINATION_LANGUAGE, fromLanguage) {
|
|
32
|
+
translate(text, toLanguage = constants_1.DESTINATION_LANGUAGE, fromLanguage, additionalInstructions = constants_1.TRANSLATION_ADDITIONAL_INSTRUCTIONS) {
|
|
32
33
|
return __awaiter(this, void 0, void 0, function* () {
|
|
33
34
|
if (!text) {
|
|
34
35
|
logger_1.default.error('Translation text should be provided');
|
|
@@ -38,12 +39,15 @@ class TranslationService extends BaseService_1.default {
|
|
|
38
39
|
Translate the following text from ${fromLanguage} to ${toLanguage} if it's not already in ${toLanguage}: ${text}.
|
|
39
40
|
`;
|
|
40
41
|
const requestBody = {
|
|
41
|
-
model: this.
|
|
42
|
+
model: this.chatGPTModel,
|
|
42
43
|
response_format: { type: 'json_object' },
|
|
43
44
|
messages: [
|
|
44
45
|
{
|
|
45
46
|
role: ChatGPTMessage_1.ChatGPTRole.SYSTEM,
|
|
46
|
-
content:
|
|
47
|
+
content: `
|
|
48
|
+
${constants_1.TRANSLATION_SYSTEM_ROLE_BASE_PROMPT}
|
|
49
|
+
<ADDITIONAL_INSTRUCTIONS>${additionalInstructions}</ADDITIONAL_INSTRUCTIONS>
|
|
50
|
+
`,
|
|
47
51
|
},
|
|
48
52
|
{
|
|
49
53
|
role: ChatGPTMessage_1.ChatGPTRole.USER,
|
|
@@ -77,7 +81,7 @@ class TranslationService extends BaseService_1.default {
|
|
|
77
81
|
return Promise.reject(new Error('Text must be provided'));
|
|
78
82
|
}
|
|
79
83
|
const translateText = `Detect the ISO language code of this text: '${text}'`, requestBody = {
|
|
80
|
-
model: this.
|
|
84
|
+
model: this.chatGPTModel,
|
|
81
85
|
response_format: { type: 'json_object' },
|
|
82
86
|
messages: [
|
|
83
87
|
{
|
|
@@ -116,7 +120,7 @@ class TranslationService extends BaseService_1.default {
|
|
|
116
120
|
return Promise.reject(new Error('Text must be provided'));
|
|
117
121
|
}
|
|
118
122
|
const translateText = `Detect the ISO language code based on the most words used in this text: '${text}'`, requestBody = {
|
|
119
|
-
model: this.
|
|
123
|
+
model: this.chatGPTModel,
|
|
120
124
|
response_format: { type: 'json_object' },
|
|
121
125
|
messages: [
|
|
122
126
|
{
|
|
@@ -6,8 +6,10 @@ export declare const MESSAGE_TYPES: {
|
|
|
6
6
|
text: string;
|
|
7
7
|
button: string;
|
|
8
8
|
};
|
|
9
|
+
export declare const DEFAULT_MODEL = "gpt-5.1";
|
|
9
10
|
export declare const DEFAULT_PROMPT = "\n You are a helpful assistant. Your role is to address visitor \n queries related to the ongoing conversation and the last message received. Please ensure \n that responses remain within the ongoing conversation. Politely decline any user queries \n that is not present in the ongoing conversation. \n\n You will always respond with a JSON. It will be in the format: \n\n { answer: '', suggestions: [], connectWithAgent: true or false }\n\n Fields in the JSON:\n\n Answer: It will consist of the user's query answer based on the ongoing conversation. \n Restrict this field to 100 characters.\n\n Suggestions: Request 2 suggestions from user's perspective that he can ask. \n It should be an array of strings. Restrict each suggestion to 50 characters.\n \n ConnectWithAgent: It is a boolean. It should be set to true if the user's query is \n not found in the ongoing conversation. Politely tell the user to talk to a real agent. \n Also when it is true, do not provide any suggestions.\n";
|
|
10
11
|
export declare const DESTINATION_LANGUAGE = "English";
|
|
11
12
|
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
13
|
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
|
|
14
|
+
export declare const TRANSLATION_SYSTEM_ROLE_BASE_PROMPT = "\n <BASE_PROMPT>\n\n You are a translator that responds exclusively in JSON format.\n\n Your response must be a JSON object containing:\n - 'translations': an array of objects. Each object in the array must contain:\n - 'original': The original input message before translation.\n - 'translation': The translated version of 'original'.\n - 'isError': a boolean value (true if translation fails, false otherwise).\n\n **You MUST return JSON format even if you fail to translate the text.**\n \n In that case:\n\n - 'translations' field should be an empty array.\n - 'isError' should be true.\n\n You must follow the response structure defined in this BASE_PROMPT strictly.\n \n Apply all instructions in ADDITIONAL_INSTRUCTIONS, but never alter the required JSON structure.\n\n </BASE_PROMPT>\n";
|
|
15
|
+
export declare const TRANSLATION_ADDITIONAL_INSTRUCTIONS = "\n Ensure that each 'translation' accurately reflects the meaning of 'original' and is phrased in a way that native speakers would naturally express it, taking into account cultural context and commonly used expressions.\n\n Do not translate commonly known Latin phrases or expressions (e.g., 'de facto', 'bona fide') when they appear mid-sentence in another language. Leave them exactly as they appear in the original text.\n";
|
package/dist/utils/constants.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.TRANSLATION_ADDITIONAL_INSTRUCTIONS = exports.TRANSLATION_SYSTEM_ROLE_BASE_PROMPT = exports.WORD_FREQUENCY_LANGUAGE_DETECTION_SYSTEM_ROLE = exports.LANGUAGE_DETECTION_SYSTEM_ROLE = exports.DESTINATION_LANGUAGE = exports.DEFAULT_PROMPT = exports.DEFAULT_MODEL = exports.MESSAGE_TYPES = exports.MESSAGE_SENDER = void 0;
|
|
4
4
|
// Message sender in conversation history
|
|
5
5
|
exports.MESSAGE_SENDER = {
|
|
6
6
|
visitor: 'visitor',
|
|
@@ -11,6 +11,7 @@ exports.MESSAGE_TYPES = {
|
|
|
11
11
|
text: 'text',
|
|
12
12
|
button: 'button'
|
|
13
13
|
};
|
|
14
|
+
exports.DEFAULT_MODEL = 'gpt-5.1';
|
|
14
15
|
// Default prompt for ChatGPT
|
|
15
16
|
exports.DEFAULT_PROMPT = `
|
|
16
17
|
You are a helpful assistant. Your role is to address visitor
|
|
@@ -50,20 +51,34 @@ exports.WORD_FREQUENCY_LANGUAGE_DETECTION_SYSTEM_ROLE = `
|
|
|
50
51
|
- 'languageCode': the detected language's ISO code (or undefined if detection fails).
|
|
51
52
|
- 'isError': a boolean value (true if detection fails, false otherwise).
|
|
52
53
|
`;
|
|
53
|
-
//
|
|
54
|
-
exports.
|
|
55
|
-
|
|
56
|
-
- 'translations': it is an array of objects. Each object in the array must contain:
|
|
57
|
-
- 'original': The original input message before translation.
|
|
58
|
-
- 'translation: The translated version of 'original', ensuring it is natural, culturally appropriate, and commonly used by native speakers.
|
|
59
|
-
- 'isError': a boolean value (true if translation fails, false otherwise).
|
|
54
|
+
// Base prompt which is focused towards the main instructions of the task
|
|
55
|
+
exports.TRANSLATION_SYSTEM_ROLE_BASE_PROMPT = `
|
|
56
|
+
<BASE_PROMPT>
|
|
60
57
|
|
|
61
|
-
|
|
58
|
+
You are a translator that responds exclusively in JSON format.
|
|
62
59
|
|
|
63
|
-
|
|
60
|
+
Your response must be a JSON object containing:
|
|
61
|
+
- 'translations': an array of objects. Each object in the array must contain:
|
|
62
|
+
- 'original': The original input message before translation.
|
|
63
|
+
- 'translation': The translated version of 'original'.
|
|
64
|
+
- 'isError': a boolean value (true if translation fails, false otherwise).
|
|
64
65
|
|
|
65
|
-
|
|
66
|
-
|
|
66
|
+
**You MUST return JSON format even if you fail to translate the text.**
|
|
67
|
+
|
|
68
|
+
In that case:
|
|
67
69
|
|
|
68
|
-
|
|
70
|
+
- 'translations' field should be an empty array.
|
|
71
|
+
- 'isError' should be true.
|
|
72
|
+
|
|
73
|
+
You must follow the response structure defined in this BASE_PROMPT strictly.
|
|
74
|
+
|
|
75
|
+
Apply all instructions in ADDITIONAL_INSTRUCTIONS, but never alter the required JSON structure.
|
|
76
|
+
|
|
77
|
+
</BASE_PROMPT>
|
|
78
|
+
`;
|
|
79
|
+
// Additional instructions for translation. This is going to be used if additional instructions are not passed as parameter by manager.
|
|
80
|
+
exports.TRANSLATION_ADDITIONAL_INSTRUCTIONS = `
|
|
81
|
+
Ensure that each 'translation' accurately reflects the meaning of 'original' and is phrased in a way that native speakers would naturally express it, taking into account cultural context and commonly used expressions.
|
|
82
|
+
|
|
83
|
+
Do not translate commonly known Latin phrases or expressions (e.g., 'de facto', 'bona fide') when they appear mid-sentence in another language. Leave them exactly as they appear in the original text.
|
|
69
84
|
`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cobrowser/chatgpt",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.36",
|
|
4
4
|
"description": "chatgpt services to connect our projects with chatgpt api",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"chatgpt",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"@cobrowser/xss-validation": "^2.0.1",
|
|
26
26
|
"axios": "^1.6.1",
|
|
27
27
|
"axios-mock-adapter": "^1.22.0",
|
|
28
|
-
"openai": "^
|
|
28
|
+
"openai": "^4.86.2"
|
|
29
29
|
},
|
|
30
30
|
"directories": {
|
|
31
31
|
"dist": "dist"
|
|
@@ -40,5 +40,5 @@
|
|
|
40
40
|
"bugs": {
|
|
41
41
|
"url": "https://bitbucket.org/cobrowser/cb_utils/issues"
|
|
42
42
|
},
|
|
43
|
-
"gitHead": "
|
|
43
|
+
"gitHead": "7a5961aa09cb038da19c5e23e25996158b2f1dfa"
|
|
44
44
|
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import ChatGPTResponse from '../../models/ChatGPTResponse';
|
|
2
|
-
import BaseService from '../BaseService/BaseService';
|
|
3
|
-
interface ResponseServiceOptions {
|
|
4
|
-
instructions?: string;
|
|
5
|
-
tools?: any[];
|
|
6
|
-
functionOutputs?: string;
|
|
7
|
-
definedSchema?: any;
|
|
8
|
-
conversationId?: string;
|
|
9
|
-
}
|
|
10
|
-
export declare class ResponseService extends BaseService {
|
|
11
|
-
promptId: string | undefined;
|
|
12
|
-
conversationId: string | undefined;
|
|
13
|
-
lastResponseId: string | undefined;
|
|
14
|
-
constructor(apiKey?: string, promptId?: string, conversationId?: string);
|
|
15
|
-
/**
|
|
16
|
-
* Create a new conversation
|
|
17
|
-
*/
|
|
18
|
-
createConversation(): Promise<string>;
|
|
19
|
-
/**
|
|
20
|
-
* Get the reply using the Response API
|
|
21
|
-
*
|
|
22
|
-
* @param message
|
|
23
|
-
* @param runOptions
|
|
24
|
-
*/
|
|
25
|
-
getReply(message: string, runOptions?: ResponseServiceOptions): Promise<ChatGPTResponse | undefined>;
|
|
26
|
-
reset(): void;
|
|
27
|
-
getConversationId(): string | undefined;
|
|
28
|
-
getLastResponseId(): string | undefined;
|
|
29
|
-
getPromptId(): string | undefined;
|
|
30
|
-
setPromptId(promptId: string): void;
|
|
31
|
-
setConversationId(conversationId: string): void;
|
|
32
|
-
setLastResponseId(lastResponseId: string): void;
|
|
33
|
-
}
|
|
34
|
-
export {};
|
|
@@ -1,193 +0,0 @@
|
|
|
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
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
-
};
|
|
14
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.ResponseService = void 0;
|
|
16
|
-
const logger_1 = __importDefault(require("../logger"));
|
|
17
|
-
const openai_1 = __importDefault(require("openai"));
|
|
18
|
-
const BaseService_1 = __importDefault(require("../BaseService/BaseService"));
|
|
19
|
-
class ResponseService extends BaseService_1.default {
|
|
20
|
-
constructor(apiKey, promptId, conversationId) {
|
|
21
|
-
super(apiKey);
|
|
22
|
-
Object.defineProperty(this, "promptId", {
|
|
23
|
-
enumerable: true,
|
|
24
|
-
configurable: true,
|
|
25
|
-
writable: true,
|
|
26
|
-
value: void 0
|
|
27
|
-
});
|
|
28
|
-
Object.defineProperty(this, "conversationId", {
|
|
29
|
-
enumerable: true,
|
|
30
|
-
configurable: true,
|
|
31
|
-
writable: true,
|
|
32
|
-
value: void 0
|
|
33
|
-
});
|
|
34
|
-
Object.defineProperty(this, "lastResponseId", {
|
|
35
|
-
enumerable: true,
|
|
36
|
-
configurable: true,
|
|
37
|
-
writable: true,
|
|
38
|
-
value: void 0
|
|
39
|
-
});
|
|
40
|
-
this.promptId = promptId;
|
|
41
|
-
this.conversationId = conversationId;
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Create a new conversation
|
|
45
|
-
*/
|
|
46
|
-
createConversation() {
|
|
47
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
48
|
-
const openai = new openai_1.default({ apiKey: this.openaiApiKey });
|
|
49
|
-
const conversation = yield openai.conversations.create();
|
|
50
|
-
this.conversationId = conversation.id;
|
|
51
|
-
return this.conversationId;
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Get the reply using the Response API
|
|
56
|
-
*
|
|
57
|
-
* @param message
|
|
58
|
-
* @param runOptions
|
|
59
|
-
*/
|
|
60
|
-
getReply(message, runOptions = {}) {
|
|
61
|
-
var _a, _b;
|
|
62
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
63
|
-
if (!this.promptId) {
|
|
64
|
-
logger_1.default.error('Prompt ID is required for Response API');
|
|
65
|
-
return Promise.reject(new Error('Prompt ID is required for Response API'));
|
|
66
|
-
}
|
|
67
|
-
logger_1.default.info(`New response with message: ${message} & options: ${JSON.stringify(runOptions)}`);
|
|
68
|
-
const openai = new openai_1.default({ apiKey: this.openaiApiKey });
|
|
69
|
-
try {
|
|
70
|
-
const responseRequest = {
|
|
71
|
-
store: true,
|
|
72
|
-
};
|
|
73
|
-
// Handle function outputs
|
|
74
|
-
if (runOptions.functionOutputs) {
|
|
75
|
-
const toolOutputs = JSON.parse(runOptions.functionOutputs);
|
|
76
|
-
const formattedInputs = toolOutputs.map((output) => ({
|
|
77
|
-
type: 'function_call_output',
|
|
78
|
-
call_id: output.call_id,
|
|
79
|
-
output: output.output
|
|
80
|
-
}));
|
|
81
|
-
responseRequest.input = formattedInputs;
|
|
82
|
-
const conversationIdToUse = runOptions.conversationId || this.conversationId;
|
|
83
|
-
if (!conversationIdToUse) {
|
|
84
|
-
const createdId = yield this.createConversation();
|
|
85
|
-
this.conversationId = createdId;
|
|
86
|
-
}
|
|
87
|
-
responseRequest.conversation = runOptions.conversationId || this.conversationId;
|
|
88
|
-
}
|
|
89
|
-
else {
|
|
90
|
-
// Handle regular message
|
|
91
|
-
if (!runOptions.conversationId && !this.conversationId) {
|
|
92
|
-
const createdId = yield this.createConversation();
|
|
93
|
-
this.conversationId = createdId;
|
|
94
|
-
}
|
|
95
|
-
responseRequest.input = message;
|
|
96
|
-
responseRequest.include = ['file_search_call.results'];
|
|
97
|
-
if (runOptions.instructions) {
|
|
98
|
-
responseRequest.instructions = runOptions.instructions;
|
|
99
|
-
}
|
|
100
|
-
const conversationIdToUse = runOptions.conversationId || this.conversationId;
|
|
101
|
-
if (conversationIdToUse) {
|
|
102
|
-
responseRequest.conversation = conversationIdToUse;
|
|
103
|
-
}
|
|
104
|
-
if ((_a = runOptions.tools) === null || _a === void 0 ? void 0 : _a.length) {
|
|
105
|
-
responseRequest.tools = runOptions.tools;
|
|
106
|
-
}
|
|
107
|
-
if (runOptions.definedSchema) {
|
|
108
|
-
responseRequest.text = {
|
|
109
|
-
format: runOptions.definedSchema
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
if (this.promptId) {
|
|
114
|
-
responseRequest.prompt = {
|
|
115
|
-
id: this.promptId
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
const response = yield openai.responses.create(responseRequest);
|
|
119
|
-
this.lastResponseId = response.id;
|
|
120
|
-
if ((_b = response.conversation) === null || _b === void 0 ? void 0 : _b.id) {
|
|
121
|
-
this.conversationId = response.conversation.id;
|
|
122
|
-
}
|
|
123
|
-
else if (runOptions.conversationId) {
|
|
124
|
-
this.conversationId = runOptions.conversationId;
|
|
125
|
-
}
|
|
126
|
-
// Process response output
|
|
127
|
-
const output = response.output || [];
|
|
128
|
-
const assistantMessages = output.filter((item) => item.type === 'message' && item.role === 'assistant');
|
|
129
|
-
const functionCalls = output.filter((item) => item.type === 'function_call');
|
|
130
|
-
if (functionCalls.length > 0) {
|
|
131
|
-
return {
|
|
132
|
-
requiredActions: JSON.stringify(functionCalls),
|
|
133
|
-
threadId: this.conversationId,
|
|
134
|
-
usageTokens: response.usage,
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
if (assistantMessages.length > 0) {
|
|
138
|
-
const textContent = assistantMessages
|
|
139
|
-
.flatMap((msg) => msg.content || [])
|
|
140
|
-
.filter((content) => content.type === 'output_text' || content.type === 'text')
|
|
141
|
-
.map((content) => content.text || content.value)
|
|
142
|
-
.filter((text) => text);
|
|
143
|
-
if (textContent.length > 0) {
|
|
144
|
-
return {
|
|
145
|
-
data: textContent.pop(),
|
|
146
|
-
threadId: this.conversationId,
|
|
147
|
-
usageTokens: response.usage,
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
if (response.output_text) {
|
|
152
|
-
return {
|
|
153
|
-
data: response.output_text,
|
|
154
|
-
threadId: this.conversationId,
|
|
155
|
-
usageTokens: response.usage,
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
return {
|
|
159
|
-
data: undefined,
|
|
160
|
-
threadId: this.conversationId,
|
|
161
|
-
usageTokens: response.usage,
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
catch (error) {
|
|
165
|
-
logger_1.default.error('Error in ResponseService.getReply:', error);
|
|
166
|
-
return Promise.reject(error);
|
|
167
|
-
}
|
|
168
|
-
});
|
|
169
|
-
}
|
|
170
|
-
reset() {
|
|
171
|
-
this.lastResponseId = undefined;
|
|
172
|
-
this.conversationId = undefined;
|
|
173
|
-
}
|
|
174
|
-
getConversationId() {
|
|
175
|
-
return this.conversationId;
|
|
176
|
-
}
|
|
177
|
-
getLastResponseId() {
|
|
178
|
-
return this.lastResponseId;
|
|
179
|
-
}
|
|
180
|
-
getPromptId() {
|
|
181
|
-
return this.promptId;
|
|
182
|
-
}
|
|
183
|
-
setPromptId(promptId) {
|
|
184
|
-
this.promptId = promptId;
|
|
185
|
-
}
|
|
186
|
-
setConversationId(conversationId) {
|
|
187
|
-
this.conversationId = conversationId;
|
|
188
|
-
}
|
|
189
|
-
setLastResponseId(lastResponseId) {
|
|
190
|
-
this.lastResponseId = lastResponseId;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
exports.ResponseService = ResponseService;
|