Skip to content
Merged
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
15 changes: 7 additions & 8 deletions agentops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from typing import List, Optional, Union, Dict, Any
from agentops.client import Client
from agentops.sdk.core import TracingCore, TraceContext
from agentops.sdk.core import TraceContext, tracer
from agentops.sdk.decorators import trace, session, agent, task, workflow, operation

from agentops.logging.config import logger
Expand Down Expand Up @@ -190,22 +190,21 @@ def start_trace(
Returns:
A TraceContext object containing the span and context token, or None if SDK not initialized.
"""
tracing_core = TracingCore.get_instance()
if not tracing_core.initialized:
if not tracer.initialized:
# Optionally, attempt to initialize the client if not already, or log a more severe warning.
# For now, align with legacy start_session that would try to init.
# However, explicit init is preferred before starting traces.
logger.warning("AgentOps SDK not initialized. Attempting to initialize with defaults before starting trace.")
try:
init() # Attempt to initialize with environment variables / defaults
if not tracing_core.initialized:
if not tracer.initialized:
logger.error("SDK initialization failed. Cannot start trace.")
return None
except Exception as e:
logger.error(f"SDK auto-initialization failed during start_trace: {e}. Cannot start trace.")
return None

return tracing_core.start_trace(trace_name=trace_name, tags=tags)
return tracer.start_trace(trace_name=trace_name, tags=tags)


def end_trace(trace_context: Optional[TraceContext] = None, end_state: str = "Success") -> None:
Expand All @@ -217,11 +216,10 @@ def end_trace(trace_context: Optional[TraceContext] = None, end_state: str = "Su
trace_context: The TraceContext object returned by start_trace. If None, ends all active traces.
end_state: The final state of the trace (e.g., "Success", "Failure", "Error").
"""
tracing_core = TracingCore.get_instance()
if not tracing_core.initialized:
if not tracer.initialized:
logger.warning("AgentOps SDK not initialized. Cannot end trace.")
return
tracing_core.end_trace(trace_context=trace_context, end_state=end_state)
tracer.end_trace(trace_context=trace_context, end_state=end_state)


__all__ = [
Expand All @@ -247,4 +245,5 @@ def end_trace(trace_context: Optional[TraceContext] = None, end_state: str = "Su
"task",
"workflow",
"operation",
"tracer",
]
16 changes: 7 additions & 9 deletions agentops/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from agentops.instrumentation import instrument_all
from agentops.logging import logger
from agentops.logging.config import configure_logging, intercept_opentelemetry_logging
from agentops.sdk.core import TracingCore, TraceContext
from agentops.sdk.core import TraceContext, tracer
from agentops.legacy import Session

# Global variables to hold the client's auto-started trace and its legacy session wrapper
Expand All @@ -25,9 +25,8 @@
logger.debug("Auto-ending client's init trace during shutdown.")
try:
# Use TracingCore to end the trace directly
tracing_core = TracingCore.get_instance()
if tracing_core.initialized and _client_init_trace_context.span.is_recording():
tracing_core.end_trace(_client_init_trace_context, end_state="Shutdown")
if tracer.initialized and _client_init_trace_context.span.is_recording():
tracer.end_trace(_client_init_trace_context, end_state="Shutdown")

Check warning on line 29 in agentops/client/client.py

View check run for this annotation

Codecov / codecov/patch

agentops/client/client.py#L28-L29

Added lines #L28 - L29 were not covered by tests
except Exception as e:
logger.warning(f"Error ending client's init trace during shutdown: {e}")
finally:
Expand Down Expand Up @@ -83,7 +82,7 @@
self._initialized = False
if self._init_trace_context and self._init_trace_context.span.is_recording():
logger.warning("Ending previously auto-started trace due to re-initialization.")
TracingCore.get_instance().end_trace(self._init_trace_context, "Reinitialized")
tracer.end_trace(self._init_trace_context, "Reinitialized")

Check warning on line 85 in agentops/client/client.py

View check run for this annotation

Codecov / codecov/patch

agentops/client/client.py#L85

Added line #L85 was not covered by tests
self._init_trace_context = None
self._legacy_session_for_init_trace = None

Expand Down Expand Up @@ -118,8 +117,7 @@
tracing_config = self.config.dict()
tracing_config["project_id"] = response["project_id"]

tracing_core = TracingCore.get_instance()
tracing_core.initialize_from_config(tracing_config, jwt=response["token"])
tracer.initialize_from_config(tracing_config, jwt=response["token"])

if self.config.instrument_llm_calls:
instrument_all()
Expand All @@ -136,7 +134,7 @@
if self._init_trace_context is None or not self._init_trace_context.span.is_recording():
logger.debug("Auto-starting init trace.")
trace_name = self.config.trace_name or "default"
self._init_trace_context = tracing_core.start_trace(
self._init_trace_context = tracer.start_trace(
trace_name=trace_name,
tags=list(self.config.default_tags) if self.config.default_tags else None,
is_init_trace=True,
Expand Down Expand Up @@ -165,7 +163,7 @@
logger.error("Failed to start the auto-init trace.")
# Even if auto-start fails, core services up to TracingCore might be initialized.
# Set self.initialized to True if TracingCore is up, but return None.
self._initialized = tracing_core.initialized
self._initialized = tracer.initialized

Check warning on line 166 in agentops/client/client.py

View check run for this annotation

Codecov / codecov/patch

agentops/client/client.py#L166

Added line #L166 was not covered by tests
return None # Failed to start trace

self._initialized = True # Successfully initialized and auto-trace started (if configured)
Expand Down
40 changes: 40 additions & 0 deletions agentops/helpers/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,46 @@
from agentops.helpers.version import get_agentops_version


def get_imported_libraries():
"""
Get the top-level imported libraries in the current script.

Returns:
list: List of imported libraries
"""
user_libs = []

Check warning on line 20 in agentops/helpers/system.py

View check run for this annotation

Codecov / codecov/patch

agentops/helpers/system.py#L20

Added line #L20 was not covered by tests

builtin_modules = {

Check warning on line 22 in agentops/helpers/system.py

View check run for this annotation

Codecov / codecov/patch

agentops/helpers/system.py#L22

Added line #L22 was not covered by tests
"builtins",
"sys",
"os",
"_thread",
"abc",
"io",
"re",
"types",
"collections",
"enum",
"math",
"datetime",
"time",
"warnings",
}

try:
main_module = sys.modules.get("__main__")
if main_module and hasattr(main_module, "__dict__"):
for name, obj in main_module.__dict__.items():
if isinstance(obj, type(sys)) and hasattr(obj, "__name__"):
mod_name = obj.__name__.split(".")[0]
if mod_name and not mod_name.startswith("_") and mod_name not in builtin_modules:
user_libs.append(mod_name)
except Exception as e:
logger.debug(f"Error getting imports: {e}")

Check warning on line 48 in agentops/helpers/system.py

View check run for this annotation

Codecov / codecov/patch

agentops/helpers/system.py#L39-L48

Added lines #L39 - L48 were not covered by tests

return user_libs

Check warning on line 50 in agentops/helpers/system.py

View check run for this annotation

Codecov / codecov/patch

agentops/helpers/system.py#L50

Added line #L50 was not covered by tests


def get_sdk_details():
try:
return {
Expand Down
4 changes: 2 additions & 2 deletions agentops/instrumentation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor # type: ignore

from agentops.logging import logger
from agentops.sdk.core import TracingCore
from agentops.sdk.core import tracer


# Module-level state variables
Expand Down Expand Up @@ -265,7 +265,7 @@ def instrument_one(loader: InstrumentorLoader) -> Optional[BaseInstrumentor]:
return None

instrumentor = loader.get_instance()
instrumentor.instrument(tracer_provider=TracingCore.get_instance()._provider)
instrumentor.instrument(tracer_provider=tracer.provider)
logger.debug(f"Instrumented {loader.class_name}")
return instrumentor

Expand Down
18 changes: 9 additions & 9 deletions agentops/integration/callbacks/langchain/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from agentops.helpers.serialization import safe_serialize
from agentops.logging import logger
from agentops.sdk.core import TracingCore
from agentops.sdk.core import tracer
from agentops.semconv import SpanKind, SpanAttributes, LangChainAttributes, LangChainAttributeValues, CoreAttributes
from agentops.integration.callbacks.langchain.utils import get_model_info

Expand Down Expand Up @@ -57,7 +57,7 @@ def _initialize_agentops(self):
"""Initialize AgentOps"""
import agentops

if not TracingCore.get_instance().initialized:
if not tracer.initialized:
init_kwargs = {
"auto_start_session": False,
"instrument_llm_calls": True,
Expand All @@ -69,11 +69,11 @@ def _initialize_agentops(self):
agentops.init(**init_kwargs)
logger.debug("AgentOps initialized from LangChain callback handler")

if not TracingCore.get_instance().initialized:
if not tracer.initialized:
logger.warning("AgentOps not initialized, session span will not be created")
return

tracer = TracingCore.get_instance().get_tracer()
otel_tracer = tracer.get_tracer()

span_name = f"session.{SpanKind.SESSION}"

Expand All @@ -85,7 +85,7 @@ def _initialize_agentops(self):
}

# Create a root session span
self.session_span = tracer.start_span(span_name, attributes=attributes)
self.session_span = otel_tracer.start_span(span_name, attributes=attributes)

# Attach session span to the current context
self.session_token = attach(set_span_in_context(self.session_span))
Expand Down Expand Up @@ -113,11 +113,11 @@ def _create_span(
Returns:
The created span
"""
if not TracingCore.get_instance().initialized:
if not tracer.initialized:
logger.warning("AgentOps not initialized, spans will not be created")
return trace.NonRecordingSpan(SpanContext.INVALID)

tracer = TracingCore.get_instance().get_tracer()
otel_tracer = tracer.get_tracer()

span_name = f"{operation_name}.{span_kind}"

Expand All @@ -137,13 +137,13 @@ def _create_span(
# Create context with parent span
parent_ctx = set_span_in_context(parent_span)
# Start span with parent context
span = tracer.start_span(span_name, context=parent_ctx, attributes=attributes)
span = otel_tracer.start_span(span_name, context=parent_ctx, attributes=attributes)
logger.debug(f"Started span: {span_name} with parent: {parent_run_id}")
else:
# If no parent_run_id or parent not found, use session as parent
parent_ctx = set_span_in_context(self.session_span)
# Start span with session as parent context
span = tracer.start_span(span_name, context=parent_ctx, attributes=attributes)
span = otel_tracer.start_span(span_name, context=parent_ctx, attributes=attributes)
logger.debug(f"Started span: {span_name} with session as parent")

# Store span in active_spans
Expand Down
21 changes: 8 additions & 13 deletions agentops/legacy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from typing import Optional, Any, Dict, List, Union

from agentops.logging import logger
from agentops.sdk.core import TracingCore, TraceContext
from agentops.sdk.core import TraceContext, tracer

_current_session: Optional["Session"] = None
_current_trace_context: Optional[TraceContext] = None
Expand Down Expand Up @@ -68,14 +68,13 @@
Starts a legacy AgentOps session. Calls TracingCore.start_trace internally.
"""
global _current_session, _current_trace_context
tracing_core = TracingCore.get_instance()

if not tracing_core.initialized:
if not tracer.initialized:
from agentops import Client

try:
Client().init(auto_start_session=False)
if not tracing_core.initialized:
if not tracer.initialized:

Check warning on line 77 in agentops/legacy/__init__.py

View check run for this annotation

Codecov / codecov/patch

agentops/legacy/__init__.py#L77

Added line #L77 was not covered by tests
logger.warning("AgentOps client init failed during legacy start_session. Creating dummy session.")
dummy_session = Session(None)
_current_session = dummy_session
Expand All @@ -88,7 +87,7 @@
_current_trace_context = None
return dummy_session

trace_context = tracing_core.start_trace(trace_name="session", tags=tags)
trace_context = tracer.start_trace(trace_name="session", tags=tags)
if trace_context is None:
logger.error("Failed to start trace via TracingCore. Returning dummy session.")
dummy_session = Session(None)
Expand Down Expand Up @@ -129,9 +128,8 @@
Supports multiple calling patterns for backward compatibility.
"""
global _current_session, _current_trace_context
tracing_core = TracingCore.get_instance()

if not tracing_core.initialized:
if not tracer.initialized:
logger.debug("Ignoring end_session: TracingCore not initialized.")
return

Expand Down Expand Up @@ -164,7 +162,7 @@
if target_trace_context.span and extra_attributes:
_set_span_attributes(target_trace_context.span, extra_attributes)

tracing_core.end_trace(target_trace_context, end_state=end_state_from_args)
tracer.end_trace(target_trace_context, end_state=end_state_from_args)

if target_trace_context is _current_trace_context:
_current_session = None
Expand All @@ -190,15 +188,12 @@

def end_all_sessions() -> None:
"""@deprecated Ends all active sessions/traces."""
from agentops.sdk.core import TracingCore

tracing_core = TracingCore.get_instance()
if not tracing_core.initialized:
if not tracer.initialized:

Check warning on line 191 in agentops/legacy/__init__.py

View check run for this annotation

Codecov / codecov/patch

agentops/legacy/__init__.py#L191

Added line #L191 was not covered by tests
logger.debug("Ignoring end_all_sessions: TracingCore not initialized.")
return

# Use the new end_trace functionality to end all active traces
tracing_core.end_trace(trace_context=None, end_state="Success")
tracer.end_trace(trace_context=None, end_state="Success")

Check warning on line 196 in agentops/legacy/__init__.py

View check run for this annotation

Codecov / codecov/patch

agentops/legacy/__init__.py#L196

Added line #L196 was not covered by tests

# Clear legacy global state
global _current_session, _current_trace_context
Expand Down
Loading
Loading