auto-gpt-ts
Version:
my take of Auto-GPT in typescript
169 lines • 7.45 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.constructMainAiConfig = exports.PromptGenerator = void 0;
const chalk_1 = __importDefault(require("chalk"));
const logging_1 = require("../logging");
const ai_config_1 = require("../config/ai-config");
const config_1 = require("../config/config");
const utils_1 = require("../utils");
const setup_1 = require("../setup");
const api_manages_1 = require("../llm/api-manages");
class PromptGenerator extends logging_1.Loggable {
constructor() {
super(...arguments);
this.constraints = [];
this.resources = [];
this.performanceEvaluation = [];
this.commands = [];
this.goals = [];
this.name = "bob";
this.role = "ai";
this.responseFormat = {
thoughts: {
text: "thought",
reasoning: "reasoning",
plan: "- short bulleted\n- list that conveys\n- long-term plan",
criticism: "constructive self-criticism",
speak: "thoughts summary to say to user",
},
command: { name: "command name", args: { "arg name": "value" } },
};
}
/**
* Add a constraint to the constraints list.
* @param constraint The constraint to be added.
*/
addConstraint(...constraints) {
this.constraints.push(constraints.join("\n"));
}
/**
* Add a command to the commands list with a label, name, and optional arguments.
* @param commandLabel The label of the command.
* @param commandName The name of the command.
* @param args A dictionary containing argument names and their values.
* @param commandFunction A callable function to be called when the command is executed.
*/
addCommand(commandLabel, commandName, args = {}, commandFunction) {
const command = {
label: commandLabel,
name: commandName,
args: args,
function: commandFunction,
};
this.commands.push(command);
}
/**
* Add a resource to the resources list.
* @param resource The resource to be added.
*/
addResource(resource) {
this.resources.push(resource);
}
/**
* Add a performance evaluation item to the performance_evaluation list.
* @param evaluation The evaluation item to be added.
*/
addPerformanceEvaluation(...evaluation) {
this.performanceEvaluation.push(evaluation.join("\n"));
}
/**
* Generate a prompt string based on the constraints, commands, resources, and performance evaluations.
*/
generatePromptString() {
const formattedResponseFormat = JSON.stringify(this.responseFormat, null, 4);
return [
`Constraints:\n${this.generateNumberedList(this.constraints)}\n\n`,
"Commands:\n",
`${this.generateNumberedList(this.generateCommandsStrings(this.commands))}\n\n`,
`Resources:\n${this.generateNumberedList(this.resources)}\n\n`,
"Performance Evaluation:\n",
`${this.generateNumberedList(this.performanceEvaluation)}\n\n`,
"You should only respond in JSON format as described below \n",
`Response Format: \n${formattedResponseFormat} `,
`Ensure the response can be parsed by javascript JSON.parse`,
];
}
/**
* Generate a formatted string representation of a command.
* @param command
*/
generateCommandString(command) {
const argsString = Object.entries(command.args)
.map(([key, value]) => `"${key}": "${value}"`)
.join(", ");
return `${command.label}: "${command.name}", args: ${argsString}`;
}
generateNumberedList(list) {
return list.map((item, i) => `${i + 1}. ${item}`).join("\n");
}
generateCommandsStrings(list) {
const commandsStrings = [];
// TODO: add registers strings
commandsStrings.push(...this.commands.map((cmd) => this.generateCommandString(cmd)), ...Object.values(this.commandRegistry.commands).filter(cmd => cmd.enabled).map(cmd => cmd.toString()));
return commandsStrings;
}
}
exports.PromptGenerator = PromptGenerator;
const logger = (0, logging_1.getLogger)("PromptGenerator");
const CFG = new config_1.Config();
function constructMainAiConfig() {
return __awaiter(this, void 0, void 0, function* () {
/**
* Construct the prompt for the AI to respond to
* @returns AIConfig: The AIConfig instance
*/
let config = ai_config_1.AIConfig.load(CFG.aiSettingsFile);
if (CFG.skipReprompt && config.aiName) {
logger.info("Name :" + chalk_1.default.green(config.aiName));
logger.info("Role :" + chalk_1.default.green(config.aiRole));
logger.info("Goals:" + chalk_1.default.green(`${config.aiGoals}`));
logger.info("API Budget: " +
chalk_1.default.green(config.apiBudget <= 0 ? "infinite" : `$${config.apiBudget}`));
}
else if (config.aiName) {
logger.info("Welcome back! " +
chalk_1.default.green(config.aiName) +
` Would you like me to return to being ${config.aiName}?`);
const should_continue = yield (0, utils_1.cleanInput)(`Continue with the last settings?
Name: ${config.aiName}
Role: ${config.aiRole}
Goals: ${config.aiGoals}
API Budget: ${config.apiBudget <= 0 ? "infinite" : `${config.apiBudget}`}
Continue (${CFG.authoriseKey}/${CFG.exitKey}) `);
if (should_continue.toLowerCase() === CFG.exitKey) {
config = new ai_config_1.AIConfig();
}
}
if (!config.aiName) {
config = yield (0, setup_1.promptUser)();
config.save(CFG.aiSettingsFile);
}
// set the total api budget
const api_manager = new api_manages_1.ApiManager();
api_manager.setTotalBudget(config.apiBudget);
// Agent Created, print message
logger.info(config.aiName + chalk_1.default.blue(" has been created with the following details:"));
// Print the ai config details
// Name
logger.info("Name: " + chalk_1.default.green(config.aiName));
// Role
logger.info("Role: " + chalk_1.default.green(config.aiRole));
// Goals
logger.info(`Goals: \n${config.aiGoals.map((goal) => "- " + chalk_1.default.green(goal)).join("\n")}`);
return config;
});
}
exports.constructMainAiConfig = constructMainAiConfig;
//# sourceMappingURL=prompt-base.js.map