|
| 1 | +"""Module with the logic to create and manage traces and steps.""" |
| 2 | + |
| 3 | +import inspect |
| 4 | +from typing import Any, Dict, Optional, Generator |
| 5 | +from contextlib import contextmanager |
| 6 | +import contextvars |
| 7 | +from functools import wraps |
| 8 | + |
| 9 | +from . import steps |
| 10 | +from . import traces |
| 11 | +import time |
| 12 | + |
| 13 | +_current_step = contextvars.ContextVar("current_step") |
| 14 | +_current_trace = contextvars.ContextVar("current_trace") |
| 15 | + |
| 16 | + |
| 17 | +@contextmanager |
| 18 | +def create_step( |
| 19 | + name: str, |
| 20 | + inputs: Optional[Any] = None, |
| 21 | + output: Optional[Any] = None, |
| 22 | + metadata: Dict[str, any] = {}, |
| 23 | +) -> Generator[steps.Step, None, None]: |
| 24 | + """Starts a trace and yields a Step object.""" |
| 25 | + new_step = steps.Step(name=name, inputs=inputs, output=output, metadata=metadata) |
| 26 | + |
| 27 | + parent_step = _current_step.get(None) |
| 28 | + is_root_step = parent_step is None |
| 29 | + |
| 30 | + if parent_step is None: |
| 31 | + print("Starting a new trace...") |
| 32 | + current_trace = traces.Trace() |
| 33 | + _current_trace.set(current_trace) # Set the current trace in context |
| 34 | + current_trace.add_step(new_step) |
| 35 | + else: |
| 36 | + print(f"Adding step {name} to parent step {parent_step.name}") |
| 37 | + current_trace = _current_trace.get() |
| 38 | + parent_step.add_nested_step(new_step) |
| 39 | + |
| 40 | + token = _current_step.set(new_step) |
| 41 | + |
| 42 | + try: |
| 43 | + yield new_step |
| 44 | + finally: |
| 45 | + _current_step.reset(token) |
| 46 | + if is_root_step: |
| 47 | + print("Ending the trace...") |
| 48 | + print("-" * 80) |
| 49 | + print(current_trace.to_dict()) |
| 50 | + print("-" * 80) |
| 51 | + else: |
| 52 | + # TODO: stream to Openlayer |
| 53 | + print(f"Ending step {name}") |
| 54 | + |
| 55 | + |
| 56 | +def trace(*step_args, **step_kwargs): |
| 57 | + def decorator(func): |
| 58 | + func_signature = inspect.signature(func) |
| 59 | + |
| 60 | + @wraps(func) |
| 61 | + def wrapper(*func_args, **func_kwargs): |
| 62 | + if step_kwargs.get("name") is None: |
| 63 | + step_kwargs["name"] = func.__name__ |
| 64 | + with create_step(*step_args, **step_kwargs) as step: |
| 65 | + output = func(*func_args, **func_kwargs) |
| 66 | + end_time = time.time() |
| 67 | + latency = (end_time - step.start_time) * 1000 # in ms |
| 68 | + inputs = func_signature.bind(*func_args, **func_kwargs).arguments |
| 69 | + |
| 70 | + step.update_data( |
| 71 | + inputs=inputs, |
| 72 | + output=output, |
| 73 | + end_time=end_time, |
| 74 | + latency=latency, |
| 75 | + ) |
| 76 | + return output |
| 77 | + |
| 78 | + return wrapper |
| 79 | + |
| 80 | + return decorator |
0 commit comments