Skip to content

Commit 397760c

Browse files
authored
Merge branch 'main' into add-concurrency-instrumentaion
2 parents 0f09692 + 51d8234 commit 397760c

File tree

18 files changed

+504
-402
lines changed

18 files changed

+504
-402
lines changed

agentops/__init__.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
from typing import List, Optional, Union, Dict, Any
1616
from agentops.client import Client
17-
from agentops.sdk.core import TracingCore, TraceContext
17+
from agentops.sdk.core import TraceContext, tracer
1818
from agentops.sdk.decorators import trace, session, agent, task, workflow, operation
1919

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

208-
return tracing_core.start_trace(trace_name=trace_name, tags=tags)
207+
return tracer.start_trace(trace_name=trace_name, tags=tags)
209208

210209

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

226224

227225
__all__ = [
@@ -247,4 +245,5 @@ def end_trace(trace_context: Optional[TraceContext] = None, end_state: str = "Su
247245
"task",
248246
"workflow",
249247
"operation",
248+
"tracer",
250249
]

agentops/client/client.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from agentops.instrumentation import instrument_all
88
from agentops.logging import logger
99
from agentops.logging.config import configure_logging, intercept_opentelemetry_logging
10-
from agentops.sdk.core import TracingCore, TraceContext
10+
from agentops.sdk.core import TraceContext, tracer
1111
from agentops.legacy import Session
1212

1313
# Global variables to hold the client's auto-started trace and its legacy session wrapper
@@ -25,9 +25,8 @@ def _end_init_trace_atexit():
2525
logger.debug("Auto-ending client's init trace during shutdown.")
2626
try:
2727
# Use TracingCore to end the trace directly
28-
tracing_core = TracingCore.get_instance()
29-
if tracing_core.initialized and _client_init_trace_context.span.is_recording():
30-
tracing_core.end_trace(_client_init_trace_context, end_state="Shutdown")
28+
if tracer.initialized and _client_init_trace_context.span.is_recording():
29+
tracer.end_trace(_client_init_trace_context, end_state="Shutdown")
3130
except Exception as e:
3231
logger.warning(f"Error ending client's init trace during shutdown: {e}")
3332
finally:
@@ -83,7 +82,7 @@ def init(self, **kwargs: Any) -> None: # Return type updated to None
8382
self._initialized = False
8483
if self._init_trace_context and self._init_trace_context.span.is_recording():
8584
logger.warning("Ending previously auto-started trace due to re-initialization.")
86-
TracingCore.get_instance().end_trace(self._init_trace_context, "Reinitialized")
85+
tracer.end_trace(self._init_trace_context, "Reinitialized")
8786
self._init_trace_context = None
8887
self._legacy_session_for_init_trace = None
8988

@@ -118,8 +117,7 @@ def init(self, **kwargs: Any) -> None: # Return type updated to None
118117
tracing_config = self.config.dict()
119118
tracing_config["project_id"] = response["project_id"]
120119

121-
tracing_core = TracingCore.get_instance()
122-
tracing_core.initialize_from_config(tracing_config, jwt=response["token"])
120+
tracer.initialize_from_config(tracing_config, jwt=response["token"])
123121

124122
if self.config.instrument_llm_calls:
125123
instrument_all()
@@ -136,7 +134,7 @@ def init(self, **kwargs: Any) -> None: # Return type updated to None
136134
if self._init_trace_context is None or not self._init_trace_context.span.is_recording():
137135
logger.debug("Auto-starting init trace.")
138136
trace_name = self.config.trace_name or "default"
139-
self._init_trace_context = tracing_core.start_trace(
137+
self._init_trace_context = tracer.start_trace(
140138
trace_name=trace_name,
141139
tags=list(self.config.default_tags) if self.config.default_tags else None,
142140
is_init_trace=True,
@@ -165,7 +163,7 @@ def init(self, **kwargs: Any) -> None: # Return type updated to None
165163
logger.error("Failed to start the auto-init trace.")
166164
# Even if auto-start fails, core services up to TracingCore might be initialized.
167165
# Set self.initialized to True if TracingCore is up, but return None.
168-
self._initialized = tracing_core.initialized
166+
self._initialized = tracer.initialized
169167
return None # Failed to start trace
170168

171169
self._initialized = True # Successfully initialized and auto-trace started (if configured)

agentops/helpers/system.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,46 @@
1010
from agentops.helpers.version import get_agentops_version
1111

1212

13+
def get_imported_libraries():
14+
"""
15+
Get the top-level imported libraries in the current script.
16+
17+
Returns:
18+
list: List of imported libraries
19+
"""
20+
user_libs = []
21+
22+
builtin_modules = {
23+
"builtins",
24+
"sys",
25+
"os",
26+
"_thread",
27+
"abc",
28+
"io",
29+
"re",
30+
"types",
31+
"collections",
32+
"enum",
33+
"math",
34+
"datetime",
35+
"time",
36+
"warnings",
37+
}
38+
39+
try:
40+
main_module = sys.modules.get("__main__")
41+
if main_module and hasattr(main_module, "__dict__"):
42+
for name, obj in main_module.__dict__.items():
43+
if isinstance(obj, type(sys)) and hasattr(obj, "__name__"):
44+
mod_name = obj.__name__.split(".")[0]
45+
if mod_name and not mod_name.startswith("_") and mod_name not in builtin_modules:
46+
user_libs.append(mod_name)
47+
except Exception as e:
48+
logger.debug(f"Error getting imports: {e}")
49+
50+
return user_libs
51+
52+
1353
def get_sdk_details():
1454
try:
1555
return {

agentops/instrumentation/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor # type: ignore
3030

3131
from agentops.logging import logger
32-
from agentops.sdk.core import TracingCore
32+
from agentops.sdk.core import tracer
3333

3434

3535
# Define the structure for instrumentor configurations
@@ -291,7 +291,7 @@ def instrument_one(loader: InstrumentorLoader) -> Optional[BaseInstrumentor]:
291291
return None
292292

293293
instrumentor = loader.get_instance()
294-
instrumentor.instrument(tracer_provider=TracingCore.get_instance()._provider)
294+
instrumentor.instrument(tracer_provider=tracer.provider)
295295
logger.debug(f"Instrumented {loader.class_name}")
296296
return instrumentor
297297

agentops/integration/callbacks/langchain/callback.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
from agentops.helpers.serialization import safe_serialize
1414
from agentops.logging import logger
15-
from agentops.sdk.core import TracingCore
15+
from agentops.sdk.core import tracer
1616
from agentops.semconv import SpanKind, SpanAttributes, LangChainAttributes, LangChainAttributeValues, CoreAttributes
1717
from agentops.integration.callbacks.langchain.utils import get_model_info
1818

@@ -57,7 +57,7 @@ def _initialize_agentops(self):
5757
"""Initialize AgentOps"""
5858
import agentops
5959

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

72-
if not TracingCore.get_instance().initialized:
72+
if not tracer.initialized:
7373
logger.warning("AgentOps not initialized, session span will not be created")
7474
return
7575

76-
tracer = TracingCore.get_instance().get_tracer()
76+
otel_tracer = tracer.get_tracer()
7777

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

@@ -85,7 +85,7 @@ def _initialize_agentops(self):
8585
}
8686

8787
# Create a root session span
88-
self.session_span = tracer.start_span(span_name, attributes=attributes)
88+
self.session_span = otel_tracer.start_span(span_name, attributes=attributes)
8989

9090
# Attach session span to the current context
9191
self.session_token = attach(set_span_in_context(self.session_span))
@@ -113,11 +113,11 @@ def _create_span(
113113
Returns:
114114
The created span
115115
"""
116-
if not TracingCore.get_instance().initialized:
116+
if not tracer.initialized:
117117
logger.warning("AgentOps not initialized, spans will not be created")
118118
return trace.NonRecordingSpan(SpanContext.INVALID)
119119

120-
tracer = TracingCore.get_instance().get_tracer()
120+
otel_tracer = tracer.get_tracer()
121121

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

@@ -137,13 +137,13 @@ def _create_span(
137137
# Create context with parent span
138138
parent_ctx = set_span_in_context(parent_span)
139139
# Start span with parent context
140-
span = tracer.start_span(span_name, context=parent_ctx, attributes=attributes)
140+
span = otel_tracer.start_span(span_name, context=parent_ctx, attributes=attributes)
141141
logger.debug(f"Started span: {span_name} with parent: {parent_run_id}")
142142
else:
143143
# If no parent_run_id or parent not found, use session as parent
144144
parent_ctx = set_span_in_context(self.session_span)
145145
# Start span with session as parent context
146-
span = tracer.start_span(span_name, context=parent_ctx, attributes=attributes)
146+
span = otel_tracer.start_span(span_name, context=parent_ctx, attributes=attributes)
147147
logger.debug(f"Started span: {span_name} with session as parent")
148148

149149
# Store span in active_spans

agentops/legacy/__init__.py

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from typing import Optional, Any, Dict, List, Union
1313

1414
from agentops.logging import logger
15-
from agentops.sdk.core import TracingCore, TraceContext
15+
from agentops.sdk.core import TraceContext, tracer
1616

1717
_current_session: Optional["Session"] = None
1818
_current_trace_context: Optional[TraceContext] = None
@@ -68,14 +68,13 @@ def start_session(
6868
Starts a legacy AgentOps session. Calls TracingCore.start_trace internally.
6969
"""
7070
global _current_session, _current_trace_context
71-
tracing_core = TracingCore.get_instance()
7271

73-
if not tracing_core.initialized:
72+
if not tracer.initialized:
7473
from agentops import Client
7574

7675
try:
7776
Client().init(auto_start_session=False)
78-
if not tracing_core.initialized:
77+
if not tracer.initialized:
7978
logger.warning("AgentOps client init failed during legacy start_session. Creating dummy session.")
8079
dummy_session = Session(None)
8180
_current_session = dummy_session
@@ -88,7 +87,7 @@ def start_session(
8887
_current_trace_context = None
8988
return dummy_session
9089

91-
trace_context = tracing_core.start_trace(trace_name="session", tags=tags)
90+
trace_context = tracer.start_trace(trace_name="session", tags=tags)
9291
if trace_context is None:
9392
logger.error("Failed to start trace via TracingCore. Returning dummy session.")
9493
dummy_session = Session(None)
@@ -129,9 +128,8 @@ def end_session(session_or_status: Any = None, **kwargs: Any) -> None:
129128
Supports multiple calling patterns for backward compatibility.
130129
"""
131130
global _current_session, _current_trace_context
132-
tracing_core = TracingCore.get_instance()
133131

134-
if not tracing_core.initialized:
132+
if not tracer.initialized:
135133
logger.debug("Ignoring end_session: TracingCore not initialized.")
136134
return
137135

@@ -164,7 +162,7 @@ def end_session(session_or_status: Any = None, **kwargs: Any) -> None:
164162
if target_trace_context.span and extra_attributes:
165163
_set_span_attributes(target_trace_context.span, extra_attributes)
166164

167-
tracing_core.end_trace(target_trace_context, end_state=end_state_from_args)
165+
tracer.end_trace(target_trace_context, end_state=end_state_from_args)
168166

169167
if target_trace_context is _current_trace_context:
170168
_current_session = None
@@ -190,15 +188,12 @@ def end_session(session_or_status: Any = None, **kwargs: Any) -> None:
190188

191189
def end_all_sessions() -> None:
192190
"""@deprecated Ends all active sessions/traces."""
193-
from agentops.sdk.core import TracingCore
194-
195-
tracing_core = TracingCore.get_instance()
196-
if not tracing_core.initialized:
191+
if not tracer.initialized:
197192
logger.debug("Ignoring end_all_sessions: TracingCore not initialized.")
198193
return
199194

200195
# Use the new end_trace functionality to end all active traces
201-
tracing_core.end_trace(trace_context=None, end_state="Success")
196+
tracer.end_trace(trace_context=None, end_state="Success")
202197

203198
# Clear legacy global state
204199
global _current_session, _current_trace_context

0 commit comments

Comments
 (0)