Skip to content

Commit ed7f161

Browse files
feat(vertexai): add sample for text translation with gemini
1 parent b9b28d7 commit ed7f161

File tree

5 files changed

+164
-0
lines changed

5 files changed

+164
-0
lines changed
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"],
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+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
backoff==2.2.1
2+
google-api-core==2.19.0
3+
pytest==8.2.0
4+
pytest-asyncio==0.23.6
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
pandas==1.3.5; python_version == '3.7'
2+
pandas==2.0.3; python_version == '3.8'
3+
pandas==2.1.4; python_version > '3.8'
4+
pillow==10.3.0; python_version < '3.8'
5+
pillow==10.3.0; python_version >= '3.8'
6+
google-cloud-aiplatform[all]==1.73.0
7+
sentencepiece==0.2.0
8+
google-auth==2.29.0
9+
anthropic[vertex]==0.28.0
10+
langchain-core==0.2.11
11+
langchain-google-vertexai==1.0.6
12+
numpy<2
13+
openai==1.30.5
14+
immutabledict==4.2.0
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Copyright 2024 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+
# https://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+
import backoff
16+
17+
from google.api_core.exceptions import ResourceExhausted
18+
19+
import translate_text_gemini
20+
21+
22+
@backoff.on_exception(backoff.expo, ResourceExhausted, max_time=10)
23+
def test_translate_text_gemini() -> None:
24+
response = translate_text_gemini.generate_translation
25+
assert response
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Copyright 2024 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+
# https://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+
import os
15+
16+
from vertexai.generative_models import GenerationResponse
17+
18+
PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
19+
20+
21+
def generate_translation() -> GenerationResponse:
22+
# [START generativeaionvertexai_translate_text_gemini]
23+
import vertexai
24+
25+
from vertexai.generative_models import GenerativeModel, HarmBlockThreshold, HarmCategory
26+
27+
# TODO(developer): Update and un-comment below line
28+
# PROJECT_ID = "your-project-id"
29+
vertexai.init(project=PROJECT_ID, location="us-central1")
30+
31+
model = GenerativeModel("gemini-1.5-flash-002")
32+
33+
prompt = """
34+
Translate the text from source to target language and return the translated text.
35+
36+
TEXT: Google's Generative AI API lets you use a large language model (LLM) to dynamically translate text.
37+
SOURCE_LANGUAGE_CODE: EN
38+
TARGET_LANGUAGE_CODE: FR
39+
"""
40+
41+
# Check the API reference for details:
42+
# https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#generationconfig
43+
generation_config = {
44+
"candidate_count": 1,
45+
"max_output_tokens": 8192,
46+
"temperature": 0.2,
47+
"top_k": 40.0,
48+
"top_p": 0.95,
49+
}
50+
safety_settings = {
51+
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
52+
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
53+
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
54+
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
55+
}
56+
# Send request to Gemini
57+
response = model.generate_content(
58+
prompt,
59+
generation_config=generation_config,
60+
safety_settings=safety_settings,
61+
)
62+
63+
print(f"Translation:\n{response.text}", )
64+
print(f"Usage metadata:\n{response.usage_metadata}")
65+
# Example response:
66+
# Translation:
67+
# L'API d'IA générative de Google vous permet d'utiliser un grand modèle linguistique (LLM) pour traduire dynamiquement du texte.
68+
#
69+
# Usage metadata:
70+
# prompt_token_count: 63
71+
# candidates_token_count: 32
72+
# total_token_count: 95
73+
74+
# [END generativeaionvertexai_translate_text_gemini]
75+
return response
76+
77+
78+
if __name__ == "__main__":
79+
generate_translation()

0 commit comments

Comments
 (0)