Skip to content

Commit acfaa04

Browse files
google-genai-botcopybara-github
authored andcommitted
feat: Improving LoggingPlugin
This CL refactors and improves the `LoggingPlugin` in the ADK core. Here's a summary of the changes: 1. **Consistent Agent Name Logging**: The plugin now consistently retrieves the agent name from `callbackContext.agentName()` in `beforeAgentCallback` and `afterAgentCallback`, instead of using `agent.name()`. 2. **Enhanced LLM Response Logging**: The `formatContent` method has been significantly updated to provide more detailed logging for different types of `Content.parts()` within an LLM response. It now explicitly logs: * Trimmed and potentially truncated text. * The name of `functionCall` and `functionResponse`. * Indicators for `codeExecutionResult` and other part types. The different parts are joined by " | ". 3. **Improved Optional Field Logging**: Optional fields like `llmResponse.errorMessage()` and `toolContext.functionCallId()` are now always logged, displaying "None" when the optional is empty, rather than only logging when the value is present. 4. **Simplified Argument Formatting**: The `formatArgs` method now uses `args.toString()` for formatting, simplifying the code while still handling truncation for long argument strings. 5. **Removed Redundant Error Logging**: Duplicate `logger.error` calls within `onLlmError` and `onToolError` have been removed, as the preceding `log` calls already capture the necessary error information. 6. **Test Updates**: `LoggingPluginTest.java` has been updated to mock `mockCallbackContext.invocationContext()` and remove an unnecessary mock for `mockCallbackContext.branch()`. PiperOrigin-RevId: 859611274
1 parent c11fe22 commit acfaa04

2 files changed

Lines changed: 31 additions & 26 deletions

File tree

core/src/main/java/com/google/adk/plugins/LoggingPlugin.java

Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ public Maybe<Content> beforeAgentCallback(BaseAgent agent, CallbackContext callb
133133
return Maybe.fromAction(
134134
() -> {
135135
log("🤖 AGENT STARTING");
136-
log(" Agent Name: " + agent.name());
136+
log(" Agent Name: " + callbackContext.agentName());
137137
log(" Invocation ID: " + callbackContext.invocationId());
138138
callbackContext.branch().ifPresent(branch -> log(" Branch: " + branch));
139139
});
@@ -144,7 +144,7 @@ public Maybe<Content> afterAgentCallback(BaseAgent agent, CallbackContext callba
144144
return Maybe.fromAction(
145145
() -> {
146146
log("🤖 AGENT COMPLETED");
147-
log(" Agent Name: " + agent.name());
147+
log(" Agent Name: " + callbackContext.agentName());
148148
log(" Invocation ID: " + callbackContext.invocationId());
149149
});
150150
}
@@ -188,7 +188,7 @@ public Maybe<LlmResponse> afterModelCallback(
188188

189189
if (llmResponse.errorCode().isPresent()) {
190190
log(" ❌ ERROR - Code: " + llmResponse.errorCode().get());
191-
llmResponse.errorMessage().ifPresent(msg -> log(" Error Message: " + msg));
191+
log(" Error Message: " + llmResponse.errorMessage().orElse("None"));
192192
} else {
193193
log(" Content: " + formatContent(llmResponse.content()));
194194
llmResponse.partial().ifPresent(partial -> log(" Partial: " + partial));
@@ -230,7 +230,7 @@ public Maybe<Map<String, Object>> beforeToolCallback(
230230
log("🔧 TOOL STARTING");
231231
log(" Tool Name: " + tool.name());
232232
log(" Agent: " + toolContext.agentName());
233-
toolContext.functionCallId().ifPresent(id -> log(" Function Call ID: " + id));
233+
log(" Function Call ID: " + toolContext.functionCallId().orElse("None"));
234234
log(" Arguments: " + formatArgs(toolArgs));
235235
});
236236
}
@@ -246,7 +246,7 @@ public Maybe<Map<String, Object>> afterToolCallback(
246246
log("🔧 TOOL COMPLETED");
247247
log(" Tool Name: " + tool.name());
248248
log(" Agent: " + toolContext.agentName());
249-
toolContext.functionCallId().ifPresent(id -> log(" Function Call ID: " + id));
249+
log(" Function Call ID: " + toolContext.functionCallId().orElse("None"));
250250
log(" Result: " + formatArgs(result));
251251
});
252252
}
@@ -259,10 +259,9 @@ public Maybe<Map<String, Object>> onToolErrorCallback(
259259
log("🔧 TOOL ERROR");
260260
log(" Tool Name: " + tool.name());
261261
log(" Agent: " + toolContext.agentName());
262-
toolContext.functionCallId().ifPresent(id -> log(" Function Call ID: " + id));
262+
log(" Function Call ID: " + toolContext.functionCallId().orElse("None"));
263263
log(" Arguments: " + formatArgs(toolArgs));
264264
log(" Error: " + error.getMessage());
265-
logger.error("[{}] Tool Error", name, error);
266265
});
267266
}
268267

