Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: reorganize session management into dedicated components #631

Closed
wants to merge 5 commits into from
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
48 changes: 16 additions & 32 deletions agentops/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,47 +198,31 @@
self,
tags: Optional[List[str]] = None,
inherited_session_id: Optional[str] = None,
) -> Union[Session, None]:
"""
Start a new session for recording events.

Args:
tags (List[str], optional): Tags that can be used for grouping or sorting later.
e.g. ["test_run"].
config: (Configuration, optional): Client configuration object
inherited_session_id (optional, str): assign session id to match existing Session
"""
) -> Optional[Session]:
"""Start a new session"""
if not self.is_initialized:
return

if inherited_session_id is not None:
try:
session_id = UUID(inherited_session_id)
except ValueError:
return logger.warning(f"Invalid session id: {inherited_session_id}")
else:
session_id = uuid4()
return None

Check warning on line 204 in agentops/client.py

View check run for this annotation

Codecov / codecov/patch

agentops/client.py#L204

Added line #L204 was not covered by tests

session_tags = self._config.default_tags.copy()
if tags is not None:
session_tags.update(tags)
try:
session_id = UUID(inherited_session_id) if inherited_session_id else uuid4()
except ValueError:
return logger.warning(f"Invalid session id: {inherited_session_id}")

Check warning on line 209 in agentops/client.py

View check run for this annotation

Codecov / codecov/patch

agentops/client.py#L208-L209

Added lines #L208 - L209 were not covered by tests

default_tags = list(self._config.default_tags) if self._config.default_tags else []
session = Session(
session_id=session_id,
tags=list(session_tags),
host_env=self.host_env,
config=self._config,
tags=tags or default_tags,
host_env=self.host_env,
)

if not session.is_running:
return logger.error("Failed to start session")

if self._pre_init_queue["agents"] and len(self._pre_init_queue["agents"]) > 0:
for agent_args in self._pre_init_queue["agents"]:
session.create_agent(name=agent_args["name"], agent_id=agent_args["agent_id"])
self._pre_init_queue["agents"] = []
if session.is_running:
# Process any queued agents
if self._pre_init_queue["agents"]:
for agent_args in self._pre_init_queue["agents"]:
session.create_agent(name=agent_args["name"], agent_id=agent_args["agent_id"])
self._pre_init_queue["agents"].clear()

self._sessions.append(session)
return session

def end_session(
Expand Down
22 changes: 17 additions & 5 deletions agentops/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
end_timestamp(str): A timestamp indicating when the event ended. Defaults to the time when this Event was instantiated.
agent_id(UUID, optional): The unique identifier of the agent that triggered the event.
id(UUID): A unique identifier for the event. Defaults to a new UUID.
session_id(UUID, optional): The unique identifier of the session that the event belongs to.

foo(x=1) {
...
Expand All @@ -43,6 +44,7 @@
end_timestamp: Optional[str] = None
agent_id: Optional[UUID] = field(default_factory=check_call_stack_for_agent_id)
id: UUID = field(default_factory=uuid4)
session_id: Optional[UUID] = None


@dataclass
Expand Down Expand Up @@ -105,7 +107,7 @@


@dataclass
class ErrorEvent:
class ErrorEvent(Event):
"""
For recording any errors e.g. ones related to agent execution

Expand All @@ -115,21 +117,31 @@
code(str, optional): A code that can be used to identify the error e.g. 501.
details(str, optional): Detailed information about the error.
logs(str, optional): For detailed information/logging related to the error.
timestamp(str): A timestamp indicating when the error occurred. Defaults to the time when this ErrorEvent was instantiated.

"""

# Inherit common Event fields
event_type: str = field(default=EventType.ERROR.value)

# Error-specific fields
trigger_event: Optional[Event] = None
exception: Optional[BaseException] = None
error_type: Optional[str] = None
code: Optional[str] = None
details: Optional[Union[str, Dict[str, str]]] = None
logs: Optional[str] = field(default_factory=traceback.format_exc)
timestamp: str = field(default_factory=get_ISO_time)

def __post_init__(self):
self.event_type = EventType.ERROR.value
"""Process exception if provided"""
if self.exception:
self.error_type = self.error_type or type(self.exception).__name__
self.details = self.details or str(self.exception)
self.exception = None # removes exception from serialization

# Ensure end timestamp is set
if not self.end_timestamp:
self.end_timestamp = get_ISO_time()

@property
def timestamp(self) -> str:
"""Maintain backward compatibility with old code expecting timestamp"""
return self.init_timestamp

Check warning on line 147 in agentops/event.py

View check run for this annotation

Codecov / codecov/patch

agentops/event.py#L147

Added line #L147 was not covered by tests
Loading
Loading