UNPKG

genpower

Version:

Unified TypeScript library to generate, validate, and structure AI model outputs

67 lines (66 loc) 3.37 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.GoogleGeminiEngine = void 0; const consts_1 = require("../consts"); class GoogleGeminiEngine { constructor(apiKey, modelLabel = "Gemini 1.5 Flash") { this.apiKey = apiKey; this.apiCode = consts_1.GEMINI_MODELS[modelLabel]; } generate(prompt) { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c, _d, _e; try { const url = `https://generativelanguage.googleapis.com/v1beta/${this.apiCode}:generateContent?key=${this.apiKey}`; const body = { contents: [ { role: "user", parts: [{ text: prompt }], }, ], }; const response = yield fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!response.ok) { // Response code not in 200–299 range const errorText = yield response.text(); const errorMsg = `Gemini API error: ${response.status} ${response.statusText}${errorText}`; console.error(errorMsg); throw new Error(errorMsg); } const data = yield response.json(); const text = (_e = (_d = (_c = (_b = (_a = data === null || data === void 0 ? void 0 : data.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.text; if (!text) { const errorMsg = "No valid 'text' field in Gemini API response"; console.error(errorMsg); throw new Error(errorMsg); } return text; } catch (error) { if (error instanceof Error) { console.error(`Failed to call Gemini API: ${error.message}`); throw new Error(`Failed to call Gemini API: ${error.message}`); } else { console.error("Unknown error occurred while calling Gemini API"); throw new Error("Unknown error occurred while calling Gemini API"); } } }); } } exports.GoogleGeminiEngine = GoogleGeminiEngine;