@cobrowser/chatgpt 0.7.42-beta.2 → 0.7.43-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,7 +16,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
16
16
  var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
- var _CopilotService_instances, _CopilotService_processSuggestions;
19
+ var _CopilotService_instances, _CopilotService_processSuggestions, _CopilotService_prepareAssistantResponseAnswer;
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.CopilotService = void 0;
22
22
  const ChatGPTMessage_1 = require("../../models/ChatGPTMessage");
@@ -77,14 +77,6 @@ class CopilotService extends BaseService_1.default {
77
77
  }
78
78
  try {
79
79
  if (this.assistantId) {
80
- // Here we get the last customer message as we dont need the whole conversation
81
- // as we are doing with the other approach
82
- const conversationArray = conversation.split('\n');
83
- const lastCustomerMessage = conversationArray.reverse().find(e => e.includes('customer:'));
84
- if (!lastCustomerMessage) {
85
- logger_1.default.error('last customer message not found');
86
- return Promise.reject(new Error('last customer message not found'));
87
- }
88
80
  // Route based on id shape: asst_* => Assistant API, prompt_* => Responses API
89
81
  if (yield this.isAssistantIdFormat(this.assistantId)) {
90
82
  logger_1.default.info(':: CopilotServicee.suggest :: Fetching suggestion through Assistant API ::');
@@ -150,10 +142,11 @@ class CopilotService extends BaseService_1.default {
150
142
  content: line.replace(/^customer:\s*/, '').trim()
151
143
  });
152
144
  }
153
- else if (line.includes('agent:')) {
145
+ else if (line.includes('agent:') || line.includes('chatbot:')) {
146
+ const isAgent = line.includes('agent:'), content = isAgent ? line.replace(/^agent:\s*/, '') : line.replace(/^chatbot:\s*/, '');
154
147
  messages.push({
155
148
  role: 'assistant',
156
- content: line.replace(/^agent:\s*/, '').trim()
149
+ content: content.trim()
157
150
  });
158
151
  }
159
152
  }
@@ -184,8 +177,11 @@ class CopilotService extends BaseService_1.default {
184
177
  const messagesData = lastAssistantMessage.content.map((content) => content.type === 'text' ? content.text : '').filter(text => text);
185
178
  if (messagesData.length) {
186
179
  const answers = messagesData.map(message => message.value);
180
+ logger_1.default.info({
181
+ answers
182
+ }, ':: CopilotServicee.getAssistantSuggestions :: Raw Suggestions ::');
187
183
  return {
188
- data: __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_processSuggestions).call(this, answers),
184
+ data: __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_processSuggestions).call(this, __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_prepareAssistantResponseAnswer).call(this, answers)),
189
185
  threadId: this.threadId,
190
186
  usageTokens: undefined,
191
187
  };
@@ -217,8 +213,11 @@ class CopilotService extends BaseService_1.default {
217
213
  const { data } = yield openai.beta.threads.messages.list(currentRun.thread_id, { order: 'desc', limit: 1 }), messagesData = data.flatMap((message) => message === null || message === void 0 ? void 0 : message.content.map((content) => ((content.type === 'text' && message.role === 'assistant') ? content.text : ''))), assistantMessages = messagesData.filter(message => typeof message === 'object' && 'value' in message && typeof message.value === 'string');
218
214
  if (assistantMessages.length) {
219
215
  const answers = assistantMessages.map(message => message.value);
216
+ logger_1.default.info({
217
+ answers
218
+ }, ':: CopilotServicee.getAssistantSuggestions :: Raw Suggestions ::');
220
219
  return {
221
- data: __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_processSuggestions).call(this, answers),
220
+ data: __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_processSuggestions).call(this, __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_prepareAssistantResponseAnswer).call(this, answers)),
222
221
  threadId: currentRun.thread_id,
223
222
  usageTokens: currentRun.usage,
224
223
  };
