Skip to content

Commit 35edb49

Browse files
committed
make utils compatible with py3.9
Use Union
1 parent a98e078 commit 35edb49

File tree

14 files changed

+81
-76
lines changed

14 files changed

+81
-76
lines changed

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/_fsspec_upload/fsspec_hook.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from concurrent.futures import Future, ThreadPoolExecutor
2323
from dataclasses import asdict, dataclass
2424
from functools import partial
25-
from typing import Any, Callable, Literal, TextIO, cast
25+
from typing import Any, Callable, Literal, TextIO, cast, Union
2626
from uuid import uuid4
2727

2828
import fsspec
@@ -147,8 +147,8 @@ def upload(
147147
inputs: list[types.InputMessage],
148148
outputs: list[types.OutputMessage],
149149
system_instruction: list[types.MessagePart],
150-
span: Span | None = None,
151-
log_record: LogRecord | None = None,
150+
span: Union[Span, None] = None,
151+
log_record: Union[LogRecord, None] = None,
152152
**kwargs: Any,
153153
) -> None:
154154
completion = Completion(

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
import os
55
from dataclasses import dataclass
6-
from typing import Dict
6+
from typing import Dict, Union
77

88
from .emitters.spec import CategoryOverride
99
from .environment_variables import (
@@ -123,7 +123,7 @@ def parse_env() -> Settings:
123123

124124
def _parse_category_override(
125125
category: str, raw: str
126-
) -> CategoryOverride | None: # pragma: no cover - thin parsing
126+
) -> Union[CategoryOverride, None]: # pragma: no cover - thin parsing
127127
if not raw:
128128
return None
129129
text = raw.strip()

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/emitters/composite.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
import logging
4-
from typing import Any, Iterable, Iterator, Mapping, Sequence
4+
from typing import Any, Iterable, Iterator, Mapping, Sequence, Union
55

66
from ..interfaces import EmitterMeta, EmitterProtocol
77
from ..types import Error, EvaluationResult
@@ -37,10 +37,10 @@ class CompositeEmitter(EmitterMeta):
3737
def __init__(
3838
self,
3939
*,
40-
span_emitters: Iterable[EmitterProtocol] | None = None,
41-
metrics_emitters: Iterable[EmitterProtocol] | None = None,
42-
content_event_emitters: Iterable[EmitterProtocol] | None = None,
43-
evaluation_emitters: Iterable[EmitterProtocol] | None = None,
40+
span_emitters: Union[Iterable[EmitterProtocol], None] = None,
41+
metrics_emitters: Union[Iterable[EmitterProtocol], None] = None,
42+
content_event_emitters: Union[Iterable[EmitterProtocol], None] = None,
43+
evaluation_emitters: Union[Iterable[EmitterProtocol], None] = None,
4444
) -> None:
4545
self._categories: dict[str, list[EmitterProtocol]] = {
4646
"span": list(span_emitters or []),
@@ -64,7 +64,7 @@ def on_error(self, error: Error, obj: Any) -> None: # type: ignore[override]
6464
def on_evaluation_results(
6565
self,
6666
results: Sequence[EvaluationResult],
67-
obj: Any | None = None,
67+
obj: Union[Any, None] = None,
6868
) -> None: # type: ignore[override]
6969
if not results:
7070
return
@@ -79,7 +79,7 @@ def on_evaluation_results(
7979
# Introspection helpers used during configuration refresh
8080

8181
def iter_emitters(
82-
self, categories: Sequence[str] | None = None
82+
self, categories: Union[Sequence[str], None] = None
8383
) -> Iterator[EmitterProtocol]:
8484
names = categories or (
8585
"span",
@@ -108,9 +108,9 @@ def _dispatch(
108108
categories: Sequence[str],
109109
method_name: str,
110110
*,
111-
obj: Any | None = None,
112-
error: Error | None = None,
113-
results: Sequence[EvaluationResult] | None = None,
111+
obj: Union[Any, None] = None,
112+
error: Union[Error, None] = None,
113+
results: Union[Sequence[EvaluationResult], None] = None,
114114
) -> None:
115115
for category in categories:
116116
emitters = self._categories.get(category)

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/emitters/evaluation.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import logging
66
import os
7-
from typing import Any, Dict, Optional, Sequence
7+
from typing import Any, Dict, Optional, Sequence, Union
88

99
from opentelemetry import _events as _otel_events
1010

@@ -23,13 +23,13 @@
2323
from ..types import EvaluationResult, GenAI
2424

2525

26-
def _get_request_model(invocation: GenAI) -> str | None:
26+
def _get_request_model(invocation: GenAI) -> Union[str, None]:
2727
return getattr(invocation, "request_model", None) or getattr(
2828
invocation, "model", None
2929
)
3030

3131

32-
def _get_response_id(invocation: GenAI) -> str | None: # best-effort
32+
def _get_response_id(invocation: GenAI) -> Union[str, None]: # best-effort
3333
return getattr(invocation, "response_id", None)
3434

3535

@@ -128,7 +128,7 @@ def _direct_factory(_name: str): # ignore metric name, single hist
128128
def on_evaluation_results( # type: ignore[override]
129129
self,
130130
results: Sequence[EvaluationResult],
131-
obj: Any | None = None,
131+
obj: Union[Any, None] = None,
132132
) -> None:
133133
invocation = obj if isinstance(obj, GenAI) else None
134134
if invocation is None:
@@ -337,7 +337,7 @@ def __init__(
337337
def on_evaluation_results( # type: ignore[override]
338338
self,
339339
results: Sequence[EvaluationResult],
340-
obj: Any | None = None,
340+
obj: Union[Any, None] = None,
341341
) -> None:
342342
if self._event_logger is None:
343343
return

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/emitters/span.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import json # noqa: F401 (kept for backward compatibility if external code relies on this module re-exporting json)
55
from dataclasses import asdict # noqa: F401
6-
from typing import Any, Optional
6+
from typing import Any, Optional, Union
77

88
from opentelemetry import trace
99
from opentelemetry.semconv._incubating.attributes import (
@@ -202,7 +202,7 @@ def _apply_start_attrs(self, invocation: GenAIType):
202202
# Agent context (already covered by semconv metadata on base fields)
203203

204204
def _apply_finish_attrs(
205-
self, invocation: LLMInvocation | EmbeddingInvocation
205+
self, invocation: Union[LLMInvocation, EmbeddingInvocation]
206206
):
207207
span = getattr(invocation, "span", None)
208208
if span is None:
@@ -255,7 +255,7 @@ def _apply_finish_attrs(
255255

256256
# ---- lifecycle -------------------------------------------------------
257257
def on_start(
258-
self, invocation: LLMInvocation | EmbeddingInvocation
258+
self, invocation: Union[LLMInvocation, EmbeddingInvocation]
259259
) -> None: # type: ignore[override]
260260
# Handle new agentic types
261261
if isinstance(invocation, Workflow):
@@ -289,7 +289,7 @@ def on_start(
289289
invocation.context_token = cm # type: ignore[assignment]
290290
self._apply_start_attrs(invocation)
291291

292-
def on_end(self, invocation: LLMInvocation | EmbeddingInvocation) -> None: # type: ignore[override]
292+
def on_end(self, invocation: Union[LLMInvocation, EmbeddingInvocation]) -> None: # type: ignore[override]
293293
if isinstance(invocation, Workflow):
294294
self._finish_workflow(invocation)
295295
elif isinstance(invocation, AgentInvocation):
@@ -312,7 +312,7 @@ def on_end(self, invocation: LLMInvocation | EmbeddingInvocation) -> None: # ty
312312
span.end()
313313

314314
def on_error(
315-
self, error: Error, invocation: LLMInvocation | EmbeddingInvocation
315+
self, error: Error, invocation: Union[LLMInvocation, EmbeddingInvocation]
316316
) -> None: # type: ignore[override]
317317
if isinstance(invocation, Workflow):
318318
self._error_workflow(error, invocation)

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/emitters/spec.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
from dataclasses import dataclass, field
4-
from typing import Any, Callable, Mapping, Sequence
4+
from typing import Any, Callable, Mapping, Sequence, Union
55

66
from ..interfaces import EmitterProtocol
77

@@ -30,7 +30,7 @@ class EmitterSpec:
3030
mode: str = "append"
3131
after: Sequence[str] = field(default_factory=tuple)
3232
before: Sequence[str] = field(default_factory=tuple)
33-
invocation_types: Sequence[str] | None = None
33+
invocation_types: Union[Sequence[str], None] = None
3434

3535

3636
@dataclass(frozen=True)

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/emitters/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import json
55
from dataclasses import asdict
6-
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence
6+
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Union
77

88
from opentelemetry import trace
99
from opentelemetry._logs import (
@@ -56,7 +56,7 @@
5656

5757

5858
def filter_semconv_gen_ai_attributes(
59-
attributes: Mapping[str, Any] | None,
59+
attributes: Union[Mapping[str, Any], None],
6060
*,
6161
extras: Iterable[str] = (),
6262
) -> dict[str, Any]:
@@ -564,7 +564,7 @@ def _record_token_metrics(
564564

565565
def _record_duration(
566566
duration_histogram: Histogram,
567-
invocation: LLMInvocation | EmbeddingInvocation | ToolCall,
567+
invocation: Union[LLMInvocation, EmbeddingInvocation, ToolCall],
568568
metric_attributes: Dict[str, AttributeValue],
569569
*,
570570
span: Optional[Span] = None,

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/evaluators/base.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from __future__ import annotations
1616

1717
from abc import ABC
18-
from typing import Iterable, Mapping, Sequence
18+
from typing import Iterable, Mapping, Sequence, Union
1919

2020
from opentelemetry.util.genai.types import (
2121
AgentInvocation,
@@ -35,10 +35,10 @@ class Evaluator(ABC):
3535

3636
def __init__(
3737
self,
38-
metrics: Iterable[str] | None = None,
38+
metrics: Union[Iterable[str], None] = None,
3939
*,
40-
invocation_type: str | None = None,
41-
options: Mapping[str, str] | None = None,
40+
invocation_type: Union[str, None] = None,
41+
options: Union[Mapping[str, str], None] = None,
4242
) -> None:
4343
default_metrics = (
4444
self.default_metrics_for(invocation_type)
@@ -65,7 +65,7 @@ def default_metrics(self) -> Sequence[str]: # pragma: no cover - trivial
6565
return ()
6666

6767
def default_metrics_for(
68-
self, invocation_type: str | None
68+
self, invocation_type: Union[str, None]
6969
) -> Sequence[str]:
7070
mapping = self.default_metrics_by_type()
7171
if invocation_type and invocation_type in mapping:

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/evaluators/manager.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import threading
66
import time
77
from dataclasses import dataclass
8-
from typing import TYPE_CHECKING, Mapping, Protocol, Sequence
8+
from typing import TYPE_CHECKING, Mapping, Protocol, Sequence, Union
99

1010
from ..callbacks import CompletionCallback
1111
from ..environment_variables import (
@@ -75,8 +75,8 @@ def __init__(
7575
self,
7676
handler: "TelemetryHandler",
7777
*,
78-
interval: float | None = None,
79-
aggregate_results: bool | None = None,
78+
interval: Union[float, None] = None,
79+
aggregate_results: Union[bool, None] = None,
8080
) -> None:
8181
self._handler = handler
8282
evaluation_sample_rate = _read_evaluation_sample_rate()
@@ -91,7 +91,7 @@ def __init__(
9191
self._evaluators = self._instantiate_evaluators(self._plans)
9292
self._queue: queue.Queue[GenAI] = queue.Queue()
9393
self._shutdown = threading.Event()
94-
self._worker: threading.Thread | None = None
94+
self._worker: Union[threading.Thread, None] = None
9595
if self.has_evaluators:
9696
self._worker = threading.Thread(
9797
target=self._worker_loop,
@@ -138,7 +138,7 @@ def offer(self, invocation: GenAI) -> None:
138138
"Failed to enqueue invocation for evaluation", exc_info=True
139139
)
140140

141-
def wait_for_all(self, timeout: float | None = None) -> None:
141+
def wait_for_all(self, timeout: Union[float, None] = None) -> None:
142142
if not self.has_evaluators:
143143
return
144144
if timeout is None:
@@ -239,11 +239,14 @@ def _emit_results(
239239
return flattened
240240

241241
def _flag_invocation(self, invocation: GenAI) -> None:
242+
# print(f"_flag_invocation:")
242243
if not self.has_evaluators:
243244
return
244245
attributes = getattr(invocation, "attributes", None)
246+
# print(f"attributes inside _flag_invocation: {attributes}")
245247
if isinstance(attributes, dict):
246248
attributes.setdefault("gen_ai.evaluation.executed", True)
249+
# print(f"attributes inside _flag_invocation: {attributes['gen_ai.evaluation.executed']}")
247250

248251
# Configuration ------------------------------------------------------
249252
def _load_plans(self) -> Sequence[EvaluatorPlan]:
@@ -383,7 +386,7 @@ def _generate_default_plans(self) -> Sequence[EvaluatorPlan]:
383386
# Environment parsing helpers
384387

385388

386-
def _read_raw_evaluator_config() -> str | None:
389+
def _read_raw_evaluator_config() -> Union[str, None]:
387390
return _get_env(OTEL_INSTRUMENTATION_GENAI_EVALS_EVALUATORS)
388391

389392

@@ -422,7 +425,7 @@ def _read_evaluation_sample_rate() -> float:
422425
return value
423426

424427

425-
def _get_env(name: str) -> str | None:
428+
def _get_env(name: str) -> Union[str, None]:
426429
import os
427430

428431
return os.environ.get(name)

util/opentelemetry-util-genai-dev/src/opentelemetry/util/genai/evaluators/registry.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import inspect
1818
import logging
1919
from dataclasses import dataclass
20-
from typing import Callable, Dict, Mapping, Sequence
20+
from typing import Callable, Dict, Mapping, Sequence, Union
2121

2222
from opentelemetry.util._importlib_metadata import (
2323
entry_points,
@@ -45,9 +45,9 @@ class EvaluatorRegistration:
4545
def _call_with_optional_params(
4646
target: EvaluatorFactory,
4747
*,
48-
metrics: Sequence[str] | None = None,
49-
invocation_type: str | None = None,
50-
options: Mapping[str, str] | None = None,
48+
metrics: Union[Sequence[str], None] = None,
49+
invocation_type: Union[str, None] = None,
50+
options: Union[Mapping[str, str], None] = None,
5151
) -> Evaluator:
5252
"""Call a factory/constructor handling optional ``metrics`` gracefully."""
5353

@@ -169,7 +169,7 @@ def _load_entry_points() -> None:
169169
"Failed to load evaluator entry point '%s': %s", ep.name, exc
170170
)
171171
continue
172-
registration: EvaluatorRegistration | None = None
172+
registration: Union[EvaluatorRegistration, None] = None
173173
if isinstance(target, EvaluatorRegistration):
174174
registration = target
175175
elif hasattr(target, "factory") and hasattr(target, "default_metrics"):
@@ -204,10 +204,10 @@ def _load_entry_points() -> None:
204204

205205
def get_evaluator(
206206
name: str,
207-
metrics: Sequence[str] | None = None,
207+
metrics: Union[Sequence[str], None] = None,
208208
*,
209-
invocation_type: str | None = None,
210-
options: Mapping[str, str] | None = None,
209+
invocation_type: Union[str, None] = None,
210+
options: Union[Mapping[str, str], None] = None,
211211
) -> Evaluator:
212212
_load_entry_points()
213213
key = name.lower()

0 commit comments

Comments
 (0)