-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
36ebaa8
Add generateWithVertex sample function.
jenh 642d2b9
Set node version to 18
jenh 4eb2b14
Update pnpm-lock.yaml
jenh fdb9d14
Update Node/remote-config-server-with-vertex/functions/package.json
jenh a94f4c2
Add first draft callable function for Remote Config server, Vertex AI…
jenh 8580b48
Set node version to 18, run
jenh 85df0ba
Misc cleanup, send errors to web interface, update readmes, caveat th…
jenh 0113036
Fix error message clearance and add waiting dots.
jenh 82611fd
Fixes to address PR comments, fix config.ts
jenh 28a8ce1
Remove obsolete comment.
jenh 9fa0056
Update README.md
jenh 547306d
Update README.md
jenh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
/// <reference types="vite/client" /> |
11 changes: 11 additions & 0 deletions
11
Node/call-vertex-remote-config-server/client/vite.config.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/**" | ||
] | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.