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 @@ -32,6 +32,7 @@
import com.google.adk.models.LlmResponse;
import com.google.adk.plugins.BasePlugin;
import com.google.adk.plugins.agentanalytics.JsonFormatter.TruncationResult;
import com.google.adk.plugins.agentanalytics.TraceManager.LiveTurnBoundaryKind;
import com.google.adk.plugins.agentanalytics.TraceManager.LlmResponseSpanSnapshot;
import com.google.adk.plugins.agentanalytics.TraceManager.RecordData;
import com.google.adk.plugins.agentanalytics.TraceManager.SpanIds;
Expand Down Expand Up @@ -68,10 +69,10 @@
import com.google.genai.types.FunctionCall;
import com.google.genai.types.FunctionResponse;
import com.google.genai.types.Part;
import com.google.genai.types.Transcription;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Maybe;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
Expand Down Expand Up @@ -707,18 +708,18 @@ public Maybe<Event> onEventCallback(InvocationContext invocationContext, Event e
if (!config.enabled() || state.isProcessed(invocationContext.invocationId())) {
return Maybe.empty();
}
// Function-response and input-transcription events never close an open llm_request span.
boolean isLive = isLiveInvocation(invocationContext);
TraceManager traceManager = state.getTraceManager(invocationContext.invocationId());
String eventBranch = event.branch().orElse(null);
// Function-response and input-transcription events never close an open llm_request span.
if (event.functionResponses().isEmpty() && event.inputTranscription().isEmpty()) {
if (isLive) {
if (!event.partial().orElse(false) && isLiveTurnBoundary(event)) {
traceManager.popLiveLlmRequestSpan(
invocationContext, eventBranch, isBareLiveInterrupted(event));
invocationContext, eventBranch, liveTurnBoundaryKind(event));
} else if (!Objects.equals(event.author(), "user")
&& event.functionCalls().isEmpty()
&& (event.content().isPresent() || event.outputTranscription().isPresent())) {
&& (event.content().isPresent() || hasNonEmptyOutputTranscription(event))) {
traceManager.markLiveOutputObserved(invocationContext, eventBranch);
}
} else if (!event.partial().orElse(false)) {
Expand Down Expand Up @@ -924,21 +925,43 @@ && continuesLiveConnectionAfterFunctionResponse(event)) {
private static boolean isLiveTurnBoundary(Event event) {
return event.turnComplete().orElse(false)
|| event.interrupted().orElse(false)
|| event
.errorCode()
.filter(BigQueryAgentAnalyticsPlugin::isTerminalLiveErrorCode)
.isPresent();
|| hasTerminalLiveError(event);
}

private static LiveTurnBoundaryKind liveTurnBoundaryKind(Event event) {
boolean interrupted = event.interrupted().orElse(false);
boolean turnComplete = event.turnComplete().orElse(false);
// A bare boundary carries exactly one of the two flags and nothing else that ends the turn.
boolean isBare =
interrupted != turnComplete
&& event.content().isEmpty()
&& !hasNonEmptyOutputTranscription(event)
&& !hasTerminalLiveError(event);
if (!isBare) {
return LiveTurnBoundaryKind.TERMINAL;
}
return interrupted
? LiveTurnBoundaryKind.BARE_INTERRUPTED
: LiveTurnBoundaryKind.BARE_TURN_COMPLETE;
}

/**
* Returns whether {@code event} carries spoken model output. A live server may end a
* transcription with an empty finished chunk, which carries no output for the turn it arrives in.
*/
private static boolean hasNonEmptyOutputTranscription(Event event) {
return event
.outputTranscription()
.flatMap(Transcription::text)
.filter(text -> !text.isEmpty())
.isPresent();
}

private static boolean isBareLiveInterrupted(Event event) {
return event.interrupted().orElse(false)
&& !event.turnComplete().orElse(false)
&& event.content().isEmpty()
&& event.outputTranscription().isEmpty()
&& event
.errorCode()
.filter(BigQueryAgentAnalyticsPlugin::isTerminalLiveErrorCode)
.isEmpty();
private static boolean hasTerminalLiveError(Event event) {
return event
.errorCode()
.filter(BigQueryAgentAnalyticsPlugin::isTerminalLiveErrorCode)
.isPresent();
}

private static boolean continuesLiveConnectionAfterFunctionResponse(Event event) {
Expand Down Expand Up @@ -1098,8 +1121,8 @@ public Maybe<LlmResponse> afterModelCallback(
|| state.isProcessed(callbackContext.invocationContext().invocationId())) {
return Maybe.empty();
}
TraceManager traceManager =
state.getTraceManager(callbackContext.invocationContext().invocationId());
InvocationContext invocationContext = callbackContext.invocationContext();
TraceManager traceManager = state.getTraceManager(invocationContext.invocationId());

Map<String, Object> usageDict = new HashMap<>();
llmResponse
Expand All @@ -1114,25 +1137,15 @@ public Maybe<LlmResponse> afterModelCallback(
.ifPresent(c -> usageDict.put("cached_content_token_count", c));
});

InvocationContext invocationContext = callbackContext.invocationContext();
LlmResponseSpanSnapshot spanSnapshot =
traceManager.captureLlmResponseSpan(
invocationContext,
isLiveInvocation(invocationContext),
llmResponse.partial().orElse(false));
Duration duration = spanSnapshot.duration();
Duration ttft =
spanSnapshot.startTime().isPresent() && spanSnapshot.firstTokenTime().isPresent()
? Duration.between(spanSnapshot.startTime().get(), spanSnapshot.firstTokenTime().get())
: null;

EventData.Builder eventDataBuilder = EventData.builder();
if (!duration.isZero()) {
eventDataBuilder.setLatency(duration);
}
if (ttft != null) {
eventDataBuilder.setTimeToFirstToken(ttft);
}
spanSnapshot.duration().ifPresent(eventDataBuilder::setLatency);
spanSnapshot.timeToFirstToken().ifPresent(eventDataBuilder::setTimeToFirstToken);
llmResponse.modelVersion().ifPresent(eventDataBuilder::setModelVersion);

if (!usageDict.isEmpty()) {
Expand All @@ -1159,29 +1172,18 @@ public Maybe<LlmResponse> onModelErrorCallback(
|| state.isProcessed(callbackContext.invocationContext().invocationId())) {
return Maybe.empty();
}
TraceManager traceManager =
state.getTraceManager(callbackContext.invocationContext().invocationId());
InvocationContext invocationContext = callbackContext.invocationContext();
TraceManager traceManager = state.getTraceManager(invocationContext.invocationId());
Optional<RecordData> popped = traceManager.popSpan(invocationContext, "llm_request");
String spanId = popped.map(RecordData::spanId).orElse(null);
String parentSpanId =
popped
.flatMap(RecordData::parentSpanId)
.or(() -> traceManager.getCurrentSpanAndParent(invocationContext).spanId())
.orElse(null);

EventData.Builder eventDataBuilder =
EventData.builder().setStatus("ERROR").setErrorMessage(formatErrorMessage(error));
if (popped.isPresent() && !popped.get().hasSyntheticStartTime()) {
eventDataBuilder.setLatency(popped.get().duration());
}
// Always record the internal execution-tree span so parent_span_id references a logged row.
if (spanId != null) {
eventDataBuilder.setSpanIdOverride(spanId);
}
if (parentSpanId != null) {
eventDataBuilder.setParentSpanIdOverride(parentSpanId);
}
// With no span popped, the row resolves to the enclosing span and that span's parent.
popped.ifPresent(p -> eventDataBuilder.setSpanIdOverride(p.spanId()));
popped.flatMap(RecordData::parentSpanId).ifPresent(eventDataBuilder::setParentSpanIdOverride);
return logEvent("LLM_ERROR", invocationContext, null, Optional.of(eventDataBuilder.build()))
.andThen(Maybe.empty());
}
Expand Down Expand Up @@ -1214,13 +1216,11 @@ public Maybe<Map<String, Object>> afterToolCallback(
if (!config.enabled() || state.isProcessed(toolContext.invocationContext().invocationId())) {
return Maybe.empty();
}
state
.getTraceManager(toolContext.invocationContext().invocationId())
.ensureInvocationSpan(toolContext.invocationContext());
InvocationContext invocationContext = toolContext.invocationContext();
TraceManager traceManager = state.getTraceManager(invocationContext.invocationId());
traceManager.ensureInvocationSpan(invocationContext);
Optional<RecordData> popped =
state
.getTraceManager(toolContext.invocationContext().invocationId())
.popSpan(toolContext.invocationContext(), "tool", toolOperationId(toolContext));
traceManager.popSpan(invocationContext, "tool", toolOperationId(toolContext));
TruncationResult truncationResult = smartTruncate(result, config.maxContentLength());
ImmutableMap<String, Object> contentMap =
ImmutableMap.of(
Expand All @@ -1243,7 +1243,7 @@ public Maybe<Map<String, Object>> afterToolCallback(

return logEvent(
"TOOL_COMPLETED",
toolContext.invocationContext(),
invocationContext,
contentMap,
truncationResult.isTruncated(),
Optional.of(eventDataBuilder.build()))
Expand All @@ -1256,13 +1256,11 @@ public Maybe<Map<String, Object>> onToolErrorCallback(
if (!config.enabled() || state.isProcessed(toolContext.invocationContext().invocationId())) {
return Maybe.empty();
}
state
.getTraceManager(toolContext.invocationContext().invocationId())
.ensureInvocationSpan(toolContext.invocationContext());
InvocationContext invocationContext = toolContext.invocationContext();
TraceManager traceManager = state.getTraceManager(invocationContext.invocationId());
traceManager.ensureInvocationSpan(invocationContext);
Optional<RecordData> popped =
state
.getTraceManager(toolContext.invocationContext().invocationId())
.popSpan(toolContext.invocationContext(), "tool", toolOperationId(toolContext));
traceManager.popSpan(invocationContext, "tool", toolOperationId(toolContext));

TruncationResult truncationResult = smartTruncate(toolArgs, config.maxContentLength());
ImmutableMap<String, Object> contentMap =
Expand All @@ -1285,7 +1283,7 @@ public Maybe<Map<String, Object>> onToolErrorCallback(

return logEvent(
"TOOL_ERROR",
toolContext.invocationContext(),
invocationContext,
contentMap,
truncationResult.isTruncated(),
Optional.of(eventDataBuilder.build()))
Expand Down
Loading
Loading