Context manager encompassing `generate_content {model.name}` span. When an external library for inference instrumentation is installed (e.g. opentelemetry-instrumentation-google-genai), span creation is delegated to said library.
(
llm_request: LlmRequest,
invocation_context: InvocationContext,
model_response_event: Event,
)
| 579 | |
| 580 | @asynccontextmanager |
| 581 | async def use_inference_span( |
| 582 | llm_request: LlmRequest, |
| 583 | invocation_context: InvocationContext, |
| 584 | model_response_event: Event, |
| 585 | ) -> AsyncIterator[GenerateContentSpan | None]: |
| 586 | """Context manager encompassing `generate_content {model.name}` span. |
| 587 | |
| 588 | When an external library for inference instrumentation is installed (e.g. |
| 589 | opentelemetry-instrumentation-google-genai), |
| 590 | span creation is delegated to said library. |
| 591 | """ |
| 592 | |
| 593 | telemetry_config = _telemetry_config_from_invocation_context( |
| 594 | invocation_context |
| 595 | ) |
| 596 | common_attributes = { |
| 597 | GEN_AI_AGENT_NAME: invocation_context.agent.name, |
| 598 | GEN_AI_CONVERSATION_ID: invocation_context.session.id, |
| 599 | "gcp.vertex.agent.event_id": model_response_event.id, |
| 600 | "gcp.vertex.agent.invocation_id": invocation_context.invocation_id, |
| 601 | } |
| 602 | log_only_common_attributes = {} |
| 603 | if invocation_context.session.user_id is not None: |
| 604 | log_only_common_attributes[USER_ID] = invocation_context.session.user_id |
| 605 | if _should_emit_native_telemetry(invocation_context.agent): |
| 606 | async with _use_native_generate_content_span( |
| 607 | llm_request=llm_request, |
| 608 | common_attributes=common_attributes, |
| 609 | log_only_common_attributes=log_only_common_attributes, |
| 610 | telemetry_config=telemetry_config, |
| 611 | ) as gc_span: |
| 612 | if telemetry_config.should_use_experimental_genai_semconv: |
| 613 | set_operation_details_common_attributes( |
| 614 | gc_span.operation_details_common_attributes, |
| 615 | telemetry_config, |
| 616 | common_attributes, |
| 617 | log_only_attributes=log_only_common_attributes, |
| 618 | ) |
| 619 | try: |
| 620 | yield gc_span |
| 621 | finally: |
| 622 | maybe_log_completion_details( |
| 623 | gc_span.span, |
| 624 | otel_logger, |
| 625 | gc_span.operation_details_attributes, |
| 626 | gc_span.operation_details_common_attributes, |
| 627 | telemetry_config, |
| 628 | ) |
| 629 | else: |
| 630 | with _use_extra_generate_content_attributes( |
| 631 | common_attributes, |
| 632 | log_only_extra_attributes=log_only_common_attributes, |
| 633 | ): |
| 634 | yield |
| 635 | |
| 636 | |
| 637 | def _instrumented_with_opentelemetry_instrumentation_google_genai() -> bool: |