Skip to content

Add function sample for server-side Remote Config + Vertex AI Gemini API #1135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions Node/call-vertex-remote-config-server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
Call the Vertex AI Gemini API with Remote Config and App Check
==============================================================

Introduction
------------

This is a sample callable function that authenticates calling apps with App
Check and then sends queries to Gemini using the Vertex AI Gemini API. Vertex
AI model parameters are controlled using the Remote Config server
functionality provided by the Firebase Admin SDK for Node.js. Use the client
provided in `client/` to access the function through basic web page.

- [Read more about Remote Config for servers](https://firebase.google.com/docs/remote-config/server).
- [Read more about App Check](https://firebase.google.com/docs/app-check).
- [Read more about the Vertex AI Node.js Client library](https://cloud.google.com/nodejs/docs/reference/aiplatform/latest).

Important: Vertex AI and Cloud Functions require a billing account. Review
[Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and
[Firebase pricing](https://firebase.google.com/pricing) before running
this function. If you're new to Firebase and Google Cloud, check to see if
you're eligible for a
[$300 credit](https://firebase.google.com/support/faq#pricing-free-trial) and
a Free Trial Cloud Billing account.

Get Started
---------------

1. Follow the instructions in client/README.md to create a Firebase project,
enable ReCAPTCHA Enterprise, enable Firebase App Check, and add your
Firebase config and ReCAPTCHA Enterprise key to the client config.
2. Enable [recommended Vertex AI APIs](https://console.cloud.google.com/vertex-ai).
3. Configure a Remote Config server template on the Firebase console. Use the template
described in
[Use server side Remote Config with Cloud Functions and Vertex
AI](https://firebase.google.com/docs/remote-config/solution-server#implementation-create-template),
which contains all of the parameters used in the function sample.
4. Install dependencies: `cd functions && npm install`
5. If you haven't already done so, install firebase-tools: `npm i firebase-tools@latest`
6. Log into Firebase: `firebase login`
7. Deploy the function. We recommend testing in the
[Firebase emulator](https://firebase.google.com/docs/remote-config/solution-server#implementation-deploy-and-test-in-emulator).
8. If testing in the emulator, verify that `testMode` is set to `true` in
`client/main.ts`, then start the client: `cd public && npm run dev`
9. Open the [client app in a browser](http://localhost:5173) and enter a
prompt. To access the Vertex AI Gemini API, make sure that you have
set the `is_vertex_enabled` boolean parameter in your Remote Config
server template to `true`.

Support
-------

- [Firebase Support](https://firebase.google.com/support/)

License
-------

© Google, 2024. Licensed under an [Apache-2](../../LICENSE) license.
50 changes: 50 additions & 0 deletions Node/call-vertex-remote-config-server/client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
Test client for call-vertex-remote-config-server
================================================

Introduction
------------

This is a basic web app that calls the `callVertexWithRC` function. The
function uses values stored in Remote Config server templates with
the Firebase Admin SDK to change Vertex AI Gemini API parameters on the
fly. Access is controlled using Firebase App Check.

- [Read more about Remote Config for servers](https://firebase.google.com/docs/remote-config/server).
- [Read more about App Check](https://firebase.google.com/docs/app-check).
- [Read more about the Vertex AI Node.js Client library](https://cloud.google.com/nodejs/docs/reference/aiplatform/latest).

Important: Vertex AI and Cloud Functions require a billing account. Review
[Vertex AI pricing](https://cloud.google.com/vertex-ai/pricing) and
[Firebase pricing](https://firebase.google.com/pricing) before running
this function. If you're new to Firebase and Google Cloud, check to see if
you're eligible for a
[$300 credit](https://firebase.google.com/support/faq#pricing-free-trial) and
a Free Trial Cloud Billing account.

Get started
---------------

1. Create a [Firebase project and register a web app](https://firebase.google.com/docs/web/setup#create-firebase-project-and-app).
2. [Create a ReCAPTCHA Enterprise key](https://firebase.google.com/docs/app-check/web/recaptcha-enterprise-provider#project-setup)
in the same project.
3. [Enable App Check](https://firebase.google.com/docs/app-check/web/recaptcha-enterprise-provider)
in the Firebase console with the ReCAPTCHA Enterprise site key you created.
4. Copy your Firebase project config and your ReCAPTCHA Enterprise site key
into the appropriate places in `config.ts` in this directory.
5. In this directory, run `npm install`.
6. Set up the function as described in [../README.md](../README.md).
7. In this directory, run `npm run dev` to run the client.

We recommend running and testing functions locally before deploying to Google
Cloud. To run this app against the `callVertexWithRC` function running in an
emulator, set `testMode` to true.

Support
-------

- [Firebase Support](https://firebase.google.com/support/)

License
-------

© Google, 2024. Licensed under an [Apache-2](../../../LICENSE) license.
8 changes: 8 additions & 0 deletions Node/call-vertex-remote-config-server/client/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const firebaseConfig = {
YOUR_FIREBASE_CONFIG
};

// Your ReCAPTCHA Enterprise site key (must be from the same project
// as the Firebase config above).
export const RECAPTCHA_ENTERPRISE_SITE_KEY =
"YOUR_RECAPTCHA_KEY";
72 changes: 72 additions & 0 deletions Node/call-vertex-remote-config-server/client/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Client app for Remote Config server function with Vertex AI and App Check</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
justify-content: center;
align-items: center;
height: 100vh;
margin: 70px;
}

h1 {
margin-bottom: 20px;
}

.container {
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
max-width: 400px;
width: 100%;
text-align: center;
}

input[type="text"],
input[type="submit"] {
width: 35%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}

input[type="submit"] {
background-color: #FFA500;
color: white;
border: none;
cursor: pointer;
font-size: 16px;
font-weight: bold;
}

input[type="submit"]:hover {
background-color: #45a049;
}

#waitingMessage,
#generatedText,
#errorMessage {
margin-top: 20px;
text-align: left;
}
</style>
</head>

<body>
<div>
<h1>Client app for Remote Config server function with Vertex AI and App Check</h1>
<br />
</div>
<script type="module" src="main.ts"></script>
</body>

</html>
118 changes: 118 additions & 0 deletions Node/call-vertex-remote-config-server/client/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { initializeApp } from "firebase/app";
import { firebaseConfig, RECAPTCHA_ENTERPRISE_SITE_KEY } from "./config";
import {
initializeAppCheck,
ReCaptchaEnterpriseProvider,
} from "firebase/app-check";
import {
getFunctions,
httpsCallable,
connectFunctionsEmulator,
} from "firebase/functions";

// Set to true to test in emulator.
const testMode = true;

// Use showdown to convert Gemini-provided Markdown to HTML
import { Converter } from "showdown";
const converter = new Converter();

// Set up output elements.
const outputDiv = document.createElement("div");
document.body.appendChild(outputDiv);

// Initialize Firebase app.
const app = initializeApp(firebaseConfig);

// Initialize App Check.
initializeAppCheck(app, {
provider: new ReCaptchaEnterpriseProvider(RECAPTCHA_ENTERPRISE_SITE_KEY),
});

// Define callVertexWithRC as a call to the callVertexWithRC function.
const callVertexWithRC = httpsCallable(getFunctions(), "callVertexWithRC", {
limitedUseAppCheckTokens: true,
});

// Enable emulator so that it can be used in test mode.
const functions = getFunctions(app, "us-central1"); // Replace with your region

if (testMode) {
connectFunctionsEmulator(functions, "localhost", 5001);
}

// Generate body for index.html.
document.body.innerHTML += `

<div id="waitingMessage"></div>
<div id="generatedText"></div>
<div id="errorMessage"></div>
<br/>
<form id="promptForm">
<label for="promptInput">Ask Gemini a question!</label><br>
<input type="text" id="promptInput" name="prompt"><br><br>
<input type="submit" value="Submit">
</form>
`;

const promptForm = document.getElementById("promptForm") as HTMLFormElement;

promptForm.addEventListener("submit", async (event) => {
event.preventDefault();
const promptInput = document.getElementById(
"promptInput"
) as HTMLInputElement;
const prompt = promptInput.value;

const waitingMessageElement = document.getElementById("waitingMessage");
//waitingMessageElement.textContent = "Waiting for response...";

// Define a variable to keep track of the number of dots
let dotCount = 0;

// Set interval to add dots every second
const intervalId = setInterval(() => {
// Increment dotCount
dotCount = (dotCount + 1) % 7;
const dots = ".".repeat(dotCount);
waitingMessageElement.textContent = "Waiting for response" + dots;
}, 1000);

const errorMessageElement = document.getElementById("errorMessage");
errorMessageElement.textContent = "";

try {
const { data } = await callVertexWithRC({ prompt });
const generatedTextElement = document.getElementById("generatedText"); // Access the element
const htmlContent = converter.makeHtml(data);
if (!generatedTextElement) {
throw new Error("Missing generated text.");
}
generatedTextElement.innerHTML = htmlContent; // Set the element's content
waitingMessageElement.textContent = "";
errorMessageElement.textContent = "";

} catch (error) {
errorMessageElement.textContent = "Error calling function: " + error.message;
waitingMessageElement.textContent = "";
}
// Clear welcome dots.
clearInterval(intervalId);
});
33 changes: 33 additions & 0 deletions Node/call-vertex-remote-config-server/client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "call-vertex-remote-config-server-client",
"version": "1.0.0",
"description": "JavaScript quickstart for Vertex AI, Firebase Remote Config server, and App Check.",
"repository": {
"type": "git",
"url": "git+https://github.com/firebase/functions-samples.git"
},
"author": "",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/firebase/functions-samples/issues"
},
"engines": {
"npm": ">=9.0.0 <10.0.0",
"node": ">=18.0.0 <=20.0.0"
},
"homepage": "https://github.com/firebase/functions-samples#readme",
"devDependencies": {
"typescript": "^5.1.6",
"vite": "^4.4.9"
},
"scripts": {
"dev": "vite",
"build": "vite build",
"format": "prettier --write ."
},
"dependencies": {
"@firebase/functions": "^0.11.5",
"firebase": "^10.12.1",
"showdown": "^2.1.0"
}
}
1 change: 1 addition & 0 deletions Node/call-vertex-remote-config-server/client/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
11 changes: 11 additions & 0 deletions Node/call-vertex-remote-config-server/client/vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineConfig } from 'vite';

export default defineConfig({
base: '',
build: {
rollupOptions: {
input: ['index.html','main.ts'],
},
},
logLevel: 'info',
});
32 changes: 32 additions & 0 deletions Node/call-vertex-remote-config-server/firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"functions": [
{
"source": "functions",
"codebase": "call-vertex-remote-config-server",
"ignore": [
"node_modules",
".git",
"firebase-debug.log",
"firebase-debug.*.log",
"*.local",
"*.bak"
]
}
],
"emulators": {
"functions": {
"port": 5001
},
"ui": {
"enabled": true
},
"singleProjectMode": true
},
"hosting": {
"public": "client/dist",
"ignore": [
"firebase.json",
"**/node_modules/**"
]
}
}
Loading