Skip to content
Closed
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
45 changes: 5 additions & 40 deletions agentops/instrumentation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,15 +144,9 @@
package_name_key in UTILITY_INSTRUMENTORS
and UTILITY_INSTRUMENTORS[package_name_key].get("package_name") == "python"
):
logger.debug(
f"_is_installed_package: Module '{package_name_key}' is a Python standard library module. Considering it an installed package."
)
return True

if not hasattr(module_obj, "__file__") or not module_obj.__file__:
logger.debug(
f"_is_installed_package: Module '{package_name_key}' has no __file__, assuming it might be an SDK namespace package. Returning True."
)
return True

module_path = os.path.normcase(os.path.realpath(os.path.abspath(module_obj.__file__)))
Expand All @@ -171,13 +165,9 @@

for sp_dir in normalized_site_packages_dirs:
if module_path.startswith(sp_dir):
logger.debug(
f"_is_installed_package: Module '{package_name_key}' is a library, instrumenting '{package_name_key}'."
)
return True

# Priority 2: If not in site-packages, it's highly likely a local module or not an SDK we target.
logger.debug(f"_is_installed_package: Module '{package_name_key}' is a local module, skipping instrumentation.")
return False


Expand Down Expand Up @@ -232,9 +222,7 @@
new_active_instrumentors.append(instrumentor)

if uninstrumented_any or not new_active_instrumentors and _active_instrumentors:
logger.debug(
f"_uninstrument_providers: Processed. Previous active: {len(_active_instrumentors)}, New active after filtering providers: {len(new_active_instrumentors)}"
)
pass
_active_instrumentors = new_active_instrumentors


Expand All @@ -247,22 +235,17 @@

# If already instrumented by AgentOps (using our refined check), skip.
if _is_package_instrumented(package_name):
logger.debug(f"_should_instrument_package: '{package_name}' already instrumented by AgentOps. Skipping.")
return False

# Utility instrumentors should always be instrumented regardless of agentic library state
if package_name in UTILITY_INSTRUMENTORS:
logger.debug(f"_should_instrument_package: '{package_name}' is a utility instrumentor. Always allowing.")
return True

# Only apply agentic/provider logic if it's NOT a utility instrumentor
is_target_agentic = package_name in AGENTIC_LIBRARIES
is_target_provider = package_name in PROVIDERS

if not is_target_agentic and not is_target_provider:
logger.debug(
f"_should_instrument_package: '{package_name}' is not a targeted provider or agentic library. Skipping."
)
return False

if _has_agentic_library:
Expand All @@ -286,14 +269,8 @@
_uninstrument_providers()
return True
if is_target_provider:
logger.debug(
f"_should_instrument_package: '{package_name}' is a provider, no agentic library active. Allowing."
)
return True

logger.debug(
f"_should_instrument_package: Defaulting to False for '{package_name}' (state: _has_agentic_library={_has_agentic_library})"
)
return False


Expand All @@ -310,9 +287,6 @@
and package_name not in AGENTIC_LIBRARIES
and package_name not in UTILITY_INSTRUMENTORS
):
logger.debug(
f"_perform_instrumentation: Package '{package_name}' not found in PROVIDERS, AGENTIC_LIBRARIES, or UTILITY_INSTRUMENTORS. Skipping."
)
return

config = PROVIDERS.get(package_name) or AGENTIC_LIBRARIES.get(package_name) or UTILITY_INSTRUMENTORS[package_name]
Expand Down Expand Up @@ -342,9 +316,7 @@
and existing_inst._agentops_instrumented_package_key == package_name
):
is_newly_added = False
logger.debug(
f"_perform_instrumentation: Instrumentor for '{package_name}' already in _active_instrumentors. Not adding again."
)

break
if is_newly_added:
_active_instrumentors.append(instrumentor_instance)
Expand All @@ -356,9 +328,7 @@
# _uninstrument_providers() was already called in _should_instrument_package for the first agentic library.
_has_agentic_library = True
else:
logger.debug(
f"_perform_instrumentation: instrument_one for '{package_name}' returned None. Not added to active instrumentors."
)
pass

Check warning on line 331 in agentops/instrumentation/__init__.py

View check run for this annotation

Codecov / codecov/patch

agentops/instrumentation/__init__.py#L331

Added line #L331 was not covered by tests


