Skip to content

Commit

Permalink
fix: tslinting content
Browse files Browse the repository at this point in the history
  • Loading branch information
fbatiga committed May 9, 2023
1 parent acfab5b commit fa6b698
Show file tree
Hide file tree
Showing 12 changed files with 189 additions and 79 deletions.
95 changes: 89 additions & 6 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"sourceType": "module",
"ecmaVersion": 2020
},
"plugins": ["@typescript-eslint", "jest"],
"plugins": ["@typescript-eslint", "jest", "promise"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
Expand All @@ -19,10 +19,93 @@
"prettier"
],
"rules": {
// The following rule is enabled only to supplement the inline suppression
// examples, and because it is not a recommended rule, you should either
// disable it, or understand what it enforces.
// https://typescript-eslint.io/rules/explicit-function-return-type/
"@typescript-eslint/explicit-function-return-type": "warn"
"@typescript-eslint/explicit-function-return-type": "warn",
"no-await-in-loop": "off",
"quotes": ["error", "single", { "avoidEscape": true }],
"no-param-reassign": 0,
"no-useless-escape": 0,
"no-underscore-dangle": [
2,
{
"allow": [
"_id",
"_source",
"_changed",
"_previousDataValues",
"_dataValues",
"__"
]
}
],
"prefer-destructuring": 0,
"no-iterator": 1,
"no-restricted-syntax": [
"error",
"ForInStatement",
"LabeledStatement",
"WithStatement"
],
"consistent-return": 0,
"comma-dangle": 0,
"guard-for-in": 0,
"object-curly-newline": ["error", { "minProperties": 2, "multiline": true }],
"indent": [
2,
2,
{
"SwitchCase": 2
}
],
"radix": 0,
"object-shorthand": 1,
"newline-per-chained-call": [
1,
{
"ignoreChainWithDepth": 3
}
],
"no-confusing-arrow": "error",
"import/extensions": 0,
"no-mixed-operators": 2,
"class-methods-use-this": 0,
"no-unused-vars": [
"error",
{
"vars": "all",
"args": "after-used",
"varsIgnorePattern": "[(colors|models)]",
"ignoreRestSiblings": false
}
],
"no-console": "off",
"no-continue": "off",
"no-plusplus": [
"error",
{
"allowForLoopAfterthoughts": true
}
],
"max-len": [
"error",
{
"code": 150,
"ignoreUrls": true
}
],
"promise/always-return": "warn",
"promise/no-return-wrap": "warn",
"promise/param-names": "warn",
"promise/catch-or-return": "error",
"promise/no-native": "off",
"promise/no-nesting": 1,
"promise/no-promise-in-callback": "warn",
"promise/no-callback-in-promise": "warn",
"promise/avoid-new": 0,
"promise/no-new-statics": "warn",
"promise/no-return-in-finally": "warn",
"promise/valid-params": "warn",
"max-lines-per-function": ["warn", 120],
"max-lines": ["error", { "max": 600, "skipComments": true }],
"no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 0 }]
}
}
20 changes: 2 additions & 18 deletions __tests__/main.test.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,12 @@
import { Delays, greeter } from '../src/index.js';

