File: /home/dnlightw-124/dn.lightweb.kr/node_modules/firebase/firebase-vertexai.js.map
{"version":3,"file":"firebase-vertexai.js","sources":["../util/src/errors.ts","../component/src/component.ts","../logger/src/logger.ts","../vertexai/src/constants.ts","../vertexai/src/service.ts","../vertexai/src/errors.ts","../vertexai/src/models/vertexai-model.ts","../vertexai/src/logger.ts","../vertexai/src/requests/request.ts","../vertexai/src/types/enums.ts","../vertexai/src/types/schema.ts","../vertexai/src/types/imagen/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/models/imagen-model.ts","../vertexai/src/requests/schema-builder.ts","../vertexai/src/requests/imagen-image-format.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 // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\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","/**\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\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\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://firebasevertexai.googleapis.com';\n\nexport const DEFAULT_API_VERSION = 'v1beta';\n\nexport const PACKAGE_VERSION = version;\n\nexport const LANGUAGE_TAG = 'gl-js';\n\nexport const DEFAULT_FETCH_TIMEOUT_MS = 180 * 1000;\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 { FirebaseError } from '@firebase/util';\nimport { VertexAIErrorCode, CustomErrorData } from './types';\nimport { VERTEX_TYPE } from './constants';\n\n/**\n * Error class for the Vertex AI in 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 <code>{@link VertexAIErrorCode}</code>.\n * @param message - A human-readable message describing the error.\n * @param customErrorData - Optional error data.\n */\n constructor(\n readonly code: VertexAIErrorCode,\n 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(code, 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 // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\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 2025 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 { VertexAIError } from '../errors';\nimport { VertexAI, VertexAIErrorCode } from '../public-types';\nimport { VertexAIService } from '../service';\nimport { ApiSettings } from '../types/internal';\nimport { _isFirebaseServerApp } from '@firebase/app';\n\n/**\n * Base class for Vertex AI in Firebase model APIs.\n *\n * @public\n */\nexport abstract class VertexAIModel {\n /**\n * The fully qualified model resource name to use for generating images\n * (for example, `publishers/google/models/imagen-3.0-generate-002`).\n */\n readonly model: string;\n\n /**\n * @internal\n */\n protected _apiSettings: ApiSettings;\n\n /**\n * Constructs a new instance of the {@link VertexAIModel} class.\n *\n * This constructor should only be called from subclasses that provide\n * a model API.\n *\n * @param vertexAI - An instance of the Vertex AI in Firebase SDK.\n * @param modelName - The name of the model being used. It can be in one of the following formats:\n * - `my-model` (short name, will resolve to `publishers/google/models/my-model`)\n * - `models/my-model` (will resolve to `publishers/google/models/my-model`)\n * - `publishers/my-publisher/models/my-model` (fully qualified model name)\n *\n * @throws If the `apiKey` or `projectId` fields are missing in your\n * Firebase config.\n *\n * @internal\n */\n protected constructor(vertexAI: VertexAI, modelName: string) {\n this.model = VertexAIModel.normalizeModelName(modelName);\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\n if (\n _isFirebaseServerApp(vertexAI.app) &&\n vertexAI.app.settings.appCheckToken\n ) {\n const token = vertexAI.app.settings.appCheckToken;\n this._apiSettings.getAppCheckToken = () => {\n return Promise.resolve({ token });\n };\n } else 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 }\n\n /**\n * Normalizes the given model name to a fully qualified model resource name.\n *\n * @param modelName - The model name to normalize.\n * @returns The fully qualified model resource name.\n */\n static normalizeModelName(modelName: string): string {\n let model: string;\n if (modelName.includes('/')) {\n if (modelName.startsWith('models/')) {\n // Add 'publishers/google' if the user is only passing in 'models/model-name'.\n model = `publishers/google/${modelName}`;\n } else {\n // Any other custom format (e.g. tuned models) must be passed in correctly.\n model = modelName;\n }\n } else {\n // If path is not included, assume it's a non-tuned model.\n model = `publishers/google/models/${modelName}`;\n }\n\n return model;\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 { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/vertexai');\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 { ErrorDetails, RequestOptions, VertexAIErrorCode } from '../types';\nimport { VertexAIError } from '../errors';\nimport { ApiSettings } from '../types/internal';\nimport {\n DEFAULT_API_VERSION,\n DEFAULT_BASE_URL,\n DEFAULT_FETCH_TIMEOUT_MS,\n LANGUAGE_TAG,\n PACKAGE_VERSION\n} from '../constants';\nimport { logger } from '../logger';\n\nexport enum Task {\n GENERATE_CONTENT = 'generateContent',\n STREAM_GENERATE_CONTENT = 'streamGenerateContent',\n COUNT_TOKENS = 'countTokens',\n PREDICT = 'predict'\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) {\n headers.append('X-Firebase-AppCheck', appCheckToken.token);\n if (appCheckToken.error) {\n logger.warn(\n `Unable to obtain a valid App Check token: ${appCheckToken.error.message}`\n );\n }\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 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 let fetchTimeoutId: string | number | NodeJS.Timeout | undefined;\n try {\n const request = await constructRequest(\n model,\n task,\n apiSettings,\n stream,\n body,\n requestOptions\n );\n // Timeout is 180s by default\n const timeoutMillis =\n requestOptions?.timeout != null && requestOptions.timeout >= 0\n ? requestOptions.timeout\n : DEFAULT_FETCH_TIMEOUT_MS;\n const abortController = new AbortController();\n fetchTimeoutId = setTimeout(() => abortController.abort(), timeoutMillis);\n request.fetchOptions.signal = abortController.signal;\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 if (\n response.status === 403 &&\n errorDetails.some(\n (detail: ErrorDetails) => detail.reason === 'SERVICE_DISABLED'\n ) &&\n errorDetails.some((detail: ErrorDetails) =>\n (\n detail.links as Array<Record<string, string>>\n )?.[0]?.description.includes(\n 'Google developers console API activation'\n )\n )\n ) {\n throw new VertexAIError(\n VertexAIErrorCode.API_NOT_ENABLED,\n `The Vertex AI in Firebase SDK requires the Vertex AI in Firebase ` +\n `API ('firebasevertexai.googleapis.com') to be enabled in your ` +\n `Firebase project. Enable this API by visiting the Firebase Console ` +\n `at https://console.firebase.google.com/project/${url.apiSettings.project}/genai/ ` +\n `and clicking \"Get started\". If you enabled this API recently, ` +\n `wait a few minutes for the action to propagate to our systems and ` +\n `then retry.`,\n {\n status: response.status,\n statusText: response.statusText,\n errorDetails\n }\n );\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 as VertexAIError).code !== VertexAIErrorCode.API_NOT_ENABLED &&\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 } finally {\n if (fetchTimeoutId) {\n clearTimeout(fetchTimeoutId);\n }\n }\n return response;\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_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 /**\n * Content with `NEGLIGIBLE` will be allowed.\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Content with `NEGLIGIBLE` and `LOW` will be allowed.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Content with `NEGLIGIBLE`, `LOW`, and `MEDIUM` will be allowed.\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * All content will be allowed.\n */\n BLOCK_NONE = 'BLOCK_NONE'\n}\n\n/**\n * @public\n */\nexport enum HarmBlockMethod {\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY'\n}\n\n/**\n * Probability that a prompt or candidate matches a harm category.\n * @public\n */\nexport enum HarmProbability {\n /**\n * Content has a negligible chance of being unsafe.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Content has a low chance of being unsafe.\n */\n LOW = 'LOW',\n /**\n * Content has a medium chance of being unsafe.\n */\n MEDIUM = 'MEDIUM',\n /**\n * Content has a high chance of being unsafe.\n */\n HIGH = 'HIGH'\n}\n\n/**\n * Harm severity levels.\n * @public\n */\nexport enum HarmSeverity {\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH'\n}\n\n/**\n * Reason that a prompt was blocked.\n * @public\n */\nexport enum BlockReason {\n /**\n * Content was blocked by safety settings.\n */\n SAFETY = 'SAFETY',\n /**\n * Content was blocked, but the reason is uncategorized.\n */\n OTHER = 'OTHER',\n /**\n * Content was blocked because it contained terms from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Content was blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT'\n}\n\n/**\n * Reason that a candidate finished.\n * @public\n */\nexport enum FinishReason {\n /**\n * Natural stop point of the model or provided stop sequence.\n */\n STOP = 'STOP',\n /**\n * The maximum number of tokens as specified in the request was reached.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * The candidate content was flagged for safety reasons.\n */\n SAFETY = 'SAFETY',\n /**\n * The candidate content was flagged for recitation reasons.\n */\n RECITATION = 'RECITATION',\n /**\n * Unknown reason.\n */\n OTHER = 'OTHER',\n /**\n * The candidate content contained forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * The candidate content potentially contained prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * The candidate content potentially contained Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model was invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL'\n}\n\n/**\n * @public\n */\nexport enum FunctionCallingMode {\n /**\n * Default model behavior; model decides to predict either a function call\n * or a natural language response.\n */\n AUTO = 'AUTO',\n /**\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 */\n ANY = 'ANY',\n /**\n * Model will not predict any function call. Model behavior is same as when\n * not passing any function declarations.\n */\n NONE = 'NONE'\n}\n\n/**\n * Content part modality.\n * @public\n */\nexport enum Modality {\n /**\n * Unspecified modality.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Image.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document (for example, PDF).\n */\n DOCUMENT = 'DOCUMENT'\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 * Contains the list of OpenAPI data types\n * as defined by the\n * {@link https://swagger.io/docs/specification/data-models/data-types/ | OpenAPI specification}\n * @public\n */\nexport enum SchemaType {\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 * Basic <code>{@link Schema}</code> properties shared across several Schema-related\n * types.\n * @public\n */\nexport interface SchemaShared<T> {\n /** Optional. The format of the property. */\n format?: string;\n /** Optional. The description of the property. */\n description?: string;\n /** Optional. The items of the property. */\n items?: T;\n /** Optional. Map of `Schema` objects. */\n properties?: {\n [k: string]: T;\n };\n /** Optional. The enum of the property. */\n enum?: string[];\n /** Optional. The example of the property. */\n example?: unknown;\n /** Optional. Whether the property is nullable. */\n nullable?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Params passed to <code>{@link Schema}</code> static methods to create specific\n * <code>{@link Schema}</code> classes.\n * @public\n */\nexport interface SchemaParams extends SchemaShared<SchemaInterface> {}\n\n/**\n * Final format for <code>{@link Schema}</code> params passed to backend requests.\n * @public\n */\nexport interface SchemaRequest extends SchemaShared<SchemaRequest> {\n /**\n * The type of the property. {@link\n * SchemaType}.\n */\n type: SchemaType;\n /** Optional. Array of required property. */\n required?: string[];\n}\n\n/**\n * Interface for <code>{@link Schema}</code> class.\n * @public\n */\nexport interface SchemaInterface extends SchemaShared<SchemaInterface> {\n /**\n * The type of the property. {@link\n * SchemaType}.\n */\n type: SchemaType;\n}\n\n/**\n * Interface for <code>{@link ObjectSchema}</code> class.\n * @public\n */\nexport interface ObjectSchemaInterface extends SchemaInterface {\n type: SchemaType.OBJECT;\n optionalProperties?: string[];\n}\n","/**\n * @license\n * Copyright 2025 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 { ImagenImageFormat } from '../../requests/imagen-image-format';\n\n/**\n * Parameters for configuring an <code>{@link ImagenModel}</code>.\n *\n * @beta\n */\nexport interface ImagenModelParams {\n /**\n * The Imagen model to use for generating images.\n * For example: `imagen-3.0-generate-002`.\n *\n * Only Imagen 3 models (named `imagen-3.0-*`) are supported.\n *\n * See {@link https://firebase.google.com/docs/vertex-ai/models | model versions}\n * for a full list of supported Imagen 3 models.\n */\n model: string;\n /**\n * Configuration options for generating images with Imagen.\n */\n generationConfig?: ImagenGenerationConfig;\n /**\n * Safety settings for filtering potentially inappropriate content.\n */\n safetySettings?: ImagenSafetySettings;\n}\n\n/**\n * Configuration options for generating images with Imagen.\n *\n * See the {@link http://firebase.google.com/docs/vertex-ai/generate-images-imagen | documentation} for\n * more details.\n *\n * @beta\n */\nexport interface ImagenGenerationConfig {\n /**\n * A description of what should be omitted from the generated images.\n *\n * Support for negative prompts depends on the Imagen model.\n *\n * See the {@link http://firebase.google.com/docs/vertex-ai/model-parameters#imagen | documentation} for more details.\n */\n negativePrompt?: string;\n /**\n * The number of images to generate. The default value is 1.\n *\n * The number of sample images that may be generated in each request depends on the model\n * (typically up to 4); see the <a href=\"http://firebase.google.com/docs/vertex-ai/model-parameters#imagen\"><code>sampleCount</code></a>\n * documentation for more details.\n */\n numberOfImages?: number;\n /**\n * The aspect ratio of the generated images. The default value is square 1:1.\n * Supported aspect ratios depend on the Imagen model, see <code>{@link ImagenAspectRatio}</code>\n * for more details.\n */\n aspectRatio?: ImagenAspectRatio;\n /**\n * The image format of the generated images. The default is PNG.\n *\n * See <code>{@link ImagenImageFormat}</code> for more details.\n */\n imageFormat?: ImagenImageFormat;\n /**\n * Whether to add an invisible watermark to generated images.\n *\n * If set to `true`, an invisible SynthID watermark is embedded in generated images to indicate\n * that they are AI generated. If set to `false`, watermarking will be disabled.\n *\n * For Imagen 3 models, the default value is `true`; see the <a href=\"http://firebase.google.com/docs/vertex-ai/model-parameters#imagen\"><code>addWatermark</code></a>\n * documentation for more details.\n */\n addWatermark?: boolean;\n}\n\n/**\n * A filter level controlling how aggressively to filter sensitive content.\n *\n * Text prompts provided as inputs and images (generated or uploaded) through Imagen on Vertex AI\n * are assessed against a list of safety filters, which include 'harmful categories' (for example,\n * `violence`, `sexual`, `derogatory`, and `toxic`). This filter level controls how aggressively to\n * filter out potentially harmful content from responses. See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation }\n * and the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#safety-filters | Responsible AI and usage guidelines}\n * for more details.\n *\n * @beta\n */\nexport enum ImagenSafetyFilterLevel {\n /**\n * The most aggressive filtering level; most strict blocking.\n */\n BLOCK_LOW_AND_ABOVE = 'block_low_and_above',\n /**\n * Blocks some sensitive prompts and responses.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'block_medium_and_above',\n /**\n * Blocks few sensitive prompts and responses.\n */\n BLOCK_ONLY_HIGH = 'block_only_high',\n /**\n * The least aggressive filtering level; blocks very few sensitive prompts and responses.\n *\n * Access to this feature is restricted and may require your case to be reviewed and approved by\n * Cloud support.\n */\n BLOCK_NONE = 'block_none'\n}\n\n/**\n * A filter level controlling whether generation of images containing people or faces is allowed.\n *\n * See the <a href=\"http://firebase.google.com/docs/vertex-ai/generate-images\"><code>personGeneration</code></a>\n * documentation for more details.\n *\n * @beta\n */\nexport enum ImagenPersonFilterLevel {\n /**\n * Disallow generation of images containing people or faces; images of people are filtered out.\n */\n BLOCK_ALL = 'dont_allow',\n /**\n * Allow generation of images containing adults only; images of children are filtered out.\n *\n * Generation of images containing people or faces may require your use case to be\n * reviewed and approved by Cloud support; see the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#person-face-gen | Responsible AI and usage guidelines}\n * for more details.\n */\n ALLOW_ADULT = 'allow_adult',\n /**\n * Allow generation of images containing adults only; images of children are filtered out.\n *\n * Generation of images containing people or faces may require your use case to be\n * reviewed and approved by Cloud support; see the {@link https://cloud.google.com/vertex-ai/generative-ai/docs/image/responsible-ai-imagen#person-face-gen | Responsible AI and usage guidelines}\n * for more details.\n */\n ALLOW_ALL = 'allow_all'\n}\n\n/**\n * Settings for controlling the aggressiveness of filtering out sensitive content.\n *\n * See the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation }\n * for more details.\n *\n * @beta\n */\nexport interface ImagenSafetySettings {\n /**\n * A filter level controlling how aggressive to filter out sensitive content from generated\n * images.\n */\n safetyFilterLevel?: ImagenSafetyFilterLevel;\n /**\n * A filter level controlling whether generation of images containing people or faces is allowed.\n */\n personFilterLevel?: ImagenPersonFilterLevel;\n}\n\n/**\n * Aspect ratios for Imagen images.\n *\n * To specify an aspect ratio for generated images, set the `aspectRatio` property in your\n * <code>{@link ImagenGenerationConfig}</code>.\n *\n * See the the {@link http://firebase.google.com/docs/vertex-ai/generate-images | documentation }\n * for more details and examples of the supported aspect ratios.\n *\n * @beta\n */\nexport enum ImagenAspectRatio {\n /**\n * Square (1:1) aspect ratio.\n */\n SQUARE = '1:1',\n /**\n * Landscape (3:4) aspect ratio.\n */\n LANDSCAPE_3x4 = '3:4',\n /**\n * Portrait (4:3) aspect ratio.\n */\n PORTRAIT_4x3 = '4:3',\n /**\n * Landscape (16:9) aspect ratio.\n */\n LANDSCAPE_16x9 = '16:9',\n /**\n * Portrait (9:16) aspect ratio.\n */\n PORTRAIT_9x16 = '9:16'\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 ImagenGCSImage,\n ImagenInlineImage,\n VertexAIErrorCode\n} from '../types';\nimport { VertexAIError } from '../errors';\nimport { logger } from '../logger';\nimport { ImagenResponseInternal } from '../types/internal';\n\n/**\n * Creates an EnhancedGenerateContentResponse object that has helper functions and\n * other modifications that improve usability.\n */\nexport function createEnhancedContentResponse(\n response: GenerateContentResponse\n): EnhancedGenerateContentResponse {\n /**\n * The Vertex AI backend omits default values.\n * This causes the `index` property to be omitted from the first candidate in the\n * response, since it has index 0, and 0 is a default value.\n * See: https://github.com/firebase/firebase-js-sdk/issues/8566\n */\n if (response.candidates && !response.candidates[0].hasOwnProperty('index')) {\n response.candidates[0].index = 0;\n }\n\n const responseWithHelpers = addHelpers(response);\n return responseWithHelpers;\n}\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 logger.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 logger.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 <code>{@link FunctionCall}</code>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/**\n * Convert a generic successful fetch response body to an Imagen response object\n * that can be returned to the user. This converts the REST APIs response format to our\n * APIs representation of a response.\n *\n * @internal\n */\nexport async function handlePredictResponse<\n T extends ImagenInlineImage | ImagenGCSImage\n>(response: Response): Promise<{ images: T[]; filteredReason?: string }> {\n const responseJson: ImagenResponseInternal = await response.json();\n\n const images: T[] = [];\n let filteredReason: string | undefined = undefined;\n\n // The backend should always send a non-empty array of predictions if the response was successful.\n if (!responseJson.predictions || responseJson.predictions?.length === 0) {\n throw new VertexAIError(\n VertexAIErrorCode.RESPONSE_ERROR,\n 'No predictions or filtered reason received from Vertex AI. Please report this issue with the full error details at https://github.com/firebase/firebase-js-sdk/issues.'\n );\n }\n\n for (const prediction of responseJson.predictions) {\n if (prediction.raiFilteredReason) {\n filteredReason = prediction.raiFilteredReason;\n } else if (prediction.mimeType && prediction.bytesBase64Encoded) {\n images.push({\n mimeType: prediction.mimeType,\n bytesBase64Encoded: prediction.bytesBase64Encoded\n } as T);\n } else if (prediction.mimeType && prediction.gcsUri) {\n images.push({\n mimeType: prediction.mimeType,\n gcsURI: prediction.gcsUri\n } as T);\n } else {\n throw new VertexAIError(\n VertexAIErrorCode.RESPONSE_ERROR,\n `Predictions array in response has missing properties. Response: ${JSON.stringify(\n responseJson\n )}`\n );\n }\n }\n\n return { images, filteredReason };\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 { createEnhancedContentResponse } 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 const enhancedResponse = createEnhancedContentResponse(\n aggregateResponses(allResponses)\n );\n return enhancedResponse;\n }\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\n const enhancedResponse = createEnhancedContentResponse(value);\n yield enhancedResponse;\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 // Index will be undefined if it's the first index (0), so we should use 0 if it's undefined.\n // See: https://github.com/firebase/firebase-js-sdk/issues/8566\n const i = candidate.index || 0;\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 !== undefined) {\n // The backend can send empty text parts. If these are sent back\n // (e.g. in chat history), the backend will respond with an error.\n // To prevent this, ignore empty text parts.\n if (part.text === '') {\n continue;\n }\n newPart.text = part.text;\n }\n if (part.functionCall) {\n newPart.functionCall = part.functionCall;\n }\n if (Object.keys(newPart).length === 0) {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_CONTENT,\n 'Part should have at least one property, but there are none. This is likely caused ' +\n 'by a malformed response from the backend.'\n );\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 { createEnhancedContentResponse } 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 = createEnhancedContentResponse(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';\nimport { ImagenGenerationParams, PredictRequestBody } from '../types/internal';\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/**\n * Convert the user-defined parameters in <code>{@link ImagenGenerationParams}</code> to the format\n * that is expected from the REST API.\n *\n * @internal\n */\nexport function createPredictRequestBody(\n prompt: string,\n {\n gcsURI,\n imageFormat,\n addWatermark,\n numberOfImages = 1,\n negativePrompt,\n aspectRatio,\n safetyFilterLevel,\n personFilterLevel\n }: ImagenGenerationParams\n): PredictRequestBody {\n // Properties that are undefined will be omitted from the JSON string that is sent in the request.\n const body: PredictRequestBody = {\n instances: [\n {\n prompt\n }\n ],\n parameters: {\n storageUri: gcsURI,\n negativePrompt,\n sampleCount: numberOfImages,\n aspectRatio,\n outputOptions: imageFormat,\n addWatermark,\n safetyFilterLevel,\n personGeneration: personFilterLevel,\n includeRaiReason: true\n }\n };\n return body;\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';\nimport { logger } from '../logger';\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 * Neither blocked candidates nor the prompts that generated them are added\n * to history.\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 * <code>{@link GenerateContentResult}</code>\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 logger.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 * <code>{@link GenerateContentStreamResult}</code> 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 logger.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 logger.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} from '../types';\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 { VertexAIModel } from './vertexai-model';\n\n/**\n * Class for generative model APIs.\n * @public\n */\nexport class GenerativeModel extends VertexAIModel {\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 super(vertexAI, modelParams.model);\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 <code>{@link GenerateContentResponse}</code>.\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 <code>{@link ChatSession}</code> 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 2025 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 { VertexAI } from '../public-types';\nimport { Task, makeRequest } from '../requests/request';\nimport { createPredictRequestBody } from '../requests/request-helpers';\nimport { handlePredictResponse } from '../requests/response-helpers';\nimport {\n ImagenGCSImage,\n ImagenGenerationConfig,\n ImagenInlineImage,\n RequestOptions,\n ImagenModelParams,\n ImagenGenerationResponse,\n ImagenSafetySettings\n} from '../types';\nimport { VertexAIModel } from './vertexai-model';\n\n/**\n * Class for Imagen model APIs.\n *\n * This class provides methods for generating images using the Imagen model.\n *\n * @example\n * ```javascript\n * const imagen = new ImagenModel(\n * vertexAI,\n * {\n * model: 'imagen-3.0-generate-002'\n * }\n * );\n *\n * const response = await imagen.generateImages('A photo of a cat');\n * if (response.images.length > 0) {\n * console.log(response.images[0].bytesBase64Encoded);\n * }\n * ```\n *\n * @beta\n */\nexport class ImagenModel extends VertexAIModel {\n /**\n * The Imagen generation configuration.\n */\n generationConfig?: ImagenGenerationConfig;\n /**\n * Safety settings for filtering inappropriate content.\n */\n safetySettings?: ImagenSafetySettings;\n\n /**\n * Constructs a new instance of the <code>{@link ImagenModel}</code> class.\n *\n * @param vertexAI - An instance of the Vertex AI in Firebase SDK.\n * @param modelParams - Parameters to use when making requests to Imagen.\n * @param requestOptions - Additional options to use when making requests.\n *\n * @throws If the `apiKey` or `projectId` fields are missing in your\n * Firebase config.\n */\n constructor(\n vertexAI: VertexAI,\n modelParams: ImagenModelParams,\n public requestOptions?: RequestOptions\n ) {\n const { model, generationConfig, safetySettings } = modelParams;\n super(vertexAI, model);\n this.generationConfig = generationConfig;\n this.safetySettings = safetySettings;\n }\n\n /**\n * Generates images using the Imagen model and returns them as\n * base64-encoded strings.\n *\n * @param prompt - A text prompt describing the image(s) to generate.\n * @returns A promise that resolves to an <code>{@link ImagenGenerationResponse}</code>\n * object containing the generated images.\n *\n * @throws If the request to generate images fails. This happens if the\n * prompt is blocked.\n *\n * @remarks\n * If the prompt was not blocked, but one or more of the generated images were filtered, the\n * returned object will have a `filteredReason` property.\n * If all images are filtered, the `images` array will be empty.\n *\n * @beta\n */\n async generateImages(\n prompt: string\n ): Promise<ImagenGenerationResponse<ImagenInlineImage>> {\n const body = createPredictRequestBody(prompt, {\n ...this.generationConfig,\n ...this.safetySettings\n });\n const response = await makeRequest(\n this.model,\n Task.PREDICT,\n this._apiSettings,\n /* stream */ false,\n JSON.stringify(body),\n this.requestOptions\n );\n return handlePredictResponse<ImagenInlineImage>(response);\n }\n\n /**\n * Generates images to Cloud Storage for Firebase using the Imagen model.\n *\n * @internal This method is temporarily internal.\n *\n * @param prompt - A text prompt describing the image(s) to generate.\n * @param gcsURI - The URI of file stored in a Cloud Storage for Firebase bucket.\n * This should be a directory. For example, `gs://my-bucket/my-directory/`.\n * @returns A promise that resolves to an <code>{@link ImagenGenerationResponse}</code>\n * object containing the URLs of the generated images.\n *\n * @throws If the request fails to generate images fails. This happens if\n * the prompt is blocked.\n *\n * @remarks\n * If the prompt was not blocked, but one or more of the generated images were filtered, the\n * returned object will have a `filteredReason` property.\n * If all images are filtered, the `images` array will be empty.\n */\n async generateImagesGCS(\n prompt: string,\n gcsURI: string\n ): Promise<ImagenGenerationResponse<ImagenGCSImage>> {\n const body = createPredictRequestBody(prompt, {\n gcsURI,\n ...this.generationConfig,\n ...this.safetySettings\n });\n const response = await makeRequest(\n this.model,\n Task.PREDICT,\n this._apiSettings,\n /* stream */ false,\n JSON.stringify(body),\n this.requestOptions\n );\n return handlePredictResponse<ImagenGCSImage>(response);\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 { VertexAIError } from '../errors';\nimport { VertexAIErrorCode } from '../types';\nimport {\n SchemaInterface,\n SchemaType,\n SchemaParams,\n SchemaRequest,\n ObjectSchemaInterface\n} from '../types/schema';\n\n/**\n * Parent class encompassing all Schema types, with static methods that\n * allow building specific Schema types. This class can be converted with\n * `JSON.stringify()` into a JSON string accepted by Vertex AI REST endpoints.\n * (This string conversion is automatically done when calling SDK methods.)\n * @public\n */\nexport abstract class Schema implements SchemaInterface {\n /**\n * Optional. The type of the property. {@link\n * SchemaType}.\n */\n type: SchemaType;\n /** Optional. The format of the property.\n * Supported formats:<br/>\n * <ul>\n * <li>for NUMBER type: \"float\", \"double\"</li>\n * <li>for INTEGER type: \"int32\", \"int64\"</li>\n * <li>for STRING type: \"email\", \"byte\", etc</li>\n * </ul>\n */\n format?: string;\n /** Optional. The description of the property. */\n description?: string;\n /** Optional. Whether the property is nullable. Defaults to false. */\n nullable: boolean;\n /** Optional. The example of the property. */\n example?: unknown;\n /**\n * Allows user to add other schema properties that have not yet\n * been officially added to the SDK.\n */\n [key: string]: unknown;\n\n constructor(schemaParams: SchemaInterface) {\n // eslint-disable-next-line guard-for-in\n for (const paramKey in schemaParams) {\n this[paramKey] = schemaParams[paramKey];\n }\n // Ensure these are explicitly set to avoid TS errors.\n this.type = schemaParams.type;\n this.nullable = schemaParams.hasOwnProperty('nullable')\n ? !!schemaParams.nullable\n : false;\n }\n\n /**\n * Defines how this Schema should be serialized as JSON.\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_behavior\n * @internal\n */\n toJSON(): SchemaRequest {\n const obj: { type: SchemaType; [key: string]: unknown } = {\n type: this.type\n };\n for (const prop in this) {\n if (this.hasOwnProperty(prop) && this[prop] !== undefined) {\n if (prop !== 'required' || this.type === SchemaType.OBJECT) {\n obj[prop] = this[prop];\n }\n }\n }\n return obj as SchemaRequest;\n }\n\n static array(arrayParams: SchemaParams & { items: Schema }): ArraySchema {\n return new ArraySchema(arrayParams, arrayParams.items);\n }\n\n static object(\n objectParams: SchemaParams & {\n properties: {\n [k: string]: Schema;\n };\n optionalProperties?: string[];\n }\n ): ObjectSchema {\n return new ObjectSchema(\n objectParams,\n objectParams.properties,\n objectParams.optionalProperties\n );\n }\n\n // eslint-disable-next-line id-blacklist\n static string(stringParams?: SchemaParams): StringSchema {\n return new StringSchema(stringParams);\n }\n\n static enumString(\n stringParams: SchemaParams & { enum: string[] }\n ): StringSchema {\n return new StringSchema(stringParams, stringParams.enum);\n }\n\n static integer(integerParams?: SchemaParams): IntegerSchema {\n return new IntegerSchema(integerParams);\n }\n\n // eslint-disable-next-line id-blacklist\n static number(numberParams?: SchemaParams): NumberSchema {\n return new NumberSchema(numberParams);\n }\n\n // eslint-disable-next-line id-blacklist\n static boolean(booleanParams?: SchemaParams): BooleanSchema {\n return new BooleanSchema(booleanParams);\n }\n}\n\n/**\n * A type that includes all specific Schema types.\n * @public\n */\nexport type TypedSchema =\n | IntegerSchema\n | NumberSchema\n | StringSchema\n | BooleanSchema\n | ObjectSchema\n | ArraySchema;\n\n/**\n * Schema class for \"integer\" types.\n * @public\n */\nexport class IntegerSchema extends Schema {\n constructor(schemaParams?: SchemaParams) {\n super({\n type: SchemaType.INTEGER,\n ...schemaParams\n });\n }\n}\n\n/**\n * Schema class for \"number\" types.\n * @public\n */\nexport class NumberSchema extends Schema {\n constructor(schemaParams?: SchemaParams) {\n super({\n type: SchemaType.NUMBER,\n ...schemaParams\n });\n }\n}\n\n/**\n * Schema class for \"boolean\" types.\n * @public\n */\nexport class BooleanSchema extends Schema {\n constructor(schemaParams?: SchemaParams) {\n super({\n type: SchemaType.BOOLEAN,\n ...schemaParams\n });\n }\n}\n\n/**\n * Schema class for \"string\" types. Can be used with or without\n * enum values.\n * @public\n */\nexport class StringSchema extends Schema {\n enum?: string[];\n constructor(schemaParams?: SchemaParams, enumValues?: string[]) {\n super({\n type: SchemaType.STRING,\n ...schemaParams\n });\n this.enum = enumValues;\n }\n\n /**\n * @internal\n */\n toJSON(): SchemaRequest {\n const obj = super.toJSON();\n if (this.enum) {\n obj['enum'] = this.enum;\n }\n return obj as SchemaRequest;\n }\n}\n\n/**\n * Schema class for \"array\" types.\n * The `items` param should refer to the type of item that can be a member\n * of the array.\n * @public\n */\nexport class ArraySchema extends Schema {\n constructor(schemaParams: SchemaParams, public items: TypedSchema) {\n super({\n type: SchemaType.ARRAY,\n ...schemaParams\n });\n }\n\n /**\n * @internal\n */\n toJSON(): SchemaRequest {\n const obj = super.toJSON();\n obj.items = this.items.toJSON();\n return obj;\n }\n}\n\n/**\n * Schema class for \"object\" types.\n * The `properties` param must be a map of `Schema` objects.\n * @public\n */\nexport class ObjectSchema extends Schema {\n constructor(\n schemaParams: SchemaParams,\n public properties: {\n [k: string]: TypedSchema;\n },\n public optionalProperties: string[] = []\n ) {\n super({\n type: SchemaType.OBJECT,\n ...schemaParams\n });\n }\n\n /**\n * @internal\n */\n toJSON(): SchemaRequest {\n const obj = super.toJSON();\n obj.properties = { ...this.properties };\n const required = [];\n if (this.optionalProperties) {\n for (const propertyKey of this.optionalProperties) {\n if (!this.properties.hasOwnProperty(propertyKey)) {\n throw new VertexAIError(\n VertexAIErrorCode.INVALID_SCHEMA,\n `Property \"${propertyKey}\" specified in \"optionalProperties\" does not exist.`\n );\n }\n }\n }\n for (const propertyKey in this.properties) {\n if (this.properties.hasOwnProperty(propertyKey)) {\n obj.properties[propertyKey] = this.properties[\n propertyKey\n ].toJSON() as SchemaRequest;\n if (!this.optionalProperties.includes(propertyKey)) {\n required.push(propertyKey);\n }\n }\n }\n if (required.length > 0) {\n obj.required = required;\n }\n delete (obj as ObjectSchemaInterface).optionalProperties;\n return obj as SchemaRequest;\n }\n}\n","/**\n * @license\n * Copyright 2025 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 { logger } from '../logger';\n\n/**\n * Defines the image format for images generated by Imagen.\n *\n * Use this class to specify the desired format (JPEG or PNG) and compression quality\n * for images generated by Imagen. This is typically included as part of\n * <code>{@link ImagenModelParams}</code>.\n *\n * @example\n * ```javascript\n * const imagenModelParams = {\n * // ... other ImagenModelParams\n * imageFormat: ImagenImageFormat.jpeg(75) // JPEG with a compression level of 75.\n * }\n * ```\n *\n * @beta\n */\nexport class ImagenImageFormat {\n /**\n * The MIME type.\n */\n mimeType: string;\n /**\n * The level of compression (a number between 0 and 100).\n */\n compressionQuality?: number;\n\n private constructor() {\n this.mimeType = 'image/png';\n }\n\n /**\n * Creates an <code>{@link ImagenImageFormat}</code> for a JPEG image.\n *\n * @param compressionQuality - The level of compression (a number between 0 and 100).\n * @returns An <code>{@link ImagenImageFormat}</code> object for a JPEG image.\n *\n * @beta\n */\n static jpeg(compressionQuality?: number): ImagenImageFormat {\n if (\n compressionQuality &&\n (compressionQuality < 0 || compressionQuality > 100)\n ) {\n logger.warn(\n `Invalid JPEG compression quality of ${compressionQuality} specified; the supported range is [0, 100].`\n );\n }\n return { mimeType: 'image/jpeg', compressionQuality };\n }\n\n /**\n * Creates an <code>{@link ImagenImageFormat}</code> for a PNG image.\n *\n * @returns An <code>{@link ImagenImageFormat}</code> object for a PNG image.\n *\n * @beta\n */\n static png(): ImagenImageFormat {\n return { mimeType: 'image/png' };\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 { 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 {\n ImagenModelParams,\n ModelParams,\n RequestOptions,\n VertexAIErrorCode\n} from './types';\nimport { VertexAIError } from './errors';\nimport { VertexAIModel, GenerativeModel, ImagenModel } from './models';\n\nexport { ChatSession } from './methods/chat-session';\nexport * from './requests/schema-builder';\nexport { ImagenImageFormat } from './requests/imagen-image-format';\nexport { VertexAIModel, GenerativeModel, ImagenModel };\nexport { VertexAIError };\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n [VERTEX_TYPE]: VertexAIService;\n }\n}\n\n/**\n * Returns a <code>{@link VertexAI}</code> 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 <code>{@link GenerativeModel}</code> 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/**\n * Returns an <code>{@link ImagenModel}</code> class with methods for using Imagen.\n *\n * Only Imagen 3 models (named `imagen-3.0-*`) are supported.\n *\n * @param vertexAI - An instance of the Vertex AI in Firebase SDK.\n * @param modelParams - Parameters to use when making Imagen requests.\n * @param requestOptions - Additional options to use when making requests.\n *\n * @throws If the `apiKey` or `projectId` fields are missing in your\n * Firebase config.\n *\n * @beta\n */\nexport function getImagenModel(\n vertexAI: VertexAI,\n modelParams: ImagenModelParams,\n requestOptions?: RequestOptions\n): ImagenModel {\n if (!modelParams.model) {\n throw new VertexAIError(\n VertexAIErrorCode.NO_MODEL,\n `Must provide a model name. Example: getImagenModel({ model: 'my-model-name' })`\n );\n }\n return new ImagenModel(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 in 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 esm2017, cjs2017, 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","LogLevel","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","info","INFO","warn","WARN","error","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","instance","logType","args","logLevel","now","Date","toISOString","method","console","VERTEX_TYPE","DEFAULT_LOCATION","PACKAGE_VERSION","version","VertexAIService","app","authProvider","appCheckProvider","options","appCheck","getImmediate","optional","auth","location","_a","_delete","Promise","resolve","VertexAIError","customErrorData","toString","VertexAIModel","vertexAI","modelName","model","normalizeModelName","_b","apiKey","_d","_c","projectId","_apiSettings","project","_isFirebaseServerApp","settings","appCheckToken","token","getAppCheckToken","getToken","getAuthToken","includes","startsWith","logger","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","log","Task","RequestUrl","task","apiSettings","stream","requestOptions","url","baseUrl","fullModelString","modelString","async","getHeaders","headers","Headers","append","getClientHeaders","loggingTags","push","join","authToken","accessToken","makeRequest","body","response","fetchTimeoutId","request","constructRequest","fetchOptions","timeoutMillis","timeout","abortController","AbortController","setTimeout","abort","signal","fetch","ok","errorDetails","json","details","JSON","stringify","e","status","some","detail","reason","links","description","statusText","err","stack","clearTimeout","POSSIBLE_ROLES","HarmCategory","HarmBlockThreshold","HarmBlockMethod","HarmProbability","HarmSeverity","BlockReason","FinishReason","FunctionCallingMode","Modality","SchemaType","ImagenSafetyFilterLevel","ImagenPersonFilterLevel","ImagenAspectRatio","createEnhancedContentResponse","candidates","hasOwnProperty","index","responseWithHelpers","addHelpers","text","length","hadBadFinishReason","formatBlockErrorMessage","getText","textStrings","content","parts","part","promptFeedback","functionCalls","getFunctionCalls","functionCall","badFinishReasons","RECITATION","SAFETY","candidate","finishReason","firstCandidate","finishMessage","blockReason","blockReasonMessage","handlePredictResponse","responseJson","images","filteredReason","predictions","prediction","raiFilteredReason","mimeType","bytesBase64Encoded","gcsUri","gcsURI","responseLineRE","processStream","responseStream","getResponseStream","inputStream","reader","getReader","ReadableStream","start","controller","currentText","pump","read","then","done","trim","close","parsedResponse","match","parse","enqueue","substring","pipeThrough","TextDecoderStream","fatal","stream1","stream2","tee","generateResponseSequence","getResponsePromise","allResponses","aggregateResponses","__await","enhancedResponse","responses","lastResponse","aggregatedResponse","i","citationMetadata","safetyRatings","role","newPart","undefined","keys","generateContentStream","params","STREAM_GENERATE_CONTENT","generateContent","GENERATE_CONTENT","formatSystemInstruction","input","formatNewContent","newParts","partOrString","assignRoleToPartsAndValidateSendMessageRequest","userContent","functionContent","hasUserContent","hasFunctionContent","formatGenerateContentInput","formattedRequest","contents","systemInstruction","createPredictRequestBody","prompt","imageFormat","addWatermark","numberOfImages","negativePrompt","aspectRatio","safetyFilterLevel","personFilterLevel","instances","parameters","storageUri","sampleCount","outputOptions","personGeneration","includeRaiReason","VALID_PART_FIELDS","VALID_PARTS_PER_ROLE","user","function","system","VALID_PREVIOUS_CONTENT_ROLES","SILENT_ERROR","ChatSession","_history","_sendPromise","history","validateChatHistory","prevContent","currContent","Array","isArray","countFields","inlineData","functionResponse","validParts","getHistory","sendMessage","newContent","generateContentRequest","safetySettings","generationConfig","tools","toolConfig","_e","finalResult","result","responseContent","blockErrorMessage","sendMessageStream","streamPromise","catch","_ignored","streamResult","assign","GenerativeModel","modelParams","formattedParams","startChat","startChatParams","countTokens","COUNT_TOKENS","ImagenModel","generateImages","PREDICT","generateImagesGCS","Schema","schemaParams","paramKey","nullable","toJSON","obj","prop","OBJECT","array","arrayParams","ArraySchema","items","object","objectParams","ObjectSchema","properties","optionalProperties","string","stringParams","StringSchema","enumString","enum","integer","integerParams","IntegerSchema","number","numberParams","NumberSchema","boolean","booleanParams","BooleanSchema","INTEGER","NUMBER","BOOLEAN","enumValues","STRING","ARRAY","required","propertyKey","ImagenImageFormat","jpeg","compressionQuality","png","getVertexAI","getApp","getModularInstance","_delegate","_getProvider","identifier","getGenerativeModel","getImagenModel","registerVertex","_registerComponent","container","instanceIdentifier","getProvider","registerVersion"],"mappings":"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