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

Change recording to create a span of type "record_root" #1703

Open
wants to merge 8 commits into
base: garett/SNOW-1854278
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
188 changes: 152 additions & 36 deletions examples/experimental/otel_exporter.ipynb
Original file line number Diff line number Diff line change
@@ -1,14 +1,153 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# !pip install opentelemetry-api\n",
"# !pip install opentelemetry-sdk"
]
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# !pip install opentelemetry-api\n",
"# !pip install opentelemetry-sdk"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"import sys\n",
"\n",
"# Add base dir to path to be able to access test folder.\n",
"base_dir = Path().cwd().parent.parent.resolve()\n",
"if str(base_dir) not in sys.path:\n",
" print(f\"Adding {base_dir} to sys.path\")\n",
" sys.path.append(str(base_dir))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import logging\n",
"\n",
"root = logging.getLogger()\n",
"root.setLevel(logging.DEBUG)\n",
"handler = logging.StreamHandler(sys.stdout)\n",
"handler.setLevel(logging.DEBUG)\n",
"handler.addFilter(logging.Filter(\"trulens\"))\n",
"formatter = logging.Formatter(\n",
" \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n",
")\n",
"handler.setFormatter(formatter)\n",
"root.addHandler(handler)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from trulens.experimental.otel_tracing.core.instrument import instrument\n",
"\n",
"\n",
"class TestApp:\n",
" @instrument()\n",
" def respond_to_query(self, query: str) -> str:\n",
" return f\"answer: {self.nested(query)}\"\n",
"\n",
" @instrument(attributes={\"nested_attr1\": \"value1\"})\n",
" def nested(self, query: str) -> str:\n",
" return f\"nested: {self.nested2(query)}\"\n",
"\n",
" @instrument(\n",
" attributes=lambda ret, exception, *args, **kwargs: {\n",
" \"nested2_ret\": ret,\n",
" \"nested2_args[0]\": args[0],\n",
" }\n",
" )\n",
" def nested2(self, query: str) -> str:\n",
" nested_result = \"\"\n",
"\n",
" try:\n",
" nested_result = self.nested3(query)\n",
" except Exception:\n",
" pass\n",
"\n",
" return f\"nested2: {nested_result}\"\n",
"\n",
" @instrument(\n",
" attributes=lambda ret, exception, *args, **kwargs: {\n",
" \"nested3_ex\": exception.args if exception else None,\n",
" \"nested3_ret\": ret,\n",
" \"selector_name\": \"special\",\n",
" \"cows\": \"moo\",\n",
" }\n",
" )\n",
" def nested3(self, query: str) -> str:\n",
" if query == \"throw\":\n",
" raise ValueError(\"nested3 exception\")\n",
" return \"nested3\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import dotenv\n",
"from trulens.core.session import TruSession\n",
"from trulens.experimental.otel_tracing.core.init import init\n",
"\n",
"dotenv.load_dotenv()\n",
"\n",
"session = TruSession()\n",
"session.experimental_enable_feature(\"otel_tracing\")\n",
"session.reset_database()\n",
"init(session, debug=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from trulens.apps.custom import TruCustomApp\n",
"\n",
"test_app = TestApp()\n",
"custom_app = TruCustomApp(test_app)\n",
"\n",
"with custom_app as recording:\n",
" test_app.respond_to_query(\"test\")\n",
"\n",
"with custom_app as recording:\n",
" test_app.respond_to_query(\"throw\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "trulens",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3"
}
},
{
"cell_type": "code",
Expand Down Expand Up @@ -65,33 +204,13 @@
" return f\"nested: {self.nested2(query)}\"\n",
"\n",
" @instrument(\n",
" attributes=lambda ret, exception, *args, **kwargs: {\n",
" attributes=lambda ret, *args, **kwargs: {\n",
" \"nested2_ret\": ret,\n",
" \"nested2_args[0]\": args[0],\n",
" }\n",
" )\n",
" def nested2(self, query: str) -> str:\n",
" nested_result = \"\"\n",
"\n",
" try:\n",
" nested_result = self.nested3(query)\n",
" except Exception:\n",
" pass\n",
"\n",
" return f\"nested2: {nested_result}\"\n",
"\n",
" @instrument(\n",
" attributes=lambda ret, exception, *args, **kwargs: {\n",
" \"nested3_ex\": exception.args if exception else None,\n",
" \"nested3_ret\": ret,\n",
" \"selector_name\": \"special\",\n",
" \"cows\": \"moo\",\n",
" }\n",
" )\n",
" def nested3(self, query: str) -> str:\n",
" if query == \"throw\":\n",
" raise ValueError(\"nested3 exception\")\n",
" return \"nested3\""
" return f\"nested2: {query}\""
]
},
{
Expand Down Expand Up @@ -124,10 +243,7 @@
"custom_app = TruCustomApp(test_app)\n",
"\n",
"with custom_app as recording:\n",
" test_app.respond_to_query(\"test\")\n",
"\n",
"with custom_app as recording:\n",
" test_app.respond_to_query(\"throw\")"
" test_app.respond_to_query(\"test\")"
]
}
],
Expand Down
38 changes: 28 additions & 10 deletions src/core/trulens/core/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from abc import ABC
from abc import ABCMeta
from abc import abstractmethod
import contextlib
import contextvars
import datetime
import inspect
Expand Down Expand Up @@ -421,6 +422,17 @@ def tru(self) -> core_connector.DBConnector:
pydantic.PrivateAttr(default_factory=dict)
)

