Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

All notable changes to this project will be documented in this file.

<!-- generated by git-cliff -->
83 changes: 83 additions & 0 deletions cliff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# git-cliff ~ default configuration file
# https://git-cliff.org/docs/configuration
#
# Lines starting with "#" are comments.
# Configuration options are organized into tables and keys.
# See documentation for more information on available options.

[changelog]
# changelog header
header = """
# Changelog\n
All notable changes to this project will be documented in this file.\n
"""
# template for the changelog body
# https://keats.github.io/tera/docs/#introduction
body = """
{% if version %}\
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
{% else %}\
## [unreleased]
{% endif %}\
{% for group, commits in commits | group_by(attribute="group") %}
### {{ group | upper_first }}
{% for commit in commits %}
- {% if commit.breaking %}[**breaking**] {% endif %}{{ commit.message | upper_first }}\
{% endfor %}
{% endfor %}\n
"""
# remove the leading and trailing whitespace from the template
trim = true
# changelog footer
footer = """
<!-- generated by git-cliff -->
"""
# postprocessors
postprocessors = [
# { pattern = '<REPO>', replace = "https://github.com/orhun/git-cliff" }, # replace repository URL
]
[git]
# parse the commits based on https://www.conventionalcommits.org
conventional_commits = true
# filter out the commits that are not conventional
filter_unconventional = true
# process each line of a commit as an individual commit
split_commits = false
# regex for preprocessing the commit messages
commit_preprocessors = [
# { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](<REPO>/issues/${2}))"}, # replace issue numbers
]
# regex for parsing and grouping commits
commit_parsers = [
{ message = "^feat", group = "Features" },
{ message = "^fix", group = "Bug Fixes" },
{ message = "^doc", group = "Documentation" },
{ message = "^perf", group = "Performance" },
{ message = "^refactor", group = "Refactor" },
{ message = "^style", group = "Styling" },
{ message = "^test", group = "Testing" },
{ message = "^chore\\(release\\): prepare for", skip = true },
{ message = "^chore\\(deps\\)", skip = true },
{ message = "^chore\\(pr\\)", skip = true },
{ message = "^chore\\(pull\\)", skip = true },
{ message = "^chore|ci", group = "Miscellaneous Tasks" },
{ body = ".*security", group = "Security" },
{ message = "^revert", group = "Revert" },
]
# protect breaking changes from being skipped due to matching a skipping commit_parser
protect_breaking_commits = false
# filter out the commits that are not matched by commit parsers
filter_commits = false
# regex for matching git tags
tag_pattern = "v[0-9].*"

# regex for skipping tags
skip_tags = "v0.1.0-beta.1"
# regex for ignoring tags
ignore_tags = ""
# sort the tags topologically
topo_order = false
# sort the commits inside sections by oldest/newest order
sort_commits = "oldest"
# limit the number of commits included in the changelog.
# limit_commits = 42
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ebenjs/gpt-shell",
"version": "1.0.0",
"version": "1.1.1",
"description": "Chat-GPT in the console",
"main": "index.js",
"type": "module",
Expand Down
21 changes: 15 additions & 6 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,26 @@ import { sendOpenApiRequest } from "./request-helper.js";
import { logger } from "./utilities/logger.js";

export const ask = (prompt) => {
sendOpenApiRequest(prompt).then((data) => {
logger.logResponse(data.choices[0].message.content);
});
sendOpenApiRequest(prompt)
.then((data) => {
logger.logResponse(data.choices[0].message.content);
})
.catch((error) => {
logger.logError(JSON.parse(error.message));
});
};

