Skip to content

Commit 8a8369c

Browse files
refactor(genai): refactor GenAI code samples (#13166)
* refactor(genai): Update docs, filename and comments * update template folder examples * refactor(genai): Update docs, filename and comments * update template folder examples * refactor(genai): Update docs, filename and comments * update template folder examples * refactor(genai): clean unused file & update pkg version * refactor(genai): rollback accidental changes * docs(genai): update readme pages * docs(genai): Temporarily restoring old region tags * docs(genai): Temporarily restoring old region tags
1 parent 0586ab2 commit 8a8369c

24 files changed

+251
-198
lines changed

genai/README.md

Lines changed: 47 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,65 @@
11
# Generative AI Samples on Google Cloud
22

3-
Welcome to the Python samples folder for Generative AI on Vertex AI! In this folder, you can find the Python samples
4-
used in [Google Cloud Generative AI documentation](https://cloud.google.com/ai/generative-ai?hl=en).
5-
6-
If you are looking for colab notebook, then please check https://github.com/GoogleCloudPlatform/generative-ai.
3+
This directory contains Python code samples demonstrating how to use Google Cloud's Generative AI capabilities on Vertex AI. These samples accompany the [Google Cloud Generative AI documentation](https://cloud.google.com/ai/generative-ai) and provide practical examples of various features and use cases.
74

85
## Getting Started
96

10-
To try and run these Code samples, we recommend using Google Cloud IDE or Google Colab.
7+
To run these samples, we recommend using either Google Cloud Shell, Cloud Code IDE, or Google Colab. You'll need a Google Cloud Project and appropriate credentials.
8+
9+
**Prerequisites:**
10+
11+
- **Google Cloud Project:** Create or select a project in the [Google Cloud Console](https://console.cloud.google.com).
12+
- **Authentication:** Ensure you've authenticated with your Google Cloud account. See the [authentication documentation](https://cloud.google.com/docs/authentication) for details.
13+
- **Enable the Vertex AI API:** Enable the API in your project through the [Cloud Console](https://console.cloud.google.com/apis/library/aiplatform.googleapis.com).
14+
15+
## Sample Categories
16+
17+
The samples are organized into the following categories:
18+
19+
### Batch Prediction (`batch_prediction`)
20+
21+
Demonstrates how to use batch prediction with Generative AI models. This allows efficient processing of large datasets. See the [Batch Prediction documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/batch-prediction-gemini) for more details.
22+
23+
### Content Cache (`content_cache`)
24+
25+
Illustrates how to create, update, use, and delete content caches. Caches store frequently used content to improve performance and reduce costs. See the [Content Cache documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview) for more information.
26+
27+
### Controlled Generation (`controlled_generation`)
28+
29+
Provides examples of how to control various aspects of the generated content, such as length, format, safety attributes, and more. This allows for tailoring the output to specific requirements and constraints. See the [Controlled Generation documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/control-generated-output) for details.
30+
31+
### Count Tokens (`count_tokens`)
32+
33+
Shows how to estimate token usage for inputs and outputs of Generative AI models. Understanding token consumption is crucial for managing costs and optimizing performance. See the [Token Counting documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/list-token) for more details.
34+
35+
### Express Mode (`express_mode`)
36+
37+
Demonstrates how to use Express Mode for simpler and faster interactions with Generative AI models using an API key. This mode is ideal for quick prototyping and experimentation. See the [Express Mode documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview) for details.
38+
39+
### Live API (`live_api`)
40+
41+
Provides examples of using the Generative AI [Live API](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal-live-api). This allows for real-time interactions and dynamic content generation.
42+
43+
### Safety (`safety`)
1144

12-
Note: A Google Cloud Project is a pre-requisite.
45+
Provides examples demonstrating how to configure and apply safety settings to Generative AI models. This includes techniques for content filtering and moderation to ensure responsible AI usage. See the [Safety documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/configure-safety-attributes) for details.
1346

14-
## Features folders
47+
### Text Generation (`text_generation`)
1548

16-
All GenAI code samples are organised into folders, referred as Feature folders.
49+
Provides examples of generating text using various input modalities (text, images, audio, video) and features like asynchronous generation, chat, and text streaming. See the [Text Generation documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/send-chat-prompts-gemini) for details.
1750

18-
### Features
51+
### Tools (`tools`)
1952

20-
<table>
21-
<tr>
22-
<td><strong>Python Samples Folder</strong>
23-
</td>
24-
<td><strong>Google Cloud Product</strong>
25-
</td>
26-
<td><strong>Short Description</strong></td>
27-
</tr>
28-
<tr>
29-
<td>[Template Folder](/template_folder) </td>
30-
<td><a href="add-link-here">Link to the feature</a> </td>
31-
<td>Short description</td>
32-
</tr>
33-
</table>
53+
Showcases how to use tools like function calling, code execution, and grounding with Google Search to enhance Generative AI interactions. See the [Tools documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling) for more information.
3454

3555
## Contributing
3656

37-
Contributions welcome! See the [Contributing Guide](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/CONTRIBUTING.md).
57+
Contributions are welcome! See the [Contributing Guide](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/CONTRIBUTING.md).
3858

39-
## Getting help
59+
## Getting Help
4060

41-
Please use the [issues page](https://github.com/GoogleCloudPlatform/python-docs-samples/issues) to provide suggestions, feedback or submit a bug report.
61+
For questions, feedback, or bug reports, please use the [issues page](https://github.com/GoogleCloudPlatform/python-docs-samples/issues).
4262

4363
## Disclaimer
4464

45-
This repository itself is not an officially supported Google product. The code in this repository is for demonstrative purposes only.
65+
This repository is not an officially supported Google product. The code is provided for demonstrative purposes only.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Copyright 2021 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# Default TEST_CONFIG_OVERRIDE for python repos.
16+
17+
# You can copy this file into your directory, then it will be imported from
18+
# the noxfile.py.
19+
20+
# The source of truth:
21+
# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/noxfile_config.py
22+
23+
TEST_CONFIG_OVERRIDE = {
24+
# You can opt out from the test for specific Python versions.
25+
"ignored_versions": ["2.7", "3.7", "3.8", "3.10", "3.11", "3.12"],
26+
# Old samples are opted out of enforcing Python type hints
27+
# All new samples should feature them
28+
"enforce_type_hints": True,
29+
# An envvar key for determining the project id to use. Change it
30+
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
31+
# build specific Cloud project. You can also use your own string
32+
# to use your own Cloud project.
33+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
34+
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',
35+
# If you need to use a specific version of pip,
36+
# change pip_version_override to the string representation
37+
# of the version number, for example, "20.2.4"
38+
"pip_version_override": None,
39+
# A dictionary you want to inject into your test. Don't put any
40+
# secrets here. These values will override predefined values.
41+
"envs": {},
42+
}

genai/batch_prediction/test_batch_predict.py renamed to genai/batch_prediction/test_batch_prediction_examples.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,12 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
#
16+
# Using Google Cloud Vertex AI to test the code samples.
17+
#
18+
1519
from datetime import datetime as dt
20+
1621
import os
1722

1823
from google.cloud import bigquery, storage
@@ -33,7 +38,7 @@
3338

3439

3540
@pytest.fixture(scope="session")
36-
def bq_output_uri():
41+
def bq_output_uri() -> str:
3742
table_name = f"text_output_{dt.now().strftime('%Y_%m_%d_T%H_%M_%S')}"
3843
table_uri = f"{BQ_OUTPUT_DATASET}.{table_name}"
3944

@@ -44,7 +49,7 @@ def bq_output_uri():
4449

4550

4651
@pytest.fixture(scope="session")
47-
def gcs_output_uri():
52+
def gcs_output_uri() -> str:
4853
prefix = f"text_output/{dt.now()}"
4954

5055
yield f"gs://{GCS_OUTPUT_BUCKET}/{prefix}"
@@ -56,11 +61,11 @@ def gcs_output_uri():
5661
blob.delete()
5762

5863

59-
def test_batch_prediction_with_bq(bq_output_uri) -> None:
64+
def test_batch_prediction_with_bq(bq_output_uri: str) -> None:
6065
response = batchpredict_with_bq.generate_content(output_uri=bq_output_uri)
6166
assert response == JobState.JOB_STATE_SUCCEEDED
6267

6368

64-
def test_batch_prediction_with_gcs(gcs_output_uri) -> None:
69+
def test_batch_prediction_with_gcs(gcs_output_uri: str) -> None:
6570
response = batchpredict_with_gcs.generate_content(output_uri=gcs_output_uri)
6671
assert response == JobState.JOB_STATE_SUCCEEDED

genai/content_cache/contentcache_use_with_txt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ def generate_content(cache_name: str) -> str:
2323
# Use content cache to generate text response
2424
# E.g cache_name = 'projects/111111111111/locations/us-central1/cachedContents/1111111111111111111'
2525
response = client.models.generate_content(
26-
model='gemini-1.5-pro-002',
27-
contents='Summarize the pdfs',
26+
model="gemini-1.5-pro-002",
27+
contents="Summarize the pdfs",
2828
config=GenerateContentConfig(
2929
cached_content=cache_name,
3030
),

genai/count_tokens/count_tokens_compute_with_txt.py renamed to genai/count_tokens/counttoken_compute_with_txt.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313
# limitations under the License.
1414

1515

16-
def compute_tokens() -> int:
16+
def compute_tokens_example() -> int:
17+
# TODO: Remove `count_tokens` region tags after Feb 2025
1718
# [START googlegenaisdk_count_tokens_compute_with_txt]
19+
# [START googlegenaisdk_counttoken_compute_with_txt]
1820
from google import genai
1921
from google.genai.types import HttpOptions
2022

@@ -32,9 +34,10 @@ def compute_tokens() -> int:
3234
# tokens=[b'What', b"'", b's', b' the', b' longest', b' word', b' in', b' the', b' English', b' language', b'?']
3335
# )]
3436

37+
# [END googlegenaisdk_counttoken_compute_with_txt]
3538
# [END googlegenaisdk_count_tokens_compute_with_txt]
3639
return response.tokens_info
3740

3841

3942
if __name__ == "__main__":
40-
compute_tokens()
43+
compute_tokens_example()

genai/count_tokens/count_tokens_resp_with_txt.py renamed to genai/count_tokens/counttoken_resp_with_txt.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313
# limitations under the License.
1414

1515

16-
def generate_content() -> int:
16+
def count_tokens_example() -> int:
17+
# TODO: Remove `count_tokens` region tags after Feb 2025
1718
# [START googlegenaisdk_count_tokens_resp_with_txt]
19+
# [START googlegenaisdk_counttoken_resp_with_txt]
1820
from google import genai
1921
from google.genai.types import HttpOptions
2022

@@ -36,9 +38,10 @@ def generate_content() -> int:
3638
# prompt_token_count=6
3739
# total_token_count=317
3840

41+
# [END googlegenaisdk_counttoken_resp_with_txt]
3942
# [END googlegenaisdk_count_tokens_resp_with_txt]
4043
return response.usage_metadata
4144

4245

4346
if __name__ == "__main__":
44-
generate_content()
47+
count_tokens_example()

genai/count_tokens/count_tokens_with_txt.py renamed to genai/count_tokens/counttoken_with_txt.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414

1515

1616
def count_tokens() -> int:
17+
# TODO: Remove `count_tokens` region tags after Feb 2025
1718
# [START googlegenaisdk_count_tokens_with_txt]
19+
# [START googlegenaisdk_counttoken_with_txt]
1820
from google import genai
1921
from google.genai.types import HttpOptions
2022

@@ -28,6 +30,7 @@ def count_tokens() -> int:
2830
# total_tokens=10
2931
# cached_content_token_count=None
3032

33+
# [END googlegenaisdk_counttoken_with_txt]
3134
# [END googlegenaisdk_count_tokens_with_txt]
3235
return response.total_tokens
3336

genai/count_tokens/count_tokens_with_txt_img_vid.py renamed to genai/count_tokens/counttoken_with_txt_img_vid.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414

1515

1616
def count_tokens() -> int:
17+
# TODO: Remove `count_tokens` region tags after Feb 2025
1718
# [START googlegenaisdk_count_tokens_with_txt_img_vid]
19+
# [START googlegenaisdk_counttoken_with_txt_vid]
1820
from google import genai
1921
from google.genai.types import HttpOptions, Part
2022

@@ -37,6 +39,7 @@ def count_tokens() -> int:
3739
# Example output:
3840
# total_tokens=10 cached_content_token_count=None
3941

42+
# [END googlegenaisdk_counttoken_with_txt_vid]
4043
# [END googlegenaisdk_count_tokens_with_txt_img_vid]
4144
return response.total_tokens
4245

genai/count_tokens/test_count_tokens_samples.py renamed to genai/count_tokens/test_count_tokens_examples.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,28 +18,28 @@
1818

1919
import os
2020

21-
import count_tokens_compute_with_txt
22-
import count_tokens_resp_with_txt
23-
import count_tokens_with_txt
24-
import count_tokens_with_txt_img_vid
21+
import counttoken_compute_with_txt
22+
import counttoken_resp_with_txt
23+
import counttoken_with_txt
24+
import counttoken_with_txt_img_vid
2525

2626
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
2727
os.environ["GOOGLE_CLOUD_LOCATION"] = "us-central1"
2828
# The project name is included in the CICD pipeline
2929
# os.environ['GOOGLE_CLOUD_PROJECT'] = "add-your-project-name"
3030

3131

32-
def test_count_tokens_compute_with_txt() -> None:
33-
assert count_tokens_compute_with_txt.compute_tokens()
32+
def test_counttoken_compute_with_txt() -> None:
33+
assert counttoken_compute_with_txt.compute_tokens_example()
3434

3535

36-
def test_count_tokens_resp_with_txt() -> None:
37-
assert count_tokens_resp_with_txt.generate_content()
36+
def test_counttoken_resp_with_txt() -> None:
37+
assert counttoken_resp_with_txt.count_tokens_example()
3838

3939

40-
def test_count_tokens_with_txt() -> None:
41-
assert count_tokens_with_txt.count_tokens()
40+
def test_counttoken_with_txt() -> None:
41+
assert counttoken_with_txt.count_tokens()
4242

4343

44-
def test_count_tokens_with_txt_img_vid() -> None:
45-
assert count_tokens_with_txt_img_vid.count_tokens()
44+
def test_counttoken_with_txt_img_vid() -> None:
45+
assert counttoken_with_txt_img_vid.count_tokens()

0 commit comments

Comments
 (0)