Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,10 @@ public Single<RequestProcessor.RequestProcessingResult> processRequest(
StringBuilder builder =
new StringBuilder()
.append("You are an agent. Your internal name is ")
.append("\"")
.append(agent.name())
.append("\"")
.append(".");
if (!Strings.isNullOrEmpty(agent.description())) {
builder.append(" The description about you is \"").append(agent.description()).append("\".");
builder.append(" The description about you is ").append(agent.description());
}
return Single.just(
RequestProcessor.RequestProcessingResult.create(
Expand Down
31 changes: 7 additions & 24 deletions core/src/main/java/com/google/adk/models/LlmRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

package com.google.adk.models;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;

Expand Down Expand Up @@ -172,29 +170,14 @@ public final Builder appendInstructions(List<String> instructions) {
return liveConnectConfig(liveCfg.toBuilder().systemInstruction(newLiveSi).build());
}

private Content addInstructions(
Optional<Content> currentSystemInstruction, List<String> additionalInstructions) {
checkArgument(
currentSystemInstruction.isEmpty()
|| currentSystemInstruction.get().parts().map(parts -> parts.size()).orElse(0) <= 1,
"At most one instruction is supported.");

// Either append to the existing instruction, or create a new one.
String instructions = String.join("\n\n", additionalInstructions);

Optional<Part> part =
currentSystemInstruction
.flatMap(Content::parts)
.flatMap(parts -> parts.stream().findFirst());
if (part.isEmpty() || part.get().text().isEmpty()) {
part = Optional.of(Part.fromText(instructions));
} else {
part = Optional.of(Part.fromText(part.get().text().get() + "\n\n" + instructions));
}
checkState(part.isPresent(), "Failed to create instruction.");
private Content addInstructions(Optional<Content> currentSi, List<String> newInst) {
ImmutableList.Builder<Part> parts = ImmutableList.builder();
currentSi.flatMap(Content::parts).ifPresent(parts::addAll);

newInst.stream().map(Part::fromText).forEach(parts::add);

String role = currentSystemInstruction.flatMap(Content::role).orElse("user");
return Content.builder().parts(part.get()).role(role).build();
String role = currentSi.flatMap(Content::role).orElse("user");
return Content.builder().parts(parts.build()).role(role).build();
}

@CanIgnoreReturnValue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ public void processRequest_agentInstructionAndGlobalInstruction_bothAreAppendedT
instructionsProcessor.processRequest(context, initialRequest).blockingGet();

assertThat(result.updatedRequest().getSystemInstructions())
.containsExactly("Global instruction.\n\nAgent instruction.");
.containsExactly("Global instruction.", "Agent instruction.")
.inOrder();
}
}
25 changes: 13 additions & 12 deletions core/src/test/java/com/google/adk/models/LlmRequestTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ public void appendInstructions_existingInstruction_appendsNewInstructionCorrectl
assertThat(request.config()).isPresent();
Content systemInstruction = request.config().get().systemInstruction().get();
assertThat(systemInstruction.role()).hasValue("system");
assertThat(systemInstruction.parts().get()).hasSize(1);
assertThat(systemInstruction.parts().get().get(0).text())
.hasValue(initialInstructionText + "\n\n" + newInstructionText);
assertThat(systemInstruction.parts().get()).hasSize(2);
assertThat(systemInstruction.parts().get().get(0).text()).hasValue(initialInstructionText);
assertThat(systemInstruction.parts().get().get(1).text()).hasValue(newInstructionText);

assertThat(request.liveConnectConfig().systemInstruction()).isPresent();
Content liveSystemInstruction = request.liveConnectConfig().systemInstruction().get();
Expand Down Expand Up @@ -154,9 +154,10 @@ public void appendInstructions_existingInstruction_appendsNewInstructionCorrectl
assertThat(request.liveConnectConfig().systemInstruction()).isPresent();
Content liveSystemInstruction = request.liveConnectConfig().systemInstruction().get();
assertThat(liveSystemInstruction.role()).hasValue("system"); // Role preserved
assertThat(liveSystemInstruction.parts().get()).hasSize(1);
assertThat(liveSystemInstruction.parts().get()).hasSize(2);
assertThat(liveSystemInstruction.parts().get().get(0).text())
.hasValue(initialLiveInstructionText + "\n\n" + newInstructionText);
.hasValue(initialLiveInstructionText);
assertThat(liveSystemInstruction.parts().get().get(1).text()).hasValue(newInstructionText);

// Assertions for main config (should get the new instruction with default role)
assertThat(request.config()).isPresent();
Expand Down Expand Up @@ -195,16 +196,16 @@ public void appendInstructions_multipleInstructions_appendsAllInOrder() {

assertThat(request.config()).isPresent();
Content systemInstruction = request.config().get().systemInstruction().get();
assertThat(systemInstruction.parts().get()).hasSize(1);
assertThat(systemInstruction.parts().get().get(0).text())
.hasValue(instruction1 + "\n\n" + instruction2);
assertThat(systemInstruction.parts().get()).hasSize(2);
assertThat(systemInstruction.parts().get().get(0).text()).hasValue(instruction1);
assertThat(systemInstruction.parts().get().get(1).text()).hasValue(instruction2);

assertThat(request.liveConnectConfig().systemInstruction()).isPresent();
Content liveSystemInstruction = request.liveConnectConfig().systemInstruction().get();
assertThat(liveSystemInstruction.role()).hasValue("user");
assertThat(liveSystemInstruction.parts().get()).hasSize(1);
assertThat(liveSystemInstruction.parts().get().get(0).text())
.hasValue(instruction1 + "\n\n" + instruction2);
assertThat(liveSystemInstruction.parts().get()).hasSize(2);
assertThat(liveSystemInstruction.parts().get().get(0).text()).hasValue(instruction1);
assertThat(liveSystemInstruction.parts().get().get(1).text()).hasValue(instruction2);
}

@Test
Expand Down Expand Up @@ -305,7 +306,7 @@ public void getSystemInstructions_whenPresent_returnsList() {
.appendInstructions(ImmutableList.of(instruction1, instruction2))
.build();
assertThat(request.getSystemInstructions())
.containsExactly(instruction1 + "\n\n" + instruction2)
.containsExactly(instruction1, instruction2)
.inOrder();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.google.adk.sessions.BaseSessionService;
import com.google.adk.sessions.ListSessionsResponse;
import com.google.adk.sessions.Session;
import com.google.adk.web.dto.SessionRequest;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Single;
import java.util.Collections;
Expand Down Expand Up @@ -167,13 +168,15 @@ public Session createSessionWithId(
@PathVariable String appName,
@PathVariable String userId,
@PathVariable String sessionId,
@RequestBody(required = false) Map<String, Object> state) {
@RequestBody(required = false) SessionRequest body) {
log.info(
"Request received for POST /apps/{}/users/{}/sessions/{} with state: {}",
"Request received for POST /apps/{}/users/{}/sessions/{} with request body: {}",
appName,
userId,
sessionId,
state);
body);

Map<String, Object> initialState = (body != null) ? body.getState() : Collections.emptyMap();

try {
findSessionOrThrow(appName, userId, sessionId);
Expand All @@ -190,7 +193,6 @@ public Session createSessionWithId(
log.info("Session {} not found, proceeding with creation.", sessionId);
}

Map<String, Object> initialState = (state != null) ? state : Collections.emptyMap();
try {
Session createdSession =
sessionService
Expand Down Expand Up @@ -228,18 +230,18 @@ public Session createSessionWithId(
public Session createSession(
@PathVariable String appName,
@PathVariable String userId,
@RequestBody(required = false) Map<String, Object> state) {
@RequestBody(required = false) SessionRequest body) {

log.info(
"Request received for POST /apps/{}/users/{}/sessions (service generates ID) with state:"
+ " {}",
"Request received for POST /apps/{}/users/{}/sessions (service generates ID) with request"
+ " body: {}",
appName,
userId,
state);
body);

Map<String, Object> initialState = (state != null) ? state : Collections.emptyMap();
try {
Map<String, Object> initialState = (body != null) ? body.getState() : Collections.emptyMap();

try {
Session createdSession =
sessionService
.createSession(appName, userId, new ConcurrentHashMap<>(initialState), null)
Expand Down
39 changes: 39 additions & 0 deletions dev/src/main/java/com/google/adk/web/dto/SessionRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* 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 com.google.adk.web.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Collections;
import java.util.Map;

/**
* Data Transfer Object (DTO) for POST /apps/{appName}/users/{userId}/sessions and POST
* /apps/{appName}/users/{userId}/sessions/{sessionId} equests. Contains information for a session.
*/
public class SessionRequest {
@JsonProperty("state")
public Map<String, Object> state;

public SessionRequest() {}

public Map<String, Object> getState() {
if (state == null) {
return Collections.emptyMap();
}
return state;
}
}