UNPKG

firebase

Version:

Firebase JavaScript library for web and Node.js

4 lines (2 loc) • 28.3 kB
import{_isFirebaseServerApp as e,_getProvider,getApp as t,_registerComponent as n,registerVersion as s}from"https://www.gstatic.com/firebasejs/11.7.1/firebase-app.js";class FirebaseError extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},s=`${this.service}/${e}`,r=this.errors[e],i=r?function replaceTemplate(e,t){return e.replace(o,((e,n)=>{const s=t[n];return null!=s?String(s):`<${n}?>`}))}(r,n):"Error",a=`${this.serviceName}: ${i} (${s}).`;return new FirebaseError(s,a,n)}}const o=/\{\$([^}]+)}/g;class Component{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var r;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(r||(r={}));const i={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},a=r.INFO,c={[r.DEBUG]:"log",[r.VERBOSE]:"log",[r.INFO]:"info",[r.WARN]:"warn",[r.ERROR]:"error"},defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),o=c[t];if(!o)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[o](`[${s}] ${e.name}:`,...n)};function __await(e){return this instanceof __await?(this.v=e,this):new __await(e)}function __asyncGenerator(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,o=n.apply(e,t||[]),r=[];return s=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",(function awaitReturn(e){return function(t){return Promise.resolve(t).then(e,reject)}})),s[Symbol.asyncIterator]=function(){return this},s;function verb(e,t){o[e]&&(s[e]=function(t){return new Promise((function(n,s){r.push([e,t,n,s])>1||resume(e,t)}))},t&&(s[e]=t(s[e])))}function resume(e,t){try{!function step(e){e.value instanceof __await?Promise.resolve(e.value.v).then(fulfill,reject):settle(r[0][2],e)}(o[e](t))}catch(e){settle(r[0][3],e)}}function fulfill(e){resume("next",e)}function reject(e){resume("throw",e)}function settle(e,t){e(t),r.shift(),r.length&&resume(r[0][0],r[0][1])}}"function"==typeof SuppressedError&&SuppressedError;var l="@firebase/vertexai",d="1.2.2";const u="vertexAI",p="us-central1",h=d;class VertexAIService{constructor(e,t,n,s){var o;this.app=e,this.options=s;const r=null==n?void 0:n.getImmediate({optional:!0}),i=null==t?void 0:t.getImmediate({optional:!0});this.auth=i||null,this.appCheck=r||null,this.location=(null===(o=this.options)||void 0===o?void 0:o.location)||p}_delete(){return Promise.resolve()}}class VertexAIError extends FirebaseError{constructor(e,t,n){const s=`VertexAI: ${t} (${`${u}/${e}`})`;super(e,s),this.code=e,this.customErrorData=n,Error.captureStackTrace&&Error.captureStackTrace(this,VertexAIError),Object.setPrototypeOf(this,VertexAIError.prototype),this.toString=()=>s}}class VertexAIModel{constructor(t,n){var s,o,r,i,a,c;if(this.model=VertexAIModel.normalizeModelName(n),!(null===(o=null===(s=t.app)||void 0===s?void 0:s.options)||void 0===o?void 0:o.apiKey))throw new VertexAIError("no-api-key",'The "apiKey" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid API key.');if(!(null===(i=null===(r=t.app)||void 0===r?void 0:r.options)||void 0===i?void 0:i.projectId))throw new VertexAIError("no-project-id",'The "projectId" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid project ID.');if(!(null===(c=null===(a=t.app)||void 0===a?void 0:a.options)||void 0===c?void 0:c.appId))throw new VertexAIError("no-app-id",'The "appId" field is empty in the local Firebase config. Firebase VertexAI requires this field to contain a valid app ID.');if(this._apiSettings={apiKey:t.app.options.apiKey,project:t.app.options.projectId,appId:t.app.options.appId,automaticDataCollectionEnabled:t.app.automaticDataCollectionEnabled,location:t.location},e(t.app)&&t.app.settings.appCheckToken){const e=t.app.settings.appCheckToken;this._apiSettings.getAppCheckToken=()=>Promise.resolve({token:e})}else t.appCheck&&(this._apiSettings.getAppCheckToken=()=>t.appCheck.getToken());t.auth&&(this._apiSettings.getAuthToken=()=>t.auth.getToken())}static normalizeModelName(e){let t;return t=e.includes("/")?e.startsWith("models/")?`publishers/google/${e}`:e:`publishers/google/models/${e}`,t}}const g=new class Logger{constructor(e){this.name=e,this._logLevel=a,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in r))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?i[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,r.DEBUG,...e),this._logHandler(this,r.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,r.VERBOSE,...e),this._logHandler(this,r.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,r.INFO,...e),this._logHandler(this,r.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,r.WARN,...e),this._logHandler(this,r.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,r.ERROR,...e),this._logHandler(this,r.ERROR,...e)}}("@firebase/vertexai");var f;!function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.PREDICT="predict"}(f||(f={}));class RequestUrl{constructor(e,t,n,s,o){this.model=e,this.task=t,this.apiSettings=n,this.stream=s,this.requestOptions=o}toString(){var e;let t=`${(null===(e=this.requestOptions)||void 0===e?void 0:e.baseUrl)||"https://firebasevertexai.googleapis.com"}/v1beta`;return t+=`/projects/${this.apiSettings.project}`,t+=`/locations/${this.apiSettings.location}`,t+=`/${this.model}`,t+=`:${this.task}`,this.stream&&(t+="?alt=sse"),t}get fullModelString(){let e=`projects/${this.apiSettings.project}`;return e+=`/locations/${this.apiSettings.location}`,e+=`/${this.model}`,e}}async function getHeaders(e){const t=new Headers;if(t.append("Content-Type","application/json"),t.append("x-goog-api-client",function getClientHeaders(){const e=[];return e.push(`gl-js/${h}`),e.push(`fire/${h}`),e.join(" ")}()),t.append("x-goog-api-key",e.apiSettings.apiKey),e.apiSettings.automaticDataCollectionEnabled&&t.append("X-Firebase-Appid",e.apiSettings.appId),e.apiSettings.getAppCheckToken){const n=await e.apiSettings.getAppCheckToken();n&&(t.append("X-Firebase-AppCheck",n.token),n.error&&g.warn(`Unable to obtain a valid App Check token: ${n.error.message}`))}if(e.apiSettings.getAuthToken){const n=await e.apiSettings.getAuthToken();n&&t.append("Authorization",`Firebase ${n.accessToken}`)}return t}async function makeRequest(e,t,n,s,o,r){const i=new RequestUrl(e,t,n,s,r);let a,c;try{const l=await async function constructRequest(e,t,n,s,o,r){const i=new RequestUrl(e,t,n,s,r);return{url:i.toString(),fetchOptions:{method:"POST",headers:await getHeaders(i),body:o}}}(e,t,n,s,o,r),d=null!=(null==r?void 0:r.timeout)&&r.timeout>=0?r.timeout:18e4,u=new AbortController;if(c=setTimeout((()=>u.abort()),d),l.fetchOptions.signal=u.signal,a=await fetch(l.url,l.fetchOptions),!a.ok){let e,t="";try{const n=await a.json();t=n.error.message,n.error.details&&(t+=` ${JSON.stringify(n.error.details)}`,e=n.error.details)}catch(e){}if(403===a.status&&e.some((e=>"SERVICE_DISABLED"===e.reason))&&e.some((e=>{var t,n;return null===(n=null===(t=e.links)||void 0===t?void 0:t[0])||void 0===n?void 0:n.description.includes("Google developers console API activation")})))throw new VertexAIError("api-not-enabled",`The Vertex AI in Firebase SDK requires the Vertex AI in Firebase API ('firebasevertexai.googleapis.com') to be enabled in your Firebase project. Enable this API by visiting the Firebase Console at https://console.firebase.google.com/project/${i.apiSettings.project}/genai/ and clicking "Get started". If you enabled this API recently, wait a few minutes for the action to propagate to our systems and then retry.`,{status:a.status,statusText:a.statusText,errorDetails:e});throw new VertexAIError("fetch-error",`Error fetching from ${i}: [${a.status} ${a.statusText}] ${t}`,{status:a.status,statusText:a.statusText,errorDetails:e})}}catch(e){let t=e;throw"fetch-error"!==e.code&&"api-not-enabled"!==e.code&&e instanceof Error&&(t=new VertexAIError("error",`Error fetching from ${i.toString()}: ${e.message}`),t.stack=e.stack),t}finally{c&&clearTimeout(c)}return a}const m=["user","model","function","system"];var E,I,y,S,O,v,R,_,A,T,C,w,b;function createEnhancedContentResponse(e){e.candidates&&!e.candidates[0].hasOwnProperty("index")&&(e.candidates[0].index=0);const t=function addHelpers(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&g.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(e.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(e)}. Response body stored in error.response`,{response:e});return function getText(e){var t,n,s,o;const r=[];if(null===(n=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===n?void 0:n.parts)for(const t of null===(o=null===(s=e.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)t.text&&r.push(t.text);return r.length>0?r.join(""):""}(e)}if(e.promptFeedback)throw new VertexAIError("response-error",`Text not available. ${formatBlockErrorMessage(e)}`,{response:e});return""},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&g.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),hadBadFinishReason(e.candidates[0]))throw new VertexAIError("response-error",`Response error: ${formatBlockErrorMessage(e)}. Response body stored in error.response`,{response:e});return function getFunctionCalls(e){var t,n,s,o;const r=[];if(null===(n=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===n?void 0:n.parts)for(const t of null===(o=null===(s=e.candidates)||void 0===s?void 0:s[0].content)||void 0===o?void 0:o.parts)t.functionCall&&r.push(t.functionCall);return r.length>0?r:void 0}(e)}if(e.promptFeedback)throw new VertexAIError("response-error",`Function call not available. ${formatBlockErrorMessage(e)}`,{response:e})},e}(e);return t}!function(e){e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT"}(E||(E={})),function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"}(I||(I={})),function(e){e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"}(y||(y={})),function(e){e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(S||(S={})),function(e){e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"}(O||(O={})),function(e){e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT"}(v||(v={})),function(e){e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL"}(R||(R={})),function(e){e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"}(_||(_={})),function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"}(A||(A={})),function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"}(T||(T={})),function(e){e.BLOCK_LOW_AND_ABOVE="block_low_and_above",e.BLOCK_MEDIUM_AND_ABOVE="block_medium_and_above",e.BLOCK_ONLY_HIGH="block_only_high",e.BLOCK_NONE="block_none"}(C||(C={})),function(e){e.BLOCK_ALL="dont_allow",e.ALLOW_ADULT="allow_adult",e.ALLOW_ALL="allow_all"}(w||(w={})),function(e){e.SQUARE="1:1",e.LANDSCAPE_3x4="3:4",e.PORTRAIT_4x3="4:3",e.LANDSCAPE_16x9="16:9",e.PORTRAIT_9x16="9:16"}(b||(b={}));const N=[R.RECITATION,R.SAFETY];function hadBadFinishReason(e){return!!e.finishReason&&N.includes(e.finishReason)}function formatBlockErrorMessage(e){var t,n,s;let o="";if(e.candidates&&0!==e.candidates.length||!e.promptFeedback){if(null===(s=e.candidates)||void 0===s?void 0:s[0]){const t=e.candidates[0];hadBadFinishReason(t)&&(o+=`Candidate was blocked due to ${t.finishReason}`,t.finishMessage&&(o+=`: ${t.finishMessage}`))}}else o+="Response was blocked",(null===(t=e.promptFeedback)||void 0===t?void 0:t.blockReason)&&(o+=` due to ${e.promptFeedback.blockReason}`),(null===(n=e.promptFeedback)||void 0===n?void 0:n.blockReasonMessage)&&(o+=`: ${e.promptFeedback.blockReasonMessage}`);return o}async function handlePredictResponse(e){var t;const n=await e.json(),s=[];let o;if(!n.predictions||0===(null===(t=n.predictions)||void 0===t?void 0:t.length))throw new VertexAIError("response-error","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.");for(const e of n.predictions)if(e.raiFilteredReason)o=e.raiFilteredReason;else if(e.mimeType&&e.bytesBase64Encoded)s.push({mimeType:e.mimeType,bytesBase64Encoded:e.bytesBase64Encoded});else{if(!e.mimeType||!e.gcsUri)throw new VertexAIError("response-error",`Predictions array in response has missing properties. Response: ${JSON.stringify(n)}`);s.push({mimeType:e.mimeType,gcsURI:e.gcsUri})}return{images:s,filteredReason:o}}const x=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function processStream(e){const t=function getResponseStream(e){const t=e.getReader();return new ReadableStream({start(e){let n="";return pump();function pump(){return t.read().then((({value:t,done:s})=>{if(s)return n.trim()?void e.error(new VertexAIError("parse-failed","Failed to parse stream")):void e.close();n+=t;let o,r=n.match(x);for(;r;){try{o=JSON.parse(r[1])}catch(t){return void e.error(new VertexAIError("parse-failed",`Error parsing JSON response: "${r[1]}`))}e.enqueue(o),n=n.substring(r[0].length),r=n.match(x)}return pump()}))}}})}(e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))),[n,s]=t.tee();return{stream:generateResponseSequence(n),response:getResponsePromise(s)}}async function getResponsePromise(e){const t=[],n=e.getReader();for(;;){const{done:e,value:s}=await n.read();if(e){return createEnhancedContentResponse(aggregateResponses(t))}t.push(s)}}function generateResponseSequence(e){return __asyncGenerator(this,arguments,(function*generateResponseSequence_1(){const t=e.getReader();for(;;){const{value:e,done:n}=yield __await(t.read());if(n)break;const s=createEnhancedContentResponse(e);yield yield __await(s)}}))}function aggregateResponses(e){const t=e[e.length-1],n={promptFeedback:null==t?void 0:t.promptFeedback};for(const t of e)if(t.candidates)for(const e of t.candidates){const t=e.index||0;if(n.candidates||(n.candidates=[]),n.candidates[t]||(n.candidates[t]={index:e.index}),n.candidates[t].citationMetadata=e.citationMetadata,n.candidates[t].finishReason=e.finishReason,n.candidates[t].finishMessage=e.finishMessage,n.candidates[t].safetyRatings=e.safetyRatings,e.content&&e.content.parts){n.candidates[t].content||(n.candidates[t].content={role:e.content.role||"user",parts:[]});const s={};for(const o of e.content.parts){if(void 0!==o.text){if(""===o.text)continue;s.text=o.text}if(o.functionCall&&(s.functionCall=o.functionCall),0===Object.keys(s).length)throw new VertexAIError("invalid-content","Part should have at least one property, but there are none. This is likely caused by a malformed response from the backend.");n.candidates[t].content.parts.push(s)}}}return n}async function generateContentStream(e,t,n,s){return processStream(await makeRequest(t,f.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),s))}async function generateContent(e,t,n,s){const o=await makeRequest(t,f.GENERATE_CONTENT,e,!1,JSON.stringify(n),s);return{response:createEnhancedContentResponse(await o.json())}}function formatSystemInstruction(e){if(null!=e)return"string"==typeof e?{role:"system",parts:[{text:e}]}:e.text?{role:"system",parts:[e]}:e.parts?e.role?e:{role:"system",parts:e.parts}:void 0}function formatNewContent(e){let t=[];if("string"==typeof e)t=[{text:e}];else for(const n of e)"string"==typeof n?t.push({text:n}):t.push(n);return function assignRoleToPartsAndValidateSendMessageRequest(e){const t={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,o=!1;for(const r of e)"functionResponse"in r?(n.parts.push(r),o=!0):(t.parts.push(r),s=!0);if(s&&o)throw new VertexAIError("invalid-content","Within a single message, FunctionResponse cannot be mixed with other type of Part in the request for sending chat message.");if(!s&&!o)throw new VertexAIError("invalid-content","No Content is provided for sending chat message.");if(s)return t;return n}(t)}function formatGenerateContentInput(e){let t;if(e.contents)t=e;else{t={contents:[formatNewContent(e)]}}return e.systemInstruction&&(t.systemInstruction=formatSystemInstruction(e.systemInstruction)),t}function createPredictRequestBody(e,{gcsURI:t,imageFormat:n,addWatermark:s,numberOfImages:o=1,negativePrompt:r,aspectRatio:i,safetyFilterLevel:a,personFilterLevel:c}){return{instances:[{prompt:e}],parameters:{storageUri:t,negativePrompt:r,sampleCount:o,aspectRatio:i,outputOptions:n,addWatermark:s,safetyFilterLevel:a,personGeneration:c,includeRaiReason:!0}}}const L=["text","inlineData","functionCall","functionResponse"],M={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall"],system:["text"]},k={user:["model"],function:["model"],model:["user","function"],system:[]};const P="SILENT_ERROR";class ChatSession{constructor(e,t,n,s){this.model=t,this.params=n,this.requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiSettings=e,(null==n?void 0:n.history)&&(!function validateChatHistory(e){let t=null;for(const n of e){const{role:e,parts:s}=n;if(!t&&"user"!==e)throw new VertexAIError("invalid-content",`First Content should be with role 'user', got ${e}`);if(!m.includes(e))throw new VertexAIError("invalid-content",`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(m)}`);if(!Array.isArray(s))throw new VertexAIError("invalid-content","Content should have 'parts' but property with an array of Parts");if(0===s.length)throw new VertexAIError("invalid-content","Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0};for(const e of s)for(const t of L)t in e&&(o[t]+=1);const r=M[e];for(const t of L)if(!r.includes(t)&&o[t]>0)throw new VertexAIError("invalid-content",`Content with role '${e}' can't contain '${t}' part`);if(t&&!k[e].includes(t.role))throw new VertexAIError("invalid-content",`Content with role '${e}' can't follow '${t.role}'. Valid previous roles: ${JSON.stringify(k)}`);t=n}}(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e){var t,n,s,o,r;await this._sendPromise;const i=formatNewContent(e),a={safetySettings:null===(t=this.params)||void 0===t?void 0:t.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]};let c={};return this._sendPromise=this._sendPromise.then((()=>generateContent(this._apiSettings,this.model,a,this.requestOptions))).then((e=>{var t,n;if(e.response.candidates&&e.response.candidates.length>0){this._history.push(i);const s={parts:(null===(t=e.response.candidates)||void 0===t?void 0:t[0].content.parts)||[],role:(null===(n=e.response.candidates)||void 0===n?void 0:n[0].content.role)||"model"};this._history.push(s)}else{const t=formatBlockErrorMessage(e.response);t&&g.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}c=e})),await this._sendPromise,c}async sendMessageStream(e){var t,n,s,o,r;await this._sendPromise;const i=formatNewContent(e),a={safetySettings:null===(t=this.params)||void 0===t?void 0:t.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(o=this.params)||void 0===o?void 0:o.toolConfig,systemInstruction:null===(r=this.params)||void 0===r?void 0:r.systemInstruction,contents:[...this._history,i]},c=generateContentStream(this._apiSettings,this.model,a,this.requestOptions);return this._sendPromise=this._sendPromise.then((()=>c)).catch((e=>{throw new Error(P)})).then((e=>e.response)).then((e=>{if(e.candidates&&e.candidates.length>0){this._history.push(i);const t=Object.assign({},e.candidates[0].content);t.role||(t.role="model"),this._history.push(t)}else{const t=formatBlockErrorMessage(e);t&&g.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}})).catch((e=>{e.message!==P&&g.error(e)})),c}}class GenerativeModel extends VertexAIModel{constructor(e,t,n){super(e,t.model),this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=formatSystemInstruction(t.systemInstruction),this.requestOptions=n||{}}async generateContent(e){const t=formatGenerateContentInput(e);return generateContent(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},t),this.requestOptions)}async generateContentStream(e){const t=formatGenerateContentInput(e);return generateContentStream(this._apiSettings,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},t),this.requestOptions)}startChat(e){return new ChatSession(this._apiSettings,this.model,Object.assign({tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction},e),this.requestOptions)}async countTokens(e){const t=formatGenerateContentInput(e);return async function countTokens(e,t,n,s){return(await makeRequest(t,f.COUNT_TOKENS,e,!1,JSON.stringify(n),s)).json()}(this._apiSettings,this.model,t)}}class ImagenModel extends VertexAIModel{constructor(e,t,n){const{model:s,generationConfig:o,safetySettings:r}=t;super(e,s),this.requestOptions=n,this.generationConfig=o,this.safetySettings=r}async generateImages(e){const t=createPredictRequestBody(e,Object.assign(Object.assign({},this.generationConfig),this.safetySettings));return handlePredictResponse(await makeRequest(this.model,f.PREDICT,this._apiSettings,!1,JSON.stringify(t),this.requestOptions))}async generateImagesGCS(e,t){const n=createPredictRequestBody(e,Object.assign(Object.assign({gcsURI:t},this.generationConfig),this.safetySettings));return handlePredictResponse(await makeRequest(this.model,f.PREDICT,this._apiSettings,!1,JSON.stringify(n),this.requestOptions))}}class Schema{constructor(e){for(const t in e)this[t]=e[t];this.type=e.type,this.nullable=!!e.hasOwnProperty("nullable")&&!!e.nullable}toJSON(){const e={type:this.type};for(const t in this)this.hasOwnProperty(t)&&void 0!==this[t]&&("required"===t&&this.type!==T.OBJECT||(e[t]=this[t]));return e}static array(e){return new ArraySchema(e,e.items)}static object(e){return new ObjectSchema(e,e.properties,e.optionalProperties)}static string(e){return new StringSchema(e)}static enumString(e){return new StringSchema(e,e.enum)}static integer(e){return new IntegerSchema(e)}static number(e){return new NumberSchema(e)}static boolean(e){return new BooleanSchema(e)}}class IntegerSchema extends Schema{constructor(e){super(Object.assign({type:T.INTEGER},e))}}class NumberSchema extends Schema{constructor(e){super(Object.assign({type:T.NUMBER},e))}}class BooleanSchema extends Schema{constructor(e){super(Object.assign({type:T.BOOLEAN},e))}}class StringSchema extends Schema{constructor(e,t){super(Object.assign({type:T.STRING},e)),this.enum=t}toJSON(){const e=super.toJSON();return this.enum&&(e.enum=this.enum),e}}class ArraySchema extends Schema{constructor(e,t){super(Object.assign({type:T.ARRAY},e)),this.items=t}toJSON(){const e=super.toJSON();return e.items=this.items.toJSON(),e}}class ObjectSchema extends Schema{constructor(e,t,n=[]){super(Object.assign({type:T.OBJECT},e)),this.properties=t,this.optionalProperties=n}toJSON(){const e=super.toJSON();e.properties=Object.assign({},this.properties);const t=[];if(this.optionalProperties)for(const e of this.optionalProperties)if(!this.properties.hasOwnProperty(e))throw new VertexAIError("invalid-schema",`Property "${e}" specified in "optionalProperties" does not exist.`);for(const n in this.properties)this.properties.hasOwnProperty(n)&&(e.properties[n]=this.properties[n].toJSON(),this.optionalProperties.includes(n)||t.push(n));return t.length>0&&(e.required=t),delete e.optionalProperties,e}}class ImagenImageFormat{constructor(){this.mimeType="image/png"}static jpeg(e){return e&&(e<0||e>100)&&g.warn(`Invalid JPEG compression quality of ${e} specified; the supported range is [0, 100].`),{mimeType:"image/jpeg",compressionQuality:e}}static png(){return{mimeType:"image/png"}}}function getVertexAI(e=t(),n){e=function getModularInstance(e){return e&&e._delegate?e._delegate:e}(e);return _getProvider(e,u).getImmediate({identifier:(null==n?void 0:n.location)||p})}function getGenerativeModel(e,t,n){if(!t.model)throw new VertexAIError("no-model","Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })");return new GenerativeModel(e,t,n)}function getImagenModel(e,t,n){if(!t.model)throw new VertexAIError("no-model","Must provide a model name. Example: getImagenModel({ model: 'my-model-name' })");return new ImagenModel(e,t,n)}!function registerVertex(){n(new Component(u,((e,{instanceIdentifier:t})=>{const n=e.getProvider("app").getImmediate(),s=e.getProvider("auth-internal"),o=e.getProvider("app-check-internal");return new VertexAIService(n,s,o,{location:t})}),"PUBLIC").setMultipleInstances(!0)),s(l,d),s(l,d,"esm2017")}();export{ArraySchema,v as BlockReason,BooleanSchema,ChatSession,R as FinishReason,_ as FunctionCallingMode,GenerativeModel,y as HarmBlockMethod,I as HarmBlockThreshold,E as HarmCategory,S as HarmProbability,O as HarmSeverity,b as ImagenAspectRatio,ImagenImageFormat,ImagenModel,w as ImagenPersonFilterLevel,C as ImagenSafetyFilterLevel,IntegerSchema,A as Modality,NumberSchema,ObjectSchema,m as POSSIBLE_ROLES,Schema,T as SchemaType,StringSchema,VertexAIError,VertexAIModel,getGenerativeModel,getImagenModel,getVertexAI}; //# sourceMappingURL=firebase-vertexai.js.map