Skip to content

Commit 9fd817f

Browse files
authored
refactor: move events to audit module (#58)
1 parent d890fec commit 9fd817f

File tree

16 files changed

+73
-65
lines changed

16 files changed

+73
-65
lines changed

docs/how-to/create_custom_event_handler.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@ In this guide we will implement a simple [Event Handler](../reference/event_hand
1010
First, we need to create a new class that inherits from `EventHandler` and implements the all abstract methods.
1111

1212
```python
13-
from dbally.audit import EventHandler
14-
from dbally.data_models.audit import RequestStart, RequestEnd
13+
from dbally.audit import EventHandler, RequestStart, RequestEnd
1514

1615
class FileEventHandler(EventHandler):
1716

docs/reference/event_handlers/index.md

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ db-ally provides an `EventHandler` abstract class that can be used to log the ru
1010
Each run of [dbally.Collection.ask][dbally.Collection.ask] will trigger all instances of EventHandler that were passed to the Collection's constructor (or the [dbally.create_collection][dbally.create_collection] function).
1111

1212

13-
1. `EventHandler.request_start` is called with [RequestStart][dbally.data_models.audit.RequestStart], it can return a context object that will be passed to next calls.
13+
1. `EventHandler.request_start` is called with [RequestStart][dbally.audit.events.RequestStart], it can return a context object that will be passed to next calls.
1414
2. For each event that occurs during the run, `EventHandler.event_start` is called with the context object returned by `EventHandler.request_start` and an Event object. It can return context for the `EventHandler.event_end` method.
1515
3. When the event ends `EventHandler.event_end` is called with the context object returned by `EventHandler.event_start` and an Event object.
16-
4. On the end of the run `EventHandler.request_end` is called with the context object returned by `EventHandler.request_start` and the [RequestEnd][dbally.data_models.audit.RequestEnd].
16+
4. On the end of the run `EventHandler.request_end` is called with the context object returned by `EventHandler.request_start` and the [RequestEnd][dbally.audit.events.RequestEnd].
1717

1818

1919
``` mermaid
@@ -42,8 +42,14 @@ Currently handled events:
4242

4343
::: dbally.audit.EventHandler
4444

45-
::: dbally.data_models.audit.RequestStart
45+
::: dbally.audit.events.RequestStart
4646

47-
::: dbally.data_models.audit.RequestEnd
47+
::: dbally.audit.events.RequestEnd
4848

49-
::: dbally.data_models.audit.LLMEvent
49+
::: dbally.audit.events.Event
50+
51+
::: dbally.audit.events.LLMEvent
52+
53+
::: dbally.audit.events.SimilarityEvent
54+
55+
::: dbally.audit.spans.EventSpan

src/dbally/audit/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,19 @@
77
except ImportError:
88
pass
99

10+
from .event_tracker import EventTracker
11+
from .events import Event, LLMEvent, RequestEnd, RequestStart, SimilarityEvent
12+
from .spans import EventSpan
13+
1014
__all__ = [
1115
"CLIEventHandler",
1216
"LangSmithEventHandler",
17+
"Event",
1318
"EventHandler",
19+
"EventTracker",
20+
"EventSpan",
21+
"LLMEvent",
22+
"RequestEnd",
23+
"RequestStart",
24+
"SimilarityEvent",
1425
]

src/dbally/audit/event_handlers/base.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import abc
22
from abc import ABC
3-
from typing import Generic, TypeVar, Union
3+
from typing import Generic, Optional, TypeVar
44

5-
from dbally.data_models.audit import LLMEvent, RequestEnd, RequestStart, SimilarityEvent
5+
from dbally.audit.events import Event, RequestEnd, RequestStart
66

77
RequestCtx = TypeVar("RequestCtx")
88
EventCtx = TypeVar("EventCtx")
@@ -26,7 +26,7 @@ async def request_start(self, user_request: RequestStart) -> RequestCtx:
2626
"""
2727

2828
@abc.abstractmethod
29-
async def event_start(self, event: Union[LLMEvent, SimilarityEvent], request_context: RequestCtx) -> EventCtx:
29+
async def event_start(self, event: Event, request_context: RequestCtx) -> EventCtx:
3030
"""
3131
Function that is called during every event execution.
3232
@@ -40,9 +40,7 @@ async def event_start(self, event: Union[LLMEvent, SimilarityEvent], request_con
4040
"""
4141

4242
@abc.abstractmethod
43-
async def event_end(
44-
self, event: Union[None, LLMEvent, SimilarityEvent], request_context: RequestCtx, event_context: EventCtx
45-
) -> None:
43+
async def event_end(self, event: Optional[Event], request_context: RequestCtx, event_context: EventCtx) -> None:
4644
"""
4745
Function that is called during every event execution.
4846

src/dbally/audit/event_handlers/cli_event_handler.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import re
22
from io import StringIO
33
from sys import stdout
4-
from typing import Optional, Union
4+
from typing import Optional
55

66
try:
77
from rich import print as pprint
@@ -15,7 +15,7 @@
1515
pprint = print # type: ignore
1616

1717
from dbally.audit.event_handlers.base import EventHandler
18-
from dbally.data_models.audit import LLMEvent, RequestEnd, RequestStart, SimilarityEvent
18+
from dbally.audit.events import Event, LLMEvent, RequestEnd, RequestStart, SimilarityEvent
1919

2020
_RICH_FORMATING_KEYWORD_SET = {"green", "orange", "grey", "bold", "cyan"}
2121
_RICH_FORMATING_PATTERN = rf"\[.*({'|'.join(_RICH_FORMATING_KEYWORD_SET)}).*\]"
@@ -40,14 +40,14 @@ class CLIEventHandler(EventHandler):
4040
![Example output from CLIEventHandler](../../assets/event_handler_example.png)
4141
"""
4242

43-
def __init__(self, buffer: StringIO = None) -> None:
43+
def __init__(self, buffer: Optional[StringIO] = None) -> None:
4444
super().__init__()
4545

4646
self.buffer = buffer
4747
out = self.buffer if buffer else stdout
4848
self._console = Console(file=out, record=True) if RICH_OUTPUT else None
4949

50-
def _print_syntax(self, content: str, lexer: str = None) -> None:
50+
def _print_syntax(self, content: str, lexer: Optional[str] = None) -> None:
5151
if self._console:
5252
if lexer:
5353
console_content = Syntax(content, lexer, word_wrap=True)
@@ -69,7 +69,7 @@ async def request_start(self, user_request: RequestStart) -> None:
6969
self._print_syntax("[grey53]\n=======================================")
7070
self._print_syntax("[grey53]=======================================\n")
7171

72-
async def event_start(self, event: Union[LLMEvent, SimilarityEvent], request_context: None) -> None:
72+
async def event_start(self, event: Event, request_context: None) -> None:
7373
"""
7474
Displays information that event has started, then all messages inside the prompt
7575
@@ -98,9 +98,7 @@ async def event_start(self, event: Union[LLMEvent, SimilarityEvent], request_con
9898
f"[cyan bold]FETCHER: [grey53]{event.fetcher}\n"
9999
)
100100

101-
async def event_end(
102-
self, event: Union[None, LLMEvent, SimilarityEvent], request_context: None, event_context: None
103-
) -> None:
101+
async def event_end(self, event: Optional[Event], request_context: None, event_context: None) -> None:
104102
"""
105103
Displays the response from the LLM.
106104

src/dbally/audit/event_handlers/langsmith_event_handler.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import socket
22
from getpass import getuser
3-
from typing import Optional, Union
3+
from typing import Optional
44

55
from langsmith.client import Client
66
from langsmith.run_trees import RunTree
77

88
from dbally.audit.event_handlers.base import EventHandler
9-
from dbally.data_models.audit import LLMEvent, RequestEnd, RequestStart, SimilarityEvent
9+
from dbally.audit.events import Event, LLMEvent, RequestEnd, RequestStart, SimilarityEvent
1010

1111

1212
class LangSmithEventHandler(EventHandler[RunTree, RunTree]):
@@ -47,7 +47,7 @@ async def request_start(self, user_request: RequestStart) -> RunTree:
4747

4848
return run_tree
4949

50-
async def event_start(self, event: Union[None, LLMEvent, SimilarityEvent], request_context: RunTree) -> RunTree:
50+
async def event_start(self, event: Event, request_context: RunTree) -> RunTree:
5151
"""
5252
Log the start of the event.
5353
@@ -79,9 +79,7 @@ async def event_start(self, event: Union[None, LLMEvent, SimilarityEvent], reque
7979

8080
raise ValueError("Unsupported event")
8181

82-
async def event_end(
83-
self, event: Union[None, LLMEvent, SimilarityEvent], request_context: RunTree, event_context: RunTree
84-
) -> None:
82+
async def event_end(self, event: Optional[Event], request_context: RunTree, event_context: RunTree) -> None:
8583
"""
8684
Log the end of the event.
8785

src/dbally/audit/event_span.py

Lines changed: 0 additions & 22 deletions
This file was deleted.

src/dbally/audit/event_tracker.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from contextlib import asynccontextmanager
2-
from typing import AsyncIterator, Dict, List, Optional, Union
2+
from typing import AsyncIterator, Dict, List, Optional
33

44
from dbally.audit.event_handlers.base import EventHandler
5-
from dbally.audit.event_span import EventSpan
6-
from dbally.data_models.audit import LLMEvent, RequestEnd, RequestStart, SimilarityEvent
5+
from dbally.audit.events import Event, RequestEnd, RequestStart
6+
from dbally.audit.spans import EventSpan
77

88

99
class EventTracker:
@@ -69,7 +69,7 @@ def subscribe(self, event_handler: EventHandler) -> None:
6969
self._handlers.append(event_handler)
7070

7171
@asynccontextmanager
72-
async def track_event(self, event: Union[LLMEvent, SimilarityEvent]) -> AsyncIterator[EventSpan]:
72+
async def track_event(self, event: Event) -> AsyncIterator[EventSpan]:
7373
"""
7474
Context manager for processing an event.
7575

src/dbally/data_models/audit.py renamed to src/dbally/audit/events.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
1+
from abc import ABC
12
from dataclasses import dataclass
2-
from enum import Enum
33
from typing import Optional, Union
44

55
from dbally.collection.results import ExecutionResult
66
from dbally.prompts import ChatFormat
77

88

9-
class EventType(Enum):
9+
@dataclass
10+
class Event(ABC):
1011
"""
11-
Enum for event types.
12+
Base class for all events.
1213
"""
1314

14-
LLM = "LLM"
15-
1615

1716
@dataclass
18-
class LLMEvent:
17+
class LLMEvent(Event):
1918
"""
2019
Class for LLM event.
2120
"""
@@ -30,7 +29,7 @@ class LLMEvent:
3029

3130

3231
@dataclass
33-
class SimilarityEvent:
32+
class SimilarityEvent(Event):
3433
"""
3534
SimilarityEvent is fired when a SimilarityIndex lookup is performed.
3635
"""

src/dbally/audit/spans.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import Optional
2+
3+
from dbally.audit.events import Event
4+
5+
6+
class EventSpan:
7+
"""
8+
Helper class for logging events.
9+
"""
10+
11+
def __init__(self) -> None:
12+
self.data: Optional[Event] = None
13+
14+
def __call__(self, data: Event) -> None:
15+
"""
16+
Call method for logging events.
17+
18+
Args:
19+
data: Event data.
20+
"""
21+
self.data = data

0 commit comments

Comments
 (0)