describe('greeter function', () => {
const name = 'John';
let hello: string;

let timeoutSpy: jest.SpyInstance;

// Act before assertions
beforeAll(async () => {
// Read more about fake timers
// http://facebook.github.io/jest/docs/en/timer-mocks.html#content
// Jest 27 now uses "modern" implementation of fake timers
// https://jestjs.io/blog/2021/05/25/jest-27#flipping-defaults
// https://github.com/facebook/jest/pull/5171
jest.useFakeTimers();
timeoutSpy = jest.spyOn(global, 'setTimeout');

const p: Promise<string> = greeter(name);
jest.runOnlyPendingTimers();
hello = await p;
beforeAll(() => {
console.log('beforeAll');
});

// Teardown (cleanup) after assertions
Expand All @@ -29,10 +17,6 @@ describe('greeter function', () => {
// Assert if setTimeout was called properly
it('delays the greeting by 2 seconds', () => {
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(
expect.any(Function),
Delays.Long,
);
});

// Assert greeter result
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"eslint-config-prettier": "~8.8",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-jest": "~27.2",
"eslint-plugin-promise": "^6.1.1",
"jest": "~29.5",
"nodemon": "^2.0.22",
"prettier": "~2.8",
Expand Down Expand Up @@ -66,4 +67,4 @@
"db/*"
]
}
}
}
25 changes: 16 additions & 9 deletions src/chat.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// eslint-lint-disable no-continue
import 'dotenv/config';
import prompt from 'prompt';
import { chatWithGPT } from './services/openai';
import getDb from './services/db';
import { getUserInput } from './services/utils';
import { chatWithGPT } from './services/openai.ts';
import getDb from './services/db.ts';
import { getUserInput } from './services/utils.ts';

prompt.start();

Expand All @@ -18,12 +19,11 @@ const chat = async () => {
console.log('Welcome to ChatGPT CLI! Type your message and press Enter.');
const context = [];
while (true) {
// eslint-disable-next-line no-await-in-loop
const userInput = await getUserInput();
if (typeof userInput === 'string' && userInput.toLowerCase() === 'exit') {
console.log('Goodbye!');
setTimeout(() => {
process.exit(0);
}, 500);
process.exit(0);
break;
}
if (userInput === null || userInput === undefined || userInput === '') {
Expand All @@ -32,13 +32,20 @@ const chat = async () => {

// Call your chat function here, for example:
spinner.start();
// eslint-disable-next-line no-await-in-loop
const response = await chatWithGPT(userInput as string, context);
spinner.stop();
context.push({ role: 'user', content: userInput });
context.push({ role: 'system', content: response });
context.push({
role: 'user', content: userInput
});
context.push({
role: 'system', content: response
});
console.log(`ChatGPT: ${response}`);

DB.data.history[sessionId].push({ input: userInput, output: response });
DB.data.history[sessionId].push({
input: userInput, output: response
});
DB.write();
}
};
Expand Down
32 changes: 22 additions & 10 deletions src/finetuning.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
/** eslint-lint-disable no-shadow */
import 'dotenv/config';
import prompt from 'prompt';
import { join } from 'node:path';
import { debug as Debug } from 'debug';
import { openai } from './services/openai';
import getDb from './services/db';
import { getUserInput, checkForExitInput } from './services/utils';
import { writeFileSync, createReadStream } from 'fs';
import {
writeFileSync, createReadStream
} from 'fs';

import { openai } from './services/openai.ts';
import getDb from './services/db.ts';
import {
getUserInput, checkForExitInput
} from './services/utils.ts';

const debug = Debug('chat:finetuning');
let fileToUpload = process.argv[2];
Expand All @@ -18,8 +24,8 @@ prompt.start();
*/
async function inputTrainingData(): Promise<
{ prompt: string; completion: string }[]
> {
let trainingData = [];
> {
const trainingData = [];
let isInputtingData = true;
while (isInputtingData) {
console.log(
Expand All @@ -44,7 +50,9 @@ async function inputTrainingData(): Promise<
isInputtingData = false;
break;
}
trainingData.push({ prompt: input, completion });
trainingData.push({
prompt: input, completion
});
}
return trainingData;
}
Expand All @@ -64,11 +72,13 @@ const chat = async () => {
console.log('Existing fine tuning models:');
debug(existingTuningList);
console.table(
existingTuningList.map(({ id, model, status, fine_tuned_model }) => ({
existingTuningList.map(({
id, model, status, fine_tuned_model // eslint-disable-line camelcase
}) => ({
id,
model,
status,
fine_tuned_model,
fine_tuned_model, // eslint-disable-line camelcase
})),
);

Expand All @@ -93,7 +103,9 @@ const chat = async () => {
// create and upload the training file content
const trainingFileContent = trainingData
.map(
({ prompt, completion }) =>
({
prompt, completion // eslint-disable-line no-shadow
}) =>
`{"prompt": "${prompt}", "completion": "${completion}"}`,
)
.join('\n');
Expand Down
2 changes: 2 additions & 0 deletions src/services/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ async function init(db: any) {
if (db) {
return db;
}
// eslint-disable-next-line import/no-unresolved
const { Low } = await import('lowdb');
// eslint-disable-next-line import/no-unresolved
const { JSONFile } = await import('lowdb/node');

// db.json file path
Expand Down
19 changes: 12 additions & 7 deletions src/services/openai.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Configuration, OpenAIApi } from 'openai';
import { promptForApiKey } from './utils';
import {
Configuration, OpenAIApi
} from 'openai';
import { promptForApiKey } from './utils.ts';

let apiKey = process.env.OPEN_API_API_KEY || '';

if (!apiKey) {
Expand All @@ -10,9 +13,7 @@ if (!apiKey) {
.catch(console.error);
}
// OpenAI configuration creation
const configuration = new Configuration({
apiKey,
});
const configuration = new Configuration({apiKey,});
// OpenAI instance creation
export const openai = new OpenAIApi(configuration);

Expand All @@ -23,11 +24,15 @@ export async function chatWithGPT(
try {
console.log('Sending message to GPT:', [
...context,
{ role: 'user', content: message },
{
role: 'user', content: message
},
]);
const response = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: [...context, { role: 'user', content: message }],
messages: [...context, {
role: 'user', content: message
}],
max_tokens: 800,
n: 1,
stop: null,
Expand Down
25 changes: 0 additions & 25 deletions src/services/spinner.ts

This file was deleted.

1 change: 1 addition & 0 deletions src/services/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import prompt from 'prompt';
import { writeFileSync } from 'node:fs';

// eslint-disable-next-line
type GetUserInputFunction = (inputName?: string) => Promise<string>;

export const getUserInput: GetUserInputFunction = (inputName = 'input') =>
Expand Down

0 comments on commit fa6b698

Please sign in to comment.