8000 feat(modelarmor): Added quickstart modelarmor code snippets (#10062) · rebeccaellis/java-docs-samples@26355bd · GitHub
[go: up one dir, main page]

Skip to content

Commit 26355bd

Browse files
feat(modelarmor): Added quickstart modelarmor code snippets (GoogleCloudPlatform#10062)
* feat(modelarmor): Added quickstart modelarmor code snippets * feat(modelarmor): Added modelarmor quickstart code snippets * feat(modelarmor): quickstart modelarmor * feat(modelarmor): quickstart modelarmor * feat(modelarmor): resolve review comments * feat(modelarmor): quickstart cleanup * remove-annotation * address-review-comments * update-license-multiline-comment * update-exception * remove-require-env-location-condition --------- Co-authored-by: harshnasitcrest <131268456+harshnasitcrest@users.noreply.github.com> Co-authored-by: Harsh Nasit <harsh.nasit@crestdata.ai>
1 parent b0eca89 commit 26355bd

File tree

2 files changed

+232
-0
lines changed

2 files changed

+232
-0
lines changed
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package modelarmor;
18+
19+
// [START modelarmor_quickstart]
20+
21+
import com.google.cloud.modelarmor.v1.CreateTemplateRequest;
22+
import com.google.cloud.modelarmor.v1.DataItem;
23+
import com.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
24+
import com.google.cloud.modelarmor.v1.FilterConfig;
25+
import com.google.cloud.modelarmor.v1.LocationName;
26+
import com.google.cloud.modelarmor.v1.ModelArmorClient;
27+
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
28+
import com.google.cloud.modelarmor.v1.RaiFilterSettings;
29+
import com.google.cloud.modelarmor.v1.RaiFilterSettings.RaiFilter;
30+
import com.google.cloud.modelarmor.v1.RaiFilterType;
31+
import com.google.cloud.modelarmor.v1.SanitizeModelResponseRequest;
32+
import com.google.cloud.modelarmor.v1.SanitizeModelResponseResponse;
33+
import com.google.cloud.modelarmor.v1.SanitizeUserPromptRequest;
34+
import com.google.cloud.modelarmor.v1.SanitizeUserPromptResponse;
35+
import com.google.cloud.modelarmor.v1.Template;
36+
import com.google.protobuf.util.JsonFormat;
37+
import java.io.IOException;
38+
import java.util.List;
39+
40+
public class Quickstart {
41+
42+
public void main(String[] args) throws IOException {
43+
// TODO(developer): Replace these variables before running the sample.
44+
45+
// Specify the Google Project ID.
46+
String projectId = "your-project-id";
47+
// Specify the location ID. For example, us-central1.
48+
String locationId = "your-location-id";
49+
// Specify the template ID.
50+
String templateId = "your-template-id";
51+
52+
// Run quickstart method.
53+
quickstart(projectId, locationId, templateId);
54+
}
55+
56+
// This is an example to demonstrate how to use Model Armor to screen
57+
// user prompts and model responses using a Model Armor template.
58+
public static void quickstart(String projectId, String locationId, String templateId)
59+
throws IOException {
60+
61+
// Endpoint to call the Model Armor server.
62+
String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
63+
ModelArmorSettings.Builder builder = ModelArmorSettings.newBuilder();
64+
ModelArmorSettings modelArmorSettings = builder.setEndpoint(apiEndpoint).build();
65+
66+
// Initialize the client that will be used to send requests. This client
67+
// only needs to be created once, and can be reused for multiple requests.
68+
try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) {
69+
70+
// Build the parent name from the project and location.
71+
String parent = LocationName.of(projectId, locationId).toString();
72+
// Build the Model Armor template with your preferred filters.
73+
// For more details on filters, please refer to the following doc:
74+
// https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
75+
76+
// Configure Responsible AI filter with mult 6D40 iple categories and their
77+
// confidence levels.
78+
RaiFilterSettings raiFilterSettings =
79+
RaiFilterSettings.newBuilder()
80+
.addAllRaiFilters(
81+
List.of(
82+
RaiFilter.newBuilder()
83+
.setFilterType(RaiFilterType.DANGEROUS)
84+
.setConfidenceLevel(DetectionConfidenceLevel.HIGH)
85+
.build(),
86+
RaiFilter.newBuilder()
87+
.setFilterType(RaiFilterType.HATE_SPEECH)
88+
.setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
89+
.build(),
90+
RaiFilter.newBuilder()
91+
.setFilterType(RaiFilterType.SEXUALLY_EXPLICIT)
92+
.setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
93+
.build(),
94+
RaiFilter.newBuilder()
95+
.setFilterType(RaiFilterType.HARASSMENT)
96+
.setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
97+
.build()))
98+
.build();
99+
100+
FilterConfig modelArmorFilter =
101+
FilterConfig.newBuilder().setRaiSettings(raiFilterSettings).build();
102+
103+
Template template = Template.newBuilder()
104+
.setFilterConfig(modelArmorFilter)
105+
.build();
106+
107+
CreateTemplateRequest request = CreateTemplateRequest.newBuilder()
108+
.setParent(parent)
109+
.setTemplateId(templateId)
110+
.setTemplate(template)
111+
.build();
112+
113+
Template createdTemplate = client.createTemplate(request);
114+
System.out.println("Created template: " + createdTemplate.getName());
115+
116+
// Screen a user prompt using the created template.
117+
String userPrompt = "Unsafe user prompt";
118+
SanitizeUserPromptRequest userPromptRequest =
119+
SanitizeUserPromptRequest.newBuilder()
120+
.setName(createdTemplate.getName())
121+
.setUserPromptData(DataItem.newBuilder().setText(userPrompt).build())
122+
.build();
123+
124+
SanitizeUserPromptResponse userPromptResponse = client.sanitizeUserPrompt(userPromptRequest);
125+
System.out.println(
126+
"Result for the provided user prompt: "
127+
+ JsonFormat.printer().print(userPromptResponse.getSanitizationResult()));
128+
129+
// Screen a model response using the created template.
130+
String modelResponse = "Unsanitized model output";
131+
SanitizeModelResponseRequest modelResponseRequest =
132+
SanitizeModelResponseRequest.newBuilder()
133+
.setName(createdTemplate.getName())
134+
.setModelResponseData(DataItem.newBuilder().setText(modelResponse).build())
135+
.build();
136+
137+
SanitizeModelResponseResponse modelResponseResult =
138+
client.sanitizeModelResponse(modelResponseRequest);
139+
System.out.println(
140+
"Result for the provided model response: "
141+
+ JsonFormat.printer().print(modelResponseResult.getSanitizationResult()));
142+
}
143+
}
144+
}
145+
// [END modelarmor_quickstart]
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package modelarmor;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static junit.framework.TestCase.assertNotNull;
21+
22+
import com.google.cloud.modelarmor.v1.DeleteTemplateRequest;
23+
import com.google.cloud.modelarmor.v1.ModelArmorClient;
24+
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
25+
import com.google.cloud.modelarmor.v1.TemplateName;
26+
import java.io.ByteArrayOutputStream;
27+
import java.io.IOException;
28+
import java.io.PrintStream;
29+
import java.util.UUID;
30+
import org.junit.AfterClass;
31+
import org.junit.BeforeClass;
32+
import org.junit.Test;
33+
import org.junit.runner.RunWith;
34+
import org.junit.runners.JUnit4;
35+
36+
@RunWith(JUnit4.class)
37+
public class QuickstartIT {
38+
39+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
40+
private static final String LOCATION_ID = System.getenv()
41+
.getOrDefault("GOOGLE_CLOUD_PROJECT_LOCATION", "us-central1");
42+
private static final String TEMPLATE_ID = "java-quickstart-" + UUID.randomUUID().toString();
43+
44+
private static String requireEnvVar(String varName) {
45+
String value = System.getenv(varName);
46+
assertNotNull("Environment variable " + varName + " is required to perform these tests.",
47+
System.getenv(varName));
48+
return value;
49+
}
50+
51+
@BeforeClass
52+
public static void checkRequirements() {
53+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
54+
}
55+
56+
@AfterClass
57+
public static void afterAll() throws IOException {
58+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
59+
60+
// Delete the template created by quickstart.
61+
String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", LOCATION_ID);
62+
63+
ModelArmorSettings.Builder builder = ModelArmorSettings.newBuilder();
64+
ModelArmorSettings modelArmorSettings = builder.setEndpoint(apiEndpoint).build();
65+
66+
try (ModelArmorClient client = ModelArmorClient.create(modelArmorSettings)) {
67+
String templateName = TemplateName.of(PROJECT_ID, LOCATION_ID, TEMPLATE_ID).toString();
68+
client.deleteTemplate(DeleteTemplateRequest.newBuilder().setName(templateName).build());
69+
}
70+
}
71+
72+
@Test
73+
public void quickstart_test() throws IOException {
74+
PrintStream originalOut = System.out;
75+
ByteArrayOutputStream redirected = new ByteArrayOutputStream();
76+
77+
System.setOut(new PrintStream(redirected));
78+
79+
try {
80+
Quickstart.quickstart(PROJECT_ID, LOCATION_ID, TEMPLATE_ID);
81+
assertThat(redirected.toString()).contains("Result for the provided user prompt:");
82+
assertThat(redirected.toString()).contains("Result for the provided model response:");
83+
} finally {
84+
System.setOut(originalOut);
85+
}
86+
}
87+
}

0 commit comments

Comments
 (0)
0