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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Enabled the flake8-type-checking plugin rules for ruff linter. These rules do not allow the import of python objects outside the type-checking block, if they are only used for type annotations and are not used at runtime.
([#4398](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4398))
- `opentelemetry-instrumentation-asgi`: Respect `suppress_http_instrumentation` context in ASGI middleware to skip server span creation when HTTP instrumentation is suppressed
([#4375](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4375))
- `opentelemetry-instrumentation-confluent-kafka`: Loosen confluent-kafka upper bound to <3.0.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING, Sequence

from anthropic.types import MessageDeltaUsage

from opentelemetry.semconv._incubating.attributes import (
gen_ai_attributes as GenAIAttributes,
)
Expand All @@ -32,7 +30,6 @@
MessagePart,
OutputMessage,
)
from opentelemetry.util.types import AttributeValue

from .utils import (
convert_content_to_parts,
Expand All @@ -46,6 +43,7 @@
from anthropic.resources.messages import Messages
from anthropic.types import (
Message,
MessageDeltaUsage,
MessageParam,
MetadataParam,
TextBlockParam,
Expand All @@ -55,6 +53,8 @@
Usage,
)

from opentelemetry.util.types import AttributeValue


@dataclass
class MessageRequestParams:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
from typing import TYPE_CHECKING, Any, Callable, Union, cast

from anthropic._streaming import Stream as AnthropicStream
from anthropic.types import Message as AnthropicMessage

from opentelemetry.semconv._incubating.attributes import (
gen_ai_attributes as GenAIAttributes,
Expand All @@ -42,9 +41,8 @@

if TYPE_CHECKING:
from anthropic.resources.messages import Messages
from anthropic.types import Message as AnthropicMessage
from anthropic.types import RawMessageStreamEvent


_logger = logging.getLogger(__name__)
ANTHROPIC = "anthropic"

Expand Down Expand Up @@ -121,13 +119,6 @@ def traced_method(
raise

return cast(
Callable[
...,
Union[
"AnthropicMessage",
"AnthropicStream[RawMessageStreamEvent]",
MessagesStreamWrapper,
],
],
"Callable[..., Union[AnthropicMessage, AnthropicStream[RawMessageStreamEvent], MessagesStreamWrapper]]",
traced_method,
)
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@
from __future__ import annotations

import logging
from types import TracebackType
from typing import TYPE_CHECKING, Callable, Iterator, Optional

from opentelemetry.util.genai.handler import TelemetryHandler
from opentelemetry.util.genai.types import (
Error,
LLMInvocation,
Expand All @@ -41,6 +39,8 @@
)

if TYPE_CHECKING:
from types import TracebackType

from anthropic._streaming import Stream
from anthropic.types import (
Message,
Expand All @@ -49,7 +49,7 @@
Usage,
)


from opentelemetry.util.genai.handler import TelemetryHandler
_logger = logging.getLogger(__name__)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,20 @@
from __future__ import annotations

import logging
from typing import Any
from typing import TYPE_CHECKING, Any

import google.genai

from opentelemetry._logs import Logger, LoggerProvider, LogRecord
from opentelemetry.metrics import Meter, MeterProvider
from opentelemetry.semconv._incubating.metrics import gen_ai_metrics
from opentelemetry.semconv.schemas import Schemas
from opentelemetry.trace import Tracer, TracerProvider

from .version import __version__ as _LIBRARY_VERSION

if TYPE_CHECKING:
from opentelemetry.metrics import Meter, MeterProvider
from opentelemetry.trace import Tracer, TracerProvider

_logger = logging.getLogger(__name__)

_SCOPE_NAME = "opentelemetry.instrumentation.google_genai"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,22 @@

from __future__ import annotations

from typing import Any, Optional, cast
from uuid import UUID
from typing import TYPE_CHECKING, Any, Optional, cast

from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.messages import BaseMessage
from langchain_core.outputs import LLMResult

from opentelemetry.instrumentation.langchain.invocation_manager import (
_InvocationManager,
)
from opentelemetry.util.genai.handler import TelemetryHandler

if TYPE_CHECKING:
from uuid import UUID

from langchain_core.messages import BaseMessage
from langchain_core.outputs import LLMResult

from opentelemetry.util.genai.handler import TelemetryHandler

from opentelemetry.util.genai.types import (
Error,
InputMessage,
Expand Down Expand Up @@ -136,7 +141,7 @@ def on_chat_model_start(

input_messages.append(
InputMessage(
parts=cast(list[MessagePart], parts), role=role
parts=cast("list[MessagePart]", parts), role=role
)
)

Expand Down Expand Up @@ -211,7 +216,7 @@ def on_llm_end(
role = chat_generation.message.type
output_message = OutputMessage(
role=role,
parts=cast(list[MessagePart], parts),
parts=cast("list[MessagePart]", parts),
finish_reason=finish_reason,
)
output_messages.append(output_message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@
Tracer,
set_span_in_context,
)
from opentelemetry.util.types import AttributeValue

# Import all semantic convention constants
# ---- GenAI semantic convention helpers (embedded from constants.py) ----
Expand Down Expand Up @@ -297,6 +296,7 @@ def normalize_output_type(output_type: Optional[str]) -> str:
if TYPE_CHECKING:
pass

from opentelemetry.util.types import AttributeValue
# Legacy attributes removed

logger = logging.getLogger(__name__)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@

import logging
from contextlib import AsyncExitStack, ExitStack, contextmanager
from types import TracebackType
from typing import TYPE_CHECKING, Callable, Generator, Generic, TypeVar

from opentelemetry.util.genai.handler import TelemetryHandler
from opentelemetry.util.genai.types import Error, LLMInvocation

# OpenAI Responses internals are version-gated (added in openai>=1.66.0), so
Expand Down Expand Up @@ -49,6 +47,8 @@
_set_invocation_response_attributes = None

if TYPE_CHECKING:
from types import TracebackType

from openai.lib.streaming.responses._events import ( # pylint: disable=no-name-in-module
ResponseStreamEvent,
)
Expand All @@ -63,6 +63,7 @@
Response,
)

from opentelemetry.util.genai.handler import TelemetryHandler
_logger = logging.getLogger(__name__)
TextFormatT = TypeVar("TextFormatT")
ResponseT = TypeVar("ResponseT")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@
from __future__ import annotations

from dataclasses import asdict, dataclass
from typing import Any, Iterable, Literal
from typing import TYPE_CHECKING, Any, Iterable, Literal

from opentelemetry._logs import LogRecord
from opentelemetry.semconv._incubating.attributes import gen_ai_attributes
from opentelemetry.util.types import AnyValue

if TYPE_CHECKING:
from opentelemetry.util.types import AnyValue


def user_event(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
gen_ai_attributes as GenAI,
)
from opentelemetry.trace import SpanKind, Tracer
from opentelemetry.util.genai.completion_hook import CompletionHook
from opentelemetry.util.genai.types import (
ContentCapturingMode,
InputMessage,
Expand All @@ -71,6 +70,8 @@
prediction_service as prediction_service_v1beta1,
)

from opentelemetry.util.genai.completion_hook import CompletionHook


# Use parameter signature from
# https://github.com/googleapis/python-aiplatform/blob/v1.76.0/google/cloud/aiplatform_v1/services/prediction_service/client.py#L2088
Expand Down Expand Up @@ -314,15 +315,17 @@ def generate_content(
| prediction_service_v1beta1.GenerateContentResponse
):
if self.sem_conv_opt_in_mode == _StabilityMode.DEFAULT:
capture_content_bool = cast(bool, self.capture_content)
capture_content_bool = cast("bool", self.capture_content)
with self._with_default_instrumentation(
capture_content_bool, instance, args, kwargs
) as handle_response:
response = wrapped(*args, **kwargs)
handle_response(response)
return response
else:
capture_content = cast(ContentCapturingMode, self.capture_content)
capture_content = cast(
"ContentCapturingMode", self.capture_content
)
with self._with_new_instrumentation(
capture_content, instance, args, kwargs
) as handle_response:
Expand Down Expand Up @@ -351,15 +354,17 @@ async def agenerate_content(
| prediction_service_v1beta1.GenerateContentResponse
):
if self.sem_conv_opt_in_mode == _StabilityMode.DEFAULT:
capture_content_bool = cast(bool, self.capture_content)
capture_content_bool = cast("bool", self.capture_content)
with self._with_default_instrumentation(
capture_content_bool, instance, args, kwargs
) as handle_response:
response = await wrapped(*args, **kwargs)
handle_response(response)
return response
else:
capture_content = cast(ContentCapturingMode, self.capture_content)
capture_content = cast(
"ContentCapturingMode", self.capture_content
)
with self._with_new_instrumentation(
capture_content, instance, args, kwargs
) as handle_response:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@

from google.protobuf import json_format

from opentelemetry._logs import LogRecord
from opentelemetry.instrumentation._semconv import (
_StabilityMode,
)
Expand Down Expand Up @@ -62,7 +61,6 @@
Uri,
)
from opentelemetry.util.genai.utils import get_content_capturing_mode
from opentelemetry.util.types import AnyValue, AttributeValue

if TYPE_CHECKING:
from google.cloud.aiplatform_v1.types import (
Expand All @@ -80,7 +78,8 @@
tool as tool_v1beta1,
)


from opentelemetry._logs import LogRecord
from opentelemetry.util.types import AnyValue, AttributeValue
_MODEL = "model"


Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from typing import TYPE_CHECKING

import pytest
from google.api_core.exceptions import BadRequest, NotFound
from vertexai.generative_models import (
Expand All @@ -12,24 +14,27 @@
GenerativeModel as PreviewGenerativeModel,
)

from opentelemetry.instrumentation.vertexai import VertexAIInstrumentor

# Backward compatibility for InMemoryLogExporter -> InMemoryLogRecordExporter rename
try:
from opentelemetry.sdk._logs._internal.export.in_memory_log_exporter import ( # pylint: disable=no-name-in-module
InMemoryLogRecordExporter,
)
except ImportError:
# Fallback to old name for compatibility with older SDK versions
from opentelemetry.sdk._logs._internal.export.in_memory_log_exporter import (
InMemoryLogExporter as InMemoryLogRecordExporter,
)
from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
)
if TYPE_CHECKING:
from opentelemetry.sdk._logs._internal.export.in_memory_log_exporter import (
InMemoryLogExporter as InMemoryLogRecordExporter,
)

from opentelemetry.trace import StatusCode

if TYPE_CHECKING:
from opentelemetry.instrumentation.vertexai import VertexAIInstrumentor
from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
)


@pytest.mark.vcr()
def test_generate_content(
Expand Down
Loading