@@ -236,8 +235,7 @@ class CopilotService extends BaseService_1.default {
236
235
  getPromptSuggestions(conversation, suggestionLanguage) {
237
236
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
238
237
  return __awaiter(this, void 0, void 0, function* () {
239
- const conversationLines = conversation.split('\n').filter(line => line.trim());
240
- const messages = [];
238
+ const conversationLines = conversation.split('\n').filter(line => line.trim()), messages = [];
241
239
  for (const line of conversationLines) {
242
240
  if (line.includes('customer:')) {
243
241
  messages.push({
@@ -245,10 +243,11 @@ class CopilotService extends BaseService_1.default {
245
243
  content: line.replace(/^customer:\s*/, '').trim()
246
244
  });
247
245
  }
248
- else if (line.includes('agent:')) {
246
+ else if (line.includes('agent:') || line.includes('chatbot:')) {
247
+ const isAgent = line.includes('agent:'), content = isAgent ? line.replace(/^agent:\s*/, '') : line.replace(/^chatbot:\s*/, '');
249
248
  messages.push({
250
249
  role: 'assistant',
251
- content: line.replace(/^agent:\s*/, '').trim()
250
+ content: content.trim()
252
251
  });
253
252
  }
254
253
  }
@@ -257,8 +256,7 @@ class CopilotService extends BaseService_1.default {
257
256
  return Promise.reject(new Error('No valid messages found in conversation'));
258
257
  }
259
258
  const openai = new openai_1.default({ apiKey: this.openaiApiKey });
260
- let conversationId = this.conversationId;
261
- let lastMessageIndex = -1;
259
+ let conversationId = this.conversationId, lastMessageIndex = -1;
262
260
  if (!conversationId) {
263
261
  const conv = yield openai.conversations.create({
264
262
  metadata: {
@@ -293,7 +291,7 @@ class CopilotService extends BaseService_1.default {
293
291
  if (assistantMessages.length) {
294
292
  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)) || []; });
295
293
  return {
296
- data: [text[text.length - 1]],
294
+ data: __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_processSuggestions).call(this, __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_prepareAssistantResponseAnswer).call(this, text)),
297
295
  threadId: this.conversationId,
298
296
  usageTokens: undefined,
299
297
  };
@@ -312,23 +310,20 @@ class CopilotService extends BaseService_1.default {
312
310
  contextMessages.push(`${roleLabel}: ${msg.content}`);
313
311
  }
314
312
  const lastUserMessage = newMessages.filter(m => m.role === 'user').pop();
315
- if (!lastUserMessage) {
316
- if (conversationId) {
317
- try {
318
- yield openai.conversations.update(conversationId, {
319
- metadata: {
320
- lastMessageIndex: (messages.length - 1).toString(),
321
- conversationHistory: JSON.stringify(messages)
322
- }
323
- });
324
- }
325
- catch (e) {
326
- logger_1.default.error('Failed to update conversation metadata', e);
327
- }
313
+ if (!lastUserMessage && conversationId) {
314
+ try {
315
+ yield openai.conversations.update(conversationId, {
316
+ metadata: {
317
+ lastMessageIndex: (messages.length - 1).toString(),
318
+ conversationHistory: JSON.stringify(messages)
319
+ }
320
+ });
321
+ }
322
+ catch (e) {
323
+ logger_1.default.error('Failed to update conversation metadata', e);
328
324
  }
329
- return Promise.reject(new Error('No new user messages to process'));
330
325
  }
331
- let inputWithContext = lastUserMessage.content;
326
+ let inputWithContext = lastUserMessage === null || lastUserMessage === void 0 ? void 0 : lastUserMessage.content;
332
327
  if (contextMessages.length > 0 || newMessages.length > 1) {
333
328
  const allNewMessages = [];
334
329
  for (const msg of newMessages) {
@@ -338,12 +333,19 @@ class CopilotService extends BaseService_1.default {
338
333
  const fullContext = [...contextMessages, ...allNewMessages].join('\n');
339
334
  inputWithContext = fullContext;
340
335
  }
341
- const request = Object.assign({ input: inputWithContext, store: true, conversation: { id: conversationId }, include: ['file_search_call.results'] }, (suggestionLanguage ? {
342
- instructions: `IMPORTANT: You must respond in ${suggestionLanguage} language only.
343
- Regardless of the language used in the conversation, your response must be in ${suggestionLanguage}.`
344
- } : {}));
336
+ const request = {
337
+ input: inputWithContext,
338
+ store: true,
339
+ conversation: { id: conversationId },
340
+ include: ['file_search_call.results'],
341
+ };
345
342
  if (this.assistantId && (yield this.isPromptIdFormat(this.assistantId))) {
346
- request.prompt = { id: this.assistantId };
343
+ request.prompt = {
344
+ id: this.assistantId,
345
+ variables: {
346
+ language: suggestionLanguage,
347
+ }
348
+ };
347
349
  }
348
350
  const lastResponse = yield openai.responses.create(request);
349
351
  if ((_b = lastResponse.conversation) === null || _b === void 0 ? void 0 : _b.id) {
@@ -371,7 +373,7 @@ class CopilotService extends BaseService_1.default {
371
373
  if (assistantMessages.length) {
372
374
  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)) || []; });
373
375
  return {
374
- data: [text[text.length - 1]],
376
+ data: __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_processSuggestions).call(this, __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_prepareAssistantResponseAnswer).call(this, text)),
375
377
  threadId: this.conversationId,
376
378
  usageTokens: {
377
379
  prompt_tokens: Number((_d = ((_c = lastResponse.usage) === null || _c === void 0 ? void 0 : _c.prompt_tokens)) !== null && _d !== void 0 ? _d : 0),
@@ -382,7 +384,7 @@ class CopilotService extends BaseService_1.default {
382
384
  }
383
385
  if (lastResponse.output_text) {
384
386
  return {
385
- data: [lastResponse.output_text],
387
+ data: __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_processSuggestions).call(this, __classPrivateFieldGet(this, _CopilotService_instances, "m", _CopilotService_prepareAssistantResponseAnswer).call(this, lastResponse.output_text)),
386
388
  threadId: this.conversationId,
387
389
  usageTokens: {
388
390
  prompt_tokens: Number((_k = ((_j = lastResponse.usage) === null || _j === void 0 ? void 0 : _j.prompt_tokens)) !== null && _k !== void 0 ? _k : 0),
@@ -400,4 +402,22 @@ _CopilotService_instances = new WeakSet(), _CopilotService_processSuggestions =
400
402
  suggestions = suggestions ? suggestions : [];
401
403
  suggestions = suggestions.filter(suggestion => !!suggestion.trim());
402
404
  return suggestions;
405
+ }, _CopilotService_prepareAssistantResponseAnswer = function _CopilotService_prepareAssistantResponseAnswer(data) {
406
+ if (!data) {
407
+ return [];
408
+ }
409
+ if (Array.isArray(data) &&
410
+ data.length === 1 &&
411
+ typeof data[0] === 'string') {
412
+ try {
413
+ // when data is [ '["suggestion1", "suggestion2"]' ]
414
+ return JSON.parse(data[0]);
415
+ }
416
+ catch (e) {
417
+ logger_1.default.error('Failed to parse stringified array, returning the data as is...');
418
+ return data;
419
+ }
420
+ }
421
+ // return data as is if format is different
422
+ return data;
403
423
  };
@@ -6,7 +6,7 @@ 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
+ export declare const DEFAULT_MODEL = "gpt-5-nano";
10
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";
11
11
  export declare const DESTINATION_LANGUAGE = "English";
12
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";
@@ -11,7 +11,7 @@ exports.MESSAGE_TYPES = {
11
11
  text: 'text',
12
12
  button: 'button'
13
13
  };
14
- exports.DEFAULT_MODEL = 'gpt-5.1';
14
+ exports.DEFAULT_MODEL = 'gpt-5-nano';
15
15
  // Default prompt for ChatGPT
16
16
  exports.DEFAULT_PROMPT = `
17
17
  You are a helpful assistant. Your role is to address visitor
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cobrowser/chatgpt",
3
- "version": "0.7.42-beta.2",
3
+ "version": "0.7.43-beta.1",
4
4
  "description": "chatgpt services to connect our projects with chatgpt api",
5
5
  "keywords": [
6
6
  "chatgpt",
@@ -40,5 +40,5 @@
40
40
  "bugs": {
41
41
  "url": "https://bitbucket.org/cobrowser/cb_utils/issues"
42
42
  },
43
- "gitHead": "6dd7d39c92cfce900cf001c2f8a0dba438dc103e"
43
+ "gitHead": "a4d06097c6989a8956d8273ba09b5f3918963978"
44
44
  }