lmnr 0.4.6__py3-none-any.whl → 0.4.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. lmnr/sdk/decorators.py +2 -7
  2. lmnr/sdk/laminar.py +69 -4
  3. lmnr/traceloop_sdk/.flake8 +12 -0
  4. lmnr/traceloop_sdk/.python-version +1 -0
  5. lmnr/traceloop_sdk/README.md +16 -0
  6. lmnr/traceloop_sdk/__init__.py +138 -0
  7. lmnr/traceloop_sdk/config/__init__.py +13 -0
  8. lmnr/traceloop_sdk/decorators/__init__.py +131 -0
  9. lmnr/traceloop_sdk/decorators/base.py +253 -0
  10. lmnr/traceloop_sdk/instruments.py +29 -0
  11. lmnr/traceloop_sdk/metrics/__init__.py +0 -0
  12. lmnr/traceloop_sdk/metrics/metrics.py +176 -0
  13. lmnr/traceloop_sdk/tests/__init__.py +1 -0
  14. lmnr/traceloop_sdk/tests/cassettes/test_association_properties/test_langchain_and_external_association_properties.yaml +101 -0
  15. lmnr/traceloop_sdk/tests/cassettes/test_association_properties/test_langchain_association_properties.yaml +99 -0
  16. lmnr/traceloop_sdk/tests/cassettes/test_manual/test_manual_report.yaml +98 -0
  17. lmnr/traceloop_sdk/tests/cassettes/test_manual/test_resource_attributes.yaml +98 -0
  18. lmnr/traceloop_sdk/tests/cassettes/test_privacy_no_prompts/test_simple_workflow.yaml +199 -0
  19. lmnr/traceloop_sdk/tests/cassettes/test_prompt_management/test_prompt_management.yaml +202 -0
  20. lmnr/traceloop_sdk/tests/cassettes/test_sdk_initialization/test_resource_attributes.yaml +199 -0
  21. lmnr/traceloop_sdk/tests/cassettes/test_tasks/test_task_io_serialization_with_langchain.yaml +96 -0
  22. lmnr/traceloop_sdk/tests/cassettes/test_workflows/test_simple_aworkflow.yaml +98 -0
  23. lmnr/traceloop_sdk/tests/cassettes/test_workflows/test_simple_workflow.yaml +199 -0
  24. lmnr/traceloop_sdk/tests/cassettes/test_workflows/test_streaming_workflow.yaml +167 -0
  25. lmnr/traceloop_sdk/tests/conftest.py +111 -0
  26. lmnr/traceloop_sdk/tests/test_association_properties.py +229 -0
  27. lmnr/traceloop_sdk/tests/test_manual.py +48 -0
  28. lmnr/traceloop_sdk/tests/test_nested_tasks.py +47 -0
  29. lmnr/traceloop_sdk/tests/test_privacy_no_prompts.py +50 -0
  30. lmnr/traceloop_sdk/tests/test_sdk_initialization.py +57 -0
  31. lmnr/traceloop_sdk/tests/test_tasks.py +32 -0
  32. lmnr/traceloop_sdk/tests/test_workflows.py +261 -0
  33. lmnr/traceloop_sdk/tracing/__init__.py +2 -0
  34. lmnr/traceloop_sdk/tracing/content_allow_list.py +24 -0
  35. lmnr/traceloop_sdk/tracing/context_manager.py +13 -0
  36. lmnr/traceloop_sdk/tracing/manual.py +57 -0
  37. lmnr/traceloop_sdk/tracing/tracing.py +1078 -0
  38. lmnr/traceloop_sdk/utils/__init__.py +26 -0
  39. lmnr/traceloop_sdk/utils/in_memory_span_exporter.py +61 -0
  40. lmnr/traceloop_sdk/utils/json_encoder.py +20 -0
  41. lmnr/traceloop_sdk/utils/package_check.py +8 -0
  42. lmnr/traceloop_sdk/version.py +1 -0
  43. {lmnr-0.4.6.dist-info → lmnr-0.4.7.dist-info}/METADATA +40 -3
  44. lmnr-0.4.7.dist-info/RECORD +53 -0
  45. lmnr-0.4.6.dist-info/RECORD +0 -13
  46. {lmnr-0.4.6.dist-info → lmnr-0.4.7.dist-info}/LICENSE +0 -0
  47. {lmnr-0.4.6.dist-info → lmnr-0.4.7.dist-info}/WHEEL +0 -0
  48. {lmnr-0.4.6.dist-info → lmnr-0.4.7.dist-info}/entry_points.txt +0 -0
