|
17 | 17 | package com.google.adk.models; |
18 | 18 |
|
19 | 19 | import static com.google.common.base.Preconditions.checkArgument; |
20 | | -import static com.google.common.base.Preconditions.checkState; |
21 | 20 | import static com.google.common.collect.ImmutableList.toImmutableList; |
22 | 21 | import static com.google.common.collect.ImmutableMap.toImmutableMap; |
23 | 22 |
|
@@ -172,29 +171,33 @@ public final Builder appendInstructions(List<String> instructions) { |
172 | 171 | return liveConnectConfig(liveCfg.toBuilder().systemInstruction(newLiveSi).build()); |
173 | 172 | } |
174 | 173 |
|
| 174 | + // In this particular case we can keep the Optional as a type of a |
| 175 | + // parameter, since the function is private and used in only one place while |
| 176 | + // the Optional type plays nicely with flatMaps in the code (if we had a |
| 177 | + // nullable here, we'd wrap it in the Optional anyway) |
175 | 178 | private Content addInstructions( |
176 | | - Optional<Content> currentSystemInstruction, List<String> additionalInstructions) { |
| 179 | + @SuppressWarnings("checkstyle:IllegalType") Optional<Content> currentSystemInstruction, |
| 180 | + List<String> additionalInstructions) { |
177 | 181 | checkArgument( |
178 | | - currentSystemInstruction.isEmpty() |
179 | | - || currentSystemInstruction.get().parts().map(parts -> parts.size()).orElse(0) <= 1, |
| 182 | + currentSystemInstruction.flatMap(Content::parts).map(parts -> parts.size()).orElse(0) |
| 183 | + <= 1, |
180 | 184 | "At most one instruction is supported."); |
181 | 185 |
|
182 | 186 | // Either append to the existing instruction, or create a new one. |
183 | 187 | String instructions = String.join("\n\n", additionalInstructions); |
184 | 188 |
|
185 | | - Optional<Part> part = |
186 | | - currentSystemInstruction |
187 | | - .flatMap(Content::parts) |
188 | | - .flatMap(parts -> parts.stream().findFirst()); |
189 | | - if (part.isEmpty() || part.get().text().isEmpty()) { |
190 | | - part = Optional.of(Part.fromText(instructions)); |
191 | | - } else { |
192 | | - part = Optional.of(Part.fromText(part.get().text().get() + "\n\n" + instructions)); |
193 | | - } |
194 | | - checkState(part.isPresent(), "Failed to create instruction."); |
| 189 | + Part part = |
| 190 | + Part.fromText( |
| 191 | + currentSystemInstruction |
| 192 | + .flatMap(Content::parts) |
| 193 | + .flatMap(parts -> parts.stream().findFirst()) |
| 194 | + .flatMap(Part::text) |
| 195 | + .map(text -> text + "\n\n" + instructions) |
| 196 | + .orElse(instructions)); |
195 | 197 |
|
196 | 198 | String role = currentSystemInstruction.flatMap(Content::role).orElse("user"); |
197 | | - return Content.builder().parts(part.get()).role(role).build(); |
| 199 | + |
| 200 | + return Content.builder().parts(part).role(role).build(); |
198 | 201 | } |
199 | 202 |
|
200 | 203 | @CanIgnoreReturnValue |
|
0 commit comments