UNPKG

doomiaichat

Version:

Doomisoft OpenAI

163 lines (162 loc) 8.89 kB
"use strict"; 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 __asyncValues = (this && this.__asyncValues) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); /** * 接入AI平台的中间层 */ const axios_1 = __importDefault(require("axios")); const declare_1 = require("./declare"); const gptbase_1 = __importDefault(require("./gptbase")); const stream_1 = require("stream"); // import { ChatReponse } from './declare'; class AIMiddlePlatform extends gptbase_1.default { /** * * @param apikey 调用AI中台 的key * @param agent 智能体信息 */ constructor(apikey, agent) { super(); this.apikey = apikey; this.agent = agent; } /** * 非流式传输聊天请求 * @param chatText * @param callChatOption * @param axiosOption */ chatRequest(chatText, callChatOption, axiosOption = {}) { var _a; return __awaiter(this, void 0, void 0, function* () { if (!chatText) { // this.emit('chaterror', { successed: false, error: 'no text in chat' }); return { successed: false, error: 'no text in chat' }; } const question = typeof chatText === 'object' ? (_a = chatText.text) !== null && _a !== void 0 ? _a : chatText.content : chatText; axiosOption = Object.assign({}, axiosOption || { timeout: 60000 }); const opts = Object.assign({ headers: { 'Content-Type': 'application/json', 'authorization': `Bearer ${this.apikey}` }, method: 'post', url: `${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`, data: { question, session_id: callChatOption.session_id, optional: callChatOption.optional, stream: false } }, axiosOption); const response = yield (0, declare_1.request)(opts); if (!response.successed || response.data.code) return { successed: false, error: 'failed' }; const { answer: message, session_id } = response.data.data; // this.emit('chatdone', { successed: true, segment: message, text: message, finish_reason: 'stop', index: 0, session_id }) return { successed: true, message: [{ message: { content: message } }], session_id }; }); } /** * 流式传输聊天请求 * @param chatText * @param callChatOption * @param attach * @param axiosOption * @returns */ chatRequestInStream(chatText, callChatOption, attach, axiosOption) { var _a, e_1, _b, _c; var _d; return __awaiter(this, void 0, void 0, function* () { if (!chatText) this.emit('chaterror', { successed: false, error: 'no text in chat' }); // console.log('Question===>', chatText) const question = typeof chatText === 'object' ? (_d = chatText.text) !== null && _d !== void 0 ? _d : chatText.content : chatText; axiosOption = Object.assign({}, axiosOption || { timeout: 60000 }); let requestid = Math.ceil(Math.random() * (new Date().getTime() * Math.random()) / 1000); try { const opts = Object.assign({ headers: { 'Content-Type': 'application/json', 'authorization': `Bearer ${this.apikey}` }, method: 'post', url: `${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`, data: { question, session_id: callChatOption.session_id, stream: true, optional: callChatOption.optional, }, responseType: 'stream' }, axiosOption); const response = yield (0, axios_1.default)(opts); const readableStream = stream_1.Readable.from(response.data); let index = 0, session_id, fullanswer = '', errorKeeped = [], chunks = []; try { for (var _e = true, readableStream_1 = __asyncValues(readableStream), readableStream_1_1; readableStream_1_1 = yield readableStream_1.next(), _a = readableStream_1_1.done, !_a;) { _c = readableStream_1_1.value; _e = false; try { const chunk = _c; ///可能接收到的数据不完整,导致JSON.parse失败 let answerData = null, jsonStr = ''; try { jsonStr = chunk.toString().split('data:'); if (jsonStr.length) jsonStr = jsonStr[jsonStr.length - 1] + ''; answerData = JSON.parse(errorKeeped.join('') + jsonStr); } catch (e) { ////如果发生了JSON解析错误,则当前的数据不完整,留着拼凑下一回数据 // console.log('json parse error===>', errorKeeped.join('') + jsonStr) errorKeeped.push(jsonStr); // console.log('After Push===>', errorKeeped.join('') ) continue; } errorKeeped = []; const { answer, running_status, reference } = answerData.data; if (running_status === true) continue; const segment = answer ? answer.replace(fullanswer, '') : ''; fullanswer = answer !== null && answer !== void 0 ? answer : fullanswer; if (!session_id) session_id = answerData.data.session_id; if (reference && reference.chunks && reference.chunks.length) chunks = chunks.concat(reference.chunks); const finished = answerData.data === true; let output = { successed: true, requestid, segment: segment, chunks, text: fullanswer, finish_reason: finished ? 'stop' : null, index: index++, session_id }; if (attach) output = Object.assign({}, output, attach); this.emit(finished ? 'chatdone' : 'chattext', output); } finally { _e = true; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_e && !_a && (_b = readableStream_1.return)) yield _b.call(readableStream_1); } finally { if (e_1) throw e_1.error; } } return { successed: true, requestid }; } catch (error) { // this.emit('requesterror', { successed: false, requestid, error: 'call axios faied ' + error }); // return { successed: false, requestid } } }); } } exports.default = AIMiddlePlatform;