nicechat
Version:
An extensible AI chat framework for OpenAi's models
86 lines (85 loc) • 2.89 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 });
const sdk_1 = __importDefault(require("@anthropic-ai/sdk"));
const chalk_1 = __importDefault(require("chalk"));
const nicechat_1 = require("./nicechat");
const KEY = process.env.CLAUDE_KEY;
const client = new sdk_1.default({
apiKey: KEY,
});
const MODEL = "claude-3-opus-20240229";
const MAX_TOKENS = 1024;
// const system: MessageParam = {
// role: "system",
// content: "You are a helpful assistant.",
// };
function chat() {
return __awaiter(this, void 0, void 0, function* () {
// console.log("[" + chalk.blueBright(system.content) + "]");
const messages = [];
// initial use input
const input = yield (0, nicechat_1.readLine)();
messages.push(user(input));
while (true) {
const response = yield exchange(messages);
messages.push(assistant(response));
// ask user for next input
console.log("\n");
const input = yield (0, nicechat_1.readLine)();
messages.push(user(input));
}
});
}
function main() {
return __awaiter(this, void 0, void 0, function* () {
yield chat();
});
}
function user(content) {
return {
role: "user",
content,
};
}
function assistant(content) {
return {
role: "assistant",
content,
};
}
function exchange(messages) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => {
let msg = "";
client.messages
.stream({
messages,
model: MODEL,
max_tokens: MAX_TOKENS,
})
.on("text", (p) => {
// collect regular message
if (p) {
process.stdout.write(chalk_1.default.greenBright(p));
msg += p;
}
})
.on("end", () => {
resolve(msg);
});
});
});
}
main();