-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat(genai): add tuning samples #10176
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
jdomingr
wants to merge
3
commits into
GoogleCloudPlatform:main
Choose a base branch
from
jdomingr:genai-sdk-tuning-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.
+495
−0
Open
Changes from 1 commit
Commits
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
121 changes: 121 additions & 0 deletions
121
genai/snippets/src/main/java/genai/tuning/TuningJobCreate.java
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,121 @@ | ||
/* | ||
* 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 | ||
* | ||
* http://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. | ||
*/ | ||
|
||
package genai.tuning; | ||
|
||
// [START googlegenaisdk_tuning_job_create] | ||
|
||
import static com.google.genai.types.JobState.Known.JOB_STATE_PENDING; | ||
import static com.google.genai.types.JobState.Known.JOB_STATE_RUNNING; | ||
|
||
import com.google.genai.Client; | ||
import com.google.genai.types.CreateTuningJobConfig; | ||
import com.google.genai.types.GetTuningJobConfig; | ||
import com.google.genai.types.HttpOptions; | ||
import com.google.genai.types.JobState; | ||
import com.google.genai.types.TunedModel; | ||
import com.google.genai.types.TunedModelCheckpoint; | ||
import com.google.genai.types.TuningDataset; | ||
import com.google.genai.types.TuningJob; | ||
import com.google.genai.types.TuningValidationDataset; | ||
import java.util.ArrayList; | ||
import java.util.EnumSet; | ||
import java.util.List; | ||
import java.util.Optional; | ||
import java.util.Set; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
public class TuningJobCreate { | ||
|
||
public static void main(String[] args) throws InterruptedException { | ||
// TODO(developer): Replace these variables before running the sample. | ||
String model = "gemini-2.5-flash"; | ||
createTuningJob(model); | ||
} | ||
|
||
// Shows how to create a supervised fine-tuning job using training and validation datasets | ||
public static String createTuningJob(String model) throws InterruptedException { | ||
// Client Initialization. Once created, it can be reused for multiple requests. | ||
try (Client client = | ||
Client.builder() | ||
.location("us-central1") | ||
.vertexAI(true) | ||
.httpOptions(HttpOptions.builder().apiVersion("v1beta1").build()) | ||
.build()) { | ||
|
||
String trainingDatasetUri = | ||
"gs://cloud-samples-data/ai-platform/generative_ai/gemini/text/sft_train_data.jsonl"; | ||
TuningDataset trainingDataset = TuningDataset.builder().gcsUri(trainingDatasetUri).build(); | ||
|
||
String validationDatasetUri = | ||
"gs://cloud-samples-data/ai-platform/generative_ai/gemini/text/sft_validation_data.jsonl"; | ||
TuningValidationDataset validationDataset = | ||
TuningValidationDataset.builder().gcsUri(validationDatasetUri).build(); | ||
|
||
TuningJob tuningJob = | ||
client.tunings.tune( | ||
model, | ||
trainingDataset, | ||
CreateTuningJobConfig.builder() | ||
.tunedModelDisplayName("your-display-name") | ||
.validationDataset(validationDataset) | ||
.build()); | ||
|
||
String jobName = | ||
tuningJob.name().orElseThrow(() -> new IllegalStateException("Failed to get job name")); | ||
Optional<JobState> jobState = tuningJob.state(); | ||
Set<JobState.Known> runningStates = EnumSet.of(JOB_STATE_PENDING, JOB_STATE_RUNNING); | ||
|
||
while (jobState.isPresent() && runningStates.contains(jobState.get().knownEnum())) { | ||
System.out.println("Job state: " + jobState.get()); | ||
tuningJob = client.tunings.get(jobName, GetTuningJobConfig.builder().build()); | ||
jobState = tuningJob.state(); | ||
TimeUnit.SECONDS.sleep(60); | ||
} | ||
|
||
tuningJob.tunedModel().flatMap(TunedModel::model).ifPresent(System.out::println); | ||
tuningJob.tunedModel().flatMap(TunedModel::endpoint).ifPresent(System.out::println); | ||
tuningJob.experiment().ifPresent(System.out::println); | ||
// Example response: | ||
// projects/123456789012/locations/us-central1/models/6129850992130260992@1 | ||
// projects/123456789012/locations/us-central1/endpoints/105055037499113472 | ||
// projects/123456789012/locations/us-central1/metadataStores/default/contexts/experiment_id | ||
|
||
List<TunedModelCheckpoint> checkpoints = | ||
tuningJob.tunedModel().flatMap(TunedModel::checkpoints).orElse(new ArrayList<>()); | ||
|
||
int index = 0; | ||
for (TunedModelCheckpoint checkpoint : checkpoints) { | ||
System.out.println("Checkpoint " + (++index)); | ||
checkpoint | ||
.checkpointId() | ||
.ifPresent(checkpointId -> System.out.println("checkpointId=" + checkpointId)); | ||
checkpoint.epoch().ifPresent(epoch -> System.out.println("epoch=" + epoch)); | ||
checkpoint.step().ifPresent(step -> System.out.println("step=" + step)); | ||
checkpoint.endpoint().ifPresent(endpoint -> System.out.println("endpoint=" + endpoint)); | ||
} | ||
// Example response: | ||
// Checkpoint 1 | ||
// checkpointId=1 | ||
// epoch=2 | ||
// step=34 | ||
// endpoint=projects/project/locations/location/endpoints/105055037499113472 | ||
// ... | ||
return jobName; | ||
} | ||
} | ||
} | ||
// [END googlegenaisdk_tuning_job_create] |
61 changes: 61 additions & 0 deletions
61
genai/snippets/src/main/java/genai/tuning/TuningJobGet.java
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,61 @@ | ||
/* | ||
* 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 | ||
* | ||
* http://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. | ||
*/ | ||
|
||
package genai.tuning; | ||
|
||
// [START googlegenaisdk_tuning_job_get] | ||
|
||
import com.google.genai.Client; | ||
import com.google.genai.types.GetTuningJobConfig; | ||
import com.google.genai.types.HttpOptions; | ||
import com.google.genai.types.TunedModel; | ||
import com.google.genai.types.TuningJob; | ||
import java.util.Optional; | ||
|
||
public class TuningJobGet { | ||
|
||
public static void main(String[] args) { | ||
// TODO(developer): Replace these variables before running the sample. | ||
// E.g. tuningJobName = | ||
// "projects/123456789012/locations/us-central1/tuningJobs/123456789012345" | ||
String tuningJobName = "your-job-name"; | ||
getTuningJob(tuningJobName); | ||
} | ||
|
||
// Shows how to get a tuning job | ||
public static Optional<String> getTuningJob(String tuningJobName) { | ||
// Client Initialization. Once created, it can be reused for multiple requests. | ||
try (Client client = | ||
Client.builder() | ||
.location("us-central1") | ||
.vertexAI(true) | ||
.httpOptions(HttpOptions.builder().apiVersion("v1").build()) | ||
.build()) { | ||
|
||
TuningJob tuningJob = client.tunings.get(tuningJobName, GetTuningJobConfig.builder().build()); | ||
|
||
tuningJob.tunedModel().flatMap(TunedModel::model).ifPresent(System.out::println); | ||
tuningJob.tunedModel().flatMap(TunedModel::endpoint).ifPresent(System.out::println); | ||
tuningJob.experiment().ifPresent(System.out::println); | ||
// Example response: | ||
// projects/123456789012/locations/us-central1/models/6129850992130260992@1 | ||
// projects/123456789012/locations/us-central1/endpoints/105055037499113472 | ||
// projects/123456789012/locations/us-central1/metadataStores/default/contexts/experiment_id | ||
return tuningJob.name(); | ||
} | ||
} | ||
} | ||
// [END googlegenaisdk_tuning_job_get] |
54 changes: 54 additions & 0 deletions
54
genai/snippets/src/main/java/genai/tuning/TuningJobList.java
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,54 @@ | ||
/* | ||
* 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 | ||
* | ||
* http://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. | ||
*/ | ||
|
||
package genai.tuning; | ||
|
||
// [START googlegenaisdk_tuning_job_list] | ||
|
||
import com.google.genai.Client; | ||
import com.google.genai.Pager; | ||
import com.google.genai.types.HttpOptions; | ||
import com.google.genai.types.ListTuningJobsConfig; | ||
import com.google.genai.types.TuningJob; | ||
|
||
public class TuningJobList { | ||
|
||
public static void main(String[] args) { | ||
listTuningJob(); | ||
} | ||
|
||
// Shows how to list the available tuning jobs | ||
public static Pager<TuningJob> listTuningJob() { | ||
// Client Initialization. Once created, it can be reused for multiple requests. | ||
try (Client client = | ||
Client.builder() | ||
.location("us-central1") | ||
.vertexAI(true) | ||
.httpOptions(HttpOptions.builder().apiVersion("v1").build()) | ||
.build()) { | ||
|
||
Pager<TuningJob> tuningJobs = client.tunings.list(ListTuningJobsConfig.builder().build()); | ||
for (TuningJob job : tuningJobs) { | ||
job.name().ifPresent(System.out::println); | ||
// Example response: | ||
// projects/123456789012/locations/us-central1/tuningJobs/329583781566480384 | ||
} | ||
|
||
return tuningJobs; | ||
} | ||
} | ||
} | ||
// [END googlegenaisdk_tuning_job_list] |
68 changes: 68 additions & 0 deletions
68
genai/snippets/src/main/java/genai/tuning/TuningTextGenWithTxt.java
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,68 @@ | ||
/* | ||
* 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 | ||
* | ||
* http://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. | ||
*/ | ||
|
||
package genai.tuning; | ||
|
||
// [START googlegenaisdk_tuning_textgen_with_txt] | ||
|
||
import com.google.genai.Client; | ||
import com.google.genai.types.GenerateContentConfig; | ||
import com.google.genai.types.GenerateContentResponse; | ||
import com.google.genai.types.GetTuningJobConfig; | ||
import com.google.genai.types.HttpOptions; | ||
import com.google.genai.types.TunedModel; | ||
import com.google.genai.types.TuningJob; | ||
|
||
public class TuningTextGenWithTxt { | ||
|
||
public static void main(String[] args) { | ||
// TODO(developer): Replace these variables before running the sample. | ||
// E.g. tuningJobName = | ||
// "projects/123456789012/locations/us-central1/tuningJobs/123456789012345" | ||
String tuningJobName = "your-job-name"; | ||
predictWithTunedEndpoint(tuningJobName); | ||
} | ||
|
||
// Shows how to predict with a tuned model endpoint | ||
public static String predictWithTunedEndpoint(String tuningJobName) { | ||
// Client Initialization. Once created, it can be reused for multiple requests. | ||
try (Client client = | ||
Client.builder() | ||
.location("us-central1") | ||
.vertexAI(true) | ||
.httpOptions(HttpOptions.builder().apiVersion("v1").build()) | ||
.build()) { | ||
|
||
TuningJob tuningJob = client.tunings.get(tuningJobName, GetTuningJobConfig.builder().build()); | ||
|
||
String endpoint = | ||
tuningJob | ||
.tunedModel() | ||
.flatMap(TunedModel::endpoint) | ||
.orElseThrow(() -> new IllegalStateException("Failed to get endpoint")); | ||
|
||
GenerateContentResponse response = | ||
client.models.generateContent( | ||
endpoint, "Why is the sky blue?", GenerateContentConfig.builder().build()); | ||
|
||
System.out.println(response.text()); | ||
// Example response: | ||
// The sky is blue because of a phenomenon called Rayleigh scattering... | ||
return response.text(); | ||
} | ||
} | ||
} | ||
// [END googlegenaisdk_tuning_textgen_with_txt] |
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.