UNPKG

i18n-ai-translate

Version:

AI-powered localization CLI, Node library, and GitHub Action. Translate i18next JSON, Gettext PO, Java .properties, and iOS .strings with ChatGPT, Claude, Gemini, or local Ollama models.

89 lines 3.26 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("../utils"); const chat_interface_1 = __importDefault(require("./chat_interface")); const role_1 = __importDefault(require("../enums/role")); class Anthropic extends chat_interface_1.default { model; chatParams; history; rateLimiter; constructor(model, rateLimiter) { super(); this.model = model; this.chatParams = null; this.history = []; this.rateLimiter = rateLimiter; } startChat(params) { this.chatParams = params; if (params.messages.length > 0) { this.history = params.messages; } } async sendMessage(message, _format) { if (!this.chatParams) { console.trace("Chat not started"); return ""; } // Limit the history to prevent wasting tokens if (this.history.length > 2) { this.history = this.history.slice(this.history.length - 2); } // Cheap ~4-chars-per-token estimate; the limiter no-ops the TPM // check when no cap is configured. Double to account for the // response tokens we'll also be billed for. await this.rateLimiter.acquire(Math.ceil(message.length / 2)); this.history.push({ content: message, role: role_1.default.User }); try { const response = await this.model.messages.create({ ...this.chatParams, max_tokens: 1024, messages: this.history, stream: false, }); const responseBlock = response.content; if (!responseBlock || responseBlock.length < 1 || responseBlock[0].type !== "text") { return ""; } const responseText = responseBlock[0].text; this.history.push({ content: responseText, role: role_1.default.Assistant }); return responseText; } catch (err) { (0, utils_1.printError)(err); return ""; } } resetChatHistory() { this.history = []; } rollbackLastMessage() { if (this.history[this.history.length - 1].role === role_1.default.Assistant) { // Remove the last two messages (user and assistant) // so we can get back to the last successful state in history this.history.pop(); this.history.pop(); } else if (this.history[this.history.length - 1].role === role_1.default.User) { // The model didn't respond, so we only need to remove the user message this.history.pop(); } } signalInvalid(kind) { // Anthropic's messages.create only accepts alternating user / // assistant messages, so we reuse the user role rather than // tag this as system. this.history.push({ content: this.invalidMessage(kind), role: role_1.default.User, }); } } exports.default = Anthropic; //# sourceMappingURL=anthropic.js.map