File: /var/www/web.enelar.com.co/node_modules/firebase/firebase-vertexai-preview.js.map
{"version":3,"file":"firebase-vertexai-preview.js","sources":["../util/src/errors.ts","../component/src/component.ts","../../node_modules/tslib/tslib.es6.js","../vertexai/src/service.ts","../vertexai/src/constants.ts","../vertexai/src/errors.ts","../vertexai/src/requests/request.ts","../vertexai/src/types/enums.ts","../vertexai/src/types/requests.ts","../vertexai/src/requests/response-helpers.ts","../vertexai/src/requests/stream-reader.ts","../vertexai/src/methods/generate-content.ts","../vertexai/src/requests/request-helpers.ts","../vertexai/src/methods/chat-session-helpers.ts","../vertexai/src/methods/chat-session.ts","../vertexai/src/models/generative-model.ts","../vertexai/src/methods/count-tokens.ts","../vertexai/src/api.ts","../util/src/compat.ts","../vertexai/src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // Typescript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record<string, unknown>\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n 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;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { VertexAI, VertexAIOptions } from './public-types';\nimport {\n AppCheckInternalComponentName,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { DEFAULT_LOCATION } from './constants';\n\nexport class VertexAIService implements VertexAI, _FirebaseService {\n auth: FirebaseAuthInternal | null;\n appCheck: FirebaseAppCheckInternal | null;\n location: string;\n\n constructor(\n public app: FirebaseApp,\n authProvider?: Provider<FirebaseAuthInternalName>,\n appCheckProvider?: Provider<AppCheckInternalComponentName>,\n public options?: VertexAIOptions\n ) {\n const appCheck = appCheckProvider?.getImmediate({ optional: true });\n const auth = authProvider?.getImmediate({ optional: true });\n this.auth = auth || null;\n this.appCheck = appCheck || null;\n this.location = this.options?.location || DEFAULT_LOCATION;\n }\n\n _delete(): Promise<void> {\n return Promise.resolve();\n }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { version } from '../package.json';\n\nexport const VERTEX_TYPE = 'vertexAI';\n\nexport const DEFAULT_LOCATION = 'us-central1';\n\nexport const DEFAULT_BASE_URL = 'https://firebaseml.googleapis.com';\n\nexport const DEFAULT_API_VERSION = 'v2beta';\n\nexport const PACKAGE_VERSION = version;\n\nexport const LANGUAGE_TAG = 'gl-js';\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { VertexAIErrorCode, CustomErrorData } from './types';\nimport { VERTEX_TYPE } from './constants';\n\n/**\n * Error class for the Vertex AI for Firebase SDK.\n *\n * @public\n */\nexport class VertexAIError extends FirebaseError {\n /**\n * Constructs a new instance of the `VertexAIError` class.\n *\n * @param code - The error code from {@link VertexAIErrorCode}.\n * @param message - A human-readable message describing the error.\n * @param customErrorData - Optional error data.\n */\n constructor(\n readonly code: VertexAIErrorCode,\n readonly message: string,\n readonly customErrorData?: CustomErrorData\n ) {\n // Match error format used by FirebaseError from ErrorFactory\n const service = VERTEX_TYPE;\n const serviceName = 'VertexAI';\n const fullCode = `${service}/${code}`;\n const fullMessage = `${serviceName}: ${message} (${fullCode}).`;\n super(fullCode, fullMessage);\n\n // FirebaseError initializes a stack trace, but it assumes the error is created from the error\n // factory. Since we break this assumption, we set the stack trace to be originating from this\n // constructor.\n // This is only supported in V8.\n if (Error.captureStackTrace) {\n // Allows us to initialize the stack trace without including the constructor itself at the\n // top level of the stack trace.\n Error.captureStackTrace(this, VertexAIError);\n }\n\n // Allows instanceof VertexAIError in ES5/ES6\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, VertexAIError.prototype);\n\n // Since Error is an interface, we don't inherit toString and so we define it ourselves.\n this.toString = () => fullMessage;\n }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RequestOptions, VertexAIErrorCode } from '../types';\nimport { VertexAIError } from '../errors';\nimport { ApiSettings } from '../types/internal';\nimport {\n DEFAULT_API_VERSION,\n DEFAULT_BASE_URL,\n LANGUAGE_TAG,\n PACKAGE_VERSION\n} from '../constants';\n\nexport enum Task {\n GENERATE_CONTENT = 'generateContent',\n STREAM_GENERATE_CONTENT = 'streamGenerateContent',\n COUNT_TOKENS = 'countTokens'\n}\n\nexport class RequestUrl {\n constructor(\n public model: string,\n public task: Task,\n public apiSettings: ApiSettings,\n public stream: boolean,\n public requestOptions?: RequestOptions\n ) {}\n toString(): string {\n // TODO: allow user-set option if that feature becomes available\n const apiVersion = DEFAULT_API_VERSION;\n const baseUrl = this.requestOptions?.baseUrl || DEFAULT_BASE_URL;\n let url = `${baseUrl}/${apiVersion}`;\n url += `/projects/${this.apiSettings.project}`;\n url += `/locations/${this.apiSettings.location}`;\n url += `/${this.model}`;\n url += `:${this.task}`;\n if (this.stream) {\n url += '?alt=sse';\n }\n return url;\n }\n\n /**\n * If the model needs to be passed to the backend, it needs to\n * include project and location path.\n */\n get fullModelString(): string {\n let modelString = `projects/${this.apiSettings.project}`;\n modelString += `/locations/${this.apiSettings.location}`;\n modelString += `/${this.model}`;\n return modelString;\n }\n}\n\n/**\n * Log language and \"fire/version\" to x-goog-api-client\n */\nfunction getClientHeaders(): string {\n const loggingTags = [];\n loggingTags.push(`${LANGUAGE_TAG}/${PACKAGE_VERSION}`);\n loggingTags.push(`fire/${PACKAGE_VERSION}`);\n return loggingTags.join(' ');\n}\n\nexport async function getHeaders(url: RequestUrl): Promise<Headers> {\n const headers = new Headers();\n headers.append('Content-Type', 'application/json');\n headers.append('x-goog-api-client', getClientHeaders());\n headers.append('x-goog-api-key', url.apiSettings.apiKey);\n if (url.apiSettings.getAppCheckToken) {\n const appCheckToken = await url.apiSettings.getAppCheckToken();\n if (appCheckToken && !appCheckToken.error) {\n headers.append('X-Firebase-AppCheck', appCheckToken.token);\n }\n }\n\n if (url.apiSettings.getAuthToken) {\n const authToken = await url.apiSettings.getAuthToken();\n if (authToken) {\n headers.append('Authorization', `Firebase ${authToken.accessToken}`);\n }\n }\n\n return headers;\n}\n\nexport async function constructRequest(\n model: string,\n task: Task,\n apiSettings: ApiSettings,\n stream: boolean,\n body: string,\n requestOptions?: RequestOptions\n): Promise<{ url: string; fetchOptions: RequestInit }> {\n const url = new RequestUrl(model, task, apiSettings, stream, requestOptions);\n return {\n url: url.toString(),\n fetchOptions: {\n ...buildFetchOptions(requestOptions),\n method: 'POST',\n headers: await getHeaders(url),\n body\n }\n };\n}\n\nexport async function makeRequest(\n model: string,\n task: Task,\n apiSettings: ApiSettings,\n stream: boolean,\n body: string,\n requestOptions?: RequestOptions\n): Promise<Response> {\n const url = new RequestUrl(model, task, apiSettings, stream, requestOptions);\n let response;\n try {\n const request = await constructRequest(\n model,\n task,\n apiSettings,\n stream,\n body,\n requestOptions\n );\n response = await fetch(request.url, request.fetchOptions);\n if (!response.ok) {\n let message = '';\n let errorDetails;\n try {\n const json = await response.json();\n message = json.error.message;\n if (json.error.details) {\n message += ` ${JSON.stringify(json.error.details)}`;\n errorDetails = json.error.details;\n }\n } catch (e) {\n // ignored\n }\n throw new VertexAIError(\n VertexAIErrorCode.FETCH_ERROR,\n `Error fetching from ${url}: [${response.status} ${response.statusText}] ${message}`,\n {\n status: response.status,\n statusText: response.statusText,\n errorDetails\n }\n );\n }\n } catch (e) {\n let err = e as Error;\n if (\n (e as VertexAIError).code !== VertexAIErrorCode.FETCH_ERROR &&\n e instanceof Error\n ) {\n err = new VertexAIError(\n VertexAIErrorCode.ERROR,\n `Error fetching from ${url.toString()}: ${e.message}`\n );\n err.stack = e.stack;\n }\n\n throw err;\n }\n return response;\n}\n\n/**\n * Generates the request options to be passed to the fetch API.\n * @param requestOptions - The user-defined request options.\n * @returns The generated request options.\n */\nfunction buildFetchOptions(requestOptions?: RequestOptions): RequestInit {\n const fetchOptions = {} as RequestInit;\n if (requestOptions?.timeout && requestOptions?.timeout >= 0) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n setTimeout(() => abortController.abort(), requestOptions.timeout);\n fetchOptions.signal = signal;\n }\n return fetchOptions;\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Role is the producer of the content.\n * @public\n */\nexport type Role = (typeof POSSIBLE_ROLES)[number];\n\n/**\n * Possible roles.\n * @public\n */\nexport const POSSIBLE_ROLES = ['user', 'model', 'function', 'system'] as const;\n\n/**\n * Harm categories that would cause prompts or candidates to be blocked.\n * @public\n */\nexport enum HarmCategory {\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT'\n}\n\n/**\n * Threshold above which a prompt or candidate will be blocked.\n * @public\n */\nexport enum HarmBlockThreshold {\n // Threshold is unspecified.\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n // Content with NEGLIGIBLE will be allowed.\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n // Content with NEGLIGIBLE and LOW will be allowed.\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n // Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed.\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n // All content will be allowed.\n BLOCK_NONE = 'BLOCK_NONE'\n}\n\n/**\n * @public\n */\nexport enum HarmBlockMethod {\n // The harm block method is unspecified.\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n // The harm block method uses both probability and severity scores.\n SEVERITY = 'SEVERITY',\n // The harm block method uses the probability score.\n PROBABILITY = 'PROBABILITY'\n}\n\n/**\n * Probability that a prompt or candidate matches a harm category.\n * @public\n */\nexport enum HarmProbability {\n // Probability is unspecified.\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n // Content has a negligible chance of being unsafe.\n NEGLIGIBLE = 'NEGLIGIBLE',\n // Content has a low chance of being unsafe.\n LOW = 'LOW',\n // Content has a medium chance of being unsafe.\n MEDIUM = 'MEDIUM',\n // Content has a high chance of being unsafe.\n HIGH = 'HIGH'\n}\n\n/**\n * Harm severity levels.\n * @public\n */\nexport enum HarmSeverity {\n // Harm severity unspecified.\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n // Negligible level of harm severity.\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n // Low level of harm severity.\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n // Medium level of harm severity.\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n // High level of harm severity.\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH'\n}\n\n/**\n * Reason that a prompt was blocked.\n * @public\n */\nexport enum BlockReason {\n // A blocked reason was not specified.\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n // Content was blocked by safety settings.\n SAFETY = 'SAFETY',\n // Content was blocked, but the reason is uncategorized.\n OTHER = 'OTHER'\n}\n\n/**\n * Reason that a candidate finished.\n * @public\n */\nexport enum FinishReason {\n // Default value. This value is unused.\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n // Natural stop point of the model or provided stop sequence.\n STOP = 'STOP',\n // The maximum number of tokens as specified in the request was reached.\n MAX_TOKENS = 'MAX_TOKENS',\n // The candidate content was flagged for safety reasons.\n SAFETY = 'SAFETY',\n // The candidate content was flagged for recitation reasons.\n RECITATION = 'RECITATION',\n // Unknown reason.\n OTHER = 'OTHER'\n}\n\n/**\n * @public\n */\nexport enum FunctionCallingMode {\n // Unspecified function calling mode. This value should not be used.\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n // Default model behavior, model decides to predict either a function call\n // or a natural language repspose.\n AUTO = 'AUTO',\n // Model is constrained to always predicting a function call only.\n // If \"allowed_function_names\" is set, the predicted function call will be\n // limited to any one of \"allowed_function_names\", else the predicted\n // function call will be any one of the provided \"function_declarations\".\n ANY = 'ANY',\n // Model will not predict any function call. Model behavior is same as when\n // not passing any function declarations.\n NONE = 'NONE'\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Content, Part } from './content';\nimport {\n FunctionCallingMode,\n HarmBlockMethod,\n HarmBlockThreshold,\n HarmCategory\n} from './enums';\n\n/**\n * Base parameters for a number of methods.\n * @public\n */\nexport interface BaseParams {\n safetySettings?: SafetySetting[];\n generationConfig?: GenerationConfig;\n}\n\n/**\n * Params passed to {@link getGenerativeModel}.\n * @public\n */\nexport interface ModelParams extends BaseParams {\n model: string;\n tools?: Tool[];\n toolConfig?: ToolConfig;\n systemInstruction?: string | Part | Content;\n}\n\n/**\n * Request sent through {@link GenerativeModel.generateContent}\n * @public\n */\nexport interface GenerateContentRequest extends BaseParams {\n contents: Content[];\n tools?: Tool[];\n toolConfig?: ToolConfig;\n systemInstruction?: string | Part | Content;\n}\n\n/**\n * Safety setting that can be sent as part of request parameters.\n * @public\n */\nexport interface SafetySetting {\n category: HarmCategory;\n threshold: HarmBlockThreshold;\n method: HarmBlockMethod;\n}\n\n/**\n * Config options for content-related requests\n * @public\n */\nexport interface GenerationConfig {\n candidateCount?: number;\n stopSequences?: string[];\n maxOutputTokens?: number;\n temperature?: number;\n topP?: number;\n topK?: number;\n presencePenalty?: number;\n frequencyPenalty?: number;\n /**\n * Output response mimetype of the generated candidate text.\n * Supported mimetypes are `text/plain` (default, text output) and `application/json`\n * (JSON response in the candidates).\n * The model needs to be prompted to output the appropriate response type,\n * otherwise the behavior is undefined.\n * This is a preview feature.\n */\n responseMimeType?: string;\n}\n\n/**\n * Params for {@link GenerativeModel.startChat}.\n * @public\n */\nexport interface StartChatParams extends BaseParams {\n history?: Content[];\n tools?: Tool[];\n toolConfig?: ToolConfig;\n systemInstruction?: string | Part | Content;\n}\n\n/**\n * Params for calling {@link GenerativeModel.countTokens}\n * @public\n */\nexport interface CountTokensRequest {\n contents: Content[];\n}\n\n/**\n * Params passed to {@link getGenerativeModel}.\n * @public\n */\nexport interface RequestOptions {\n /**\n * Request timeout in milliseconds.\n */\n timeout?: number;\n /**\n * Base url for endpoint. Defaults to https://firebaseml.googleapis.com\n */\n baseUrl?: string;\n}\n\n/**\n * Defines a tool that model can call to access external knowledge.\n * @public\n */\nexport declare type Tool = FunctionDeclarationsTool;\n\n/**\n * Structured representation of a function declaration as defined by the\n * {@link https://spec.openapis.org/oas/v3.0.3 | OpenAPI 3.0 specification}.\n * Included\n * in this declaration are the function name and parameters. This\n * `FunctionDeclaration` is a representation of a block of code that can be used\n * as a Tool by the model and executed by the client.\n * @public\n */\nexport declare interface FunctionDeclaration {\n /**\n * The name of the function to call. Must start with a letter or an\n * underscore. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with\n * a max length of 64.\n */\n name: string;\n /**\n * Optional. Description and purpose of the function. Model uses it to decide\n * how and whether to call the function.\n */\n description?: string;\n /**\n * Optional. Describes the parameters to this function in JSON Schema Object\n * format. Reflects the Open API 3.03 Parameter Object. Parameter names are\n * case sensitive. For a function with no parameters, this can be left unset.\n */\n parameters?: FunctionDeclarationSchema;\n}\n\n/**\n * A `FunctionDeclarationsTool` is a piece of code that enables the system to\n * interact with external systems to perform an action, or set of actions,\n * outside of knowledge and scope of the model.\n * @public\n */\nexport declare interface FunctionDeclarationsTool {\n /**\n * Optional. One or more function declarations\n * to be passed to the model along with the current user query. Model may\n * decide to call a subset of these functions by populating\n * {@link FunctionCall} in the response. User should\n * provide a {@link FunctionResponse} for each\n * function call in the next turn. Based on the function responses, the model will\n * generate the final response back to the user. Maximum 64 function\n * declarations can be provided.\n */\n functionDeclarations?: FunctionDeclaration[];\n}\n\n/**\n * Contains the list of OpenAPI data types\n * as defined by https://swagger.io/docs/specification/data-models/data-types/\n * @public\n */\nexport enum FunctionDeclarationSchemaType {\n /** String type. */\n STRING = 'STRING',\n /** Number type. */\n NUMBER = 'NUMBER',\n /** Integer type. */\n INTEGER = 'INTEGER',\n /** Boolean type. */\n BOOLEAN = 'BOOLEAN',\n /** Array type. */\n ARRAY = 'ARRAY',\n /** Object type. */\n OBJECT = 'OBJECT'\n}\n\n/**\n * Schema for parameters passed to {@link FunctionDeclaration.parameters}.\n * @public\n */\nexport interface FunctionDeclarationSchema {\n /** The type of the parameter. */\n type: FunctionDeclarationSchemaType;\n /** The format of the parameter. */\n properties: { [k: string]: FunctionDeclarationSchemaProperty };\n /** Optional. Description of the parameter. */\n description?: string;\n /** Optional. Array of required parameters. */\n required?: string[];\n}\n\n/**\n * Schema is used to define the format of input/output data.\n * Represents a select subset of an OpenAPI 3.0 schema object.\n * More fields may be added in the future as needed.\n * @public\n */\nexport interface FunctionDeclarationSchemaProperty {\n /**\n * Optional. The type of the property. {@link\n * FunctionDeclarationSchemaType}.\n */\n type?: FunctionDeclarationSchemaType;\n /** Optional. The format of the property. */\n format?: string;\n /** Optional. The description of the property. */\n description?: string;\n /** Optional. Whether the property is nullable. */\n nullable?: boolean;\n /** Optional. The items of the property. {@link FunctionDeclarationSchema} */\n items?: FunctionDeclarationSchema;\n /** Optional. The enum of the property. */\n enum?: string[];\n /** Optional. Map of {@link FunctionDeclarationSchema}. */\n properties?: { [k: string]: FunctionDeclarationSchema };\n /** Optional. Array of required property. */\n required?: string[];\n /** Optional. The example of the property. */\n example?: unknown;\n}\n\n/**\n * Tool config. This config is shared for all tools provided in the request.\n * @public\n */\nexport interface ToolConfig {\n functionCallingConfig: FunctionCallingConfig;\n}\n\n/**\n * @public\n */\nexport interface FunctionCallingConfig {\n mode?: FunctionCallingMode;\n allowedFunctionNames?: string[];\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n EnhancedGenerateContentResponse,\n FinishReason,\n FunctionCall,\n GenerateContentCandidate,\n GenerateContentResponse,\n VertexAIErrorCode\n} from '../types';\nimport { VertexAIError } from '../errors';\n\n/**\n * Adds convenience helper methods to a response object, including stream\n * chunks (as long as each chunk is a complete GenerateContentResponse JSON).\n */\nexport function addHelpers(\n response: GenerateContentResponse\n): EnhancedGenerateContentResponse {\n (response as EnhancedGenerateContentResponse).text = () => {\n if (response.candidates && response.candidates.length > 0) {\n if (response.candidates.length > 1) {\n console.warn(\n `This response had ${response.candidates.length} ` +\n `candidates. Returning text from the first candidate only. ` +\n `Access response.candidates directly to use the other candidates.`\n );\n }\n if (hadBadFinishReason(response.candidates[0])) {\n throw new VertexAIError(\n VertexAIErrorCode.RESPONSE_ERROR,\n `Response error: ${formatBlockErrorMessage(\n response\n )}. Response body stored in error.response`,\n {\n response\n }\n );\n }\n return getText(response);\n } else if (response.promptFeedback) {\n throw new VertexAIError(\n VertexAIErrorCode.RESPONSE_ERROR,\n `Text not available. ${formatBlockErrorMessage(response)}`,\n {\n response\n }\n );\n }\n return '';\n };\n (response as EnhancedGenerateContentResponse).functionCalls = () => {\n if (response.candidates && response.candidates.length > 0) {\n if (response.candidates.length > 1) {\n console.warn(\n `This response had ${response.candidates.length} ` +\n `candidates. Returning function calls from the first candidate only. ` +\n `Access response.candidates directly to use the other candidates.`\n );\n }\n if (hadBadFinishReason(response.candidates[0])) {\n throw new VertexAIError(\n VertexAIErrorCode.RESPONSE_ERROR,\n `Response error: ${formatBlockErrorMessage(\n response\n )}. Response body stored in error.response`,\n {\n response\n }\n );\n }\n return getFunctionCalls(response);\n } else if (response.promptFeedback) {\n throw new VertexAIError(\n VertexAIErrorCode.RESPONSE_ERROR,\n `Function call not available. ${formatBlockErrorMessage(response)}`,\n {\n response\n }\n );\n }\n return undefined;\n };\n return response as EnhancedGenerateContentResponse;\n}\n\n/**\n * Returns all text found in all parts of first candidate.\n */\nexport function getText(response: GenerateContentResponse): string {\n const textStrings = [];\n if (response.candidates?.[0].content?.parts) {\n for (const part of response.candidates?.[0].content?.parts) {\n if (part.text) {\n textStrings.push(part.text);\n }\n }\n }\n if (textStrings.length > 0) {\n return textStrings.join('');\n } else {\n return '';\n }\n}\n\n/**\n * Returns {@link FunctionCall}s associated with first candidate.\n */\nexport function getFunctionCalls(\n response: GenerateContentResponse\n): FunctionCall[] | undefined {\n const functionCalls: FunctionCall[] = [];\n if (response.candidates?.[0].content?.parts) {\n for (const part of response.candidates?.[0].content?.parts) {\n if (part.functionCall) {\n functionCalls.push(part.functionCall);\n }\n }\n }\n if (functionCalls.length > 0) {\n return functionCalls;\n } else {\n return undefined;\n }\n}\n\nconst badFinishReasons = [FinishReason.RECITATION, FinishReason.SAFETY];\n\nfunction hadBadFinishReason(candidate: GenerateContentCandidate): boolean {\n return (\n !!candidate.finishReason &&\n badFinishReasons.includes(candidate.finishReason)\n );\n}\n\nexport function formatBlockErrorMessage(\n response: GenerateContentResponse\n): string {\n let message = '';\n if (\n (!response.candidates || response.candidates.length === 0) &&\n response.promptFeedback\n ) {\n message += 'Response was blocked';\n if (response.promptFeedback?.blockReason) {\n message += ` due to ${response.promptFeedback.blockReason}`;\n }\n if (response.promptFeedback?.blockReasonMessage) {\n message += `: ${response.promptFeedback.blockReasonMessage}`;\n }\n } else if (response.candidates?.[0]) {\n const firstCandidate = response.candidates[0];\n if (hadBadFinishReason(firstCandidate)) {\n message += `Candidate was blocked due to ${firstCandidate.finishReason}`;\n if (firstCandidate.finishMessage) {\n message += `: ${firstCandidate.finishMessage}`;\n }\n }\n }\n return message;\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n EnhancedGenerateContentResponse,\n GenerateContentCandidate,\n GenerateContentResponse,\n GenerateContentStreamResult,\n Part,\n VertexAIErrorCode\n} from '../types';\nimport { VertexAIError } from '../errors';\nimport { addHelpers } from './response-helpers';\n\nconst responseLineRE = /^data\\: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Process a response.body stream from the backend and return an\n * iterator that provides one complete GenerateContentResponse at a time\n * and a promise that resolves with a single aggregated\n * GenerateContentResponse.\n *\n * @param response - Response from a fetch call\n */\nexport function processStream(response: Response): GenerateContentStreamResult {\n const inputStream = response.body!.pipeThrough(\n new TextDecoderStream('utf8', { fatal: true })\n );\n const responseStream =\n getResponseStream<GenerateContentResponse>(inputStream);\n const [stream1, stream2] = responseStream.tee();\n return {\n stream: generateResponseSequence(stream1),\n response: getResponsePromise(stream2)\n };\n}\n\nasync function getResponsePromise(\n stream: ReadableStream<GenerateContentResponse>\n): Promise<EnhancedGenerateContentResponse> {\n const allResponses: GenerateContentResponse[] = [];\n const reader = stream.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return addHelpers(aggregateResponses(allResponses));\n }\n allResponses.push(value);\n }\n}\n\nasync function* generateResponseSequence(\n stream: ReadableStream<GenerateContentResponse>\n): AsyncGenerator<EnhancedGenerateContentResponse> {\n const reader = stream.getReader();\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n yield addHelpers(value);\n }\n}\n\n/**\n * Reads a raw stream from the fetch response and join incomplete\n * chunks, returning a new stream that provides a single complete\n * GenerateContentResponse in each iteration.\n */\nexport function getResponseStream<T>(\n inputStream: ReadableStream<string>\n): ReadableStream<T> {\n const reader = inputStream.getReader();\n const stream = new ReadableStream<T>({\n start(controller) {\n let currentText = '';\n return pump();\n function pump(): Promise<(() => Promise<void>) | undefined> {\n return reader.read().then(({ value, done }) => {\n if (done) {\n if (currentText.trim()) {\n controller.error(\n new VertexAIError(\n VertexAIErrorCode.PARSE_FAILED,\n 'Failed to parse stream'\n )\n );\n return;\n }\n controller.close();\n return;\n }\n\n currentText += value;\n let match = currentText.match(responseLineRE);\n let parsedResponse: T;\n while (match) {\n try {\n parsedResponse = JSON.parse(match[1]);\n } catch (e) {\n controller.error(\n new VertexAIError(\n VertexAIErrorCode.PARSE_FAILED,\n `Error parsing JSON response: \"${match[1]}`\n )\n );\n return;\n }\n controller.enqueue(parsedResponse);\n currentText = currentText.substring(match[0].length);\n match = currentText.match(responseLineRE);\n }\n return pump();\n });\n }\n }\n });\n return stream;\n}\n\n/**\n * Aggregates an array of `GenerateContentResponse`s into a single\n * GenerateContentResponse.\n */\nexport function aggregateResponses(\n responses: GenerateContentResponse[]\n): GenerateContentResponse {\n const lastResponse = responses[responses.length - 1];\n const aggregatedResponse: GenerateContentResponse = {\n promptFeedback: lastResponse?.promptFeedback\n };\n for (const response of responses) {\n if (response.candidates) {\n for (const candidate of response.candidates) {\n const i = candidate.index;\n if (!aggregatedResponse.candidates) {\n aggregatedResponse.candidates = [];\n }\n if (!aggregatedResponse.candidates[i]) {\n aggregatedResponse.candidates[i] = {\n index: candidate.index\n } as GenerateContentCandidate;\n }\n // Keep overwriting, the last one will be final\n aggregatedResponse.candidates[i].citationMetadata =\n candidate.citationMetadata;\n aggregatedResponse.candidates[i].finishReason = candidate.finishReason;\n aggregatedResponse.candidates[i].finishMessage =\n candidate.finishMessage;\n aggregatedResponse.candidates[i].safetyRatings =\n candidate.safetyRatings;\n\n /**\n * Candidates should always have content and parts, but this handles\n * possible malformed responses.\n */\n if (candidate.content && candidate.content.parts) {\n if (!aggregatedResponse.candidates[i].content) {\n aggregatedResponse.candidates[i].content = {\n role: candidate.content.role || 'user',\n parts: []\n };\n }\n const newPart: Partial<Part> = {};\n for (const part of candidate.content.parts) {\n if (part.text) {\n newPart.text = part.text;\n }\n if (part.functionCall) {\n newPart.functionCall = part.functionCall;\n }\n if (Object.keys(newPart).length === 0) {\n newPart.text = '';\n }\n aggregatedResponse.candidates[i].content.parts.push(\n newPart as Part\n );\n }\n }\n }\n }\n }\n return aggregatedResponse;\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n GenerateContentRequest,\n GenerateContentResponse,\n GenerateContentResult,\n GenerateContentStreamResult,\n RequestOptions\n} from '../types';\nimport { Task, makeRequest } from '../requests/request';\nimport { addHelpers } from '../requests/response-helpers';\nimport { processStream } from '../requests/stream-reader';\nimport { ApiSettings } from '../types/internal';\n\nexport async function generateContentStream(\n apiSettings: ApiSettings,\n model: string,\n params: GenerateContentRequest,\n requestOptions?: RequestOptions\n): Promise<GenerateContentStreamResult> {\n const response = await makeRequest(\n model,\n Task.STREAM_GENERATE_CONTENT,\n apiSettings,\n /* stream */ true,\n JSON.stringify(params),\n requestOptions\n );\n return processStream(response);\n}\n\nexport async function generateContent(\n apiSettings: ApiSettings,\n model: string,\n params: GenerateContentRequest,\n requestOptions?: RequestOptions\n): Promise<GenerateContentResult> {\n const response = await makeRequest(\n model,\n Task.GENERATE_CONTENT,\n apiSettings,\n /* stream */ false,\n JSON.stringify(params),\n requestOptions\n );\n const responseJson: GenerateContentResponse = await response.json();\n const enhancedResponse = addHelpers(responseJson);\n return {\n response: enhancedResponse\n };\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Content,\n GenerateContentRequest,\n Part,\n VertexAIErrorCode\n} from '../types';\nimport { VertexAIError } from '../errors';\n\nexport function formatSystemInstruction(\n input?: string | Part | Content\n): Content | undefined {\n // null or undefined\n if (input == null) {\n return undefined;\n } else if (typeof input === 'string') {\n return { role: 'system', parts: [{ text: input }] } as Content;\n } else if ((input as Part).text) {\n return { role: 'system', parts: [input as Part] };\n } else if ((input as Content).parts) {\n if (!(input as Content).role) {\n return { role: 'system', parts: (input as Content).parts };\n } else {\n return input as Content;\n }\n }\n}\n\nexport function formatNewContent(\n request: string | Array<string | Part>\n): Content {\n let newParts: Part[] = [];\n if (typeof request === 'string') {\n newParts = [{ text: request }];\n } else {\n for (const partOrString of request) {\n if (typeof partOrString === 'string') {\n newParts.push({ text: partOrString });\n } else {\n newParts.push(partOrString);\n }\n }\n }\n return assignRoleToPartsAndValidateSendMessageRequest(newParts);\n}\n\n/**\n * When multiple Part types (i.e. FunctionResponsePart and TextPart) are\n * passed in a single Part array, we may need to assign different roles to each\n * part. Currently only FunctionResponsePart requires a role other than 'user'.\n * @private\n * @param parts Array of parts to pass to the model\n * @returns Array of content items\n */\nfunction assignRoleToPartsAndValidateSendMessageRequest(\n parts: Part[]\n): Content {\n const userContent: Content = { role: 'user', parts: [] };\n const functionContent: Content = { role: 'function', parts: [] };\n let hasUserContent = false;\n let hasFunctionContent = false;\n for (const part of parts) {\n if ('functionResponse' in part) {\n functionContent.parts.push(part);\n hasFunctionContent = true;\n } else {\n userContent.parts.push(part);\n hasUserContent = true;\n }\n }\n\n if (hasUserContent && hasFunctionContent) {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_CONTENT,\n 'Within a single message, FunctionResponse cannot be mixed with other type of Part in the request for sending chat message.'\n );\n }\n\n if (!hasUserContent && !hasFunctionContent) {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_CONTENT,\n 'No Content is provided for sending chat message.'\n );\n }\n\n if (hasUserContent) {\n return userContent;\n }\n\n return functionContent;\n}\n\nexport function formatGenerateContentInput(\n params: GenerateContentRequest | string | Array<string | Part>\n): GenerateContentRequest {\n let formattedRequest: GenerateContentRequest;\n if ((params as GenerateContentRequest).contents) {\n formattedRequest = params as GenerateContentRequest;\n } else {\n // Array or string\n const content = formatNewContent(params as string | Array<string | Part>);\n formattedRequest = { contents: [content] };\n }\n if ((params as GenerateContentRequest).systemInstruction) {\n formattedRequest.systemInstruction = formatSystemInstruction(\n (params as GenerateContentRequest).systemInstruction\n );\n }\n return formattedRequest;\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Content,\n POSSIBLE_ROLES,\n Part,\n Role,\n VertexAIErrorCode\n} from '../types';\nimport { VertexAIError } from '../errors';\n\n// https://ai.google.dev/api/rest/v1beta/Content#part\n\nconst VALID_PART_FIELDS: Array<keyof Part> = [\n 'text',\n 'inlineData',\n 'functionCall',\n 'functionResponse'\n];\n\nconst VALID_PARTS_PER_ROLE: { [key in Role]: Array<keyof Part> } = {\n user: ['text', 'inlineData'],\n function: ['functionResponse'],\n model: ['text', 'functionCall'],\n // System instructions shouldn't be in history anyway.\n system: ['text']\n};\n\nconst VALID_PREVIOUS_CONTENT_ROLES: { [key in Role]: Role[] } = {\n user: ['model'],\n function: ['model'],\n model: ['user', 'function'],\n // System instructions shouldn't be in history.\n system: []\n};\n\nexport function validateChatHistory(history: Content[]): void {\n let prevContent: Content | null = null;\n for (const currContent of history) {\n const { role, parts } = currContent;\n if (!prevContent && role !== 'user') {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_CONTENT,\n `First Content should be with role 'user', got ${role}`\n );\n }\n if (!POSSIBLE_ROLES.includes(role)) {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_CONTENT,\n `Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(\n POSSIBLE_ROLES\n )}`\n );\n }\n\n if (!Array.isArray(parts)) {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_CONTENT,\n `Content should have 'parts' but property with an array of Parts`\n );\n }\n\n if (parts.length === 0) {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_CONTENT,\n `Each Content should have at least one part`\n );\n }\n\n const countFields: Record<keyof Part, number> = {\n text: 0,\n inlineData: 0,\n functionCall: 0,\n functionResponse: 0\n };\n\n for (const part of parts) {\n for (const key of VALID_PART_FIELDS) {\n if (key in part) {\n countFields[key] += 1;\n }\n }\n }\n const validParts = VALID_PARTS_PER_ROLE[role];\n for (const key of VALID_PART_FIELDS) {\n if (!validParts.includes(key) && countFields[key] > 0) {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_CONTENT,\n `Content with role '${role}' can't contain '${key}' part`\n );\n }\n }\n\n if (prevContent) {\n const validPreviousContentRoles = VALID_PREVIOUS_CONTENT_ROLES[role];\n if (!validPreviousContentRoles.includes(prevContent.role)) {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_CONTENT,\n `Content with role '${role} can't follow '${\n prevContent.role\n }'. Valid previous roles: ${JSON.stringify(\n VALID_PREVIOUS_CONTENT_ROLES\n )}`\n );\n }\n }\n prevContent = currContent;\n }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Content,\n GenerateContentRequest,\n GenerateContentResult,\n GenerateContentStreamResult,\n Part,\n RequestOptions,\n StartChatParams\n} from '../types';\nimport { formatNewContent } from '../requests/request-helpers';\nimport { formatBlockErrorMessage } from '../requests/response-helpers';\nimport { validateChatHistory } from './chat-session-helpers';\nimport { generateContent, generateContentStream } from './generate-content';\nimport { ApiSettings } from '../types/internal';\n\n/**\n * Do not log a message for this error.\n */\nconst SILENT_ERROR = 'SILENT_ERROR';\n\n/**\n * ChatSession class that enables sending chat messages and stores\n * history of sent and received messages so far.\n *\n * @public\n */\nexport class ChatSession {\n private _apiSettings: ApiSettings;\n private _history: Content[] = [];\n private _sendPromise: Promise<void> = Promise.resolve();\n\n constructor(\n apiSettings: ApiSettings,\n public model: string,\n public params?: StartChatParams,\n public requestOptions?: RequestOptions\n ) {\n this._apiSettings = apiSettings;\n if (params?.history) {\n validateChatHistory(params.history);\n this._history = params.history;\n }\n }\n\n /**\n * Gets the chat history so far. Blocked prompts are not added to history.\n * Blocked candidates are not added to history, nor are the prompts that\n * generated them.\n */\n async getHistory(): Promise<Content[]> {\n await this._sendPromise;\n return this._history;\n }\n\n /**\n * Sends a chat message and receives a non-streaming\n * {@link GenerateContentResult}\n */\n async sendMessage(\n request: string | Array<string | Part>\n ): Promise<GenerateContentResult> {\n await this._sendPromise;\n const newContent = formatNewContent(request);\n const generateContentRequest: GenerateContentRequest = {\n safetySettings: this.params?.safetySettings,\n generationConfig: this.params?.generationConfig,\n tools: this.params?.tools,\n toolConfig: this.params?.toolConfig,\n systemInstruction: this.params?.systemInstruction,\n contents: [...this._history, newContent]\n };\n let finalResult = {} as GenerateContentResult;\n // Add onto the chain.\n this._sendPromise = this._sendPromise\n .then(() =>\n generateContent(\n this._apiSettings,\n this.model,\n generateContentRequest,\n this.requestOptions\n )\n )\n .then(result => {\n if (\n result.response.candidates &&\n result.response.candidates.length > 0\n ) {\n this._history.push(newContent);\n const responseContent: Content = {\n parts: result.response.candidates?.[0].content.parts || [],\n // Response seems to come back without a role set.\n role: result.response.candidates?.[0].content.role || 'model'\n };\n this._history.push(responseContent);\n } else {\n const blockErrorMessage = formatBlockErrorMessage(result.response);\n if (blockErrorMessage) {\n console.warn(\n `sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`\n );\n }\n }\n finalResult = result;\n });\n await this._sendPromise;\n return finalResult;\n }\n\n /**\n * Sends a chat message and receives the response as a\n * {@link GenerateContentStreamResult} containing an iterable stream\n * and a response promise.\n */\n async sendMessageStream(\n request: string | Array<string | Part>\n ): Promise<GenerateContentStreamResult> {\n await this._sendPromise;\n const newContent = formatNewContent(request);\n const generateContentRequest: GenerateContentRequest = {\n safetySettings: this.params?.safetySettings,\n generationConfig: this.params?.generationConfig,\n tools: this.params?.tools,\n toolConfig: this.params?.toolConfig,\n systemInstruction: this.params?.systemInstruction,\n contents: [...this._history, newContent]\n };\n const streamPromise = generateContentStream(\n this._apiSettings,\n this.model,\n generateContentRequest,\n this.requestOptions\n );\n\n // Add onto the chain.\n this._sendPromise = this._sendPromise\n .then(() => streamPromise)\n // This must be handled to avoid unhandled rejection, but jump\n // to the final catch block with a label to not log this error.\n .catch(_ignored => {\n throw new Error(SILENT_ERROR);\n })\n .then(streamResult => streamResult.response)\n .then(response => {\n if (response.candidates && response.candidates.length > 0) {\n this._history.push(newContent);\n const responseContent = { ...response.candidates[0].content };\n // Response seems to come back without a role set.\n if (!responseContent.role) {\n responseContent.role = 'model';\n }\n this._history.push(responseContent);\n } else {\n const blockErrorMessage = formatBlockErrorMessage(response);\n if (blockErrorMessage) {\n console.warn(\n `sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`\n );\n }\n }\n })\n .catch(e => {\n // Errors in streamPromise are already catchable by the user as\n // streamPromise is returned.\n // Avoid duplicating the error message in logs.\n if (e.message !== SILENT_ERROR) {\n // Users do not have access to _sendPromise to catch errors\n // downstream from streamPromise, so they should not throw.\n console.error(e);\n }\n });\n return streamPromise;\n }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n generateContent,\n generateContentStream\n} from '../methods/generate-content';\nimport {\n Content,\n CountTokensRequest,\n CountTokensResponse,\n GenerateContentRequest,\n GenerateContentResult,\n GenerateContentStreamResult,\n GenerationConfig,\n ModelParams,\n Part,\n RequestOptions,\n SafetySetting,\n StartChatParams,\n Tool,\n ToolConfig,\n VertexAIErrorCode\n} from '../types';\nimport { VertexAIError } from '../errors';\nimport { ChatSession } from '../methods/chat-session';\nimport { countTokens } from '../methods/count-tokens';\nimport {\n formatGenerateContentInput,\n formatSystemInstruction\n} from '../requests/request-helpers';\nimport { VertexAI } from '../public-types';\nimport { ApiSettings } from '../types/internal';\nimport { VertexAIService } from '../service';\n\n/**\n * Class for generative model APIs.\n * @public\n */\nexport class GenerativeModel {\n private _apiSettings: ApiSettings;\n model: string;\n generationConfig: GenerationConfig;\n safetySettings: SafetySetting[];\n requestOptions?: RequestOptions;\n tools?: Tool[];\n toolConfig?: ToolConfig;\n systemInstruction?: Content;\n\n constructor(\n vertexAI: VertexAI,\n modelParams: ModelParams,\n requestOptions?: RequestOptions\n ) {\n if (!vertexAI.app?.options?.apiKey) {\n throw new VertexAIError(\n VertexAIErrorCode.NO_API_KEY,\n `The \"apiKey\" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid API key.`\n );\n } else if (!vertexAI.app?.options?.projectId) {\n throw new VertexAIError(\n VertexAIErrorCode.NO_PROJECT_ID,\n `The \"projectId\" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid project ID.`\n );\n } else {\n this._apiSettings = {\n apiKey: vertexAI.app.options.apiKey,\n project: vertexAI.app.options.projectId,\n location: vertexAI.location\n };\n if ((vertexAI as VertexAIService).appCheck) {\n this._apiSettings.getAppCheckToken = () =>\n (vertexAI as VertexAIService).appCheck!.getToken();\n }\n\n if ((vertexAI as VertexAIService).auth) {\n this._apiSettings.getAuthToken = () =>\n (vertexAI as VertexAIService).auth!.getToken();\n }\n }\n if (modelParams.model.includes('/')) {\n if (modelParams.model.startsWith('models/')) {\n // Add \"publishers/google\" if the user is only passing in 'models/model-name'.\n this.model = `publishers/google/${modelParams.model}`;\n } else {\n // Any other custom format (e.g. tuned models) must be passed in correctly.\n this.model = modelParams.model;\n }\n } else {\n // If path is not included, assume it's a non-tuned model.\n this.model = `publishers/google/models/${modelParams.model}`;\n }\n this.generationConfig = modelParams.generationConfig || {};\n this.safetySettings = modelParams.safetySettings || [];\n this.tools = modelParams.tools;\n this.toolConfig = modelParams.toolConfig;\n this.systemInstruction = formatSystemInstruction(\n modelParams.systemInstruction\n );\n this.requestOptions = requestOptions || {};\n }\n\n /**\n * Makes a single non-streaming call to the model\n * and returns an object containing a single {@link GenerateContentResponse}.\n */\n async generateContent(\n request: GenerateContentRequest | string | Array<string | Part>\n ): Promise<GenerateContentResult> {\n const formattedParams = formatGenerateContentInput(request);\n return generateContent(\n this._apiSettings,\n this.model,\n {\n generationConfig: this.generationConfig,\n safetySettings: this.safetySettings,\n tools: this.tools,\n toolConfig: this.toolConfig,\n systemInstruction: this.systemInstruction,\n ...formattedParams\n },\n this.requestOptions\n );\n }\n\n /**\n * Makes a single streaming call to the model\n * and returns an object containing an iterable stream that iterates\n * over all chunks in the streaming response as well as\n * a promise that returns the final aggregated response.\n */\n async generateContentStream(\n request: GenerateContentRequest | string | Array<string | Part>\n ): Promise<GenerateContentStreamResult> {\n const formattedParams = formatGenerateContentInput(request);\n return generateContentStream(\n this._apiSettings,\n this.model,\n {\n generationConfig: this.generationConfig,\n safetySettings: this.safetySettings,\n tools: this.tools,\n toolConfig: this.toolConfig,\n systemInstruction: this.systemInstruction,\n ...formattedParams\n },\n this.requestOptions\n );\n }\n\n /**\n * Gets a new {@link ChatSession} instance which can be used for\n * multi-turn chats.\n */\n startChat(startChatParams?: StartChatParams): ChatSession {\n return new ChatSession(\n this._apiSettings,\n this.model,\n {\n tools: this.tools,\n toolConfig: this.toolConfig,\n systemInstruction: this.systemInstruction,\n ...startChatParams\n },\n this.requestOptions\n );\n }\n\n /**\n * Counts the tokens in the provided request.\n */\n async countTokens(\n request: CountTokensRequest | string | Array<string | Part>\n ): Promise<CountTokensResponse> {\n const formattedParams = formatGenerateContentInput(request);\n return countTokens(this._apiSettings, this.model, formattedParams);\n }\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CountTokensRequest,\n CountTokensResponse,\n RequestOptions\n} from '../types';\nimport { Task, makeRequest } from '../requests/request';\nimport { ApiSettings } from '../types/internal';\n\nexport async function countTokens(\n apiSettings: ApiSettings,\n model: string,\n params: CountTokensRequest,\n requestOptions?: RequestOptions\n): Promise<CountTokensResponse> {\n const response = await makeRequest(\n model,\n Task.COUNT_TOKENS,\n apiSettings,\n false,\n JSON.stringify(params),\n requestOptions\n );\n return response.json();\n}\n","/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport { getModularInstance } from '@firebase/util';\nimport { DEFAULT_LOCATION, VERTEX_TYPE } from './constants';\nimport { VertexAIService } from './service';\nimport { VertexAI, VertexAIOptions } from './public-types';\nimport { ModelParams, RequestOptions, VertexAIErrorCode } from './types';\nimport { VertexAIError } from './errors';\nimport { GenerativeModel } from './models/generative-model';\n\nexport { ChatSession } from './methods/chat-session';\n\nexport { GenerativeModel };\n\nexport { VertexAIError };\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n [VERTEX_TYPE]: VertexAIService;\n }\n}\n\n/**\n * Returns a {@link VertexAI} instance for the given app.\n *\n * @public\n *\n * @param app - The {@link @firebase/app#FirebaseApp} to use.\n */\nexport function getVertexAI(\n app: FirebaseApp = getApp(),\n options?: VertexAIOptions\n): VertexAI {\n app = getModularInstance(app);\n // Dependencies\n const vertexProvider: Provider<'vertexAI'> = _getProvider(app, VERTEX_TYPE);\n\n return vertexProvider.getImmediate({\n identifier: options?.location || DEFAULT_LOCATION\n });\n}\n\n/**\n * Returns a {@link GenerativeModel} class with methods for inference\n * and other functionality.\n *\n * @public\n */\nexport function getGenerativeModel(\n vertexAI: VertexAI,\n modelParams: ModelParams,\n requestOptions?: RequestOptions\n): GenerativeModel {\n if (!modelParams.model) {\n throw new VertexAIError(\n VertexAIErrorCode.NO_MODEL,\n `Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })`\n );\n }\n return new GenerativeModel(vertexAI, modelParams, requestOptions);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n service: Compat<ExpService> | ExpService\n): ExpService {\n if (service && (service as Compat<ExpService>)._delegate) {\n return (service as Compat<ExpService>)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * The Vertex AI For Firebase Web SDK.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport { VertexAIService } from './service';\nimport { VERTEX_TYPE } from './constants';\nimport { Component, ComponentType } from '@firebase/component';\nimport { name, version } from '../package.json';\n\ndeclare global {\n interface Window {\n [key: string]: unknown;\n }\n}\n\nfunction registerVertex(): void {\n _registerComponent(\n new Component(\n VERTEX_TYPE,\n (container, { instanceIdentifier: location }) => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const auth = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n return new VertexAIService(app, auth, appCheckProvider, { location });\n },\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n\n registerVersion(name, version);\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n\nregisterVertex();\n\nexport * from './api';\nexport * from './public-types';\n"],"names":["FirebaseError","Error","constructor","code","message","customData","super","this","name","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replaceTemplate","replace","PATTERN","_","key","value","String","fullMessage","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","__await","v","__asyncGenerator","thisArg","_arguments","generator","Symbol","asyncIterator","TypeError","i","g","apply","q","verb","n","Promise","a","b","push","resume","step","r","resolve","then","fulfill","reject","settle","e","f","shift","length","VertexAIService","app","authProvider","appCheckProvider","options","appCheck","getImmediate","optional","auth","location","_a","_delete","VertexAIError","customErrorData","toString","Task","RequestUrl","model","task","apiSettings","stream","requestOptions","url","baseUrl","project","fullModelString","modelString","async","getHeaders","headers","Headers","append","getClientHeaders","loggingTags","join","apiKey","getAppCheckToken","appCheckToken","error","token","getAuthToken","authToken","accessToken","makeRequest","body","response","request","constructRequest","fetchOptions","buildFetchOptions","method","fetch","ok","errorDetails","json","details","JSON","stringify","status","statusText","err","stack","timeout","abortController","AbortController","signal","setTimeout","abort","POSSIBLE_ROLES","HarmCategory","HarmBlockThreshold","HarmBlockMethod","HarmProbability","HarmSeverity","BlockReason","FinishReason","FunctionCallingMode","FunctionDeclarationSchemaType","addHelpers","text","candidates","console","warn","hadBadFinishReason","formatBlockErrorMessage","getText","textStrings","_b","content","parts","part","_d","_c","promptFeedback","functionCalls","getFunctionCalls","functionCall","badFinishReasons","RECITATION","SAFETY","candidate","finishReason","includes","firstCandidate","finishMessage","blockReason","blockReasonMessage","responseLineRE","processStream","responseStream","getResponseStream","inputStream","reader","getReader","ReadableStream","start","controller","currentText","pump","read","done","trim","close","parsedResponse","match","parse","enqueue","substring","pipeThrough","TextDecoderStream","fatal","stream1","stream2","tee","generateResponseSequence","getResponsePromise","allResponses","aggregateResponses","responses","lastResponse","aggregatedResponse","index","citationMetadata","safetyRatings","role","newPart","keys","generateContentStream","params","STREAM_GENERATE_CONTENT","generateContent","GENERATE_CONTENT","formatSystemInstruction","input","formatNewContent","newParts","partOrString","assignRoleToPartsAndValidateSendMessageRequest","userContent","functionContent","hasUserContent","hasFunctionContent","formatGenerateContentInput","formattedRequest","contents","systemInstruction","VALID_PART_FIELDS","VALID_PARTS_PER_ROLE","user","function","system","VALID_PREVIOUS_CONTENT_ROLES","ChatSession","_history","_sendPromise","_apiSettings","history","validateChatHistory","prevContent","currContent","Array","isArray","countFields","inlineData","functionResponse","validParts","newContent","generateContentRequest","safetySettings","generationConfig","tools","toolConfig","_e","finalResult","result","responseContent","blockErrorMessage","streamPromise","catch","_ignored","streamResult","assign","GenerativeModel","vertexAI","modelParams","projectId","getToken","startsWith","formattedParams","startChat","startChatParams","countTokens","COUNT_TOKENS","getVertexAI","getApp","getModularInstance","_delegate","_getProvider","identifier","getGenerativeModel","registerVertex","_registerComponent","container","instanceIdentifier","getProv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