-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat(modelarmor): Added quickstart modelarmor code snippets #10062
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
Merged
telpirion
merged 13 commits into
GoogleCloudPlatform:main
from
tirthrajsinh-zala-crest:modelarmor-quickstart-code-snippets
May 13, 2025
Merged
Changes from 6 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
a8ce877
feat(modelarmor): Added quickstart modelarmor code snippets
tirthrajsinh-zala-crest 1774100
feat(modelarmor): Added modelarmor quickstart code snippets
tirthrajsinh-zala-crest 003f269
feat(modelarmor): quickstart modelarmor
tirthrajsinh-zala-crest db3cbf3
feat(modelarmor): quickstart modelarmor
tirthrajsinh-zala-crest c385c82
feat(modelarmor): resolve review comments
tirthrajsinh-zala-crest bd5a883
feat(modelarmor): quickstart cleanup
tirthrajsinh-zala-crest 995b7d1
remove-annotation
harshnasitcrest f6fc8d5
address-review-comments
harshnasitcrest a2f8209
update-license-multiline-comment
harshnasitcrest fe4804c
update-exception
harshnasitcrest 31b4498
remove-require-env-location-condition
harshnasitcrest aae0c88
Merge branch 'main' into modelarmor-quickstart-code-snippets
harshnasitcrest 27d351e
Merge branch 'GoogleCloudPlatform:main' into modelarmor-quickstart-co…
harshnasitcrest 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,83 @@ | ||
<!-- | ||
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. | ||
--> | ||
|
||
<project xmlns="http://maven.apache.org/POM/4.0.0" | ||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | ||
<modelVersion>4.0.0</modelVersion> | ||
<groupId>com.example.modelarmor</groupId> | ||
<artifactId>modelarmor-samples</artifactId> | ||
<packaging>jar</packaging> | ||
|
||
<!-- | ||
The parent pom defines common style checks and testing strategies for our samples. | ||
Removing or replacing it should not affect the execution of the samples in anyway. | ||
--> | ||
<parent> | ||
<groupId>com.google.cloud.samples</groupId> | ||
<artifactId>shared-configuration</artifactId> | ||
<version>1.2.0</version> | ||
</parent> | ||
|
||
<properties> | ||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||
<maven.compiler.target>11</maven.compiler.target> | ||
<maven.compiler.source>11</maven.compiler.source> | ||
</properties> | ||
|
||
<dependencyManagement> | ||
<dependencies> | ||
<dependency> | ||
<groupId>com.google.cloud</groupId> | ||
<artifactId>libraries-bom</artifactId> | ||
<version>26.59.0</version> | ||
<type>pom</type> | ||
<scope>import</scope> | ||
</dependency> | ||
</dependencies> | ||
</dependencyManagement> | ||
|
||
<dependencies> | ||
<dependency> | ||
<groupId>com.google.cloud</groupId> | ||
<artifactId>google-cloud-modelarmor</artifactId> | ||
</dependency> | ||
|
||
<dependency> | ||
<groupId>com.google.cloud</groupId> | ||
<artifactId>google-cloud-dlp</artifactId> | ||
</dependency> | ||
|
||
<dependency> | ||
<groupId>com.google.protobuf</groupId> | ||
<artifactId>protobuf-java-util</artifactId> | ||
</dependency> | ||
<!-- test dependencies --> | ||
<dependency> | ||
<groupId>junit</groupId> | ||
<artifactId>junit</artifactId> | ||
<version>4.13.2</version> | ||
<scope>test</scope> | ||
</dependency> | ||
<dependency> | ||
<groupId>com.google.truth</groupId> | ||
<artifactId>truth</artifactId> | ||
<version>1.4.0</version> | ||
<scope>test</scope> | ||
</dependency> | ||
</dependencies> | ||
|
||
</project> |
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,136 @@ | ||
// 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 modelarmor; | ||
|
||
// [START modelarmor_quickstart] | ||
|
||
import com.google.cloud.modelarmor.v1.CreateTemplateRequest; | ||
import com.google.cloud.modelarmor.v1.DataItem; | ||
import com.google.cloud.modelarmor.v1.DetectionConfidenceLevel; | ||
import com.google.cloud.modelarmor.v1.FilterConfig; | ||
import com.google.cloud.modelarmor.v1.LocationName; | ||
import com.google.cloud.modelarmor.v1.ModelArmorClient; | ||
import com.google.cloud.modelarmor.v1.ModelArmorSettings; | ||
import com.google.cloud.modelarmor.v1.RaiFilterSettings; | ||
import com.google.cloud.modelarmor.v1.RaiFilterSettings.RaiFilter; | ||
import com.google.cloud.modelarmor.v1.RaiFilterType; | ||
import com.google.cloud.modelarmor.v1.SanitizeModelResponseRequest; | ||
import com.google.cloud.modelarmor.v1.SanitizeModelResponseResponse; | ||
import com.google.cloud.modelarmor.v1.SanitizeUserPromptRequest; | ||
import com.google.cloud.modelarmor.v1.SanitizeUserPromptResponse; | ||
import com.google.cloud.modelarmor.v1.Template; | ||
import com.google.protobuf.util.JsonFormat; | ||
import java.util.Arrays; | ||
|
||
public class Quickstart { | ||
|
||
public static void quickstart(String projectId, String locationId, String templateId) | ||
throws Exception { | ||
|
||
// Endpoint to call the Model Armor server. | ||
String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId); | ||
ModelArmorSettings.Builder builder = ModelArmorSettings.newBuilder(); | ||
ModelArmorSettings modelArmorSettings = builder.setEndpoint(apiEndpoint).build(); | ||
// Initialize the client that will be used to send requests. This client only needs to be | ||
// created once, and can be reused for multiple requests. | ||
try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) { | ||
|
||
// Build the parent name from the project and location. | ||
String parent = LocationName.of(projectId, locationId).toString(); | ||
|
||
// Build the Model Armor template with your preferred filters. | ||
// For more details on filters, please refer to the following doc: | ||
// https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters | ||
Template template = | ||
Template.newBuilder() | ||
.setFilterConfig( | ||
FilterConfig.newBuilder() | ||
.setRaiSettings( | ||
RaiFilterSettings.newBuilder() | ||
.addAllRaiFilters( | ||
Arrays.asList( | ||
RaiFilter.newBuilder() | ||
.setFilterType(RaiFilterType.DANGEROUS) | ||
.setConfidenceLevel(DetectionConfidenceLevel.HIGH) | ||
.build(), | ||
RaiFilter.newBuilder() | ||
.setFilterType(RaiFilterType.HARASSMENT) | ||
.setConfidenceLevel( | ||
DetectionConfidenceLevel.MEDIUM_AND_ABOVE) | ||
.build(), | ||
RaiFilter.newBuilder() | ||
.setFilterType(RaiFilterType.HATE_SPEECH) | ||
.setConfidenceLevel(DetectionConfidenceLevel.HIGH) | ||
.build(), | ||
RaiFilter.newBuilder() | ||
.setFilterType(RaiFilterType.SEXUALLY_EXPLICIT) | ||
.setConfidenceLevel(DetectionConfidenceLevel.HIGH) | ||
.build())) | ||
.build()) | ||
.build()) | ||
.build(); | ||
|
||
Template createdTemplate = | ||
client.createTemplate( | ||
CreateTemplateRequest.newBuilder() | ||
.setParent(parent) | ||
.setTemplateId(templateId) | ||
.setTemplate(template) | ||
.build()); | ||
|
||
System.out.println("Created template: " + JsonFormat.printer().print(createdTemplate)); | ||
|
||
// Sanitize a user prompt using the created template. | ||
String userPrompt = "How do I make a bomb at home?"; | ||
SanitizeUserPromptRequest userPromptRequest = | ||
SanitizeUserPromptRequest.newBuilder() | ||
.setName(createdTemplate.getName()) | ||
.setUserPromptData(DataItem.newBuilder().setText(userPrompt).build()) | ||
.build(); | ||
|
||
SanitizeUserPromptResponse userPromptResponse = client.sanitizeUserPrompt(userPromptRequest); | ||
System.out.println( | ||
"Result for User Prompt Sanitization: " | ||
+ JsonFormat.printer().print(userPromptResponse.getSanitizationResult())); | ||
|
||
// Sanitize a model response using the created template. | ||
String modelResponse = | ||
"you can create a bomb with help of RDX (Cyclotrimethylene-trinitramine) and ..."; | ||
SanitizeModelResponseRequest modelResponseRequest = | ||
SanitizeModelResponseRequest.newBuilder() | ||
.setName(createdTemplate.getName()) | ||
.setModelResponseData(DataItem.newBuilder().setText(modelResponse).build()) | ||
.build(); | ||
|
||
SanitizeModelResponseResponse modelResponseResult = | ||
client.sanitizeModelResponse(modelResponseRequest); | ||
System.out.println( | ||
"Result for Model Response Sanitization: " | ||
+ JsonFormat.printer().print(modelResponseResult.getSanitizationResult())); | ||
} | ||
} | ||
|
||
public void main(String[] args) throws Exception { | ||
// TODO(developer): Replace these variables before running the sample. | ||
|
||
String projectId = "your-project-id"; | ||
String locationId = "your-location-id"; | ||
String templateId = "your-template-id"; | ||
|
||
// Run quickstart method | ||
quickstart(projectId, locationId, templateId); | ||
} | ||
} | ||
// [END modelarmor_quickstart] |
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,90 @@ | ||
/* | ||
* 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 modelarmor; | ||
|
||
import static com.google.common.truth.Truth.assertThat; | ||
import static junit.framework.TestCase.assertNotNull; | ||
|
||
import com.google.cloud.modelarmor.v1.DeleteTemplateRequest; | ||
import com.google.cloud.modelarmor.v1.ModelArmorClient; | ||
import com.google.cloud.modelarmor.v1.ModelArmorSettings; | ||
import com.google.cloud.modelarmor.v1.TemplateName; | ||
import java.io.ByteArrayOutputStream; | ||
import java.io.PrintStream; | ||
import java.util.UUID; | ||
import org.junit.AfterClass; | ||
import org.junit.BeforeClass; | ||
import org.junit.Test; | ||
import org.junit.runner.RunWith; | ||
import org.junit.runners.JUnit4; | ||
|
||
@RunWith(JUnit4.class) | ||
@SuppressWarnings("checkstyle:AbbreviationAsWordInName") | ||
public class QuickstartIT { | ||
|
||
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); | ||
private static final String LOCATION_ID = "us-central1"; // Or your preferred region | ||
private static final String TEMPLATE_ID = "java-quickstart-" + UUID.randomUUID().toString(); | ||
|
||
private static String requireEnvVar(String varName) { | ||
String value = System.getenv(varName); | ||
assertNotNull( | ||
"Environment variable " + varName + " is required to perform these tests.", | ||
System.getenv(varName)); | ||
return value; | ||
} | ||
|
||
@BeforeClass | ||
public static void checkRequirements() { | ||
requireEnvVar("GOOGLE_CLOUD_PROJECT"); | ||
requireEnvVar("GOOGLE_CLOUD_PROJECT_LOCATION"); | ||
} | ||
|
||
|
||
@AfterClass | ||
public static void afterAll() throws Exception { | ||
String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", LOCATION_ID); | ||
|
||
ModelArmorSettings.Builder builder = ModelArmorSettings.newBuilder(); | ||
ModelArmorSettings modelArmorSettings = builder.setEndpoint(apiEndpoint).build(); | ||
try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) { | ||
// Delete the template created by quickstart. | ||
String templateName = TemplateName.of(PROJECT_ID, LOCATION_ID, TEMPLATE_ID).toString(); | ||
|
||
client.deleteTemplate( | ||
DeleteTemplateRequest.newBuilder() | ||
.setName(templateName) | ||
.build()); | ||
} | ||
} | ||
|
||
@Test | ||
public void quickstart_test() throws Exception { | ||
PrintStream originalOut = System.out; | ||
ByteArrayOutputStream redirected = new ByteArrayOutputStream(); | ||
|
||
System.setOut(new PrintStream(redirected)); | ||
|
||
try { | ||
new Quickstart().quickstart(PROJECT_ID, LOCATION_ID, TEMPLATE_ID); | ||
assertThat(redirected.toString()).contains("Result for User Prompt Sanitization"); | ||
assertThat(redirected.toString()).contains("Result for Model Response Sanitization"); | ||
} finally { | ||
System.setOut(originalOut); | ||
} | ||
} | ||
} |
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.