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

add initial implementation for the @trace decorator #1136

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions src/intelligence_layer/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .chunk import ChunkWithIndicesOutput as ChunkWithIndicesOutput
from .chunk import ChunkWithStartEndIndices as ChunkWithStartEndIndices
from .chunk import TextChunk as TextChunk
from .decorators import trace as trace
from .detect_language import DetectLanguage as DetectLanguage
from .detect_language import DetectLanguageInput as DetectLanguageInput
from .detect_language import DetectLanguageOutput as DetectLanguageOutput
Expand Down
69 changes: 69 additions & 0 deletions src/intelligence_layer/core/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""Module for decorators used in the intelligence layer."""

from collections.abc import Callable
from functools import wraps
from typing import Any, ParamSpec, TypeVar, get_type_hints

from pydantic import BaseModel

from intelligence_layer.core.tracer.tracer import (
NoOpTracer,
Tracer,
)

T = TypeVar("T")
P = ParamSpec("P")


class SerializableInput(BaseModel):
"""Pydantic model for serializing input data."""

args: dict[str, Any]
kwargs: dict[str, Any]


def trace(func: Callable[P, T]) -> Callable[P, T]:
"""A decorator to trace the execution of a method in a Task subclass.

This decorator wraps the method execution with tracing logic, creating a task span and recording the output.
It retrieves the tracer from the Task instance and uses the method name as the task name.

Args:
func: The method to be traced.

Returns:
Callable: A decorator that traces the function execution.
"""

@wraps(func)
def wrapper(self: Any, *args: P.args, **kwargs: P.kwargs) -> T:
"""Wrapper function to execute the original function with tracing.

Args:
self: The instance of the Task subclass.
*args: Positional arguments passed to the original function.
**kwargs: Keyword arguments passed to the original function.

Returns:
PydanticSerializable: The output of the original function.
"""
tracer: Tracer = getattr(self, "_tracer", NoOpTracer())
name = func.__name__

arg_names = list(get_type_hints(func).keys())
args_dict = {arg_names[i]: arg for i, arg in enumerate(args)}
input_data = SerializableInput(args=args_dict, kwargs=kwargs)

if self.current_task_span is None:
self.current_task_span = tracer.task_span(name, input_data)
else:
self.current_task_span = self.current_task_span.task_span(name, input_data)

with self.current_task_span as task_span:
output: T = func(self, *args, **kwargs)
task_span.record_output(
SerializableInput(args={"output": output}, kwargs={})
)
return output

return wrapper # type: ignore
14 changes: 14 additions & 0 deletions src/intelligence_layer/core/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,18 @@ class Task(ABC, Generic[Input, Output]):
Output: Interface of the output returned by the task.
"""

_tracer: Tracer
_current_task_span: TaskSpan

@property
def current_task_span(self) -> TaskSpan:
"""The current task span for this task."""
return self._current_task_span

@current_task_span.setter
def current_task_span(self, task_span: TaskSpan) -> None:
self._current_task_span = task_span

@abstractmethod
def do_run(self, input: Input, task_span: TaskSpan) -> Output:
"""The implementation for this use case.
Expand Down Expand Up @@ -74,7 +86,9 @@ def run(self, input: Input, tracer: Tracer) -> Output:
Returns:
Generic output defined by the task implementation.
"""
self._tracer = tracer
with tracer.task_span(type(self).__name__, input) as task_span:
self._current_task_span = task_span
output = self.do_run(input, task_span)
task_span.record_output(output)
return output
Expand Down
Loading