UNPKG

aisapi

Version:

A JavaScript/TypeScript API library for multiple AI providers

187 lines 7.19 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MoonshotProvider = exports.MOONSHOT_PRICES = void 0; const base_1 = require("./base"); /** * Moonshot AI API价格(美元/百万tokens) * 随时间可能变化,请参考官方文档获取最新价格 */ exports.MOONSHOT_PRICES = { input: 1.50, // 输入价格 output: 2.00 // 输出价格 }; /** * Moonshot AI (Kimi) 提供商实现 */ class MoonshotProvider extends base_1.BaseProvider { /** * 创建Moonshot AI提供商实例 */ constructor(options = {}) { super(options); this.name = 'Moonshot'; this.model = options.model || 'moonshot-v1-8k'; } /** * @inheritdoc */ getDefaultBaseUrl() { return 'https://api.moonshot.cn/v1'; } /** * 获取请求头 */ getHeaders() { const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}` }; return headers; } /** * @inheritdoc */ generateText(params) { return __awaiter(this, void 0, void 0, function* () { const model = params.model || this.model; // 准备请求体 const messages = [ { role: 'user', content: params.prompt } ]; // 如果有系统消息,添加到消息列表开头 if (params.systemMessage) { messages.unshift({ role: 'system', content: params.systemMessage }); } // 使用聊天完成API return this.chatCompletion({ model, messages, maxTokens: params.maxTokens, temperature: params.temperature, topP: params.topP, stream: params.stream }); }); } /** * 聊天完成API */ chatCompletion(params) { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c, _d; const requestBody = { model: params.model || this.model, messages: params.messages, max_tokens: params.maxTokens, temperature: (_a = params.temperature) !== null && _a !== void 0 ? _a : 0.7, top_p: params.topP, stream: params.stream || false }; // 移除undefined字段 Object.keys(requestBody).forEach(key => { if (requestBody[key] === undefined) { delete requestBody[key]; } }); const response = yield this.sendRequest(`${this.baseUrl}/chat/completions`, 'POST', requestBody); return { text: response.choices[0].message.content || '', usage: { promptTokens: ((_b = response.usage) === null || _b === void 0 ? void 0 : _b.prompt_tokens) || 0, completionTokens: ((_c = response.usage) === null || _c === void 0 ? void 0 : _c.completion_tokens) || 0, totalTokens: ((_d = response.usage) === null || _d === void 0 ? void 0 : _d.total_tokens) || 0 }, rawResponse: response }; }); } /** * 流式聊天完成 */ createStreamingChatCompletion(params) { return __awaiter(this, void 0, void 0, function* () { var _a; const requestBody = { model: params.model || this.model, messages: params.messages, max_tokens: params.maxTokens, temperature: (_a = params.temperature) !== null && _a !== void 0 ? _a : 0.7, top_p: params.topP, stream: true }; // 移除undefined字段 Object.keys(requestBody).forEach(key => { if (requestBody[key] === undefined) { delete requestBody[key]; } }); const headers = this.getHeaders(); const url = `${this.baseUrl}/chat/completions`; try { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), this.timeout); const response = yield fetch(url, { method: 'POST', headers, body: JSON.stringify(requestBody), signal: controller.signal }); clearTimeout(timeoutId); if (!response.ok) { throw new Error(`API请求失败: ${response.status} ${response.statusText}`); } return response.body; } catch (error) { if (error instanceof Error) { throw new Error(`[${this.name}] ${error.message}`); } throw error; } }); } /** * 生成JSON格式输出 */ generateJSON(params) { return __awaiter(this, void 0, void 0, function* () { const model = params.model || this.model; // 构建系统消息,指示返回JSON格式 const systemMessage = params.systemMessage ? `${params.systemMessage}\n请以有效的JSON格式返回回复。` : '请以有效的JSON格式返回回复。'; const messages = [ { role: 'system', content: systemMessage }, { role: 'user', content: params.prompt } ]; const response = yield this.chatCompletion({ model, messages, maxTokens: params.maxTokens, temperature: params.temperature || 0.1, // 降低温度以获得更确定的响应 topP: params.topP, stream: false }); try { // 尝试解析响应文本为JSON return JSON.parse(response.text); } catch (error) { // 如果解析失败,返回原始文本 console.warn(`[${this.name}] 无法解析响应为JSON: ${error instanceof Error ? error.message : '未知错误'}`); return { text: response.text, error: '解析JSON失败' }; } }); } } exports.MoonshotProvider = MoonshotProvider; //# sourceMappingURL=moonshot.js.map