export const configure = (args) => {
let existingConfig = null;
if (fs.existsSync("./.gpt-shell-config.json")) {
existingConfig = JSON.parse(fs.readFileSync("./.gpt-shell-config.json"));
}

const { apikey, model, url } = args;
const config = {
apikey: apikey || process.env.OPENAI_API_KEY,
model: model || process.env.OPENAI_DEFAULT_MODEL,
url: url || process.env.OPENAI_API_URL,
apikey: apikey || existingConfig?.apikey || process.env.OPENAI_API_KEY,
model: model || existingConfig?.model || process.env.OPENAI_DEFAULT_MODEL,
url: url || existingConfig?.url || process.env.OPENAI_API_URL,
};

fs.writeFileSync("./.gpt-shell-config.json", JSON.stringify(config, null, 2));
Expand Down
14 changes: 10 additions & 4 deletions src/request-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,26 @@ export const sendOpenApiRequest = async (requestPrompt) => {
logger.logPrompt(requestPrompt + "\n");
const animation = loadingAnimation();

console.log(getConfig());
const config = getConfig();

if (config.status === "error") {
clearInterval(animation);
process.stdout.write("\r");
throw new Error(JSON.stringify(config.errors));
}

const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + getConfig().apikey,
Authorization: "Bearer " + getConfig().config.apikey,
},
body: JSON.stringify({
model: getConfig().model,
model: getConfig().config.model,
messages: [{ role: "user", content: requestPrompt }],
}),
};
const response = await fetch(getConfig().url, requestOptions);
const response = await fetch(getConfig().config.url, requestOptions);
const data = await response.json();

clearInterval(animation);
Expand Down
21 changes: 21 additions & 0 deletions src/utilities/error-handling.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { logger } from "./logger.js";

let aggregatedErrors = [];

export const addError = (error) => {
aggregatedErrors.push(error);
};

export const getErrors = () => aggregatedErrors;

export const clearErrors = () => (aggregatedErrors = []);

export const logErrors = () => {
aggregatedErrors.forEach((error) => {
logger.logError(error);
});
};

export const throwError = (message) => {
throw new Error(message);
};
29 changes: 27 additions & 2 deletions src/utilities/get-config.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,30 @@
import fs from "fs";
import { getErrors, addError } from "./error-handling.js";

const checkForRequiredEnvironmentVariables = (config) => {
if (!config.apikey) {
addError("OPENAI_API_KEY is not defined");
}

if (!config.model) {
addError("OPENAI_MODEL is not defined");
}

if (!config.url) {
addError("OPENAI_API_URL is not defined");
}

return !getErrors().length > 0;
};

export const getConfig = () => {
if (fs.existsSync("./.gpt-shell-config.json")) {
const config = JSON.parse(fs.readFileSync("./.gpt-shell-config.json"));
return config;
if (!checkForRequiredEnvironmentVariables(config)) {
return { status: "error", errors: getErrors() };
}

return { status: "success", config: config };
}

const config = {
Expand All @@ -12,5 +33,9 @@ export const getConfig = () => {
url: process.env.OPENAI_API_URL,
};

return config;
if (!checkForRequiredEnvironmentVariables(config)) {
return { status: "error", errors: getErrors() };
}

return { status: "success", config: config };
};
20 changes: 20 additions & 0 deletions src/utilities/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ const customPromptLoggerFormat = winston.format.printf(({ message }) => {
return `${chalk.blueBright("[gpt-shell-prompt]")} : ${message}`;
});

const customErrorLoggerFormat = winston.format.printf(({ message }) => {
return chalk.redBright("[error] : " + message);
});

const customPrefixedErrorLoggerFormat = (prefix) => {
return winston.format.printf(({ message }) => {
return chalk.redBright(prefix + message);
});
};

const _logger = winston.createLogger({
level: "info",
transports: [
Expand All @@ -35,8 +45,18 @@ const logResponse = (response) => {
_logger.info(response);
};

const logError = (errors) => {
_logger.format = customErrorLoggerFormat;
_logger.error("Some configuration errors were found");
errors.forEach((error, index) => {
_logger.format = customPrefixedErrorLoggerFormat(`[${index}] `);
_logger.error(error);
});
};

export const logger = {
default: _logger,
logPrompt,
logResponse,
logError,
};