polyfact
Version:
<h1 align="center">PolyFact</h1>
329 lines (328 loc) • 14.6 kB
JavaScript
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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 __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.generate = exports.Generation = void 0;
var t = __importStar(require("polyfact-io-ts"));
var process_1 = __importDefault(require("process"));
var readable_stream_1 = require("readable-stream");
var isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
var clientOpts_1 = require("./clientOpts");
var dataloader_1 = require("./dataloader");
if (typeof window !== "undefined") {
window.process = process_1.default;
}
function getMemoryIds(dataMemory, genOptionsMemoryId, genOptionsMemory) {
return __awaiter(this, void 0, void 0, function () {
var memoryIds, _b, validMemoryIds;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_b = [dataMemory,
genOptionsMemoryId];
return [4 /*yield*/, (genOptionsMemory === null || genOptionsMemory === void 0 ? void 0 : genOptionsMemory.memoryId)];
case 1:
memoryIds = _b.concat([
_c.sent()
]);
validMemoryIds = memoryIds.filter(function (id) { return id !== undefined; });
if (validMemoryIds.length === 0) {
return [2 /*return*/, undefined];
}
else if (validMemoryIds.length >= 2) {
return [2 /*return*/, validMemoryIds];
}
else {
return [2 /*return*/, validMemoryIds[0]];
}
return [2 /*return*/];
}
});
});
}
var Generation = /** @class */ (function (_super) {
__extends(Generation, _super);
function Generation(_b) {
var stop = _b.stop, clientOptions = _b.clientOptions;
var _this = _super.call(this, { read: function () { }, objectMode: true }) || this;
_this[_a] = "Generation";
_this.stop = stop || (function () { });
_this.clientOptions = clientOptions;
return _this;
}
Generation.prototype.pipeInto = function (stream) {
var _this = this;
this.on("infos", function (data) {
stream.emit("infos", data);
});
this.on("data", function (d) {
stream.push(d);
});
this.on("error", function (data) {
stream.emit("error", data);
});
this.on("end", function () {
stream.push(null);
});
stream.stop = function () { return _this.stopWrap(); };
return this;
};
Generation.prototype.stopWrap = function () {
this.stop();
};
Generation.prototype.then = function (onfulfilled, onrejected) {
return __awaiter(this, void 0, void 0, function () {
var data;
var _this = this;
return __generator(this, function (_b) {
data = "";
return [2 /*return*/, new Promise(function (resolve, reject) {
_this.on("error", reject);
_this.on("end", function () {
resolve(data);
});
_this.on("data", function (d) {
data += d;
});
}).then(onfulfilled, onrejected)];
});
});
};
Generation.prototype.catch = function (onrejected) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_b) {
return [2 /*return*/, this.then(undefined, onrejected)];
});
});
};
Generation.prototype.finally = function (onfinally) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_b) {
return [2 /*return*/, this.then(function (data) {
onfinally === null || onfinally === void 0 ? void 0 : onfinally();
return data;
}, function (data) {
onfinally === null || onfinally === void 0 ? void 0 : onfinally();
throw data;
})];
});
});
};
Generation.prototype.infos = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_b) {
return [2 /*return*/, new Promise(function (resolve, reject) {
_this.on("error", reject);
_this.on("infos", function (data) {
resolve(data);
});
})];
});
});
};
Generation.prototype.generate = function (task, options) {
var _this = this;
if (options === void 0) { options = {}; }
var resultStream = new Generation({ clientOptions: this.clientOptions });
(function () { return __awaiter(_this, void 0, void 0, function () {
var _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
// eslint-disable-next-line @typescript-eslint/no-use-before-define
_b = generate;
_c = "".concat;
return [4 /*yield*/, this];
case 1:
// eslint-disable-next-line @typescript-eslint/no-use-before-define
_b.apply(void 0, [_c.apply("", [_d.sent(), " "]).concat(task), options]).pipeInto(resultStream);
return [2 /*return*/];
}
});
}); })();
return resultStream;
};
return Generation;
}(readable_stream_1.Readable));
exports.Generation = Generation;
_a = Symbol.toStringTag;
function stream(task, options, clientOptions, onMessage) {
var _this = this;
if (options === void 0) { options = {}; }
if (clientOptions === void 0) { clientOptions = {}; }
var stopped = false;
var resultStream = new Generation({
stop: function () {
stopped = true;
resultStream.push(null);
},
clientOptions: clientOptions,
});
(function () { return __awaiter(_this, void 0, void 0, function () {
var genOptions, dataMemory, memoryIdAssignment, requestBody, _b, token, endpoint, ws;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
genOptions = options;
if (!genOptions.data) return [3 /*break*/, 2];
return [4 /*yield*/, (0, dataloader_1.loaderToMemory)(genOptions.data, clientOptions).then(function (memory) { return memory.memoryId; })];
case 1:
dataMemory = _c.sent();
_c.label = 2;
case 2: return [4 /*yield*/, getMemoryIds(dataMemory, genOptions.memoryId, genOptions.memory)];
case 3:
memoryIdAssignment = _c.sent();
requestBody = {
task: task,
provider: genOptions.provider || "",
model: genOptions.model,
memory_id: memoryIdAssignment,
stop: genOptions.stop || [],
infos: true,
system_prompt_id: genOptions.systemPromptId,
temperature: genOptions.temperature,
chat_id: genOptions.chatId,
web: genOptions.web,
language: genOptions.language,
};
return [4 /*yield*/, (0, clientOpts_1.defaultOptions)(clientOptions)];
case 4:
_b = _c.sent(), token = _b.token, endpoint = _b.endpoint;
if (stopped) {
return [2 /*return*/];
}
ws = new isomorphic_ws_1.default("".concat(endpoint.replace("http", "ws"), "/stream?token=").concat(token));
ws.onopen = function () { return ws.send(JSON.stringify(requestBody)); };
ws.onmessage = function (data) { return onMessage(data, resultStream); };
resultStream.stop = function () {
ws.send("STOP");
};
return [2 /*return*/];
}
});
}); })();
return resultStream;
}
var GenerateDataType = t.type({
data: t.string,
});
function generate(task, options, clientOptions) {
return stream(task, options, clientOptions, function (data, resultStream) {
if (!GenerateDataType.is(data)) {
resultStream.emit("error", "Invalid data");
return;
}
if (data.data === "") {
resultStream.push(null);
}
else if (data.data.startsWith("[INFOS]:")) {
try {
var potentialRessources = JSON.parse(data.data.replace("[INFOS]:", ""));
resultStream.emit("infos", potentialRessources);
}
catch (e) {
resultStream.push("");
}
}
else if (data.data.startsWith("[ERROR]:")) {
try {
var potentialRessources = JSON.parse(data.data.replace("[ERROR]:", ""));
resultStream.emit("error", potentialRessources);
}
catch (e) {
resultStream.push("");
}
}
else {
resultStream.push(data.data);
}
});
}
exports.generate = generate;
function client(clientOptions) {
if (clientOptions === void 0) { clientOptions = {}; }
return {
generate: function (task, options) {
if (options === void 0) { options = {}; }
return generate(task, options, clientOptions);
},
};
}
exports.default = client;
;