@@ -274,30 +273,36 @@ private String formatContent(Optional<Content> contentOptional) {
274273
if (content.parts().isEmpty() || content.parts().get().isEmpty()) {
275274
return "None";
276275
}
277-
278-
String combinedText =
279-
content.parts().get().stream()
280-
.map(part -> part.text().orElse(""))
281-
.collect(joining("\n"))
282-
.trim();
283-
284-
if (combinedText.length() > MAX_CONTENT_LENGTH) {
285-
return combinedText.substring(0, MAX_CONTENT_LENGTH) + "...";
286-
}
287-
return combinedText;
276+
return content.parts().get().stream()
277+
.map(
278+
part -> {
279+
if (part.text().isPresent()) {
280+
String text = part.text().get().trim();
281+
if (text.length() > MAX_CONTENT_LENGTH) {
282+
text = text.substring(0, MAX_CONTENT_LENGTH) + "...";
283+
}
284+
return String.format("text: '%s'", text);
285+
} else if (part.functionCall().isPresent()) {
286+
return String.format("function_call: %s", part.functionCall().get().name());
287+
} else if (part.functionResponse().isPresent()) {
288+
return String.format("function_response: %s", part.functionResponse().get().name());
289+
} else if (part.codeExecutionResult().isPresent()) {
290+
return "code_execution_result";
291+
} else {
292+
return "other_part";
293+
}
294+
})
295+
.collect(joining("\n"));
288296
}
289297

290298
private String formatArgs(Map<String, Object> args) {
291299
if (args == null || args.isEmpty()) {
292300
return "{}";
293301
}
294-
String argsStr =
295-
args.entrySet().stream()
296-
.map(entry -> entry.getKey() + "=" + entry.getValue())
297-
.collect(joining(", "));
298-
if (argsStr.length() > MAX_ARGS_LENGTH) {
299-
return "{" + argsStr.substring(0, MAX_ARGS_LENGTH) + "...}";
302+
String formatted = args.toString();
303+
if (formatted.length() > MAX_ARGS_LENGTH) {
304+
formatted = formatted.substring(0, MAX_ARGS_LENGTH) + "...}";
300305
}
301-
return "{" + argsStr + "}";
306+
return formatted;
302307
}
303308
}

core/src/test/java/com/google/adk/plugins/LoggingPluginTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ public void setUp() {
8787

8888
when(mockCallbackContext.invocationId()).thenReturn("invocation_id");
8989
when(mockCallbackContext.agentName()).thenReturn("agent_name");
90-
when(mockCallbackContext.branch()).thenReturn(Optional.empty());
90+
when(mockCallbackContext.invocationContext()).thenReturn(mockInvocationContext);
9191

9292
when(mockTool.name()).thenReturn("tool_name");
9393
when(mockToolContext.agentName()).thenReturn("agent_name");

0 commit comments

Comments
 (0)