traceInferenceResult function
void
traceInferenceResult(
- Object? span,
- LlmResponse llmResponse, {
- InvocationContext? invocationContext,
- Map<
String, String> ? environment,
Records inference result attributes on span.
The span can be either GenerateContentSpan or TraceSpanRecord.
Implementation
void traceInferenceResult(
Object? span,
LlmResponse llmResponse, {
InvocationContext? invocationContext,
Map<String, String>? environment,
}) {
GenerateContentSpan? generateContentSpan;
TraceSpanRecord? targetSpan;
LlmRequest? llmRequest;
if (span is GenerateContentSpan) {
generateContentSpan = span;
llmRequest = span._llmRequest;
targetSpan = span.span;
if (llmResponse.partial != true) {
span.responses.add(llmResponse);
}
if (span.endedAtMicros != null) {
return;
}
} else if (span is TraceSpanRecord) {
targetSpan = span;
}
if (targetSpan == null || llmResponse.partial == true) {
return;
}
final InvocationContext? effectiveInvocationContext =
invocationContext ?? generateContentSpan?.invocationContext;
final String? finishReason = llmResponse.finishReason;
final bool hasReportedFinishReason =
experimental_semconv.isReportedFinishReason(finishReason);
if (hasReportedFinishReason) {
targetSpan.setAttribute('gen_ai.response.finish_reasons', <String>[
finishReason!.toLowerCase(),
]);
}
final String? responseModel = _responseModel(
effectiveInvocationContext,
llmResponse,
llmRequest,
);
if (responseModel != null && responseModel.isNotEmpty) {
targetSpan.setAttribute(genAiResponseModel, responseModel);
}
_setUsageMetadataAttributes(targetSpan, llmResponse.usageMetadata);
_setContextCacheAttributes(
targetSpan,
llmResponse.cacheMetadata,
environment: environment,
);
final TelemetryConfig telemetryConfig = effectiveInvocationContext != null
? telemetryConfigFromInvocationContext(effectiveInvocationContext)
: const TelemetryConfig();
_setGroundingAttributes(
targetSpan,
llmResponse.groundingMetadata,
captureContent: telemetryConfig.resolveShouldAddContentToExperimentalSpans(
environment: environment,
),
environment: environment,
);
if (telemetryConfig.shouldUseExperimentalGenAiSemconv(
environment: environment,
) &&
generateContentSpan != null) {
experimental_semconv.setOperationDetailsAttributesFromResponse(
llmResponse,
generateContentSpan.operationDetailsAttributes,
generateContentSpan.operationDetailsCommonAttributes,
reasoning: telemetryConfig.isExperimentalFeatureEnabled(
'reasoning',
environment: environment,
),
);
if (hasReportedFinishReason) {
generateContentSpan.endInference();
}
return;
}
_emitChoiceLog(
llmResponse,
invocationContext: effectiveInvocationContext,
llmRequest: llmRequest,
telemetryConfig: telemetryConfig,
environment: environment,
);
if (hasReportedFinishReason) {
generateContentSpan?.endInference();
}
}