@cobrowser/chatgpt 0.2.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/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # `chatgpt`
2
+
3
+ > TODO: description
4
+
5
+ ## Usage
6
+
7
+ ```
8
+ const chatgpt = require('chatgpt');
9
+
10
+ // TODO: DEMONSTRATE API
11
+ ```
@@ -0,0 +1 @@
1
+ export * from './services/TranslationService/TranslationService';
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./services/TranslationService/TranslationService"), exports);
@@ -0,0 +1,14 @@
1
+ export declare enum ChatGptRole {
2
+ USER = "user",
3
+ ASSISTANT = "assistant",
4
+ SYSTEM = "system"
5
+ }
6
+ export interface ChatGptRequestBody {
7
+ model: string;
8
+ messages: ChatGptMessage[];
9
+ }
10
+ interface ChatGptMessage {
11
+ role: ChatGptRole;
12
+ content: string;
13
+ }
14
+ export default ChatGptMessage;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChatGptRole = void 0;
4
+ var ChatGptRole;
5
+ (function (ChatGptRole) {
6
+ ChatGptRole["USER"] = "user";
7
+ ChatGptRole["ASSISTANT"] = "assistant";
8
+ ChatGptRole["SYSTEM"] = "system";
9
+ })(ChatGptRole = exports.ChatGptRole || (exports.ChatGptRole = {}));
@@ -0,0 +1,25 @@
1
+ import { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
2
+ declare class BaseService {
3
+ request: AxiosInstance;
4
+ readonly BASE_CHAT_COMPLETION_URL = "https://api.openai.com/v1/chat/completions";
5
+ chatGptModel: string;
6
+ maxNumberOfChatCompletionResult: number;
7
+ /**
8
+ *
9
+ * @param apiUrl Api url to be used to make API calls to openAI services
10
+ * @param model the main chatGPT model to use
11
+ * @param maxNumberOfChoices How many chat completion choices to generate for each request.
12
+ */
13
+ constructor(apiUrl?: string, model?: string, maxNumberOfChoices?: number);
14
+ /**
15
+ * Filter the response from chatGpt API and only get the first choice
16
+ * @param response
17
+ */
18
+ getResponseFirstChoice(response: AxiosResponse): string | undefined;
19
+ /**
20
+ * function to handle requests errors
21
+ * @param error
22
+ */
23
+ handleErrors(error: AxiosError): void;
24
+ }
25
+ export default BaseService;
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const axios_1 = __importDefault(require("axios"));
7
+ const logger_1 = __importDefault(require("../logger"));
8
+ class BaseService {
9
+ /**
10
+ *
11
+ * @param apiUrl Api url to be used to make API calls to openAI services
12
+ * @param model the main chatGPT model to use
13
+ * @param maxNumberOfChoices How many chat completion choices to generate for each request.
14
+ */
15
+ constructor(apiUrl, model = 'gpt-3.5-turbo', maxNumberOfChoices = 1) {
16
+ Object.defineProperty(this, "request", {
17
+ enumerable: true,
18
+ configurable: true,
19
+ writable: true,
20
+ value: void 0
21
+ });
22
+ Object.defineProperty(this, "BASE_CHAT_COMPLETION_URL", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: 'https://api.openai.com/v1/chat/completions'
27
+ });
28
+ Object.defineProperty(this, "chatGptModel", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: ''
33
+ });
34
+ Object.defineProperty(this, "maxNumberOfChatCompletionResult", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: 1
39
+ });
40
+ this.request = axios_1.default.create({
41
+ baseURL: apiUrl || this.BASE_CHAT_COMPLETION_URL,
42
+ headers: {
43
+ 'Content-Type': 'application/json',
44
+ Authorization: `Bearer ${process.env.OPEN_API_KEY} `,
45
+ },
46
+ });
47
+ this.chatGptModel = model;
48
+ this.maxNumberOfChatCompletionResult = maxNumberOfChoices;
49
+ }
50
+ /**
51
+ * Filter the response from chatGpt API and only get the first choice
52
+ * @param response
53
+ */
54
+ getResponseFirstChoice(response) {
55
+ var _a;
56
+ if ((_a = response.data.choices) === null || _a === void 0 ? void 0 : _a.length) {
57
+ const firstChatGptResponseMessage = response.data.choices[0].message;
58
+ logger_1.default.info(`First ChatGpt Message: ${firstChatGptResponseMessage.content}`);
59
+ return firstChatGptResponseMessage.content;
60
+ }
61
+ return undefined;
62
+ }
63
+ /**
64
+ * function to handle requests errors
65
+ * @param error
66
+ */
67
+ handleErrors(error) {
68
+ if (error.response) {
69
+ // The request was made and the server responded with a status code
70
+ // that falls out of the range of 2xx
71
+ logger_1.default.error(`response status code is ${error.response.status}`);
72
+ logger_1.default.error(`response data ${error.response.data}`);
73
+ }
74
+ else if (error.request) {
75
+ // The request was made but no response was received
76
+ logger_1.default.error(error.request);
77
+ }
78
+ logger_1.default.error(`error message ${error.message}`);
79
+ }
80
+ }
81
+ exports.default = BaseService;
@@ -0,0 +1,12 @@
1
+ import BaseService from '../BaseService/BaseService';
2
+ export declare class TranslationService extends BaseService {
3
+ DESTINATION_LANGUAGE: string;
4
+ constructor(apiUrl?: string, model?: string, maxNumberOfChoices?: number);
5
+ /**
6
+ * request the chatGpt Api to translate a specific test to a desired language
7
+ * @param text the text to translate
8
+ * @param toLanguage the desired language to translate to ( English is the default )
9
+ * @param fromLanguage if we want to specify the language of the text, we can use this ( optional)
10
+ */
11
+ translate(text: string, toLanguage?: string, fromLanguage?: string): Promise<string | undefined>;
12
+ }
@@ -0,0 +1,63 @@
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.TranslationService = void 0;
16
+ const ChatGptMessage_1 = require("../../models/ChatGptMessage");
17
+ const BaseService_1 = __importDefault(require("../BaseService/BaseService"));
18
+ const logger_1 = __importDefault(require("../logger"));
19
+ class TranslationService extends BaseService_1.default {
20
+ constructor(apiUrl, model, maxNumberOfChoices) {
21
+ super(apiUrl, model, maxNumberOfChoices);
22
+ Object.defineProperty(this, "DESTINATION_LANGUAGE", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: 'English'
27
+ });
28
+ }
29
+ /**
30
+ * request the chatGpt Api to translate a specific test to a desired language
31
+ * @param text the text to translate
32
+ * @param toLanguage the desired language to translate to ( English is the default )
33
+ * @param fromLanguage if we want to specify the language of the text, we can use this ( optional)
34
+ */
35
+ translate(text, toLanguage = 'English', fromLanguage) {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ if (!text) {
38
+ logger_1.default.error('translation text should be provided');
39
+ return Promise.reject(new Error('test must be provided'));
40
+ }
41
+ const desiredLanguage = toLanguage || this.DESTINATION_LANGUAGE,
42
+ // instruction on what to do with the text
43
+ translateText = `Translate the following ${fromLanguage} text to ${desiredLanguage}: ${text}`,
44
+ // the body we need to send to the request
45
+ requestBody = {
46
+ model: this.chatGptModel,
47
+ messages: [{
48
+ role: ChatGptMessage_1.ChatGptRole.USER,
49
+ content: translateText,
50
+ }],
51
+ };
52
+ try {
53
+ const response = yield this.request.post('', requestBody);
54
+ return this.getResponseFirstChoice(response);
55
+ }
56
+ catch (e) {
57
+ this.handleErrors(e);
58
+ return Promise.reject(e);
59
+ }
60
+ });
61
+ }
62
+ }
63
+ exports.TranslationService = TranslationService;
@@ -0,0 +1,2 @@
1
+ declare const logger: any;
2
+ export default logger;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
5
+ const logger = require('@cobrowser/logger')({
6
+ level: (_a = process.env.LOG_LEVEL) !== null && _a !== void 0 ? _a : 'debug',
7
+ redact: ['secret.*'],
8
+ pretty: false,
9
+ timestamp: false,
10
+ });
11
+ exports.default = logger;
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@cobrowser/chatgpt",
3
+ "version": "0.2.0",
4
+ "description": "chatgpt services to connect our projects with chatgpt api",
5
+ "keywords": [
6
+ "chatgpt",
7
+ "ai",
8
+ "API",
9
+ "services"
10
+ ],
11
+ "author": "Mostafa Tourad <mostafa@cobrowser.net>",
12
+ "homepage": "https://bitbucket.org/cobrowser/cb_utils#readme",
13
+ "main": "dist/index.js",
14
+ "scripts": {
15
+ "compile": "tsc -p tsconfig-build.json",
16
+ "test": "npx jest",
17
+ "lint": "npx eslint",
18
+ "lint-fix": "npm run lint -- --fix",
19
+ "security": "npm audit --production",
20
+ "upgrade": "npm outdated",
21
+ "precommit": "npm run lint && npm run test && npm run upgrade && npm run security"
22
+ },
23
+ "dependencies": {
24
+ "@cobrowser/logger": "^1.0.0",
25
+ "axios": "^1.3.5",
26
+ "axios-mock-adapter": "^1.21.4"
27
+ },
28
+ "directories": {
29
+ "dist": "dist"
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+ssh://git@bitbucket.org/cobrowser/cb_utils.git"
37
+ },
38
+ "bugs": {
39
+ "url": "https://bitbucket.org/cobrowser/cb_utils/issues"
40
+ },
41
+ "gitHead": "116e8ba0b35f1fe2e5479fbac11033f346affd1b"
42
+ }