UNPKG

doomiaichat

Version:

Doomisoft OpenAI

150 lines (149 loc) 8.45 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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); /** * 火山方舟-豆包大模型引擎 */ const declare_1 = require("./declare"); const gptbase_1 = __importDefault(require("./gptbase")); class DouBaoAI extends gptbase_1.default { /** * 构造函数 */ constructor(apiKey, apiOption = {}) { super(); this.apiOption = {}; this.apiKey = apiKey; this.apiOption = apiOption; } /** * 请求接口 */ chatRequest(chatText, callChatOption, axiosOption = {}) { return __awaiter(this, void 0, void 0, function* () { if (!chatText) return { successed: false, error: { errcode: 2, errmsg: '缺失聊天的内容' } }; const callParams = this.assembleApiParams(chatText, false, callChatOption, axiosOption); try { const response = yield (0, declare_1.request)(callParams); if (response.successed && !response.data.code) return { successed: true, message: response.data.choices, usage: response.data.usage }; return Object.assign({ successed: false }, response.data); } catch (error) { console.log('result is error ', error); return { successed: false, error }; } }); } /** * 组装最后的调用参数 * @param callChatOption * @returns */ assembleApiParams(chatText, streamCall = false, callChatOption, axiosOption = {}) { let messages = typeof (chatText) == 'string' ? [{ role: 'user', content: chatText }] : chatText; let params = {}; if ((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.temperature) || this.apiOption.temperature) params.temperature = Number((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.temperature) || this.apiOption.temperature); params.max_tokens = Number((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.maxtoken) || this.apiOption.maxtoken); if ((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.top_p) || this.apiOption.top_p) params.top_p = Number((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.top_p) || this.apiOption.top_p); if ((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.presence_penalty) || this.apiOption.presence_penalty) params.presence_penalty = Number((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.presence_penalty) || this.apiOption.presence_penalty); if ((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.frequency_penalty) || this.apiOption.frequency_penalty) params.frequency_penalty = Number((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.frequency_penalty) || this.apiOption.frequency_penalty); if ((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.top_logprobs) || this.apiOption.top_logprobs) { params.logprobs = true; params.top_logprobs = Number((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.top_logprobs) || this.apiOption.top_logprobs); } params.tools = ((callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.enableToolCall) === 1 && (callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.tools)) ? callChatOption.tools : undefined; params.tool_choice = (callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.enableToolCall) === 1 ? 'auto' : undefined; const axiosParams = Object.assign(Object.assign({}, axiosOption), { method: "post", headers: { 'Content-Type': 'application/json', 'authorization': `Bearer ${this.apiKey}` }, data: Object.assign(Object.assign({ model: (callChatOption === null || callChatOption === void 0 ? void 0 : callChatOption.model) || this.apiOption.model }, params), { messages, stream: streamCall }), url: 'https://ark.cn-beijing.volces.com/api/v3/chat/completions' }); if (streamCall) axiosParams.responseType = 'stream'; return axiosParams; } /** * 流式的聊天模式 * @param chatText * @param _paramOption * @param axiosOption */ chatRequestInStream(chatText, callChatOption, attach, axiosOption) { return __awaiter(this, void 0, void 0, function* () { if (!chatText) this.emit('chaterror', { successed: false, error: 'no text in chat' }); axiosOption = Object.assign({}, axiosOption || { timeout: 10000 }); const callParams = this.assembleApiParams(chatText, true, callChatOption, axiosOption); let requestid = Math.ceil(Math.random() * (new Date().getTime() * Math.random()) / 1000), replytext = []; try { (0, declare_1.requestStream)(callParams, (chunk) => { let streamText = chunk.toString().replace('[DONE]', '').replace(/[\r\n]+/gm, ''); this.processChunkData(streamText.split(/data: /), requestid, replytext, attach); }); return { successed: true, requestid }; } catch (error) { this.emit('requesterror', { successed: false, requestid, error: 'call axios faied ' + error }); return { successed: false, requestid }; } }); } /** * 处理每次流式返回的对话片段 * @param chunks * @param requestid * @param replytext * @param attach */ processChunkData(chunks, requestid, replytext, attach) { let has_tool_calls = 0, currentIndex, previous_index = -1, tool_calls = []; // 使用数组来存储工具调用 for (const splitString of chunks) { if (!splitString) continue; const chunk = JSON.parse(splitString); const [choice] = chunk.choices, { finish_reason: finishreason, index, usage } = choice, { content, tool_calls: toolCalls } = choice.delta; if (toolCalls && toolCalls.length) { currentIndex = toolCalls[0].index; has_tool_calls = 1; if (currentIndex !== previous_index) { tool_calls.push({ id: toolCalls[0].id, type: 'function', function: { name: toolCalls[0].function.name, arguments: toolCalls[0].function.arguments } }); // 更新previousIndex以供下次比较 previous_index = currentIndex; } else { tool_calls[previous_index].function.arguments += toolCalls[0].function.arguments; } } else replytext.push(content); let output = { successed: true, requestid, segment: content, text: replytext.join(''), finish_reason: finishreason, index, usage, has_tool_calls: has_tool_calls, tool_calls: tool_calls }; if (attach) output = Object.assign({}, output, attach); this.emit(finishreason ? 'chatdone' : 'chattext', output); } } } exports.default = DouBaoAI;