"use strict";
/*
 * ATTENTION: An "eval-source-map" devtool has been used.
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
exports.id = "vendor-chunks/@google";
exports.ids = ["vendor-chunks/@google"];
exports.modules = {

/***/ "(action-browser)/./node_modules/@google/generative-ai/dist/index.mjs":
/*!***********************************************************!*\
  !*** ./node_modules/@google/generative-ai/dist/index.mjs ***!
  \***********************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   BlockReason: () => (/* binding */ BlockReason),\n/* harmony export */   ChatSession: () => (/* binding */ ChatSession),\n/* harmony export */   DynamicRetrievalMode: () => (/* binding */ DynamicRetrievalMode),\n/* harmony export */   ExecutableCodeLanguage: () => (/* binding */ ExecutableCodeLanguage),\n/* harmony export */   FinishReason: () => (/* binding */ FinishReason),\n/* harmony export */   FunctionCallingMode: () => (/* binding */ FunctionCallingMode),\n/* harmony export */   GenerativeModel: () => (/* binding */ GenerativeModel),\n/* harmony export */   GoogleGenerativeAI: () => (/* binding */ GoogleGenerativeAI),\n/* harmony export */   GoogleGenerativeAIAbortError: () => (/* binding */ GoogleGenerativeAIAbortError),\n/* harmony export */   GoogleGenerativeAIError: () => (/* binding */ GoogleGenerativeAIError),\n/* harmony export */   GoogleGenerativeAIFetchError: () => (/* binding */ GoogleGenerativeAIFetchError),\n/* harmony export */   GoogleGenerativeAIRequestInputError: () => (/* binding */ GoogleGenerativeAIRequestInputError),\n/* harmony export */   GoogleGenerativeAIResponseError: () => (/* binding */ GoogleGenerativeAIResponseError),\n/* harmony export */   HarmBlockThreshold: () => (/* binding */ HarmBlockThreshold),\n/* harmony export */   HarmCategory: () => (/* binding */ HarmCategory),\n/* harmony export */   HarmProbability: () => (/* binding */ HarmProbability),\n/* harmony export */   Outcome: () => (/* binding */ Outcome),\n/* harmony export */   POSSIBLE_ROLES: () => (/* binding */ POSSIBLE_ROLES),\n/* harmony export */   SchemaType: () => (/* binding */ SchemaType),\n/* harmony export */   TaskType: () => (/* binding */ TaskType)\n/* harmony export */ });\n/**\n * Contains the list of OpenAPI data types\n * as defined by https://swagger.io/docs/specification/data-models/data-types/\n * @public\n */ var SchemaType;\n(function(SchemaType) {\n    /** String type. */ SchemaType[\"STRING\"] = \"string\";\n    /** Number type. */ SchemaType[\"NUMBER\"] = \"number\";\n    /** Integer type. */ SchemaType[\"INTEGER\"] = \"integer\";\n    /** Boolean type. */ SchemaType[\"BOOLEAN\"] = \"boolean\";\n    /** Array type. */ SchemaType[\"ARRAY\"] = \"array\";\n    /** Object type. */ SchemaType[\"OBJECT\"] = \"object\";\n})(SchemaType || (SchemaType = {}));\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 * @public\n */ var ExecutableCodeLanguage;\n(function(ExecutableCodeLanguage) {\n    ExecutableCodeLanguage[\"LANGUAGE_UNSPECIFIED\"] = \"language_unspecified\";\n    ExecutableCodeLanguage[\"PYTHON\"] = \"python\";\n})(ExecutableCodeLanguage || (ExecutableCodeLanguage = {}));\n/**\n * Possible outcomes of code execution.\n * @public\n */ var Outcome;\n(function(Outcome) {\n    /**\n     * Unspecified status. This value should not be used.\n     */ Outcome[\"OUTCOME_UNSPECIFIED\"] = \"outcome_unspecified\";\n    /**\n     * Code execution completed successfully.\n     */ Outcome[\"OUTCOME_OK\"] = \"outcome_ok\";\n    /**\n     * Code execution finished but with a failure. `stderr` should contain the\n     * reason.\n     */ Outcome[\"OUTCOME_FAILED\"] = \"outcome_failed\";\n    /**\n     * Code execution ran for too long, and was cancelled. There may or may not\n     * be a partial output present.\n     */ Outcome[\"OUTCOME_DEADLINE_EXCEEDED\"] = \"outcome_deadline_exceeded\";\n})(Outcome || (Outcome = {}));\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 * Possible roles.\n * @public\n */ const POSSIBLE_ROLES = [\n    \"user\",\n    \"model\",\n    \"function\",\n    \"system\"\n];\n/**\n * Harm categories that would cause prompts or candidates to be blocked.\n * @public\n */ var HarmCategory;\n(function(HarmCategory) {\n    HarmCategory[\"HARM_CATEGORY_UNSPECIFIED\"] = \"HARM_CATEGORY_UNSPECIFIED\";\n    HarmCategory[\"HARM_CATEGORY_HATE_SPEECH\"] = \"HARM_CATEGORY_HATE_SPEECH\";\n    HarmCategory[\"HARM_CATEGORY_SEXUALLY_EXPLICIT\"] = \"HARM_CATEGORY_SEXUALLY_EXPLICIT\";\n    HarmCategory[\"HARM_CATEGORY_HARASSMENT\"] = \"HARM_CATEGORY_HARASSMENT\";\n    HarmCategory[\"HARM_CATEGORY_DANGEROUS_CONTENT\"] = \"HARM_CATEGORY_DANGEROUS_CONTENT\";\n    HarmCategory[\"HARM_CATEGORY_CIVIC_INTEGRITY\"] = \"HARM_CATEGORY_CIVIC_INTEGRITY\";\n})(HarmCategory || (HarmCategory = {}));\n/**\n * Threshold above which a prompt or candidate will be blocked.\n * @public\n */ var HarmBlockThreshold;\n(function(HarmBlockThreshold) {\n    /** Threshold is unspecified. */ HarmBlockThreshold[\"HARM_BLOCK_THRESHOLD_UNSPECIFIED\"] = \"HARM_BLOCK_THRESHOLD_UNSPECIFIED\";\n    /** Content with NEGLIGIBLE will be allowed. */ HarmBlockThreshold[\"BLOCK_LOW_AND_ABOVE\"] = \"BLOCK_LOW_AND_ABOVE\";\n    /** Content with NEGLIGIBLE and LOW will be allowed. */ HarmBlockThreshold[\"BLOCK_MEDIUM_AND_ABOVE\"] = \"BLOCK_MEDIUM_AND_ABOVE\";\n    /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */ HarmBlockThreshold[\"BLOCK_ONLY_HIGH\"] = \"BLOCK_ONLY_HIGH\";\n    /** All content will be allowed. */ HarmBlockThreshold[\"BLOCK_NONE\"] = \"BLOCK_NONE\";\n})(HarmBlockThreshold || (HarmBlockThreshold = {}));\n/**\n * Probability that a prompt or candidate matches a harm category.\n * @public\n */ var HarmProbability;\n(function(HarmProbability) {\n    /** Probability is unspecified. */ HarmProbability[\"HARM_PROBABILITY_UNSPECIFIED\"] = \"HARM_PROBABILITY_UNSPECIFIED\";\n    /** Content has a negligible chance of being unsafe. */ HarmProbability[\"NEGLIGIBLE\"] = \"NEGLIGIBLE\";\n    /** Content has a low chance of being unsafe. */ HarmProbability[\"LOW\"] = \"LOW\";\n    /** Content has a medium chance of being unsafe. */ HarmProbability[\"MEDIUM\"] = \"MEDIUM\";\n    /** Content has a high chance of being unsafe. */ HarmProbability[\"HIGH\"] = \"HIGH\";\n})(HarmProbability || (HarmProbability = {}));\n/**\n * Reason that a prompt was blocked.\n * @public\n */ var BlockReason;\n(function(BlockReason) {\n    // A blocked reason was not specified.\n    BlockReason[\"BLOCKED_REASON_UNSPECIFIED\"] = \"BLOCKED_REASON_UNSPECIFIED\";\n    // Content was blocked by safety settings.\n    BlockReason[\"SAFETY\"] = \"SAFETY\";\n    // Content was blocked, but the reason is uncategorized.\n    BlockReason[\"OTHER\"] = \"OTHER\";\n})(BlockReason || (BlockReason = {}));\n/**\n * Reason that a candidate finished.\n * @public\n */ var FinishReason;\n(function(FinishReason) {\n    // Default value. This value is unused.\n    FinishReason[\"FINISH_REASON_UNSPECIFIED\"] = \"FINISH_REASON_UNSPECIFIED\";\n    // Natural stop point of the model or provided stop sequence.\n    FinishReason[\"STOP\"] = \"STOP\";\n    // The maximum number of tokens as specified in the request was reached.\n    FinishReason[\"MAX_TOKENS\"] = \"MAX_TOKENS\";\n    // The candidate content was flagged for safety reasons.\n    FinishReason[\"SAFETY\"] = \"SAFETY\";\n    // The candidate content was flagged for recitation reasons.\n    FinishReason[\"RECITATION\"] = \"RECITATION\";\n    // The candidate content was flagged for using an unsupported language.\n    FinishReason[\"LANGUAGE\"] = \"LANGUAGE\";\n    // Token generation stopped because the content contains forbidden terms.\n    FinishReason[\"BLOCKLIST\"] = \"BLOCKLIST\";\n    // Token generation stopped for potentially containing prohibited content.\n    FinishReason[\"PROHIBITED_CONTENT\"] = \"PROHIBITED_CONTENT\";\n    // Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n    FinishReason[\"SPII\"] = \"SPII\";\n    // The function call generated by the model is invalid.\n    FinishReason[\"MALFORMED_FUNCTION_CALL\"] = \"MALFORMED_FUNCTION_CALL\";\n    // Unknown reason.\n    FinishReason[\"OTHER\"] = \"OTHER\";\n})(FinishReason || (FinishReason = {}));\n/**\n * Task type for embedding content.\n * @public\n */ var TaskType;\n(function(TaskType) {\n    TaskType[\"TASK_TYPE_UNSPECIFIED\"] = \"TASK_TYPE_UNSPECIFIED\";\n    TaskType[\"RETRIEVAL_QUERY\"] = \"RETRIEVAL_QUERY\";\n    TaskType[\"RETRIEVAL_DOCUMENT\"] = \"RETRIEVAL_DOCUMENT\";\n    TaskType[\"SEMANTIC_SIMILARITY\"] = \"SEMANTIC_SIMILARITY\";\n    TaskType[\"CLASSIFICATION\"] = \"CLASSIFICATION\";\n    TaskType[\"CLUSTERING\"] = \"CLUSTERING\";\n})(TaskType || (TaskType = {}));\n/**\n * @public\n */ var FunctionCallingMode;\n(function(FunctionCallingMode) {\n    // Unspecified function calling mode. This value should not be used.\n    FunctionCallingMode[\"MODE_UNSPECIFIED\"] = \"MODE_UNSPECIFIED\";\n    // Default model behavior, model decides to predict either a function call\n    // or a natural language repspose.\n    FunctionCallingMode[\"AUTO\"] = \"AUTO\";\n    // Model is constrained to always predicting a function call only.\n    // If \"allowed_function_names\" are 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    FunctionCallingMode[\"ANY\"] = \"ANY\";\n    // Model will not predict any function call. Model behavior is same as when\n    // not passing any function declarations.\n    FunctionCallingMode[\"NONE\"] = \"NONE\";\n})(FunctionCallingMode || (FunctionCallingMode = {}));\n/**\n * The mode of the predictor to be used in dynamic retrieval.\n * @public\n */ var DynamicRetrievalMode;\n(function(DynamicRetrievalMode) {\n    // Unspecified function calling mode. This value should not be used.\n    DynamicRetrievalMode[\"MODE_UNSPECIFIED\"] = \"MODE_UNSPECIFIED\";\n    // Run retrieval only when system decides it is necessary.\n    DynamicRetrievalMode[\"MODE_DYNAMIC\"] = \"MODE_DYNAMIC\";\n})(DynamicRetrievalMode || (DynamicRetrievalMode = {}));\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 * Basic error type for this SDK.\n * @public\n */ class GoogleGenerativeAIError extends Error {\n    constructor(message){\n        super(`[GoogleGenerativeAI Error]: ${message}`);\n    }\n}\n/**\n * Errors in the contents of a response from the model. This includes parsing\n * errors, or responses including a safety block reason.\n * @public\n */ class GoogleGenerativeAIResponseError extends GoogleGenerativeAIError {\n    constructor(message, response){\n        super(message);\n        this.response = response;\n    }\n}\n/**\n * Error class covering HTTP errors when calling the server. Includes HTTP\n * status, statusText, and optional details, if provided in the server response.\n * @public\n */ class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {\n    constructor(message, status, statusText, errorDetails){\n        super(message);\n        this.status = status;\n        this.statusText = statusText;\n        this.errorDetails = errorDetails;\n    }\n}\n/**\n * Errors in the contents of a request originating from user input.\n * @public\n */ class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {\n}\n/**\n * Error thrown when a request is aborted, either due to a timeout or\n * intentional cancellation by the user.\n * @public\n */ class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError {\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 */ const DEFAULT_BASE_URL = \"https://generativelanguage.googleapis.com\";\nconst DEFAULT_API_VERSION = \"v1beta\";\n/**\n * We can't `require` package.json if this runs on web. We will use rollup to\n * swap in the version number here at build time.\n */ const PACKAGE_VERSION = \"0.24.1\";\nconst PACKAGE_LOG_HEADER = \"genai-js\";\nvar Task;\n(function(Task) {\n    Task[\"GENERATE_CONTENT\"] = \"generateContent\";\n    Task[\"STREAM_GENERATE_CONTENT\"] = \"streamGenerateContent\";\n    Task[\"COUNT_TOKENS\"] = \"countTokens\";\n    Task[\"EMBED_CONTENT\"] = \"embedContent\";\n    Task[\"BATCH_EMBED_CONTENTS\"] = \"batchEmbedContents\";\n})(Task || (Task = {}));\nclass RequestUrl {\n    constructor(model, task, apiKey, stream, requestOptions){\n        this.model = model;\n        this.task = task;\n        this.apiKey = apiKey;\n        this.stream = stream;\n        this.requestOptions = requestOptions;\n    }\n    toString() {\n        var _a, _b;\n        const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;\n        const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;\n        let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`;\n        if (this.stream) {\n            url += \"?alt=sse\";\n        }\n        return url;\n    }\n}\n/**\n * Simple, but may become more complex if we add more versions to log.\n */ function getClientHeaders(requestOptions) {\n    const clientHeaders = [];\n    if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) {\n        clientHeaders.push(requestOptions.apiClient);\n    }\n    clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`);\n    return clientHeaders.join(\" \");\n}\nasync function getHeaders(url) {\n    var _a;\n    const headers = new Headers();\n    headers.append(\"Content-Type\", \"application/json\");\n    headers.append(\"x-goog-api-client\", getClientHeaders(url.requestOptions));\n    headers.append(\"x-goog-api-key\", url.apiKey);\n    let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders;\n    if (customHeaders) {\n        if (!(customHeaders instanceof Headers)) {\n            try {\n                customHeaders = new Headers(customHeaders);\n            } catch (e) {\n                throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`);\n            }\n        }\n        for (const [headerName, headerValue] of customHeaders.entries()){\n            if (headerName === \"x-goog-api-key\") {\n                throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`);\n            } else if (headerName === \"x-goog-api-client\") {\n                throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`);\n            }\n            headers.append(headerName, headerValue);\n        }\n    }\n    return headers;\n}\nasync function constructModelRequest(model, task, apiKey, stream, body, requestOptions) {\n    const url = new RequestUrl(model, task, apiKey, stream, requestOptions);\n    return {\n        url: url.toString(),\n        fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), {\n            method: \"POST\",\n            headers: await getHeaders(url),\n            body\n        })\n    };\n}\nasync function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, // Allows this to be stubbed for tests\nfetchFn = fetch) {\n    const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions);\n    return makeRequest(url, fetchOptions, fetchFn);\n}\nasync function makeRequest(url, fetchOptions, fetchFn = fetch) {\n    let response;\n    try {\n        response = await fetchFn(url, fetchOptions);\n    } catch (e) {\n        handleResponseError(e, url);\n    }\n    if (!response.ok) {\n        await handleResponseNotOk(response, url);\n    }\n    return response;\n}\nfunction handleResponseError(e, url) {\n    let err = e;\n    if (err.name === \"AbortError\") {\n        err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`);\n        err.stack = e.stack;\n    } else if (!(e instanceof GoogleGenerativeAIFetchError || e instanceof GoogleGenerativeAIRequestInputError)) {\n        err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`);\n        err.stack = e.stack;\n    }\n    throw err;\n}\nasync function handleResponseNotOk(response, url) {\n    let message = \"\";\n    let errorDetails;\n    try {\n        const json = await response.json();\n        message = json.error.message;\n        if (json.error.details) {\n            message += ` ${JSON.stringify(json.error.details)}`;\n            errorDetails = json.error.details;\n        }\n    } catch (e) {\n    // ignored\n    }\n    throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails);\n}\n/**\n * Generates the request options to be passed to the fetch API.\n * @param requestOptions - The user-defined request options.\n * @returns The generated request options.\n */ function buildFetchOptions(requestOptions) {\n    const fetchOptions = {};\n    if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {\n        const controller = new AbortController();\n        if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {\n            setTimeout(()=>controller.abort(), requestOptions.timeout);\n        }\n        if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) {\n            requestOptions.signal.addEventListener(\"abort\", ()=>{\n                controller.abort();\n            });\n        }\n        fetchOptions.signal = controller.signal;\n    }\n    return fetchOptions;\n}\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Adds convenience helper methods to a response object, including stream\n * chunks (as long as each chunk is a complete GenerateContentResponse JSON).\n */ function addHelpers(response) {\n    response.text = ()=>{\n        if (response.candidates && response.candidates.length > 0) {\n            if (response.candidates.length > 1) {\n                console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning text from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`);\n            }\n            if (hadBadFinishReason(response.candidates[0])) {\n                throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);\n            }\n            return getText(response);\n        } else if (response.promptFeedback) {\n            throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response);\n        }\n        return \"\";\n    };\n    /**\n     * TODO: remove at next major version\n     */ response.functionCall = ()=>{\n        if (response.candidates && response.candidates.length > 0) {\n            if (response.candidates.length > 1) {\n                console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning function calls from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`);\n            }\n            if (hadBadFinishReason(response.candidates[0])) {\n                throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);\n            }\n            console.warn(`response.functionCall() is deprecated. ` + `Use response.functionCalls() instead.`);\n            return getFunctionCalls(response)[0];\n        } else if (response.promptFeedback) {\n            throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);\n        }\n        return undefined;\n    };\n    response.functionCalls = ()=>{\n        if (response.candidates && response.candidates.length > 0) {\n            if (response.candidates.length > 1) {\n                console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning function calls from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`);\n            }\n            if (hadBadFinishReason(response.candidates[0])) {\n                throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);\n            }\n            return getFunctionCalls(response);\n        } else if (response.promptFeedback) {\n            throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);\n        }\n        return undefined;\n    };\n    return response;\n}\n/**\n * Returns all text found in all parts of first candidate.\n */ function getText(response) {\n    var _a, _b, _c, _d;\n    const textStrings = [];\n    if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {\n        for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts){\n            if (part.text) {\n                textStrings.push(part.text);\n            }\n            if (part.executableCode) {\n                textStrings.push(\"\\n```\" + part.executableCode.language + \"\\n\" + part.executableCode.code + \"\\n```\\n\");\n            }\n            if (part.codeExecutionResult) {\n                textStrings.push(\"\\n```\\n\" + part.codeExecutionResult.output + \"\\n```\\n\");\n            }\n        }\n    }\n    if (textStrings.length > 0) {\n        return textStrings.join(\"\");\n    } else {\n        return \"\";\n    }\n}\n/**\n * Returns functionCall of first candidate.\n */ function getFunctionCalls(response) {\n    var _a, _b, _c, _d;\n    const functionCalls = [];\n    if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {\n        for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.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}\nconst badFinishReasons = [\n    FinishReason.RECITATION,\n    FinishReason.SAFETY,\n    FinishReason.LANGUAGE\n];\nfunction hadBadFinishReason(candidate) {\n    return !!candidate.finishReason && badFinishReasons.includes(candidate.finishReason);\n}\nfunction formatBlockErrorMessage(response) {\n    var _a, _b, _c;\n    let message = \"\";\n    if ((!response.candidates || response.candidates.length === 0) && response.promptFeedback) {\n        message += \"Response was blocked\";\n        if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) {\n            message += ` due to ${response.promptFeedback.blockReason}`;\n        }\n        if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) {\n            message += `: ${response.promptFeedback.blockReasonMessage}`;\n        }\n    } else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[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/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol */ function __await(v) {\n    return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\nfunction __asyncGenerator(thisArg, _arguments, generator) {\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\n    return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function() {\n        return this;\n    }, i;\n    function verb(n) {\n        if (g[n]) i[n] = function(v) {\n            return new Promise(function(a, b) {\n                q.push([\n                    n,\n                    v,\n                    a,\n                    b\n                ]) > 1 || resume(n, v);\n            });\n        };\n    }\n    function resume(n, v) {\n        try {\n            step(g[n](v));\n        } catch (e) {\n            settle(q[0][3], e);\n        }\n    }\n    function step(r) {\n        r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);\n    }\n    function fulfill(value) {\n        resume(\"next\", value);\n    }\n    function reject(value) {\n        resume(\"throw\", value);\n    }\n    function settle(f, v) {\n        if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);\n    }\n}\ntypeof SuppressedError === \"function\" ? SuppressedError : function(error, suppressed, message) {\n    var e = new Error(message);\n    return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\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 */ const responseLineRE = /^data\\: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\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 */ function processStream(response) {\n    const inputStream = response.body.pipeThrough(new TextDecoderStream(\"utf8\", {\n        fatal: true\n    }));\n    const responseStream = getResponseStream(inputStream);\n    const [stream1, stream2] = responseStream.tee();\n    return {\n        stream: generateResponseSequence(stream1),\n        response: getResponsePromise(stream2)\n    };\n}\nasync function getResponsePromise(stream) {\n    const allResponses = [];\n    const reader = stream.getReader();\n    while(true){\n        const { done, value } = await reader.read();\n        if (done) {\n            return addHelpers(aggregateResponses(allResponses));\n        }\n        allResponses.push(value);\n    }\n}\nfunction generateResponseSequence(stream) {\n    return __asyncGenerator(this, arguments, function* generateResponseSequence_1() {\n        const reader = stream.getReader();\n        while(true){\n            const { value, done } = yield __await(reader.read());\n            if (done) {\n                break;\n            }\n            yield yield __await(addHelpers(value));\n        }\n    });\n}\n/**\n * Reads a raw stream from the fetch response and join incomplete\n * chunks, returning a new stream that provides a single complete\n * GenerateContentResponse in each iteration.\n */ function getResponseStream(inputStream) {\n    const reader = inputStream.getReader();\n    const stream = new ReadableStream({\n        start (controller) {\n            let currentText = \"\";\n            return pump();\n            function pump() {\n                return reader.read().then(({ value, done })=>{\n                    if (done) {\n                        if (currentText.trim()) {\n                            controller.error(new GoogleGenerativeAIError(\"Failed to parse stream\"));\n                            return;\n                        }\n                        controller.close();\n                        return;\n                    }\n                    currentText += value;\n                    let match = currentText.match(responseLineRE);\n                    let parsedResponse;\n                    while(match){\n                        try {\n                            parsedResponse = JSON.parse(match[1]);\n                        } catch (e) {\n                            controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: \"${match[1]}\"`));\n                            return;\n                        }\n                        controller.enqueue(parsedResponse);\n                        currentText = currentText.substring(match[0].length);\n                        match = currentText.match(responseLineRE);\n                    }\n                    return pump();\n                }).catch((e)=>{\n                    let err = e;\n                    err.stack = e.stack;\n                    if (err.name === \"AbortError\") {\n                        err = new GoogleGenerativeAIAbortError(\"Request aborted when reading from the stream\");\n                    } else {\n                        err = new GoogleGenerativeAIError(\"Error reading from the stream\");\n                    }\n                    throw err;\n                });\n            }\n        }\n    });\n    return stream;\n}\n/**\n * Aggregates an array of `GenerateContentResponse`s into a single\n * GenerateContentResponse.\n */ function aggregateResponses(responses) {\n    const lastResponse = responses[responses.length - 1];\n    const aggregatedResponse = {\n        promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback\n    };\n    for (const response of responses){\n        if (response.candidates) {\n            let candidateIndex = 0;\n            for (const candidate of response.candidates){\n                if (!aggregatedResponse.candidates) {\n                    aggregatedResponse.candidates = [];\n                }\n                if (!aggregatedResponse.candidates[candidateIndex]) {\n                    aggregatedResponse.candidates[candidateIndex] = {\n                        index: candidateIndex\n                    };\n                }\n                // Keep overwriting, the last one will be final\n                aggregatedResponse.candidates[candidateIndex].citationMetadata = candidate.citationMetadata;\n                aggregatedResponse.candidates[candidateIndex].groundingMetadata = candidate.groundingMetadata;\n                aggregatedResponse.candidates[candidateIndex].finishReason = candidate.finishReason;\n                aggregatedResponse.candidates[candidateIndex].finishMessage = candidate.finishMessage;\n                aggregatedResponse.candidates[candidateIndex].safetyRatings = candidate.safetyRatings;\n                /**\n                 * Candidates should always have content and parts, but this handles\n                 * possible malformed responses.\n                 */ if (candidate.content && candidate.content.parts) {\n                    if (!aggregatedResponse.candidates[candidateIndex].content) {\n                        aggregatedResponse.candidates[candidateIndex].content = {\n                            role: candidate.content.role || \"user\",\n                            parts: []\n                        };\n                    }\n                    const newPart = {};\n                    for (const part of candidate.content.parts){\n                        if (part.text) {\n                            newPart.text = part.text;\n                        }\n                        if (part.functionCall) {\n                            newPart.functionCall = part.functionCall;\n                        }\n                        if (part.executableCode) {\n                            newPart.executableCode = part.executableCode;\n                        }\n                        if (part.codeExecutionResult) {\n                            newPart.codeExecutionResult = part.codeExecutionResult;\n                        }\n                        if (Object.keys(newPart).length === 0) {\n                            newPart.text = \"\";\n                        }\n                        aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart);\n                    }\n                }\n            }\n            candidateIndex++;\n        }\n        if (response.usageMetadata) {\n            aggregatedResponse.usageMetadata = response.usageMetadata;\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 */ async function generateContentStream(apiKey, model, params, requestOptions) {\n    const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey, /* stream */ true, JSON.stringify(params), requestOptions);\n    return processStream(response);\n}\nasync function generateContent(apiKey, model, params, requestOptions) {\n    const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey, /* stream */ false, JSON.stringify(params), requestOptions);\n    const responseJson = await response.json();\n    const enhancedResponse = addHelpers(responseJson);\n    return {\n        response: enhancedResponse\n    };\n}\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function formatSystemInstruction(input) {\n    // null or undefined\n    if (input == null) {\n        return undefined;\n    } else if (typeof input === \"string\") {\n        return {\n            role: \"system\",\n            parts: [\n                {\n                    text: input\n                }\n            ]\n        };\n    } else if (input.text) {\n        return {\n            role: \"system\",\n            parts: [\n                input\n            ]\n        };\n    } else if (input.parts) {\n        if (!input.role) {\n            return {\n                role: \"system\",\n                parts: input.parts\n            };\n        } else {\n            return input;\n        }\n    }\n}\nfunction formatNewContent(request) {\n    let newParts = [];\n    if (typeof request === \"string\") {\n        newParts = [\n            {\n                text: request\n            }\n        ];\n    } else {\n        for (const partOrString of request){\n            if (typeof partOrString === \"string\") {\n                newParts.push({\n                    text: partOrString\n                });\n            } else {\n                newParts.push(partOrString);\n            }\n        }\n    }\n    return assignRoleToPartsAndValidateSendMessageRequest(newParts);\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 */ function assignRoleToPartsAndValidateSendMessageRequest(parts) {\n    const userContent = {\n        role: \"user\",\n        parts: []\n    };\n    const functionContent = {\n        role: \"function\",\n        parts: []\n    };\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    if (hasUserContent && hasFunctionContent) {\n        throw new GoogleGenerativeAIError(\"Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.\");\n    }\n    if (!hasUserContent && !hasFunctionContent) {\n        throw new GoogleGenerativeAIError(\"No content is provided for sending chat message.\");\n    }\n    if (hasUserContent) {\n        return userContent;\n    }\n    return functionContent;\n}\nfunction formatCountTokensInput(params, modelParams) {\n    var _a;\n    let formattedGenerateContentRequest = {\n        model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model,\n        generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig,\n        safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings,\n        tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools,\n        toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig,\n        systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction,\n        cachedContent: (_a = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a === void 0 ? void 0 : _a.name,\n        contents: []\n    };\n    const containsGenerateContentRequest = params.generateContentRequest != null;\n    if (params.contents) {\n        if (containsGenerateContentRequest) {\n            throw new GoogleGenerativeAIRequestInputError(\"CountTokensRequest must have one of contents or generateContentRequest, not both.\");\n        }\n        formattedGenerateContentRequest.contents = params.contents;\n    } else if (containsGenerateContentRequest) {\n        formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest);\n    } else {\n        // Array or string\n        const content = formatNewContent(params);\n        formattedGenerateContentRequest.contents = [\n            content\n        ];\n    }\n    return {\n        generateContentRequest: formattedGenerateContentRequest\n    };\n}\nfunction formatGenerateContentInput(params) {\n    let formattedRequest;\n    if (params.contents) {\n        formattedRequest = params;\n    } else {\n        // Array or string\n        const content = formatNewContent(params);\n        formattedRequest = {\n            contents: [\n                content\n            ]\n        };\n    }\n    if (params.systemInstruction) {\n        formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction);\n    }\n    return formattedRequest;\n}\nfunction formatEmbedContentInput(params) {\n    if (typeof params === \"string\" || Array.isArray(params)) {\n        const content = formatNewContent(params);\n        return {\n            content\n        };\n    }\n    return params;\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 */ // https://ai.google.dev/api/rest/v1beta/Content#part\nconst VALID_PART_FIELDS = [\n    \"text\",\n    \"inlineData\",\n    \"functionCall\",\n    \"functionResponse\",\n    \"executableCode\",\n    \"codeExecutionResult\"\n];\nconst VALID_PARTS_PER_ROLE = {\n    user: [\n        \"text\",\n        \"inlineData\"\n    ],\n    function: [\n        \"functionResponse\"\n    ],\n    model: [\n        \"text\",\n        \"functionCall\",\n        \"executableCode\",\n        \"codeExecutionResult\"\n    ],\n    // System instructions shouldn't be in history anyway.\n    system: [\n        \"text\"\n    ]\n};\nfunction validateChatHistory(history) {\n    let prevContent = false;\n    for (const currContent of history){\n        const { role, parts } = currContent;\n        if (!prevContent && role !== \"user\") {\n            throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`);\n        }\n        if (!POSSIBLE_ROLES.includes(role)) {\n            throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`);\n        }\n        if (!Array.isArray(parts)) {\n            throw new GoogleGenerativeAIError(\"Content should have 'parts' property with an array of Parts\");\n        }\n        if (parts.length === 0) {\n            throw new GoogleGenerativeAIError(\"Each Content should have at least one part\");\n        }\n        const countFields = {\n            text: 0,\n            inlineData: 0,\n            functionCall: 0,\n            functionResponse: 0,\n            fileData: 0,\n            executableCode: 0,\n            codeExecutionResult: 0\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 GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`);\n            }\n        }\n        prevContent = true;\n    }\n}\n/**\n * Returns true if the response is valid (could be appended to the history), flase otherwise.\n */ function isValidResponse(response) {\n    var _a;\n    if (response.candidates === undefined || response.candidates.length === 0) {\n        return false;\n    }\n    const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content;\n    if (content === undefined) {\n        return false;\n    }\n    if (content.parts === undefined || content.parts.length === 0) {\n        return false;\n    }\n    for (const part of content.parts){\n        if (part === undefined || Object.keys(part).length === 0) {\n            return false;\n        }\n        if (part.text !== undefined && part.text === \"\") {\n            return false;\n        }\n    }\n    return true;\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 * Do not log a message for this error.\n */ const SILENT_ERROR = \"SILENT_ERROR\";\n/**\n * ChatSession class that enables sending chat messages and stores\n * history of sent and received messages so far.\n *\n * @public\n */ class ChatSession {\n    constructor(apiKey, model, params, _requestOptions = {}){\n        this.model = model;\n        this.params = params;\n        this._requestOptions = _requestOptions;\n        this._history = [];\n        this._sendPromise = Promise.resolve();\n        this._apiKey = apiKey;\n        if (params === null || params === void 0 ? void 0 : params.history) {\n            validateChatHistory(params.history);\n            this._history = params.history;\n        }\n    }\n    /**\n     * Gets the chat history so far. Blocked prompts are not added to history.\n     * Blocked candidates are not added to history, nor are the prompts that\n     * generated them.\n     */ async getHistory() {\n        await this._sendPromise;\n        return this._history;\n    }\n    /**\n     * Sends a chat message and receives a non-streaming\n     * {@link GenerateContentResult}.\n     *\n     * Fields set in the optional {@link SingleRequestOptions} parameter will\n     * take precedence over the {@link RequestOptions} values provided to\n     * {@link GoogleGenerativeAI.getGenerativeModel }.\n     */ async sendMessage(request, requestOptions = {}) {\n        var _a, _b, _c, _d, _e, _f;\n        await this._sendPromise;\n        const newContent = formatNewContent(request);\n        const generateContentRequest = {\n            safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,\n            generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,\n            tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,\n            toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,\n            systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,\n            cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,\n            contents: [\n                ...this._history,\n                newContent\n            ]\n        };\n        const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n        let finalResult;\n        // Add onto the chain.\n        this._sendPromise = this._sendPromise.then(()=>generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions)).then((result)=>{\n            var _a;\n            if (isValidResponse(result.response)) {\n                this._history.push(newContent);\n                const responseContent = Object.assign({\n                    parts: [],\n                    // Response seems to come back without a role set.\n                    role: \"model\"\n                }, (_a = result.response.candidates) === null || _a === void 0 ? void 0 : _a[0].content);\n                this._history.push(responseContent);\n            } else {\n                const blockErrorMessage = formatBlockErrorMessage(result.response);\n                if (blockErrorMessage) {\n                    console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);\n                }\n            }\n            finalResult = result;\n        }).catch((e)=>{\n            // Resets _sendPromise to avoid subsequent calls failing and throw error.\n            this._sendPromise = Promise.resolve();\n            throw e;\n        });\n        await this._sendPromise;\n        return finalResult;\n    }\n    /**\n     * Sends a chat message and receives the response as a\n     * {@link GenerateContentStreamResult} containing an iterable stream\n     * and a response promise.\n     *\n     * Fields set in the optional {@link SingleRequestOptions} parameter will\n     * take precedence over the {@link RequestOptions} values provided to\n     * {@link GoogleGenerativeAI.getGenerativeModel }.\n     */ async sendMessageStream(request, requestOptions = {}) {\n        var _a, _b, _c, _d, _e, _f;\n        await this._sendPromise;\n        const newContent = formatNewContent(request);\n        const generateContentRequest = {\n            safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,\n            generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,\n            tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,\n            toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,\n            systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,\n            cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,\n            contents: [\n                ...this._history,\n                newContent\n            ]\n        };\n        const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n        const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions);\n        // Add onto the chain.\n        this._sendPromise = this._sendPromise.then(()=>streamPromise)// 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        }).then((streamResult)=>streamResult.response).then((response)=>{\n            if (isValidResponse(response)) {\n                this._history.push(newContent);\n                const responseContent = Object.assign({}, response.candidates[0].content);\n                // Response seems to come back without a role set.\n                if (!responseContent.role) {\n                    responseContent.role = \"model\";\n                }\n                this._history.push(responseContent);\n            } else {\n                const blockErrorMessage = formatBlockErrorMessage(response);\n                if (blockErrorMessage) {\n                    console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);\n                }\n            }\n        }).catch((e)=>{\n            // Errors in streamPromise are already catchable by the user as\n            // streamPromise is returned.\n            // Avoid duplicating the error message in logs.\n            if (e.message !== SILENT_ERROR) {\n                // Users do not have access to _sendPromise to catch errors\n                // downstream from streamPromise, so they should not throw.\n                console.error(e);\n            }\n        });\n        return streamPromise;\n    }\n}\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ async function countTokens(apiKey, model, params, singleRequestOptions) {\n    const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions);\n    return response.json();\n}\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ async function embedContent(apiKey, model, params, requestOptions) {\n    const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions);\n    return response.json();\n}\nasync function batchEmbedContents(apiKey, model, params, requestOptions) {\n    const requestsWithModel = params.requests.map((request)=>{\n        return Object.assign(Object.assign({}, request), {\n            model\n        });\n    });\n    const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({\n        requests: requestsWithModel\n    }), requestOptions);\n    return response.json();\n}\n/**\n * @license\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ /**\n * Class for generative model APIs.\n * @public\n */ class GenerativeModel {\n    constructor(apiKey, modelParams, _requestOptions = {}){\n        this.apiKey = apiKey;\n        this._requestOptions = _requestOptions;\n        if (modelParams.model.includes(\"/\")) {\n            // Models may be named \"models/model-name\" or \"tunedModels/model-name\"\n            this.model = modelParams.model;\n        } else {\n            // If path is not included, assume it's a non-tuned model.\n            this.model = `models/${modelParams.model}`;\n        }\n        this.generationConfig = modelParams.generationConfig || {};\n        this.safetySettings = modelParams.safetySettings || [];\n        this.tools = modelParams.tools;\n        this.toolConfig = modelParams.toolConfig;\n        this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);\n        this.cachedContent = modelParams.cachedContent;\n    }\n    /**\n     * Makes a single non-streaming call to the model\n     * and returns an object containing a single {@link GenerateContentResponse}.\n     *\n     * Fields set in the optional {@link SingleRequestOptions} parameter will\n     * take precedence over the {@link RequestOptions} values provided to\n     * {@link GoogleGenerativeAI.getGenerativeModel }.\n     */ async generateContent(request, requestOptions = {}) {\n        var _a;\n        const formattedParams = formatGenerateContentInput(request);\n        const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n        return generateContent(this.apiKey, this.model, Object.assign({\n            generationConfig: this.generationConfig,\n            safetySettings: this.safetySettings,\n            tools: this.tools,\n            toolConfig: this.toolConfig,\n            systemInstruction: this.systemInstruction,\n            cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name\n        }, formattedParams), generativeModelRequestOptions);\n    }\n    /**\n     * Makes a single streaming call to the model and returns an object\n     * containing an iterable stream that iterates over all chunks in the\n     * streaming response as well as a promise that returns the final\n     * aggregated response.\n     *\n     * Fields set in the optional {@link SingleRequestOptions} parameter will\n     * take precedence over the {@link RequestOptions} values provided to\n     * {@link GoogleGenerativeAI.getGenerativeModel }.\n     */ async generateContentStream(request, requestOptions = {}) {\n        var _a;\n        const formattedParams = formatGenerateContentInput(request);\n        const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n        return generateContentStream(this.apiKey, this.model, Object.assign({\n            generationConfig: this.generationConfig,\n            safetySettings: this.safetySettings,\n            tools: this.tools,\n            toolConfig: this.toolConfig,\n            systemInstruction: this.systemInstruction,\n            cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name\n        }, formattedParams), generativeModelRequestOptions);\n    }\n    /**\n     * Gets a new {@link ChatSession} instance which can be used for\n     * multi-turn chats.\n     */ startChat(startChatParams) {\n        var _a;\n        return new ChatSession(this.apiKey, this.model, Object.assign({\n            generationConfig: this.generationConfig,\n            safetySettings: this.safetySettings,\n            tools: this.tools,\n            toolConfig: this.toolConfig,\n            systemInstruction: this.systemInstruction,\n            cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name\n        }, startChatParams), this._requestOptions);\n    }\n    /**\n     * Counts the tokens in the provided request.\n     *\n     * Fields set in the optional {@link SingleRequestOptions} parameter will\n     * take precedence over the {@link RequestOptions} values provided to\n     * {@link GoogleGenerativeAI.getGenerativeModel }.\n     */ async countTokens(request, requestOptions = {}) {\n        const formattedParams = formatCountTokensInput(request, {\n            model: this.model,\n            generationConfig: this.generationConfig,\n            safetySettings: this.safetySettings,\n            tools: this.tools,\n            toolConfig: this.toolConfig,\n            systemInstruction: this.systemInstruction,\n            cachedContent: this.cachedContent\n        });\n        const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n        return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);\n    }\n    /**\n     * Embeds the provided content.\n     *\n     * Fields set in the optional {@link SingleRequestOptions} parameter will\n     * take precedence over the {@link RequestOptions} values provided to\n     * {@link GoogleGenerativeAI.getGenerativeModel }.\n     */ async embedContent(request, requestOptions = {}) {\n        const formattedParams = formatEmbedContentInput(request);\n        const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n        return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);\n    }\n    /**\n     * Embeds an array of {@link EmbedContentRequest}s.\n     *\n     * Fields set in the optional {@link SingleRequestOptions} parameter will\n     * take precedence over the {@link RequestOptions} values provided to\n     * {@link GoogleGenerativeAI.getGenerativeModel }.\n     */ async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) {\n        const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);\n        return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions);\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 * Top-level class for this SDK\n * @public\n */ class GoogleGenerativeAI {\n    constructor(apiKey){\n        this.apiKey = apiKey;\n    }\n    /**\n     * Gets a {@link GenerativeModel} instance for the provided model name.\n     */ getGenerativeModel(modelParams, requestOptions) {\n        if (!modelParams.model) {\n            throw new GoogleGenerativeAIError(`Must provide a model name. ` + `Example: genai.getGenerativeModel({ model: 'my-model-name' })`);\n        }\n        return new GenerativeModel(this.apiKey, modelParams, requestOptions);\n    }\n    /**\n     * Creates a {@link GenerativeModel} instance from provided content cache.\n     */ getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) {\n        if (!cachedContent.name) {\n            throw new GoogleGenerativeAIRequestInputError(\"Cached content must contain a `name` field.\");\n        }\n        if (!cachedContent.model) {\n            throw new GoogleGenerativeAIRequestInputError(\"Cached content must contain a `model` field.\");\n        }\n        /**\n         * Not checking tools and toolConfig for now as it would require a deep\n         * equality comparison and isn't likely to be a common case.\n         */ const disallowedDuplicates = [\n            \"model\",\n            \"systemInstruction\"\n        ];\n        for (const key of disallowedDuplicates){\n            if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) && cachedContent[key] && (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) {\n                if (key === \"model\") {\n                    const modelParamsComp = modelParams.model.startsWith(\"models/\") ? modelParams.model.replace(\"models/\", \"\") : modelParams.model;\n                    const cachedContentComp = cachedContent.model.startsWith(\"models/\") ? cachedContent.model.replace(\"models/\", \"\") : cachedContent.model;\n                    if (modelParamsComp === cachedContentComp) {\n                        continue;\n                    }\n                }\n                throw new GoogleGenerativeAIRequestInputError(`Different value for \"${key}\" specified in modelParams` + ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`);\n            }\n        }\n        const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), {\n            model: cachedContent.model,\n            tools: cachedContent.tools,\n            toolConfig: cachedContent.toolConfig,\n            systemInstruction: cachedContent.systemInstruction,\n            cachedContent\n        });\n        return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions);\n    }\n}\n //# sourceMappingURL=index.mjs.map\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 135840 characters]\n//# sourceURL=webpack-internal:///(action-browser)/./node_modules/@google/generative-ai/dist/index.mjs\n");

/***/ })

};
;