-
Notifications
You must be signed in to change notification settings - Fork 2k
feat(genai): Add samples for Embeddings, Provisioned Throughput, Safety #4196
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
Open
Guiners
wants to merge
17
commits into
GoogleCloudPlatform:main
Choose a base branch
from
Guiners:samples/rest-of-samples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
e9b3b27
adding samples
4a05941
feat(samples): add and update code samples
6fab992
updating package.json
d565c52
fixing package.json
8a37e54
fixing failed tests
706cf4b
fixing failed tests
58df642
fixing failed tests
91998da
fixing failed tests
042be12
Merge branch 'main' into samples/rest-of-samples
Guiners 51da8f9
fixing failed tests
dd5a345
Merge remote-tracking branch 'origin/samples/rest-of-samples' into sa…
13fa4cb
fixing failed tests
f928c1a
fixing failed tests
87f9f78
fixing failed tests
e5cf084
fixing failed tests
16e46fd
fixing failing test
b553a8a
Merge branch 'main' into samples/rest-of-samples
Guiners 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,59 @@ | ||
| // Copyright 2025 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 | ||
| // | ||
| // https://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. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| // [START googlegenaisdk_embeddings_docretrieval_with_txt] | ||
| const {GoogleGenAI} = require('@google/genai'); | ||
|
|
||
| const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT; | ||
|
|
||
| async function generateEmbeddingsForRetrieval( | ||
| projectId = GOOGLE_CLOUD_PROJECT | ||
| ) { | ||
| const client = new GoogleGenAI({ | ||
| vertexai: true, | ||
| project: projectId, | ||
| }); | ||
|
|
||
| const prompt = [ | ||
| "How do I get a driver's license/learner's permit?", | ||
| "How long is my driver's license valid for?", | ||
| "Driver's knowledge test study guide", | ||
| ]; | ||
|
|
||
| const response = await client.models.embedContent({ | ||
| model: 'gemini-embedding-001', | ||
| contents: prompt, | ||
| config: { | ||
| taskType: 'RETRIEVAL_DOCUMENT', // Optional | ||
| outputDimensionality: 3072, // Optional | ||
| title: "Driver's License", // Optional | ||
| }, | ||
| }); | ||
|
|
||
| console.log(response); | ||
|
|
||
| // Example response: | ||
| // embeddings=[ContentEmbedding(values=[-0.06302902102470398, 0.00928034819662571, 0.014716853387653828, -0.028747491538524628, ... ], | ||
| // statistics=ContentEmbeddingStatistics(truncated=False, token_count=13.0))] | ||
| // metadata=EmbedContentMetadata(billable_character_count=112) | ||
|
|
||
| return response; | ||
| } | ||
| // [END googlegenaisdk_embeddings_docretrieval_with_txt] | ||
|
|
||
| module.exports = { | ||
| generateEmbeddingsForRetrieval, | ||
| }; |
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,43 @@ | ||
| // Copyright 2025 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 | ||
| // | ||
| // https://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. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| // [START googlegenaisdk_vertexai_express_mode] | ||
| const {GoogleGenAI} = require('@google/genai'); | ||
| const API_KEY = 'PUT HERE YOUR API KEY'; | ||
|
|
||
| async function generateWithApiKey(apiKey = API_KEY) { | ||
| const client = new GoogleGenAI({ | ||
| vertexai: true, | ||
| apiKey: apiKey, | ||
| }); | ||
|
|
||
| const response = await client.models.generateContentStream({ | ||
| model: 'gemini-2.5-flash', | ||
| contents: 'Explain bubble sort to me.', | ||
| }); | ||
|
|
||
| console.log(response.text); | ||
|
|
||
| // Example response: | ||
| // Bubble Sort is a simple sorting algorithm that repeatedly steps through the list | ||
|
|
||
| return response; | ||
| } | ||
| // [END googlegenaisdk_vertexai_express_mode] | ||
|
|
||
| module.exports = { | ||
| generateWithApiKey, | ||
| }; | ||
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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
62 changes: 62 additions & 0 deletions
62
genai/provisioned-throughput/provisionedthroughput-with-txt.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,62 @@ | ||
| // Copyright 2025 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 | ||
| // | ||
| // https://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. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| // [START googlegenaisdk_provisionedthroughput_with_txt] | ||
| const {GoogleGenAI} = require('@google/genai'); | ||
|
|
||
| const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT; | ||
| const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global'; | ||
|
|
||
| async function generateWithProvisionedThroughput( | ||
| projectId = GOOGLE_CLOUD_PROJECT, | ||
| location = GOOGLE_CLOUD_LOCATION | ||
| ) { | ||
| const client = new GoogleGenAI({ | ||
| vertexai: true, | ||
| project: projectId, | ||
| location: location, | ||
| httpOptions: { | ||
| apiVersion: 'v1', | ||
| headers: { | ||
| // Options: | ||
| // - "dedicated": Use Provisioned Throughput | ||
| // - "shared": Use pay-as-you-go | ||
| // https://cloud.google.com/vertex-ai/generative-ai/docs/use-provisioned-throughput | ||
| 'X-Vertex-AI-LLM-Request-Type': 'shared', | ||
Guiners marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| const response = await client.models.generateContent({ | ||
| model: 'gemini-2.5-flash', | ||
| contents: 'How does AI work?', | ||
| }); | ||
|
|
||
| console.log(response.text); | ||
|
|
||
| // Example response: | ||
| // Okay, let's break down how AI works. It's a broad field, so I'll focus on the ... | ||
| // Here's a simplified overview: | ||
| // ... | ||
|
|
||
| return response.text; | ||
| } | ||
|
|
||
| // [END googlegenaisdk_provisionedthroughput_with_txt] | ||
|
|
||
| module.exports = { | ||
| generateWithProvisionedThroughput, | ||
| }; | ||
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,115 @@ | ||
| // Copyright 2025 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 | ||
| // | ||
| // https://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. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| // [START googlegenaisdk_safety_with_txt] | ||
| const {GoogleGenAI} = require('@google/genai'); | ||
|
|
||
| const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT; | ||
| const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global'; | ||
|
|
||
| async function generateWithSafetySettings( | ||
| projectId = GOOGLE_CLOUD_PROJECT, | ||
| location = GOOGLE_CLOUD_LOCATION | ||
| ) { | ||
| const client = new GoogleGenAI({ | ||
| vertexai: true, | ||
| project: projectId, | ||
| location: location, | ||
| }); | ||
|
|
||
| const systemInstruction = 'Be as mean as possible.'; | ||
|
|
||
| const prompt = | ||
| 'Write a list of 5 disrespectful things that I might say to the universe after stubbing my toe in the dark.'; | ||
|
|
||
| const safetySettings = [ | ||
| { | ||
| category: 'HARM_CATEGORY_DANGEROUS_CONTENT', | ||
| threshold: 'BLOCK_LOW_AND_ABOVE', | ||
| }, | ||
| { | ||
| category: 'HARM_CATEGORY_HARASSMENT', | ||
| threshold: 'BLOCK_LOW_AND_ABOVE', | ||
| }, | ||
| { | ||
| category: 'HARM_CATEGORY_HATE_SPEECH', | ||
| threshold: 'BLOCK_LOW_AND_ABOVE', | ||
| }, | ||
| { | ||
| category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', | ||
| threshold: 'BLOCK_LOW_AND_ABOVE', | ||
| }, | ||
| ]; | ||
|
|
||
| const response = await client.models.generateContent({ | ||
| model: 'gemini-2.5-flash', | ||
| contents: prompt, | ||
| config: { | ||
| systemInstruction: systemInstruction, | ||
| safetySettings: safetySettings, | ||
| }, | ||
| }); | ||
|
|
||
| // console.log(response.text); | ||
| // console.log(response.candidates[0].finishMessage); | ||
| // | ||
| // for (const each of response.candidates[0].safetyRatings) { | ||
| // console.log('\nCategory:', String(each.category)); | ||
| // console.log('Is Blocked:', each.blocked); | ||
| // console.log('Probability:', each.probability); | ||
| // console.log('Probability Score:', each.probabilityScore); | ||
| // console.log('Severity:', each.severity); | ||
| // console.log('Severity Score:', each.severityScore); | ||
| // } | ||
|
|
||
| // Example response: | ||
| // | ||
| // Category: HarmCategory.HARM_CATEGORY_HATE_SPEECH | ||
| // Is Blocked: False | ||
| // Probability: HarmProbability.NEGLIGIBLE | ||
| // Probability Score: 2.547714e-05 | ||
| // Severity: HarmSeverity.HARM_SEVERITY_NEGLIGIBLE | ||
| // Severity Score: None | ||
| // | ||
| // Category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT | ||
| // Is Blocked: False | ||
| // Probability: HarmProbability.NEGLIGIBLE | ||
| // Probability Score: 3.6103818e-06 | ||
| // Severity: HarmSeverity.HARM_SEVERITY_NEGLIGIBLE | ||
| // Severity Score: None | ||
| // | ||
| // Category: HarmCategory.HARM_CATEGORY_HARASSMENT | ||
| // Is Blocked: True | ||
| // Probability: HarmProbability.MEDIUM | ||
| // Probability Score: 0.71599233 | ||
| // Severity: HarmSeverity.HARM_SEVERITY_MEDIUM | ||
| // Severity Score: 0.30782545 | ||
| // | ||
| // Category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT | ||
| // Is Blocked: False | ||
| // Probability: HarmProbability.NEGLIGIBLE | ||
| // Probability Score: 1.5624657e-05 | ||
| // Severity: HarmSeverity.HARM_SEVERITY_NEGLIGIBLE | ||
| // Severity Score: None | ||
|
|
||
| return response; | ||
| } | ||
|
|
||
| // [END googlegenaisdk_safety_with_txt] | ||
|
|
||
| module.exports = { | ||
| generateWithSafetySettings, | ||
| }; |
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,53 @@ | ||
| // Copyright 2025 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 | ||
| // | ||
| // https://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. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| const {assert} = require('chai'); | ||
| const {describe, it} = require('mocha'); | ||
| const {delay} = require('./util'); | ||
| const proxyquire = require('proxyquire').noCallThru(); | ||
|
|
||
| describe('vertexai-express-mode', () => { | ||
| it('should call generateContentStream and return the mocked response', async function () { | ||
| this.timeout(10000); | ||
|
|
||
| this.retries(4); | ||
| await delay(this.test); | ||
|
|
||
| const mockGenerateContentStreamResult = { | ||
| text: 'Bubble sort works by repeatedly swapping adjacent elements until sorted.', | ||
| }; | ||
|
|
||
| class MockModels { | ||
| async generateContentStream() { | ||
| return mockGenerateContentStreamResult; | ||
| } | ||
| } | ||
|
|
||
| class MockGoogleGenAI { | ||
| constructor() { | ||
| this.models = new MockModels(); | ||
| } | ||
| } | ||
|
|
||
| const sample = proxyquire('../express-mode/api-key-example.js', { | ||
| '@google/genai': {GoogleGenAI: MockGoogleGenAI}, | ||
| }); | ||
|
|
||
| const response = await sample.generateWithApiKey('FAKE_API_KEY'); | ||
|
|
||
| assert.strictEqual(response.text, mockGenerateContentStreamResult.text); | ||
| }); | ||
| }); |
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,31 @@ | ||
| // Copyright 2025 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 | ||
| // | ||
| // https://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. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| const {assert} = require('chai'); | ||
| const {describe, it} = require('mocha'); | ||
|
|
||
| const projectId = process.env.CAIP_PROJECT_ID; | ||
| const sample = require('../embeddings/embeddings-docretrieval-with-txt.js'); | ||
| const {delay} = require('./util'); | ||
|
|
||
| describe('embeddings-docretrieval-with-txt', () => { | ||
| it('should return an object containing embeddings and metadata', async function () { | ||
| this.retries(4); | ||
| await delay(this.test); | ||
| const result = await sample.generateEmbeddingsForRetrieval(projectId); | ||
| assert.containsAllKeys(result, ['embeddings', 'metadata']); | ||
| }); | ||
| }); |
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
Oops, something went wrong.
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.