Skip to content

Commit 6fa9dd5

Browse files
committed
Introduced start_trace and end_trace functions for user-managed tracing, allowing concurrent traces.
1 parent 85a2041 commit 6fa9dd5

5 files changed

Lines changed: 424 additions & 242 deletions

File tree

agentops/__init__.py

Lines changed: 62 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@
1212
LLMEvent,
1313
) # type: ignore
1414

15-
from typing import List, Optional, Union
15+
from typing import List, Optional, Union, Dict, Any
1616
from agentops.client import Client
17+
from agentops.sdk.core import TracingCore, TraceContext
1718

19+
from agentops.logging.config import logger
1820

1921
# Client global instance; one per process runtime
2022
_client = Client()
@@ -51,18 +53,14 @@ def init(
5153
app_url: Optional[str] = None,
5254
max_wait_time: Optional[int] = None,
5355
max_queue_size: Optional[int] = None,
54-
tags: Optional[List[str]] = None,
5556
default_tags: Optional[List[str]] = None,
5657
instrument_llm_calls: Optional[bool] = None,
5758
auto_start_session: Optional[bool] = None,
58-
auto_init: Optional[bool] = None,
59-
skip_auto_end_session: Optional[bool] = None,
6059
env_data_opt_out: Optional[bool] = None,
6160
log_level: Optional[Union[str, int]] = None,
62-
fail_safe: Optional[bool] = None,
6361
exporter_endpoint: Optional[str] = None,
6462
**kwargs,
65-
):
63+
) -> None:
6664
"""
6765
Initializes the AgentOps SDK.
6866
@@ -76,45 +74,30 @@ def init(
7674
max_wait_time (int, optional): The maximum time to wait in milliseconds before flushing the queue.
7775
Defaults to 5,000 (5 seconds)
7876
max_queue_size (int, optional): The maximum size of the event queue. Defaults to 512.
79-
tags (List[str], optional): [Deprecated] Use `default_tags` instead.
80-
default_tags (List[str], optional): Default tags for the sessions that can be used for grouping or sorting later (e.g. ["GPT-4"]).
77+
default_tags (List[str], optional): Default tags for the sessions that can be used for grouping or sorting later (e.g. [\"GPT-4\"]).
8178
instrument_llm_calls (bool): Whether to instrument LLM calls and emit LLMEvents.
82-
auto_start_session (bool): Whether to start a session automatically when the client is created.
83-
auto_init (bool): Whether to automatically initialize the client on import. Defaults to True.
84-
skip_auto_end_session (optional, bool): Don't automatically end session based on your framework's decision-making
85-
(i.e. Crew determining when tasks are complete and ending the session)
79+
auto_start_session (bool): Whether to start an initial trace automatically when the client is initialized. Defaults to True via Config.
8680
env_data_opt_out (bool): Whether to opt out of collecting environment data.
8781
log_level (str, int): The log level to use for the client. Defaults to 'CRITICAL'.
88-
fail_safe (bool): Whether to suppress errors and continue execution when possible.
89-
exporter_endpoint (str, optional): Endpoint for the exporter. If none is provided, key will
90-
be read from the AGENTOPS_EXPORTER_ENDPOINT environment variable.
91-
**kwargs: Additional configuration parameters to be passed to the client.
82+
exporter_endpoint (str, optional): Endpoint for the OTLP exporter. Defaults to AgentOps collector.
83+
**kwargs: Additional configuration parameters to be passed to the client's Config object.
9284
"""
9385
global _client
9486

95-
# Merge tags and default_tags if both are provided
96-
merged_tags = None
97-
if tags and default_tags:
98-
merged_tags = list(set(tags + default_tags))
99-
elif tags:
100-
merged_tags = tags
101-
elif default_tags:
102-
merged_tags = default_tags
103-
104-
return _client.init(
87+
# The client.init() method now handles its own configuration loading and defaults.
88+
# We pass through the relevant parameters.
89+
# client.init() returns None.
90+
_client.init(
10591
api_key=api_key,
10692
endpoint=endpoint,
10793
app_url=app_url,
10894
max_wait_time=max_wait_time,
10995
max_queue_size=max_queue_size,
110-
default_tags=merged_tags,
96+
default_tags=default_tags,
11197
instrument_llm_calls=instrument_llm_calls,
11298
auto_start_session=auto_start_session,
113-
auto_init=auto_init,
114-
skip_auto_end_session=skip_auto_end_session,
11599
env_data_opt_out=env_data_opt_out,
116100
log_level=log_level,
117-
fail_safe=fail_safe,
118101
exporter_endpoint=exporter_endpoint,
119102
**kwargs,
120103
)
@@ -165,18 +148,65 @@ def configure(**kwargs):
165148
# Check for invalid parameters
166149
invalid_params = set(kwargs.keys()) - valid_params
167150
if invalid_params:
168-
from .logging.config import logger
169-
170151
logger.warning(f"Invalid configuration parameters: {invalid_params}")
171152

172153
_client.configure(**kwargs)
173154

174155

156+
def start_trace(
157+
trace_name: str = "session", tags: Optional[Union[Dict[str, Any], List[str]]] = None
158+
) -> Optional[TraceContext]:
159+
"""
160+
Starts a new trace (root span) and returns its context.
161+
This allows for multiple concurrent, user-managed traces.
162+
163+
Args:
164+
trace_name: Name for the trace (e.g., "session", "my_custom_task").
165+
tags: Optional tags to attach to the trace span (list of strings or dict).
166+
167+
Returns:
168+
A TraceContext object containing the span and context token, or None if SDK not initialized.
169+
"""
170+
tracing_core = TracingCore.get_instance()
171+
if not tracing_core.initialized:
172+
# Optionally, attempt to initialize the client if not already, or log a more severe warning.
173+
# For now, align with legacy start_session that would try to init.
174+
# However, explicit init is preferred before starting traces.
175+
logger.warning("AgentOps SDK not initialized. Attempting to initialize with defaults before starting trace.")
176+
try:
177+
init() # Attempt to initialize with environment variables / defaults
178+
if not tracing_core.initialized:
179+
logger.error("SDK initialization failed. Cannot start trace.")
180+
return None
181+
except Exception as e:
182+
logger.error(f"SDK auto-initialization failed during start_trace: {e}. Cannot start trace.")
183+
return None
184+
185+
return tracing_core.start_trace(trace_name=trace_name, tags=tags)
186+
187+
188+
def end_trace(trace_context: TraceContext, end_state: str = "Success") -> None:
189+
"""
190+
Ends a trace (its root span) and finalizes it.
191+
192+
Args:
193+
trace_context: The TraceContext object returned by start_trace.
194+
end_state: The final state of the trace (e.g., "Success", "Failure", "Error").
195+
"""
196+
tracing_core = TracingCore.get_instance()
197+
if not tracing_core.initialized:
198+
logger.warning("AgentOps SDK not initialized. Cannot end trace.")
199+
return
200+
tracing_core.end_trace(trace_context=trace_context, end_state=end_state)
201+
202+
175203
__all__ = [
176204
"init",
177205
"configure",
178206
"get_client",
179207
"record",
208+
"start_trace",
209+
"end_trace",
180210
"start_session",
181211
"end_session",
182212
"track_agent",

0 commit comments

Comments
 (0)