def _import_monitor(name: str, globals_dict=None, locals_dict=None, fromlist=(), level=0):
Expand Down Expand Up @@ -419,9 +389,7 @@
)
continue
else:
logger.debug(
f"_import_monitor: No module object found in sys.modules for '{package_to_check}', proceeding with SDK instrumentation attempt."
)
pass

Check warning on line 392 in agentops/instrumentation/__init__.py

View check run for this annotation

Codecov / codecov/patch

agentops/instrumentation/__init__.py#L392

Added line #L392 was not covered by tests

_instrumenting_packages.add(package_to_check)
try:
Expand Down Expand Up @@ -552,9 +520,7 @@
if not is_sdk:
continue
else:
logger.debug(
f"instrument_all: No module object found for '{package_to_check}' in sys.modules during startup scan. Proceeding cautiously."
)
pass

Check warning on line 523 in agentops/instrumentation/__init__.py

View check run for this annotation

Codecov / codecov/patch

agentops/instrumentation/__init__.py#L523

Added line #L523 was not covered by tests

_instrumenting_packages.add(package_to_check)
try:
Expand All @@ -571,7 +537,6 @@
builtins.__import__ = _original_builtins_import
for instrumentor in _active_instrumentors:
instrumentor.uninstrument()
logger.debug(f"Uninstrumented {instrumentor.__class__.__name__}")
_active_instrumentors = []
_has_agentic_library = False

Expand Down
8 changes: 3 additions & 5 deletions agentops/instrumentation/agentic/ag2/instrumentor.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,8 @@ def _custom_wrap(self, **kwargs):
for module, method, wrapper_factory in methods_to_wrap:
try:
wrap_function_wrapper(module, method, wrapper_factory(self._tracer))
logger.debug(f"Successfully wrapped {method}")
except (AttributeError, ModuleNotFoundError) as e:
logger.debug(f"Failed to wrap {method}: {e}")
logger.warning(f"Failed to wrap {method}: {e}")

def _custom_unwrap(self, **kwargs):
"""Remove instrumentation from AG2."""
Expand All @@ -98,9 +97,8 @@ def _custom_unwrap(self, **kwargs):
try:
for module, method in methods_to_unwrap:
otel_unwrap(module, method)
logger.debug("Successfully uninstrumented AG2")
except Exception as e:
logger.debug(f"Failed to unwrap AG2 methods: {e}")
logger.warning(f"Failed to unwrap AG2 methods: {e}")

def _set_llm_config_attributes(self, span, llm_config):
if not isinstance(llm_config, dict):
Expand Down Expand Up @@ -411,7 +409,7 @@ def _extract_chat_history(self, span, initiator, recipient):
if "model" in meta:
span.set_attribute(SpanAttributes.LLM_RESPONSE_MODEL, meta["model"])
except Exception as e:
logger.debug(f"Could not extract chat history: {e}")
logger.warning(f"Could not extract chat history: {e}")

def _set_message_attributes(self, span, message, index, prefix):
"""Set message attributes on span."""
Expand Down
5 changes: 2 additions & 3 deletions agentops/instrumentation/agentic/agno/instrumentor.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,6 @@ def _custom_wrap(self, **kwargs):
def _perform_wrapping(self):
"""Actually perform the wrapping - called after imports are complete."""
if not self._tracer:
logger.debug("No tracer available for Agno wrapping")
return

from agentops.instrumentation.common.wrappers import wrap_function_wrapper, WrapConfig, wrap
Expand Down Expand Up @@ -989,7 +988,7 @@ def _perform_wrapping(self):
wrap(wrap_config, self._tracer)
wrapped_count += 1
except Exception as e:
logger.debug(f"Failed to wrap {wrap_config}: {e}")
logger.warning(f"Failed to wrap {wrap_config}: {e}")

