Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
6fa9dd5
Introduced `start_trace` and `end_trace` functions for user-managed t…
Dwij1704 May 22, 2025
efacc7c
Enhance tracing functionality by introducing new decorators and impro…
Dwij1704 May 22, 2025
a369761
cleanup
Dwij1704 May 22, 2025
206dd6f
Enhance `init` function in AgentOps SDK by adding new parameters: `ta…
Dwij1704 May 22, 2025
79c7637
Merge branch 'main' into better-root-span-management
dot-agi May 25, 2025
6f284c7
Refactor legacy session handling by replacing `LegacySession` with `S…
Dwij1704 May 27, 2025
16893b6
Enhance unit tests for URL logging in TracingCore and InternalSpanPro…
Dwij1704 May 27, 2025
e8de762
Refactor CrewAI workflow instrumentation to enhance span management a…
Dwij1704 May 27, 2025
cd17b13
Refactor force_flush method in TracingCore to remove timeout paramete…
Dwij1704 May 27, 2025
1faf0e3
Refactor Client initialization logic to clarify re-initialization con…
Dwij1704 May 27, 2025
a701e4b
Refactor Client initialization to support backward compatibility with…
Dwij1704 May 27, 2025
67b2f80
Improve authentication error handling in Client and V3Client. Added e…
Dwij1704 May 27, 2025
fa82e41
Refactor integration tests for session concurrency to improve isolati…
Dwij1704 May 27, 2025
8c8e974
Enhance trace management by updating end_trace function to allow endi…
Dwij1704 May 27, 2025
c49191c
Merge branch 'main' into better-root-span-management
Dwij1704 May 27, 2025
fa6eca3
Enhance trace ID handling in TracingCore by adding exception handling…
Dwij1704 May 27, 2025
310aeed
Merge branch 'better-root-span-management' of github.com:AgentOps-AI/…
Dwij1704 May 27, 2025
27f1701
revert crewai
Dwij1704 May 27, 2025
abd53c3
Merge branch 'main' into better-root-span-management
Dwij1704 May 27, 2025
ce4ab1a
Merge branch 'main' into better-root-span-management
Dwij1704 May 27, 2025
51bbf7f
Enhance tracing functionality by adding `trace_name` parameter to con…
Dwij1704 May 27, 2025
89767bb
Merge branch 'better-root-span-management' of github.com:AgentOps-AI/…
Dwij1704 May 27, 2025
4fe79d9
Remove unused span variables in entity decorator function to streamli…
Dwij1704 May 27, 2025
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
68 changes: 64 additions & 4 deletions agentops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@
LLMEvent,
) # type: ignore

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

from agentops.logging.config import logger

# Client global instance; one per process runtime
_client = Client()
Expand Down Expand Up @@ -53,6 +56,7 @@
max_queue_size: Optional[int] = None,
tags: Optional[List[str]] = None,
default_tags: Optional[List[str]] = None,
trace_name: Optional[str] = None,
instrument_llm_calls: Optional[bool] = None,
auto_start_session: Optional[bool] = None,
auto_init: Optional[bool] = None,
Expand All @@ -78,6 +82,7 @@
max_queue_size (int, optional): The maximum size of the event queue. Defaults to 512.
tags (List[str], optional): [Deprecated] Use `default_tags` instead.
default_tags (List[str], optional): Default tags for the sessions that can be used for grouping or sorting later (e.g. ["GPT-4"]).
trace_name (str, optional): Name for the default trace/session. If none is provided, defaults to "default".
instrument_llm_calls (bool): Whether to instrument LLM calls and emit LLMEvents.
auto_start_session (bool): Whether to start a session automatically when the client is created.
auto_init (bool): Whether to automatically initialize the client on import. Defaults to True.
Expand Down Expand Up @@ -108,6 +113,7 @@
max_wait_time=max_wait_time,
max_queue_size=max_queue_size,
default_tags=merged_tags,
trace_name=trace_name,
instrument_llm_calls=instrument_llm_calls,
auto_start_session=auto_start_session,
auto_init=auto_init,
Expand Down Expand Up @@ -165,26 +171,80 @@
# Check for invalid parameters
invalid_params = set(kwargs.keys()) - valid_params
if invalid_params:
from .logging.config import logger