lmnr/sdk/decorators.py CHANGED
@@ -1,9 +1,9 @@
1
- from traceloop.sdk.decorators.base import (
1
+ from lmnr.traceloop_sdk.decorators.base import (
2
2
  entity_method,
3
3
  aentity_method,
4
4
  )
5
5
  from opentelemetry.trace import INVALID_SPAN, get_current_span
6
- from traceloop.sdk import Traceloop
6
+ from lmnr.traceloop_sdk import Traceloop
7
7
 
8
8
  from typing import Callable, Optional, ParamSpec, TypeVar, cast
9
9
 
@@ -42,11 +42,6 @@ def observe(
42
42
  """
43
43
 
44
44
  def decorator(func: Callable[P, R]) -> Callable[P, R]:
45
- if not L.is_initialized():
46
- raise Exception(
47
- "Laminar is not initialized. Please "
48
- + "call Laminar.initialize() first."
49
- )
50
45
  current_span = get_current_span()
51
46
  if current_span != INVALID_SPAN:
52
47
  if session_id is not None:
lmnr/sdk/laminar.py CHANGED
@@ -4,11 +4,15 @@ from opentelemetry.trace import (
4
4
  get_current_span,
5
5
  set_span_in_context,
6
6
  Span,
7
+ SpanKind,
7
8
  )
8
9
  from opentelemetry.semconv_ai import SpanAttributes
9
10
  from opentelemetry.util.types import AttributeValue
10
- from traceloop.sdk import Traceloop
11
- from traceloop.sdk.tracing import get_tracer
11
+ from opentelemetry.context.context import Context
12
+ from opentelemetry.util import types
13
+ from lmnr.traceloop_sdk import Traceloop
14
+ from lmnr.traceloop_sdk.tracing import get_tracer
15
+ from contextlib import contextmanager
12
16
  from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
13
17
 
14
18
  from pydantic.alias_generators import to_snake
@@ -96,8 +100,6 @@ class Laminar:
96
100
  cls.__initialized = True
97
101
  cls._initialize_logger()
98
102
  Traceloop.init(
99
- api_endpoint=cls.__base_url,
100
- api_key=cls.__project_api_key,
101
103
  exporter=OTLPSpanExporter(
102
104
  endpoint=cls.__base_url,
103
105
  headers={"authorization": f"Bearer {cls.__project_api_key}"},
@@ -289,6 +291,68 @@ class Laminar:
289
291
 
290
292
  current_span.add_event(name, event)
291
293
 
294
+ @classmethod
295
+ @contextmanager
296
+ def start_as_current_span(
297
+ cls,
298
+ name: str,
299
+ input: Any = None,
300
+ context: Optional[Context] = None,
301
+ kind: SpanKind = SpanKind.INTERNAL,
302
+ attributes: types.Attributes = None,
303
+ links=None,
304
+ start_time: Optional[int] = None,
305
+ record_exception: bool = True,
306
+ set_status_on_exception: bool = True,
307
+ end_on_exit: bool = True,
308
+ ):
309
+ """Start a new span as the current span. Useful for manual instrumentation.
310
+ This is the preferred and more stable way to use manual instrumentation.
311
+
312
+ Usage example:
313
+ ```python
314
+ with Laminar.start_as_current_span("my_span", input="my_input"):
315
+ await my_async_function()
316
+ ```
317
+
318
+ Args:
319
+ name (str): name of the span
320
+ input (Any, optional): input to the span. Will be sent as an
321
+ attribute, so must be json serializable. Defaults to None.
322
+ context (Optional[Context], optional): context to start the span in.
323
+ Defaults to None.
324
+ kind (SpanKind, optional): kind of the span. Defaults to SpanKind.INTERNAL.
325
+ attributes (types.Attributes, optional): attributes to set on the span.
326
+ Defaults to None.
327
+ links ([type], optional): links to set on the span. Defaults to None.
328
+ start_time (Optional[int], optional): start time of the span.
329
+ Defaults to None.
330
+ record_exception (bool, optional): whether to record exceptions.
331
+ Defaults to True.
332
+ set_status_on_exception (bool, optional): whether to set status on exception.
333
+ Defaults to True.
334
+ end_on_exit (bool, optional): whether to end the span on exit.
335
+ Defaults to True.
336
+ """
337
+ with get_tracer() as tracer:
338
+ with tracer.start_as_current_span(
339
+ name,
340
+ context=context,
341
+ kind=kind,
342
+ attributes=attributes,
343
+ links=links,
344
+ start_time=start_time,
345
+ record_exception=record_exception,
346
+ set_status_on_exception=set_status_on_exception,
347
+ end_on_exit=end_on_exit,
348
+ ) as span:
349
+ if input is not None:
350
+ span.set_attribute(
351
+ SpanAttributes.TRACELOOP_ENTITY_INPUT,
352
+ json.dumps({"input": input}),
353
+ )
354
+ yield span
355
+
292
356
  @classmethod
293
357
  def start_span(
294
358
  cls,
@@ -453,6 +517,7 @@ class Laminar:
453
517
 
454
518
  @classmethod
455
519
  def _headers(cls):
520
+ assert cls.__project_api_key is not None, "Project API key is not set"
456
521
  return {
457
522
  "Authorization": "Bearer " + cls.__project_api_key,
458
523
  "Content-Type": "application/json",
@@ -0,0 +1,12 @@
1
+ [flake8]
2
+ exclude =
3
+ .git,
4
+ __pycache__,
5
+ build,
6
+ dist,
7
+ .tox,
8
+ venv,
9
+ .venv,
10
+ .pytest_cache
11
+ max-line-length = 120
12
+ per-file-ignores = __init__.py:F401
@@ -0,0 +1 @@
1
+ 3.9.5
@@ -0,0 +1,16 @@
1
+ # traceloop-sdk
2
+
3
+ Traceloop’s Python SDK allows you to easily start monitoring and debugging your LLM execution. Tracing is done in a non-intrusive way, built on top of OpenTelemetry. You can choose to export the traces to Traceloop, or to your existing observability stack.
4
+
5
+ ```python
6
+ Traceloop.init(app_name="joke_generation_service")
7
+
8
+ @workflow(name="joke_creation")
9
+ def create_joke():
10
+ completion = openai.ChatCompletion.create(
11
+ model="gpt-3.5-turbo",
12
+ messages=[{"role": "user", "content": "Tell me a joke about opentelemetry"}],
13
+ )
14
+
15
+ return completion.choices[0].message.content
16
+ ```
@@ -0,0 +1,138 @@
1
+ import os
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ from typing import Optional, Set
6
+ from colorama import Fore
7
+ from opentelemetry.sdk.trace import SpanProcessor
8
+ from opentelemetry.sdk.trace.export import SpanExporter
9
+ from opentelemetry.sdk.metrics.export import MetricExporter
10
+ from opentelemetry.sdk.resources import SERVICE_NAME
11
+ from opentelemetry.propagators.textmap import TextMapPropagator
12
+ from opentelemetry.util.re import parse_env_headers
13
+
14
+ from lmnr.traceloop_sdk.metrics.metrics import MetricsWrapper
15
+ from lmnr.traceloop_sdk.instruments import Instruments
16
+ from lmnr.traceloop_sdk.config import (
17
+ is_content_tracing_enabled,
18
+ is_tracing_enabled,
19
+ is_metrics_enabled,
20
+ )
21
+ from lmnr.traceloop_sdk.tracing.tracing import (
22
+ TracerWrapper,
23
+ set_association_properties,
24
+ set_external_prompt_tracing_context,
25
+ )
26
+ from typing import Dict
27
+
28
+
29
+ class Traceloop:
30
+ AUTO_CREATED_KEY_PATH = str(
31
+ Path.home() / ".cache" / "traceloop" / "auto_created_key"
32
+ )
33
+ AUTO_CREATED_URL = str(Path.home() / ".cache" / "traceloop" / "auto_created_url")
34
+
35
+ __tracer_wrapper: TracerWrapper
36
+
37
+ @staticmethod
38
+ def init(
39
+ app_name: Optional[str] = sys.argv[0],
40
+ api_endpoint: str = "https://api.lmnr.ai",
41
+ api_key: str = None,
42
+ headers: Dict[str, str] = {},
43
+ disable_batch=False,
44
+ exporter: SpanExporter = None,
45
+ metrics_exporter: MetricExporter = None,
46
+ metrics_headers: Dict[str, str] = None,
47
+ processor: SpanProcessor = None,
48
+ propagator: TextMapPropagator = None,
49
+ should_enrich_metrics: bool = True,
50
+ resource_attributes: dict = {},
51
+ instruments: Optional[Set[Instruments]] = None,
52
+ ) -> None:
53
+ api_endpoint = os.getenv("TRACELOOP_BASE_URL") or api_endpoint
54
+ api_key = os.getenv("TRACELOOP_API_KEY") or api_key
55
+
56
+ if not is_tracing_enabled():
57
+ print(Fore.YELLOW + "Tracing is disabled" + Fore.RESET)
58
+ return
59
+
60
+ enable_content_tracing = is_content_tracing_enabled()
61
+
62
+ if exporter or processor:
63
+ print(Fore.GREEN + "Laminar exporting traces to a custom exporter")
64
+
65
+ headers = os.getenv("TRACELOOP_HEADERS") or headers
66
+
67
+ if isinstance(headers, str):
68
+ headers = parse_env_headers(headers)
69
+
70
+ if (
71
+ not exporter
72
+ and not processor
73
+ and api_endpoint == "https://api.lmnr.ai"
74
+ and not api_key
75
+ ):
76
+ print(
77
+ Fore.RED
78
+ + "Error: Missing API key,"
79
+ + " go to project settings to create one"
80
+ )
81
+ print("Set the LMNR_PROJECT_API_KEY environment variable to the key")
82
+ print(Fore.RESET)
83
+ return
84
+
85
+ if not exporter and not processor and headers:
86
+ print(
87
+ Fore.GREEN
88
+ + f"Laminar exporting traces to {api_endpoint}, authenticating with custom headers"
89
+ )
90
+
91
+ if api_key and not exporter and not processor and not headers:
92
+ print(
93
+ Fore.GREEN
94
+ + f"Laminar exporting traces to {api_endpoint} authenticating with bearer token"
95
+ )
96
+ headers = {
97
+ "Authorization": f"Bearer {api_key}",
98
+ }
99
+
100
+ print(Fore.RESET)
101
+
102
+ # Tracer init
103
+ resource_attributes.update({SERVICE_NAME: app_name})
104
+ TracerWrapper.set_static_params(
105
+ resource_attributes, enable_content_tracing, api_endpoint, headers
106
+ )
107
+ Traceloop.__tracer_wrapper = TracerWrapper(
108
+ disable_batch=disable_batch,
109
+ processor=processor,
110
+ propagator=propagator,
111
+ exporter=exporter,
112
+ should_enrich_metrics=should_enrich_metrics,
113
+ instruments=instruments,
114
+ )
115
+
116
+ if not metrics_exporter and exporter:
117
+ return
118
+
119
+ metrics_endpoint = os.getenv("TRACELOOP_METRICS_ENDPOINT") or api_endpoint
120
+ metrics_headers = (
121
+ os.getenv("TRACELOOP_METRICS_HEADERS") or metrics_headers or headers
122
+ )
123
+
124
+ if not is_metrics_enabled() or not metrics_exporter and exporter:
125
+ print(Fore.YELLOW + "Metrics are disabled" + Fore.RESET)
126
+ return
127
+
128
+ MetricsWrapper.set_static_params(
129
+ resource_attributes, metrics_endpoint, metrics_headers
130
+ )
131
+
132
+ Traceloop.__metrics_wrapper = MetricsWrapper(exporter=metrics_exporter)
133
+
134
+ def set_association_properties(properties: dict) -> None:
135
+ set_association_properties(properties)
136
+
137
+ def set_prompt(template: str, variables: dict, version: int):
138
+ set_external_prompt_tracing_context(template, variables, version)
@@ -0,0 +1,13 @@
1
+ import os
2
+
3
+
4
+ def is_tracing_enabled() -> bool:
5
+ return (os.getenv("TRACELOOP_TRACING_ENABLED") or "true").lower() == "true"
6
+
7
+
8
+ def is_content_tracing_enabled() -> bool:
9
+ return (os.getenv("TRACELOOP_TRACE_CONTENT") or "true").lower() == "true"
10
+
11
+
12
+ def is_metrics_enabled() -> bool:
13
+ return (os.getenv("TRACELOOP_METRICS_ENABLED") or "true").lower() == "true"
@@ -0,0 +1,131 @@
1
+ from typing import Optional
2
+
3
+ from opentelemetry.semconv_ai import TraceloopSpanKindValues
4
+
5
+ from lmnr.traceloop_sdk.decorators.base import (
6
+ aentity_class,
7
+ aentity_method,
8
+ entity_class,
9
+ entity_method,
10
+ )
11
+
12
+
13
+ def task(
14
+ name: Optional[str] = None,
15
+ version: Optional[int] = None,
16
+ method_name: Optional[str] = None,
17
+ tlp_span_kind: Optional[TraceloopSpanKindValues] = TraceloopSpanKindValues.TASK,
18
+ ):
19
+ if method_name is None:
20
+ return entity_method(name=name, version=version, tlp_span_kind=tlp_span_kind)
21
+ else:
22
+ return entity_class(
23
+ name=name,
24
+ version=version,
25
+ method_name=method_name,
26
+ tlp_span_kind=tlp_span_kind,
27
+ )
28
+
29
+
30
+ def workflow(
31
+ name: Optional[str] = None,
32
+ version: Optional[int] = None,
33
+ method_name: Optional[str] = None,
34
+ tlp_span_kind: Optional[TraceloopSpanKindValues] = TraceloopSpanKindValues.WORKFLOW,
35
+ ):
36
+ if method_name is None:
37
+ return entity_method(name=name, version=version, tlp_span_kind=tlp_span_kind)
38
+ else:
39
+ return entity_class(
40
+ name=name,
41
+ version=version,
42
+ method_name=method_name,
43
+ tlp_span_kind=tlp_span_kind,
44
+ )
45
+
46
+
47
+ def agent(
48
+ name: Optional[str] = None,
49
+ version: Optional[int] = None,
50
+ method_name: Optional[str] = None,
51
+ ):
52
+ return workflow(
53
+ name=name,
54
+ version=version,
55
+ method_name=method_name,
56
+ tlp_span_kind=TraceloopSpanKindValues.AGENT,
57
+ )
58
+
59
+
60
+ def tool(
61
+ name: Optional[str] = None,
62
+ version: Optional[int] = None,
63
+ method_name: Optional[str] = None,
64
+ ):
65
+ return task(
66
+ name=name,
67
+ version=version,
68
+ method_name=method_name,
69
+ tlp_span_kind=TraceloopSpanKindValues.TOOL,
70
+ )
71
+
72
+
73
+ # Async Decorators
74
+ def atask(
75
+ name: Optional[str] = None,
76
+ version: Optional[int] = None,
77
+ method_name: Optional[str] = None,
78
+ tlp_span_kind: Optional[TraceloopSpanKindValues] = TraceloopSpanKindValues.TASK,
79
+ ):
80
+ if method_name is None:
81
+ return aentity_method(name=name, version=version, tlp_span_kind=tlp_span_kind)
82
+ else:
83
+ return aentity_class(
84
+ name=name,
85
+ version=version,
86
+ method_name=method_name,
87
+ tlp_span_kind=tlp_span_kind,
88
+ )
89
+
90
+
91
+ def aworkflow(
92
+ name: Optional[str] = None,
93
+ version: Optional[int] = None,
94
+ method_name: Optional[str] = None,
95
+ tlp_span_kind: Optional[TraceloopSpanKindValues] = TraceloopSpanKindValues.WORKFLOW,
96
+ ):
97
+ if method_name is None:
98
+ return aentity_method(name=name, version=version, tlp_span_kind=tlp_span_kind)
99
+ else:
100
+ return aentity_class(
101
+ name=name,
102
+ version=version,
103
+ method_name=method_name,
104
+ tlp_span_kind=tlp_span_kind,
105
+ )
106
+
107
+
108
+ def aagent(
109
+ name: Optional[str] = None,
110
+ version: Optional[int] = None,
111
+ method_name: Optional[str] = None,
112
+ ):
113
+ return atask(
114
+ name=name,
115
+ version=version,
116
+ method_name=method_name,
117
+ tlp_span_kind=TraceloopSpanKindValues.AGENT,
118
+ )
119
+
120
+
121
+ def atool(
122
+ name: Optional[str] = None,
123
+ version: Optional[int] = None,
124
+ method_name: Optional[str] = None,
125
+ ):
126
+ return atask(
127
+ name=name,
128
+ version=version,
129
+ method_name=method_name,
130
+ tlp_span_kind=TraceloopSpanKindValues.TOOL,
131
+ )
@@ -0,0 +1,253 @@
1
+ import json
2
+ from functools import wraps
3
+ import os
4
+ import types
5
+ from typing import Any, Optional
6
+ import warnings
7
+
8
+ from opentelemetry import trace
9
+ from opentelemetry import context as context_api
10
+ from opentelemetry.semconv_ai import SpanAttributes, TraceloopSpanKindValues
11
+
12
+ from lmnr.traceloop_sdk.tracing import get_tracer, set_workflow_name
13
+ from lmnr.traceloop_sdk.tracing.tracing import (
14
+ TracerWrapper,
15
+ set_entity_path,
16
+ get_chained_entity_path,
17
+ )
18
+ from lmnr.traceloop_sdk.utils import camel_to_snake
19
+ from lmnr.traceloop_sdk.utils.json_encoder import JSONEncoder
20
+
21
+
22
+ class CustomJSONEncoder(JSONEncoder):
23
+ def default(self, o: Any) -> Any:
24
+ try:
25
+ return super().default(o)
26
+ except TypeError:
27
+ return str(o) # Fallback to string representation for unsupported types
28
+
29
+
30
+ def _json_dumps(data: dict) -> str:
31
+ try:
32
+ with warnings.catch_warnings():
33
+ warnings.simplefilter("ignore", RuntimeWarning)
34
+ return json.dumps(data, cls=CustomJSONEncoder)
35
+ except Exception:
36
+ # Log the exception and return a placeholder if serialization completely fails
37
+ # Telemetry().log_exception(e)
38
+ return "{}" # Return an empty JSON object as a fallback
39
+
40
+
41
+ def entity_method(
42
+ name: Optional[str] = None,
43
+ version: Optional[int] = None,
44
+ tlp_span_kind: Optional[TraceloopSpanKindValues] = TraceloopSpanKindValues.TASK,
45
+ ):
46
+ def decorate(fn):
47
+ @wraps(fn)
48
+ def wrap(*args, **kwargs):
49
+ if not TracerWrapper.verify_initialized():
50
+ return fn(*args, **kwargs)
51
+
52
+ entity_name = name or fn.__name__
53
+ if tlp_span_kind in [
54
+ TraceloopSpanKindValues.WORKFLOW,
55
+ TraceloopSpanKindValues.AGENT,
56
+ ]:
57
+ set_workflow_name(entity_name)
58
+ span_name = f"{entity_name}.{tlp_span_kind.value}"
59
+
60
+ with get_tracer() as tracer:
61
+ span = tracer.start_span(span_name)
62
+ ctx = trace.set_span_in_context(span)
63
+ ctx_token = context_api.attach(ctx)
64
+
65
+ if tlp_span_kind in [
66
+ TraceloopSpanKindValues.TASK,
67
+ TraceloopSpanKindValues.TOOL,
68
+ ]:
69
+ entity_path = get_chained_entity_path(entity_name)
70
+ set_entity_path(entity_path)
71
+
72
+ span.set_attribute(
73
+ SpanAttributes.TRACELOOP_SPAN_KIND, tlp_span_kind.value
74
+ )
75
+ span.set_attribute(SpanAttributes.TRACELOOP_ENTITY_NAME, entity_name)
76
+ if version:
77
+ span.set_attribute(SpanAttributes.TRACELOOP_ENTITY_VERSION, version)
78
+
79
+ try:
80
+ if _should_send_prompts():
81
+ span.set_attribute(
82
+ SpanAttributes.TRACELOOP_ENTITY_INPUT,
83
+ _json_dumps({"args": args, "kwargs": kwargs}),
84
+ )
85
+ except TypeError:
86
+ pass
87
+
88
+ res = fn(*args, **kwargs)
89
+
90
+ # span will be ended in the generator
91
+ if isinstance(res, types.GeneratorType):
92
+ return _handle_generator(span, res)
93
+
94
+ try:
95
+ if _should_send_prompts():
96
+ span.set_attribute(
97
+ SpanAttributes.TRACELOOP_ENTITY_OUTPUT,
98
+ _json_dumps(res),
99
+ )
100
+ except TypeError:
101
+ pass
102
+
103
+ span.end()
104
+ context_api.detach(ctx_token)
105
+
106
+ return res
107
+
108
+ return wrap
109
+
110
+ return decorate
111
+
112
+
113
+ def entity_class(
114
+ name: Optional[str],
115
+ version: Optional[int],
116
+ method_name: str,
117
+ tlp_span_kind: Optional[TraceloopSpanKindValues] = TraceloopSpanKindValues.TASK,
118
+ ):
119
+ def decorator(cls):
120
+ task_name = name if name else camel_to_snake(cls.__name__)
121
+ method = getattr(cls, method_name)
122
+ setattr(
123
+ cls,
124
+ method_name,
125
+ entity_method(name=task_name, version=version, tlp_span_kind=tlp_span_kind)(
126
+ method
127
+ ),
128
+ )
129
+ return cls
130
+
131
+ return decorator
132
+
133
+
134
+ # Async Decorators
135
+
136
+
137
+ def aentity_method(
138
+ name: Optional[str] = None,
139
+ version: Optional[int] = None,
140
+ tlp_span_kind: Optional[TraceloopSpanKindValues] = TraceloopSpanKindValues.TASK,
141
+ ):
142
+ def decorate(fn):
143
+ @wraps(fn)
144
+ async def wrap(*args, **kwargs):
145
+ if not TracerWrapper.verify_initialized():
146
+ print("Tracer not initialized")
147
+ return await fn(*args, **kwargs)
148
+
149
+ entity_name = name or fn.__name__
150
+ if tlp_span_kind in [
151
+ TraceloopSpanKindValues.WORKFLOW,
152
+ TraceloopSpanKindValues.AGENT,
153
+ ]:
154
+ set_workflow_name(entity_name)
155
+ span_name = f"{entity_name}.{tlp_span_kind.value}"
156
+
157
+ with get_tracer() as tracer:
158
+ span = tracer.start_span(span_name)
159
+ ctx = trace.set_span_in_context(span)
160
+ ctx_token = context_api.attach(ctx)
161
+
162
+ if tlp_span_kind in [
163
+ TraceloopSpanKindValues.TASK,
164
+ TraceloopSpanKindValues.TOOL,
165
+ ]:
166
+ entity_path = get_chained_entity_path(entity_name)
167
+ set_entity_path(entity_path)
168
+
169
+ span.set_attribute(
170
+ SpanAttributes.TRACELOOP_SPAN_KIND, tlp_span_kind.value
171
+ )
172
+ span.set_attribute(SpanAttributes.TRACELOOP_ENTITY_NAME, entity_name)
173
+ if version:
174
+ span.set_attribute(SpanAttributes.TRACELOOP_ENTITY_VERSION, version)
175
+
176
+ try:
177
+ if _should_send_prompts():
178
+ span.set_attribute(
179
+ SpanAttributes.TRACELOOP_ENTITY_INPUT,
180
+ _json_dumps({"args": args, "kwargs": kwargs}),
181
+ )
182
+ except TypeError:
183
+ pass
184
+
185
+ res = await fn(*args, **kwargs)
186
+
187
+ # span will be ended in the generator
188
+ if isinstance(res, types.AsyncGeneratorType):
189
+ return await _ahandle_generator(span, ctx_token, res)
190
+
191
+ try:
192
+ if _should_send_prompts():
193
+ span.set_attribute(
194
+ SpanAttributes.TRACELOOP_ENTITY_OUTPUT, json.dumps(res)
195
+ )
196
+ except TypeError:
197
+ pass
198
+
199
+ span.end()
200
+ context_api.detach(ctx_token)
201
+
202
+ return res
203
+
204
+ return wrap
205
+
206
+ return decorate
207
+
208
+
209
+ def aentity_class(
210
+ name: Optional[str],
211
+ version: Optional[int],
212
+ method_name: str,
213
+ tlp_span_kind: Optional[TraceloopSpanKindValues] = TraceloopSpanKindValues.TASK,
214
+ ):
215
+ def decorator(cls):
216
+ task_name = name if name else camel_to_snake(cls.__name__)
217
+ method = getattr(cls, method_name)
218
+ setattr(
219
+ cls,
220
+ method_name,
221
+ aentity_method(
222
+ name=task_name, version=version, tlp_span_kind=tlp_span_kind
223
+ )(method),
224
+ )
225
+ return cls
226
+
227
+ return decorator
228
+
229
+
230
+ def _handle_generator(span, res):
231
+ # for some reason the SPAN_KEY is not being set in the context of the generator, so we re-set it
232
+ context_api.attach(trace.set_span_in_context(span))
233
+ yield from res
234
+
235
+ span.end()
236
+
237
+ # Note: we don't detach the context here as this fails in some situations
238
+ # https://github.com/open-telemetry/opentelemetry-python/issues/2606
239
+ # This is not a problem since the context will be detached automatically during garbage collection
240
+
241
+
242
+ async def _ahandle_generator(span, ctx_token, res):
243
+ async for part in res:
244
+ yield part
245
+
246
+ span.end()
247
+ context_api.detach(ctx_token)
248
+
249
+
250
+ def _should_send_prompts():
251
+ return (
252
+ os.getenv("TRACELOOP_TRACE_CONTENT") or "true"
253
+ ).lower() == "true" or context_api.get_value("override_enable_content_tracing")