# Now wrap the streaming methods that need custom wrappers
streaming_methods = [
Expand Down Expand Up @@ -1017,7 +1016,7 @@ def _perform_wrapping(self):
wrap_function_wrapper(package, method, wrapper)
wrapped_count += 1
except Exception as e:
logger.debug(f"Failed to wrap {package}.{method}: {e}")
logger.warning(f"Failed to wrap {package}.{method}: {e}")

if wrapped_count > 0:
logger.info(f"Agno instrumentation: Successfully wrapped {wrapped_count} methods")
Expand Down
12 changes: 5 additions & 7 deletions agentops/instrumentation/agentic/google_adk/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ def _extract_llm_attributes(llm_request_dict: dict, llm_response: Any) -> dict:
attributes[SpanAttributes.LLM_RESPONSE_ID] = response_dict["id"]

except Exception as e:
logger.debug(f"Failed to extract response attributes: {e}")
logger.warning(f"Failed to extract response attributes: {e}")

return attributes

Expand Down Expand Up @@ -647,7 +647,7 @@ def _patch(module_name: str, object_name: str, method_name: str, wrapper_functio
obj = getattr(module, object_name)
wrapt.wrap_function_wrapper(obj, method_name, wrapper_function(agentops_tracer))
_wrapped_methods.append((obj, method_name))
logger.debug(f"Successfully wrapped {module_name}.{object_name}.{method_name}")

except Exception as e:
logger.warning(f"Could not wrap {module_name}.{object_name}.{method_name}: {e}")

Expand All @@ -658,14 +658,13 @@ def _patch_module_function(module_name: str, function_name: str, wrapper_functio
module = __import__(module_name, fromlist=[function_name])
wrapt.wrap_function_wrapper(module, function_name, wrapper_function(agentops_tracer))
_wrapped_methods.append((module, function_name))
logger.debug(f"Successfully wrapped {module_name}.{function_name}")

except Exception as e:
logger.warning(f"Could not wrap {module_name}.{function_name}: {e}")


def patch_adk(agentops_tracer):
"""Apply all patches to Google ADK modules."""
logger.debug("Applying Google ADK patches for AgentOps instrumentation")

# First, disable ADK's own tracer by replacing it with our NoOpTracer
noop_tracer = NoOpTracer()
Expand Down Expand Up @@ -694,7 +693,7 @@ def patch_adk(agentops_tracer):
module = sys.modules[module_name]
if hasattr(module, "tracer"):
module.tracer = noop_tracer
logger.debug(f"Replaced tracer in {module_name}")

except Exception as e:
logger.warning(f"Failed to replace tracer in {module_name}: {e}")

Expand Down Expand Up @@ -739,7 +738,6 @@ def patch_adk(agentops_tracer):

def unpatch_adk():
"""Remove all patches from Google ADK modules."""
logger.debug("Removing Google ADK patches")

# Restore ADK's tracer
try:
Expand All @@ -757,7 +755,7 @@ def unpatch_adk():
if hasattr(getattr(obj, method_name), "__wrapped__"):
original = getattr(obj, method_name).__wrapped__
setattr(obj, method_name, original)
logger.debug(f"Successfully unwrapped {obj}.{method_name}")

except Exception as e:
logger.warning(f"Failed to unwrap {obj}.{method_name}: {e}")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,6 @@ def get_span_attributes(span_data: Any) -> AttributeMap:
elif span_type == "SpeechGroupSpanData":
attributes = get_speech_group_span_attributes(span_data)
else:
logger.debug(f"[agentops.instrumentation.openai_agents.attributes] Unknown span type: {span_type}")
attributes = {}

return attributes
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

from agentops.instrumentation.common.attributes import AttributeMap

from agentops.logging import logger
from agentops.helpers.serialization import model_to_dict
from agentops.semconv import (
SpanAttributes,
Expand Down Expand Up @@ -88,7 +87,6 @@ def get_raw_response_attributes(response: Dict[str, Any]) -> Dict[str, Any]:
usage_attrs: AttributeMap = {}
process_token_usage(raw_response["usage"], usage_attrs)
result.update(usage_attrs)
logger.debug(f"Extracted token usage from raw_responses[{i}]: {usage_attrs}")

# Extract output content
if "output" in raw_response and isinstance(raw_response["output"], list):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
return json.loads(content)
except (json.JSONDecodeError, TypeError, ValueError):
# If parsing fails, log a debug message and return None
logger.debug(f"Failed to parse JSON content: {content[:100]}...")
logger.warning(f"Failed to parse JSON content: {content[:100]}...")

Check warning on line 32 in agentops/instrumentation/agentic/openai_agents/attributes/tokens.py

View check run for this annotation

Codecov / codecov/patch

agentops/instrumentation/agentic/openai_agents/attributes/tokens.py#L32

Added line #L32 was not covered by tests
return None


Expand Down Expand Up @@ -202,7 +202,7 @@
# Process this usage data recursively
return process_token_usage(parsed_text["usage"], attributes)
except Exception as e:
logger.debug(f"Error during deep token extraction: {e}")
logger.warning(f"Error during deep token extraction: {e}")

Check warning on line 205 in agentops/instrumentation/agentic/openai_agents/attributes/tokens.py

View check run for this annotation

Codecov / codecov/patch

agentops/instrumentation/agentic/openai_agents/attributes/tokens.py#L205

Added line #L205 was not covered by tests

return result

Expand Down
5 changes: 2 additions & 3 deletions agentops/instrumentation/agentic/openai_agents/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,9 @@
if hasattr(ctx, "trace_id") and ctx.trace_id:
# Convert trace_id to 32-character hex string as shown in the API
otel_trace_id = f"{ctx.trace_id:032x}" if isinstance(ctx.trace_id, int) else str(ctx.trace_id)
logger.debug(f"[SPAN] Export | Type: {span_type} | TRACE ID: {otel_trace_id}")

return otel_trace_id

logger.debug(f"[SPAN] Export | Type: {span_type} | NO TRACE ID AVAILABLE")
return None


Expand Down Expand Up @@ -137,7 +136,7 @@
trace_id = getattr(trace, "trace_id", "unknown")

if not hasattr(trace, "trace_id"):
logger.debug("Cannot export trace: missing trace_id")
logger.warning("Cannot export trace: missing trace_id")

Check warning on line 139 in agentops/instrumentation/agentic/openai_agents/exporter.py

View check run for this annotation

Codecov / codecov/patch

agentops/instrumentation/agentic/openai_agents/exporter.py#L139

Added line #L139 was not covered by tests
return

# Determine if this is a trace end event using status field
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,10 @@ def instrumentation_dependencies(self) -> Collection[str]:
def _instrument(self, **kwargs):
"""Instrument the OpenAI Agents SDK."""
if self._is_instrumented_instance_flag:
logger.debug("OpenAI Agents SDK already instrumented. Skipping.")
return

tracer_provider = kwargs.get("tracer_provider")
if self._tracer is None:
logger.debug("OpenAI Agents SDK tracer is None, creating new tracer.")
self._tracer = trace.get_tracer("agentops.instrumentation.openai_agents", LIBRARY_VERSION)

try:
Expand All @@ -82,7 +80,6 @@ def _instrument(self, **kwargs):
def _uninstrument(self, **kwargs):
"""Remove instrumentation from OpenAI Agents SDK."""
if not self._is_instrumented_instance_flag:
logger.debug("OpenAI Agents SDK not currently instrumented. Skipping uninstrument.")
return
try:
# Clean up any active spans in the exporter
Expand Down
5 changes: 0 additions & 5 deletions agentops/instrumentation/agentic/openai_agents/processor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from typing import Any
from opentelemetry.trace import StatusCode
from agentops.logging import logger


class OpenAIAgentsProcessor:
Expand All @@ -19,7 +18,6 @@ def __init__(self, exporter=None):
def on_trace_start(self, sdk_trace: Any) -> None:
"""Called when a trace starts in the Agents SDK."""

logger.debug(f"[agentops.instrumentation.openai_agents] Trace started: {sdk_trace}")
self.exporter.export_trace(sdk_trace)

def on_trace_end(self, sdk_trace: Any) -> None:
Expand All @@ -29,13 +27,11 @@ def on_trace_end(self, sdk_trace: Any) -> None:
# This is used by the exporter to determine whether to create or update a trace
sdk_trace.status = StatusCode.OK.name

logger.debug(f"[agentops.instrumentation.openai_agents] Trace ended: {sdk_trace}")
self.exporter.export_trace(sdk_trace)

def on_span_start(self, span: Any) -> None:
"""Called when a span starts in the Agents SDK."""

logger.debug(f"[agentops.instrumentation.openai_agents] Span started: {span}")
self.exporter.export_span(span)

def on_span_end(self, span: Any) -> None:
Expand All @@ -45,7 +41,6 @@ def on_span_end(self, span: Any) -> None:
# This is used by the exporter to determine whether to create or update a span
span.status = StatusCode.OK.name

logger.debug(f"[agentops.instrumentation.openai_agents] Span ended: {span}")
self.exporter.export_span(span)

def shutdown(self) -> None:
Expand Down
Loading
Loading