Skip to content

Commit 57430eb

Browse files
authored
Import custom func demo from Next 24 (#464)
1 parent b33ea37 commit 57430eb

File tree

4 files changed

+165
-0
lines changed

4 files changed

+165
-0
lines changed

ai/custom_func_vertex/Code.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/**
2+
* Passes a prompt and a data range to Gemini AI.
3+
*
4+
* @param {range} range The range of cells.
5+
* @param {string} prompt The text prompt as a string or single cell reference.
6+
* @return The Gemini response.
7+
* @customfunction
8+
*/
9+
function gemini(range,prompt) {
10+
prompt = `For the table of data: ${range}, Answer the following: ${prompt}. Do not use formatting. Remove all markdown.`
11+
return getAiSummary(prompt);
12+
}

ai/custom_func_vertex/README.md

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Google Sheets Custom Function with AI Studio
2+
3+
## Project Description
4+
5+
Google Sheets Custom Function to be used as a bound Apps Script project with a Google Sheets Spreadsheet.
6+
7+
## Prerequisites
8+
9+
* Google Cloud Project (aka Standard Cloud Project for Apps Script) with billing enabled
10+
11+
## Set up your environment
12+
13+
1. Create a Cloud Project
14+
1. Enable the Vertex AI API
15+
1. Create a Service Account and grant the role Service Account Token Creator Role
16+
1. Create a private key with type JSON. This will download the JSON file for use in the next section.
17+
1. Open an Apps Script Project bound to a Google Sheets Spreadsheet
18+
1. From Project Settings, change project to GCP project number of Cloud Project from step 1
19+
1. Add a Script Property. Enter `model_id` as the property name and `gemini-pro` as the value.
20+
1. Add a Script Property. Enter `project_location` as the property name and `us-central-1` as the value.
21+
1. Add a Script Property. Enter `service_account_key` as the property name and paste the JSON key from the service account as the value.
22+
1. Add OAuth2 v43 Apps Script Library using the ID `1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF`.
23+
1. Add the project code to Apps Script
24+
25+
## Usage
26+
27+
Insert a custom function in Google Sheets, passing a range and a prompt as parameters
28+
29+
Example:
30+
31+
```
32+
=gemini(A1:A10,"Extract colors from the product description")
33+
```

ai/custom_func_vertex/aiVertex.js

+108
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/*
2+
Copyright 2024 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
https://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
const VERTEX_AI_LOCATION = PropertiesService.getScriptProperties().getProperty('project_location');
18+
const MODEL_ID = PropertiesService.getScriptProperties().getProperty('model_id');
19+
const SERVICE_ACCOUNT_KEY = PropertiesService.getScriptProperties().getProperty('service_account_key');
20+
21+
/**
22+
* Packages prompt and necessary settings, then sends a request to
23+
* Vertex API. Returns the response as an JSON object extracted from the
24+
* Vertex API response object.
25+
*
26+
* @param prompt - String representing your prompt for Gemini AI.
27+
*/
28+
function getAiSummary(prompt) {
29+
30+
const request = {
31+
"contents": [{
32+
"role": "user",
33+
"parts": [{
34+
"text": prompt
35+
}]
36+
}],
37+
"generationConfig": {
38+
"temperature": 0.1,
39+
"maxOutputTokens": 2048,
40+
},
41+
"safetySettings": [
42+
{
43+
"category": "HARM_CATEGORY_HARASSMENT",
44+
"threshold": "BLOCK_NONE"
45+
},
46+
{
47+
"category": "HARM_CATEGORY_HATE_SPEECH",
48+
"threshold": "BLOCK_NONE"
49+
},
50+
{
51+
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
52+
"threshold": "BLOCK_NONE"
53+
},
54+
{
55+
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
56+
"threshold": "BLOCK_NONE"
57+
}
58+
]
59+
};
60+
61+
const credentials = credentialsForVertexAI();
62+
63+
const fetchOptions = {
64+
method: 'post',
65+
headers: {
66+
'Authorization': `Bearer ${credentials.accessToken}`
67+
},
68+
contentType: 'application/json',
69+
muteHttpExceptions: true,
70+
payload: JSON.stringify(request)
71+
}
72+
73+
const url = `https://${VERTEX_AI_LOCATION}-aiplatform.googleapis.com/v1/projects/${credentials.projectId}/`
74+
+ `locations/${VERTEX_AI_LOCATION}/publishers/google/models/${MODEL_ID}:generateContent`
75+
76+
const response = UrlFetchApp.fetch(url, fetchOptions);
77+
78+
const payload = JSON.parse(response);
79+
const text = payload.candidates[0].content.parts[0].text
80+
81+
return text
82+
}
83+
84+
/**
85+
* Gets credentials required to call Vertex API using a Service Account.
86+
* Requires use of Service Account Key stored with project
87+
*
88+
* @return {!Object} Containing the Cloud Project Id and the access token.
89+
*/
90+
function credentialsForVertexAI() {
91+
const credentials = SERVICE_ACCOUNT_KEY;
92+
if (!credentials) {
93+
throw new Error("service_account_key script property must be set.");
94+
}
95+
96+
const parsedCredentials = JSON.parse(credentials);
97+
98+
const service = OAuth2.createService("Vertex")
99+
.setTokenUrl('https://oauth2.googleapis.com/token')
100+
.setPrivateKey(parsedCredentials['private_key'])
101+
.setIssuer(parsedCredentials['client_email'])
102+
.setPropertyStore(PropertiesService.getScriptProperties())
103+
.setScope("https://www.googleapis.com/auth/cloud-platform");
104+
return {
105+
projectId: parsedCredentials['project_id'],
106+
accessToken: service.getAccessToken(),
107+
}
108+
}

ai/custom_func_vertex/appsscript.json

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"timeZone": "America/Los_Angeles",
3+
"dependencies": {
4+
"libraries": [{
5+
"userSymbol": "OAuth2",
6+
"libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF",
7+
"version": "43"
8+
}]
9+
},
10+
"exceptionLogging": "STACKDRIVER",
11+
"runtimeVersion": "V8"
12+
}

0 commit comments

Comments
 (0)