|
| 1 | +# Copyright The OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import json |
| 19 | +import logging |
| 20 | +import posixpath |
| 21 | +import threading |
| 22 | +from concurrent.futures import Future, ThreadPoolExecutor |
| 23 | +from dataclasses import asdict, dataclass |
| 24 | +from functools import partial |
| 25 | +from typing import Any, Callable, Literal, TextIO, cast |
| 26 | +from uuid import uuid4 |
| 27 | + |
| 28 | +import fsspec |
| 29 | + |
| 30 | +from opentelemetry._logs import LogRecord |
| 31 | +from opentelemetry.trace import Span |
| 32 | +from opentelemetry.util.genai import types |
| 33 | +from opentelemetry.util.genai.upload_hook import UploadHook |
| 34 | + |
| 35 | +_logger = logging.getLogger(__name__) |
| 36 | + |
| 37 | + |
| 38 | +@dataclass |
| 39 | +class Completion: |
| 40 | + inputs: list[types.InputMessage] |
| 41 | + outputs: list[types.OutputMessage] |
| 42 | + system_instruction: list[types.MessagePart] |
| 43 | + |
| 44 | + |
| 45 | +@dataclass |
| 46 | +class CompletionRefs: |
| 47 | + inputs_ref: str |
| 48 | + outputs_ref: str |
| 49 | + system_instruction_ref: str |
| 50 | + |
| 51 | + |
| 52 | +JsonEncodeable = list[dict[str, Any]] |
| 53 | + |
| 54 | +# mapping of upload path to function computing upload data dict |
| 55 | +UploadData = dict[str, Callable[[], JsonEncodeable]] |
| 56 | + |
| 57 | + |
| 58 | +def fsspec_open(urlpath: str, mode: Literal["w"]) -> TextIO: |
| 59 | + """typed wrapper around `fsspec.open`""" |
| 60 | + return cast(TextIO, fsspec.open(urlpath, mode)) # pyright: ignore[reportUnknownMemberType] |
| 61 | + |
| 62 | + |
| 63 | +class FsspecUploadHook(UploadHook): |
| 64 | + """An upload hook using ``fsspec`` to upload to external storage |
| 65 | +
|
| 66 | + This function can be used as the |
| 67 | + :func:`~opentelemetry.util.genai.upload_hook.load_upload_hook` implementation by |
| 68 | + setting :envvar:`OTEL_INSTRUMENTATION_GENAI_UPLOAD_HOOK` to ``fsspec``. |
| 69 | + :envvar:`OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH` must be configured to specify the |
| 70 | + base path for uploads. |
| 71 | +
|
| 72 | + Both the ``fsspec`` and ``opentelemetry-sdk`` packages should be installed, or a no-op |
| 73 | + implementation will be used instead. You can use ``opentelemetry-util-genai[fsspec]`` |
| 74 | + as a requirement to achieve this. |
| 75 | + """ |
| 76 | + |
| 77 | + def __init__( |
| 78 | + self, |
| 79 | + *, |
| 80 | + base_path: str, |
| 81 | + max_size: int = 20, |
| 82 | + ) -> None: |
| 83 | + self._base_path = base_path |
| 84 | + self._max_size = max_size |
| 85 | + |
| 86 | + # Use a ThreadPoolExecutor for its queueing and thread management. The semaphore |
| 87 | + # limits the number of queued tasks. If the queue is full, data will be dropped. |
| 88 | + self._executor = ThreadPoolExecutor(max_workers=max_size) |
| 89 | + self._semaphore = threading.BoundedSemaphore(max_size) |
| 90 | + |
| 91 | + def _submit_all(self, upload_data: UploadData) -> None: |
| 92 | + def done(future: Future[None]) -> None: |
| 93 | + self._semaphore.release() |
| 94 | + |
| 95 | + try: |
| 96 | + future.result() |
| 97 | + except Exception: # pylint: disable=broad-except |
| 98 | + _logger.exception("fsspec uploader failed") |
| 99 | + |
| 100 | + for path, json_encodeable in upload_data.items(): |
| 101 | + # could not acquire, drop data |
| 102 | + if not self._semaphore.acquire(blocking=False): # pylint: disable=consider-using-with |
| 103 | + _logger.warning( |
| 104 | + "fsspec upload queue is full, dropping upload %s", |
| 105 | + path, |
| 106 | + ) |
| 107 | + continue |
| 108 | + |
| 109 | + try: |
| 110 | + fut = self._executor.submit( |
| 111 | + self._do_upload, path, json_encodeable |
| 112 | + ) |
| 113 | + fut.add_done_callback(done) |
| 114 | + except RuntimeError: |
| 115 | + _logger.info( |
| 116 | + "attempting to upload file after FsspecUploadHook.shutdown() was already called" |
| 117 | + ) |
| 118 | + break |
| 119 | + |
| 120 | + def _calculate_ref_path(self) -> CompletionRefs: |
| 121 | + # TODO: experimental with using the trace_id and span_id, or fetching |
| 122 | + # gen_ai.response.id from the active span. |
| 123 | + |
| 124 | + uuid_str = str(uuid4()) |
| 125 | + return CompletionRefs( |
| 126 | + inputs_ref=posixpath.join( |
| 127 | + self._base_path, f"{uuid_str}_inputs.json" |
| 128 | + ), |
| 129 | + outputs_ref=posixpath.join( |
| 130 | + self._base_path, f"{uuid_str}_outputs.json" |
| 131 | + ), |
| 132 | + system_instruction_ref=posixpath.join( |
| 133 | + self._base_path, f"{uuid_str}_system_instruction.json" |
| 134 | + ), |
| 135 | + ) |
| 136 | + |
| 137 | + @staticmethod |
| 138 | + def _do_upload( |
| 139 | + path: str, json_encodeable: Callable[[], JsonEncodeable] |
| 140 | + ) -> None: |
| 141 | + with fsspec_open(path, "w") as file: |
| 142 | + json.dump(json_encodeable(), file, separators=(",", ":")) |
| 143 | + |
| 144 | + def upload( |
| 145 | + self, |
| 146 | + *, |
| 147 | + inputs: list[types.InputMessage], |
| 148 | + outputs: list[types.OutputMessage], |
| 149 | + system_instruction: list[types.MessagePart], |
| 150 | + span: Span | None = None, |
| 151 | + log_record: LogRecord | None = None, |
| 152 | + **kwargs: Any, |
| 153 | + ) -> None: |
| 154 | + completion = Completion( |
| 155 | + inputs=inputs, |
| 156 | + outputs=outputs, |
| 157 | + system_instruction=system_instruction, |
| 158 | + ) |
| 159 | + # generate the paths to upload to |
| 160 | + ref_names = self._calculate_ref_path() |
| 161 | + |
| 162 | + def to_dict( |
| 163 | + dataclass_list: list[types.InputMessage] |
| 164 | + | list[types.OutputMessage] |
| 165 | + | list[types.MessagePart], |
| 166 | + ) -> JsonEncodeable: |
| 167 | + return [asdict(dc) for dc in dataclass_list] |
| 168 | + |
| 169 | + self._submit_all( |
| 170 | + { |
| 171 | + # Use partial to defer as much as possible to the background threads |
| 172 | + ref_names.inputs_ref: partial(to_dict, completion.inputs), |
| 173 | + ref_names.outputs_ref: partial(to_dict, completion.outputs), |
| 174 | + ref_names.system_instruction_ref: partial( |
| 175 | + to_dict, completion.system_instruction |
| 176 | + ), |
| 177 | + }, |
| 178 | + ) |
| 179 | + |
| 180 | + # TODO: stamp the refs on telemetry |
| 181 | + |
| 182 | + def shutdown(self) -> None: |
| 183 | + # TODO: support timeout |
| 184 | + self._executor.shutdown() |
0 commit comments