token: Optional[object] = None
"""
OTEL context token for the current context manager.
"""

span_context: Optional[contextlib.AbstractContextManager] = None
"""
Span context manager. Required to help keep track of the appropriate span context
to enter/exit.
"""

def __init__(
self,
connector: Optional[core_connector.DBConnector] = None,
Expand Down Expand Up @@ -1048,27 +1060,29 @@ def __enter__(self):
if self.session.experimental_feature(
core_experimental.Feature.OTEL_TRACING
):
from trulens.experimental.otel_tracing.core.app import _App
from trulens.experimental.otel_tracing.core.instrument import (
App as OTELApp,
)

return _App.__enter__(self)
return OTELApp.__enter__(self)

ctx = core_instruments._RecordingContext(app=self)

token = self.recording_contexts.set(ctx)
ctx.token = token

# self._set_context_vars()

return ctx

# For use as a context manager.
def __exit__(self, exc_type, exc_value, exc_tb):
if self.session.experimental_feature(
core_experimental.Feature.OTEL_TRACING
):
from trulens.experimental.otel_tracing.core.app import _App
from trulens.experimental.otel_tracing.core.instrument import (
App as OTELApp,
)

return _App.__exit__(self, exc_type, exc_value, exc_tb)
return OTELApp.__exit__(self, exc_type, exc_value, exc_tb)

ctx = self.recording_contexts.get()
self.recording_contexts.reset(ctx.token)
Expand All @@ -1085,9 +1099,11 @@ async def __aenter__(self):
if self.session.experimental_feature(
core_experimental.Feature.OTEL_TRACING
):
from trulens.experimental.otel_tracing.core.app import _App
from trulens.experimental.otel_tracing.core.instrument import (
App as OTELApp,
)

return await _App.__aenter__(self)
return OTELApp.__enter__(self)

ctx = core_instruments._RecordingContext(app=self)

Expand All @@ -1103,9 +1119,11 @@ async def __aexit__(self, exc_type, exc_value, exc_tb):
if self.session.experimental_feature(
core_experimental.Feature.OTEL_TRACING
):
from trulens.experimental.otel_tracing.core.app import _App
from trulens.experimental.otel_tracing.core.instrument import (
App as OTELApp,
)

return await _App.__aexit__(self, exc_type, exc_value, exc_tb)
return OTELApp.__exit__(self, exc_type, exc_value, exc_tb)

ctx = self.recording_contexts.get()
self.recording_contexts.reset(ctx.token)
Expand Down
Loading