firebase
Version:
Firebase JavaScript library for web and Node.js
4 lines (2 loc) • 19.3 kB
JavaScript
import{_getProvider,getApp as e,_registerComponent as t,registerVersion as n}from"https://www.gstatic.com/firebasejs/10.12.2/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]||{},o=`${this.service}/${e}`,i=this.errors[e],r=i?function replaceTemplate(e,t){return e.replace(s,((e,n)=>{const s=t[n];return null!=s?String(s):`<${n}?>`}))}(i,n):"Error",a=`${this.serviceName}: ${r} (${o}).`;return new FirebaseError(o,a,n)}}const s=/\{\$([^}]+)}/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}}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||[]),i=[];return s={},verb("next"),verb("throw"),verb("return"),s[Symbol.asyncIterator]=function(){return this},s;function verb(e){o[e]&&(s[e]=function(t){return new Promise((function(n,s){i.push([e,t,n,s])>1||resume(e,t)}))})}function resume(e,t){try{!function step(e){e.value instanceof __await?Promise.resolve(e.value.v).then(fulfill,reject):settle(i[0][2],e)}(o[e](t))}catch(e){settle(i[0][3],e)}}function fulfill(e){resume("next",e)}function reject(e){resume("throw",e)}function settle(e,t){e(t),i.shift(),i.length&&resume(i[0][0],i[0][1])}}var o="@firebase/vertexai-preview";class VertexAIService{constructor(e,t,n,s){var o;this.app=e,this.options=s;const i=null==n?void 0:n.getImmediate({optional:!0}),r=null==t?void 0:t.getImmediate({optional:!0});this.auth=r||null,this.appCheck=i||null,this.location=(null===(o=this.options)||void 0===o?void 0:o.location)||"us-central1"}_delete(){return Promise.resolve()}}const i=new ErrorFactory("vertexAI","VertexAI",{"fetch-error":"Error fetching from {$url}: {$message}","invalid-content":"Content formatting error: {$message}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase VertexAI requires this field tocontain a valid API key.',"no-project-id":'The "projectId" field is empty in the local Firebase config. Firebase VertexAI requires this field tocontain a valid project ID.',"no-model":"Must provide a model name. Example: getGenerativeModel({ model: 'my-model-name' })","parse-failed":"Parsing failed: {$message}","response-error":"Response error: {$message}. Response body stored in error.customData.response"});var r;!function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens"}(r||(r={}));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://firebaseml.googleapis.com"}/v2beta`;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/0.0.2"),e.push("fire/0.0.2"),e.join(" ")}()),t.append("x-goog-api-key",e.apiSettings.apiKey),e.apiSettings.getAppCheckToken){const n=await e.apiSettings.getAppCheckToken();n&&!n.error&&t.append("X-Firebase-AppCheck",n.token)}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 a=new RequestUrl(e,t,n,s,r);let c;try{const i=await async function constructRequest(e,t,n,s,o,i){const r=new RequestUrl(e,t,n,s,i);return{url:r.toString(),fetchOptions:Object.assign(Object.assign({},buildFetchOptions(i)),{method:"POST",headers:await getHeaders(r),body:o})}}(e,t,n,s,o,r);if(c=await fetch(i.url,i.fetchOptions),!c.ok){let e="";try{const t=await c.json();e=t.error.message,t.error.details&&(e+=` ${JSON.stringify(t.error.details)}`)}catch(e){}throw new Error(`[${c.status} ${c.statusText}] ${e}`)}}catch(e){const t=e,n=i.create("fetch-error",{url:a.toString(),message:t.message});throw n.stack=t.stack,n}return c}function buildFetchOptions(e){const t={};if((null==e?void 0:e.timeout)&&(null==e?void 0:e.timeout)>=0){const n=new AbortController,s=n.signal;setTimeout((()=>n.abort()),e.timeout),t.signal=s}return t}const a=["user","model","function","system"];var c,l,d,u,h,p,f,g,m;function addHelpers(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.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 i.create("response-error",{message:`${formatBlockErrorMessage(e)}`,response:e});return function getText(e){var t,n,s,o;const i=[];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&&i.push(t.text);return i.length>0?i.join(""):""}(e)}if(e.promptFeedback)throw i.create("response-error",{message:`Text not available. ${formatBlockErrorMessage(e)}`,response:e});return""},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.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 i.create("response-error",{message:`${formatBlockErrorMessage(e)}`,response:e});return function getFunctionCalls(e){var t,n,s,o;const i=[];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&&i.push(t.functionCall);return i.length>0?i:void 0}(e)}if(e.promptFeedback)throw i.create("response-error",{message:`Function call not available. ${formatBlockErrorMessage(e)}`,response:e})},e}!function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",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"}(c||(c={})),function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",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"}(l||(l={})),function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"}(d||(d={})),function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(u||(u={})),function(e){e.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",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"}(h||(h={})),function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"}(p||(p={})),function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.OTHER="OTHER"}(f||(f={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"}(g||(g={})),function(e){e.STRING="STRING",e.NUMBER="NUMBER",e.INTEGER="INTEGER",e.BOOLEAN="BOOLEAN",e.ARRAY="ARRAY",e.OBJECT="OBJECT"}(m||(m={}));const E=[f.RECITATION,f.SAFETY];function hadBadFinishReason(e){return!!e.finishReason&&E.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}const _=/^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(i.create("parse-failed",{message:"Failed to parse stream"})):void e.close();n+=t;let o,r=n.match(_);for(;r;){try{o=JSON.parse(r[1])}catch(t){return void e.error(i.create("parse-failed",{message:`Error parsing JSON response: "${r[1]}"`}))}e.enqueue(o),n=n.substring(r[0].length),r=n.match(_)}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 addHelpers(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;yield yield __await(addHelpers(e))}}))}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;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)o.text&&(s.text=o.text),o.functionCall&&(s.functionCall=o.functionCall),0===Object.keys(s).length&&(s.text=""),n.candidates[t].content.parts.push(s)}}return n}async function generateContentStream(e,t,n,s){return processStream(await makeRequest(t,r.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),s))}async function generateContent(e,t,n,s){const o=await makeRequest(t,r.GENERATE_CONTENT,e,!1,JSON.stringify(n),s);return{response:addHelpers(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 i of e)"functionResponse"in i?(n.parts.push(i),o=!0):(t.parts.push(i),s=!0);if(s&&o)throw i.create("invalid-content",{message:"Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message."});if(!s&&!o)throw i.create("invalid-content",{message:"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}const I=["text","inlineData","functionCall","functionResponse"],v={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall"],system:["text"]},R={user:["model"],function:["model"],model:["user","function"],system:[]};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 i.create("invalid-content",{message:`First content should be with role 'user', got ${e}`});if(!a.includes(e))throw i.create("invalid-content",{message:`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(a)}`});if(!Array.isArray(s))throw i.create("invalid-content",{message:"Content should have 'parts' property with an array of Parts"});if(0===s.length)throw i.create("invalid-content",{message:"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 I)t in e&&(o[t]+=1);const r=v[e];for(const t of I)if(!r.includes(t)&&o[t]>0)throw i.create("invalid-content",{message:`Content with role '${e}' can't contain '${t}' part`});if(t&&!R[e].includes(t.role))throw i.create("invalid-content",{message:`Content with role '${e}' can't follow '${t.role}'. Valid previous roles: ${JSON.stringify(R)}`});t=n}}(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e){var t,n,s,o,i;await this._sendPromise;const r=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===(i=this.params)||void 0===i?void 0:i.systemInstruction,contents:[...this._history,r]};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(r);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&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}c=e})),await this._sendPromise,c}async sendMessageStream(e){var t,n,s,o,i;await this._sendPromise;const r=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===(i=this.params)||void 0===i?void 0:i.systemInstruction,contents:[...this._history,r]},c=generateContentStream(this._apiSettings,this.model,a,this.requestOptions);return this._sendPromise=this._sendPromise.then((()=>c)).catch((e=>{throw new Error("SILENT_ERROR")})).then((e=>e.response)).then((e=>{if(e.candidates&&e.candidates.length>0){this._history.push(r);const t=Object.assign({},e.candidates[0].content);t.role||(t.role="model"),this._history.push(t)}else{const t=formatBlockErrorMessage(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}})).catch((e=>{"SILENT_ERROR"!==e.message&&console.error(e)})),c}}class GenerativeModel{constructor(e,t,n){var s,o,r,a;if(!(null===(o=null===(s=e.app)||void 0===s?void 0:s.options)||void 0===o?void 0:o.apiKey))throw i.create("no-api-key");if(!(null===(a=null===(r=e.app)||void 0===r?void 0:r.options)||void 0===a?void 0:a.projectId))throw i.create("no-project-id");this._apiSettings={apiKey:e.app.options.apiKey,project:e.app.options.projectId,location:e.location},e.appCheck&&(this._apiSettings.getAppCheckToken=()=>e.appCheck.getToken()),e.auth&&(this._apiSettings.getAuthToken=()=>e.auth.getToken()),t.model.includes("/")?t.model.startsWith("models/")?this.model=`publishers/google/${t.model}`:this.model=t.model:this.model=`publishers/google/models/${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,r.COUNT_TOKENS,e,!1,JSON.stringify(n),s)).json()}(this._apiSettings,this.model,t)}}function getVertexAI(t=e(),n){t=function getModularInstance(e){return e&&e._delegate?e._delegate:e}(t);return _getProvider(t,"vertexAI").getImmediate({identifier:(null==n?void 0:n.location)||"us-central1"})}function getGenerativeModel(e,t,n){if(!t.model)throw i.create("no-model");return new GenerativeModel(e,t,n)}!function registerVertex(){t(new Component("vertexAI",((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)),n(o,"0.0.2"),n(o,"0.0.2","esm2017")}();export{p as BlockReason,ChatSession,f as FinishReason,g as FunctionCallingMode,m as FunctionDeclarationSchemaType,GenerativeModel,d as HarmBlockMethod,l as HarmBlockThreshold,c as HarmCategory,u as HarmProbability,h as HarmSeverity,a as POSSIBLE_ROLES,getGenerativeModel,getVertexAI};
//# sourceMappingURL=firebase-vertexai-preview.js.map