Skip to content

Commit d3c36d2

Browse files
authored
feat(genai): Multiple updates to improve samples quality, consistency and readability (#13157)
* feat(genai): Update Gen AI SDK Samples for Consistency/Readability - Updated to latest SDK version - Added Typing and consistent imports - Changed all GA Samples to include `HttpOptions` for `v1` endpoint - Updated Gemini 2.0 Exp to Gemini 2.0 Flash GA - Updated Batch Prediction to Gemini 2.0 GA * Fix issue with PIL Image load * Rename BatchPredict Files
1 parent d99c471 commit d3c36d2

33 files changed

+174
-143
lines changed

genai/batch_prediction/submit_with_bq.py renamed to genai/batch_prediction/batchpredict_with_bq.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,17 @@ def generate_content(output_uri: str) -> str:
1818
import time
1919

2020
from google import genai
21+
from google.genai.types import CreateBatchJobConfig, JobState, HttpOptions
22+
23+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2124

22-
client = genai.Client()
2325
# TODO(developer): Update and un-comment below line
2426
# output_uri = f"bq://your-project.your_dataset.your_table"
2527

2628
job = client.batches.create(
27-
model="gemini-1.5-pro-002",
29+
model="gemini-2.0-flash-001",
2830
src="bq://storage-samples.generative_ai.batch_requests_for_multimodal_input",
29-
config={
30-
"dest": output_uri
31-
}
31+
config=CreateBatchJobConfig(dest=output_uri),
3232
)
3333
print(f"Job name: {job.name}")
3434
print(f"Job state: {job.state}")
@@ -37,12 +37,13 @@ def generate_content(output_uri: str) -> str:
3737
# Job state: JOB_STATE_PENDING
3838

3939
# See the documentation: https://googleapis.github.io/python-genai/genai.html#genai.types.BatchJob
40-
completed_states = [
41-
"JOB_STATE_SUCCEEDED",
42-
"JOB_STATE_FAILED",
43-
"JOB_STATE_CANCELLED",
44-
"JOB_STATE_PAUSED",
45-
]
40+
completed_states = {
41+
JobState.JOB_STATE_SUCCEEDED,
42+
JobState.JOB_STATE_FAILED,
43+
JobState.JOB_STATE_CANCELLED,
44+
JobState.JOB_STATE_PAUSED,
45+
}
46+
4647
while job.state not in completed_states:
4748
time.sleep(30)
4849
job = client.batches.get(name=job.name)
@@ -59,6 +60,4 @@ def generate_content(output_uri: str) -> str:
5960

6061

6162
if __name__ == "__main__":
62-
generate_content(
63-
output_uri="bq://your-project.your_dataset.your_table"
64-
)
63+
generate_content(output_uri="bq://your-project.your_dataset.your_table")

genai/batch_prediction/submit_with_gcs.py renamed to genai/batch_prediction/batchpredict_with_gcs.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,18 @@ def generate_content(output_uri: str) -> str:
1818
import time
1919

2020
from google import genai
21+
from google.genai.types import CreateBatchJobConfig, JobState, HttpOptions
2122

22-
client = genai.Client()
23+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2324
# TODO(developer): Update and un-comment below line
2425
# output_uri = "gs://your-bucket/your-prefix"
2526

2627
# See the documentation: https://googleapis.github.io/python-genai/genai.html#genai.batches.Batches.create
2728
job = client.batches.create(
28-
model="gemini-1.5-pro-002",
29+
model="gemini-2.0-flash-001",
2930
# Source link: https://storage.cloud.google.com/cloud-samples-data/batch/prompt_for_batch_gemini_predict.jsonl
3031
src="gs://cloud-samples-data/batch/prompt_for_batch_gemini_predict.jsonl",
31-
config={
32-
"dest": output_uri
33-
}
32+
config=CreateBatchJobConfig(dest=output_uri),
3433
)
3534
print(f"Job name: {job.name}")
3635
print(f"Job state: {job.state}")
@@ -39,12 +38,13 @@ def generate_content(output_uri: str) -> str:
3938
# Job state: JOB_STATE_PENDING
4039

4140
# See the documentation: https://googleapis.github.io/python-genai/genai.html#genai.types.BatchJob
42-
completed_states = [
43-
"JOB_STATE_SUCCEEDED",
44-
"JOB_STATE_FAILED",
45-
"JOB_STATE_CANCELLED",
46-
"JOB_STATE_PAUSED",
47-
]
41+
completed_states = {
42+
JobState.JOB_STATE_SUCCEEDED,
43+
JobState.JOB_STATE_FAILED,
44+
JobState.JOB_STATE_CANCELLED,
45+
JobState.JOB_STATE_PAUSED,
46+
}
47+
4848
while job.state not in completed_states:
4949
time.sleep(30)
5050
job = client.batches.get(name=job.name)
@@ -61,6 +61,4 @@ def generate_content(output_uri: str) -> str:
6161

6262

6363
if __name__ == "__main__":
64-
generate_content(
65-
output_uri="gs://your-bucket/your-prefix"
66-
)
64+
generate_content(output_uri="gs://your-bucket/your-prefix")
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
google-genai==0.8.0
1+
google-genai==1.2.0

genai/batch_prediction/test_batch_predict.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@
2020

2121
import pytest
2222

23-
import submit_with_bq
24-
import submit_with_gcs
23+
import batchpredict_with_bq
24+
import batchpredict_with_gcs
2525

2626

2727
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
@@ -57,10 +57,10 @@ def gcs_output_uri():
5757

5858

5959
def test_batch_prediction_with_bq(bq_output_uri) -> None:
60-
response = submit_with_bq.generate_content(output_uri=bq_output_uri)
60+
response = batchpredict_with_bq.generate_content(output_uri=bq_output_uri)
6161
assert response == JobState.JOB_STATE_SUCCEEDED
6262

6363

6464
def test_batch_prediction_with_gcs(gcs_output_uri) -> None:
65-
response = submit_with_gcs.generate_content(output_uri=gcs_output_uri)
65+
response = batchpredict_with_gcs.generate_content(output_uri=gcs_output_uri)
6666
assert response == JobState.JOB_STATE_SUCCEEDED

genai/controlled_generation/ctrlgen_with_class_schema.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,23 +16,27 @@
1616
def generate_content() -> str:
1717
# [START googlegenaisdk_ctrlgen_with_class_schema]
1818
from google import genai
19+
from google.genai.types import GenerateContentConfig, HttpOptions
20+
1921
from pydantic import BaseModel
2022

2123
class Recipe(BaseModel):
2224
recipe_name: str
2325
ingredients: list[str]
2426

25-
client = genai.Client()
27+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2628
response = client.models.generate_content(
2729
model="gemini-2.0-flash-001",
2830
contents="List a few popular cookie recipes.",
29-
config={
30-
"response_mime_type": "application/json",
31-
"response_schema": list[Recipe],
32-
},
31+
config=GenerateContentConfig(
32+
response_mime_type="application/json",
33+
response_schema=list[Recipe],
34+
),
3335
)
3436
# Use the response as a JSON string.
3537
print(response.text)
38+
# Use the response as an object
39+
print(response.parsed)
3640

3741
# Example output:
3842
# [Recipe(recipe_name='Chocolate Chip Cookies', ingredients=['2 1/4 cups all-purpose flour'

genai/controlled_generation/ctrlgen_with_enum_schema.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,19 @@
1616
def generate_content() -> str:
1717
# [START googlegenaisdk_ctrlgen_with_enum_schema]
1818
from google import genai
19+
from google.genai.types import GenerateContentConfig, HttpOptions
1920

20-
client = genai.Client()
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2122
response = client.models.generate_content(
2223
model="gemini-2.0-flash-001",
2324
contents="What type of instrument is an oboe?",
24-
config={
25-
"response_mime_type": "text/x.enum",
26-
"response_schema": {
25+
config=GenerateContentConfig(
26+
response_mime_type="text/x.enum",
27+
response_schema={
2728
"type": "STRING",
2829
"enum": ["Percussion", "String", "Woodwind", "Brass", "Keyboard"],
2930
},
30-
},
31+
),
3132
)
3233

3334
print(response.text)

genai/controlled_generation/ctrlgen_with_nested_class_schema.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@
1515

1616
def generate_content() -> str:
1717
# [START googlegenaisdk_ctrlgen_with_nested_class_schema]
18+
import enum
19+
1820
from google import genai
21+
from google.genai.types import GenerateContentConfig, HttpOptions
1922

20-
import enum
2123
from pydantic import BaseModel
2224

2325
class Grade(enum.Enum):
@@ -32,14 +34,14 @@ class Recipe(BaseModel):
3234
recipe_name: str
3335
rating: Grade
3436

35-
client = genai.Client()
37+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
3638
response = client.models.generate_content(
3739
model="gemini-2.0-flash-001",
3840
contents="List about 10 home-baked cookies and give them grades based on tastiness.",
39-
config={
40-
"response_mime_type": "application/json",
41-
"response_schema": list[Recipe],
42-
},
41+
config=GenerateContentConfig(
42+
response_mime_type="application/json",
43+
response_schema=list[Recipe],
44+
),
4345
)
4446

4547
print(response.text)

genai/controlled_generation/ctrlgen_with_nullable_schema.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
def generate_content() -> str:
1717
# [START googlegenaisdk_ctrlgen_with_nullable_schema]
1818
from google import genai
19+
from google.genai.types import GenerateContentConfig, HttpOptions
1920

2021
response_schema = {
2122
"type": "OBJECT",
@@ -48,14 +49,14 @@ def generate_content() -> str:
4849
Finally, Saturday rounds off the week with sunny skies, a temperature of 80°F, and a humidity level of 40%. Winds will be gentle at 8 km/h.
4950
"""
5051

51-
client = genai.Client()
52+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
5253
response = client.models.generate_content(
5354
model="gemini-2.0-flash-001",
5455
contents=prompt,
55-
config={
56-
"response_mime_type": "application/json",
57-
"response_schema": response_schema,
58-
},
56+
config=GenerateContentConfig(
57+
response_mime_type="application/json",
58+
response_schema=response_schema,
59+
),
5960
)
6061

6162
print(response.text)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
google-genai==1.2.0
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
google-genai==1.0.0
1+
google-genai==1.2.0

genai/text_generation/textgen_async_with_txt.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@
1818
async def generate_content() -> str:
1919
# [START googlegenaisdk_textgen_async_with_txt]
2020
from google import genai
21-
from google.genai.types import GenerateContentConfig
21+
from google.genai.types import GenerateContentConfig, HttpOptions
2222

23-
client = genai.Client()
24-
model_id = "gemini-2.0-flash-exp"
23+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
24+
model_id = "gemini-2.0-flash-001"
2525

2626
response = await client.aio.models.generate_content(
2727
model=model_id,

genai/text_generation/textgen_chat_stream_with_txt.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@
1616
def generate_content() -> str:
1717
# [START googlegenaisdk_textgen_chat_stream_with_txt]
1818
from google import genai
19+
from google.genai.types import HttpOptions
1920

20-
client = genai.Client(http_options={'api_version': 'v1'})
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2122
chat = client.chats.create(model="gemini-2.0-flash-001")
2223
response_text = ""
2324

2425
for chunk in chat.send_message_stream("Why is the sky blue?"):
25-
print(chunk.text)
26+
print(chunk.text, end="")
2627
response_text += chunk.text
2728
# Example response:
2829
# The

genai/text_generation/textgen_chat_with_txt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
def generate_content() -> str:
1717
# [START googlegenaisdk_textgen_chat_with_txt]
1818
from google import genai
19-
from google.genai.types import Content, Part
19+
from google.genai.types import Content, HttpOptions, Part
2020

21-
client = genai.Client(http_options={'api_version': 'v1'})
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2222
chat = client.chats.create(
2323
model="gemini-2.0-flash-001",
2424
history=[

genai/text_generation/textgen_code_with_pdf.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@
1818
def generate_content() -> str:
1919
# [START googlegenaisdk_textgen_code_with_pdf]
2020
from google import genai
21-
from google.genai import types
21+
from google.genai.types import HttpOptions, Part
2222

23-
client = genai.Client()
24-
model_id = "gemini-2.0-flash-exp"
23+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
24+
model_id = "gemini-2.0-flash-001"
2525

26-
python_code = types.Part.from_uri(
26+
python_code = Part.from_uri(
2727
file_uri="https://storage.googleapis.com/cloud-samples-data/generative-ai/text/inefficient_fibonacci_series_python_code.pdf",
2828
mime_type="application/pdf",
2929
)

genai/text_generation/textgen_config_with_txt.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,14 @@
1616
def generate_content() -> str:
1717
# [START googlegenaisdk_textgen_config_with_txt]
1818
from google import genai
19-
from google.genai import types
19+
from google.genai.types import GenerateContentConfig, HttpOptions
2020

21-
client = genai.Client(http_options={'api_version': 'v1'})
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2222
response = client.models.generate_content(
2323
model="gemini-2.0-flash-001",
2424
contents="Why is the sky blue?",
2525
# See the documentation: https://googleapis.github.io/python-genai/genai.html#genai.types.GenerateContentConfig
26-
config=types.GenerateContentConfig(
26+
config=GenerateContentConfig(
2727
temperature=0,
2828
candidate_count=1,
2929
response_mime_type="application/json",

genai/text_generation/textgen_sys_instr_with_txt.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@
1616
def generate_content() -> str:
1717
# [START googlegenaisdk_textgen_sys_instr_with_txt]
1818
from google import genai
19-
from google.genai import types
19+
from google.genai.types import GenerateContentConfig, HttpOptions
2020

21-
client = genai.Client(http_options={'api_version': 'v1'})
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2222
response = client.models.generate_content(
2323
model="gemini-2.0-flash-001",
2424
contents="Why is the sky blue?",
25-
config=types.GenerateContentConfig(
25+
config=GenerateContentConfig(
2626
system_instruction=[
2727
"You're a language translator.",
2828
"Your mission is to translate text in English to French.",

genai/text_generation/textgen_transcript_with_gcs_audio.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
def generate_content() -> str:
1717
# [START googlegenaisdk_textgen_transcript_with_gcs_audio]
1818
from google import genai
19-
from google.genai.types import Part
19+
from google.genai.types import HttpOptions, Part
2020

21-
client = genai.Client(http_options={'api_version': 'v1'})
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2222
prompt = """
2323
Transcribe the interview, in the format of timecode, speaker, caption.
2424
Use speaker A, speaker B, etc. to identify speakers.

genai/text_generation/textgen_with_gcs_audio.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
def generate_content() -> str:
1717
# [START googlegenaisdk_textgen_with_gcs_audio]
1818
from google import genai
19-
from google.genai.types import Part
19+
from google.genai.types import HttpOptions, Part
2020

21-
client = genai.Client(http_options={'api_version': 'v1'})
21+
client = genai.Client(http_options=HttpOptions(api_version="v1"))
2222
prompt = """
2323
Provide the summary of the audio file.
2424
Summarize the main points of the audio concisely.

0 commit comments

Comments
 (0)