|
| 1 | +""" |
| 2 | +Copyright (c) 2025 Scale3 Labs |
| 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 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +Unless required by applicable law or agreed to in writing, software |
| 8 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +See the License for the specific language governing permissions and |
| 11 | +limitations under the License. |
| 12 | +""" |
| 13 | + |
| 14 | +import importlib.metadata |
| 15 | +import logging |
| 16 | +from typing import Any, Collection, Optional |
| 17 | + |
| 18 | +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor |
| 19 | +from opentelemetry.trace import TracerProvider, get_tracer |
| 20 | +from wrapt import wrap_function_wrapper |
| 21 | + |
| 22 | +from langtrace_python_sdk.instrumentation.openai_agents.patch import \ |
| 23 | + get_new_response |
| 24 | + |
| 25 | +logging.basicConfig(level=logging.FATAL) |
| 26 | + |
| 27 | + |
| 28 | +class OpenAIAgentsInstrumentation(BaseInstrumentor): # type: ignore |
| 29 | + |
| 30 | + def instrumentation_dependencies(self) -> Collection[str]: |
| 31 | + return ["openai-agents >= 0.0.3", "trace-attributes >= 4.0.5"] |
| 32 | + |
| 33 | + def _instrument(self, **kwargs: Any) -> None: |
| 34 | + tracer_provider: Optional[TracerProvider] = kwargs.get("tracer_provider") |
| 35 | + tracer = get_tracer(__name__, "", tracer_provider) |
| 36 | + version: str = importlib.metadata.version("openai") |
| 37 | + |
| 38 | + # TODO(Karthik): This is adding a lot of noise to the trace. |
| 39 | + # wrap_function_wrapper( |
| 40 | + # "agents.run", |
| 41 | + # "Runner._get_handoffs", |
| 42 | + # get_handoffs(version, tracer), |
| 43 | + # ) |
| 44 | + |
| 45 | + wrap_function_wrapper( |
| 46 | + "agents.run", |
| 47 | + "Runner._get_new_response", |
| 48 | + get_new_response(version, tracer), |
| 49 | + ) |
| 50 | + |
| 51 | + def _uninstrument(self, **kwargs: Any) -> None: |
| 52 | + pass |
0 commit comments