logger.warning(f"Invalid configuration parameters: {invalid_params}")

_client.configure(**kwargs)


def start_trace(
trace_name: str = "session", tags: Optional[Union[Dict[str, Any], List[str]]] = None
) -> Optional[TraceContext]:
"""
Starts a new trace (root span) and returns its context.
This allows for multiple concurrent, user-managed traces.

Args:
trace_name: Name for the trace (e.g., "session", "my_custom_task").
tags: Optional tags to attach to the trace span (list of strings or dict).

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:
# 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:
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

Check warning on line 206 in agentops/__init__.py

View check run for this annotation

Codecov / codecov/patch

agentops/__init__.py#L202-L206

Added lines #L202 - L206 were not covered by tests

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


def end_trace(trace_context: Optional[TraceContext] = None, end_state: str = "Success") -> None:
"""
Ends a trace (its root span) and finalizes it.
If no trace_context is provided, ends all active session spans.

Args:
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:
logger.warning("AgentOps SDK not initialized. Cannot end trace.")
return

Check warning on line 223 in agentops/__init__.py

View check run for this annotation

Codecov / codecov/patch

agentops/__init__.py#L222-L223

Added lines #L222 - L223 were not covered by tests
tracing_core.end_trace(trace_context=trace_context, end_state=end_state)


__all__ = [
"init",
"configure",
"get_client",
"record",
"start_trace",
"end_trace",
"start_session",
"end_session",
"track_agent",
"track_tool",
"end_all_sessions",
"Session",
"ToolEvent",
"ErrorEvent",
"ActionEvent",
"LLMEvent",
"Session",
"trace",
"session",
"agent",
"task",
"workflow",
"operation",
]
38 changes: 18 additions & 20 deletions agentops/client/api/versions/v3.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,26 @@

r = self.post(path, data, headers)

if r.status_code != 200:
error_msg = f"Authentication failed: {r.status_code}"
try:
error_data = r.json()
if "error" in error_data:
error_msg = f"{error_data['error']}"
except Exception:
pass
logger.error(f"{error_msg} - Perhaps an invalid API key?")
raise ApiServerException(error_msg)

Check warning on line 42 in agentops/client/api/versions/v3.py

View check run for this annotation

Codecov / codecov/patch

agentops/client/api/versions/v3.py#L34-L42

Added lines #L34 - L42 were not covered by tests

try:
if r.status_code != 200:
error_msg = f"Authentication failed: {r.status_code}"
try:
error_data = r.json()
if "error" in error_data:
error_msg = f"{error_data['error']}"
except Exception:
pass
raise ApiServerException(error_msg)
jr = r.json()
token = jr.get("token")
if not token:
raise ApiServerException("No token in authentication response")

Check warning on line 48 in agentops/client/api/versions/v3.py

View check run for this annotation

Codecov / codecov/patch

agentops/client/api/versions/v3.py#L48

Added line #L48 was not covered by tests

try:
jr = r.json()
token = jr.get("token")
if not token:
raise ApiServerException("No token in authentication response")

return jr
except Exception as e:
raise ApiServerException(f"Failed to process authentication response: {str(e)}")
return jr
except Exception as e:
logger.error(f"{str(e)} - Perhaps an invalid API key?")
return None
logger.error(f"Failed to process authentication response: {str(e)}")
raise ApiServerException(f"Failed to process authentication response: {str(e)}")

Check warning on line 53 in agentops/client/api/versions/v3.py

View check run for this annotation

Codecov / codecov/patch

agentops/client/api/versions/v3.py#L52-L53

Added lines #L52 - L53 were not covered by tests

# Add V3-specific API methods here
Loading
Loading