Skip to content

Langchain instrumentor implementation #3662

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

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
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
7 changes: 7 additions & 0 deletions docs/instrumentation-genai/langchain/langchain.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
OpenTelemetry Jinja2 Instrumentation
====================================

.. automodule:: opentelemetry.instrumentation.langchain
:members:
:undoc-members:
:show-inheritance:
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from typing import Collection
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper

from opentelemetry.trace import get_tracer
from opentelemetry.instrumentation.utils import unwrap

# from opentelemetry.instrumentation.langchain_v2.version import __version__
from opentelemetry.instrumentation.langchain.version import __version__
from opentelemetry.instrumentation.langchain_v2.callback_handler import OpenTelemetryCallbackHandler
from opentelemetry.instrumentation.langchain_v2.async_callback_handler import OpenTelemetryAsyncCallbackHandler


__all__ = ["OpenTelemetryCallbackHandler"]

_instruments = ("langchain >= 0.1.0",)

class LangChainInstrumentor(BaseInstrumentor):

def instrumentation_dependencies(cls) -> Collection[str]:
return _instruments

def _instrument(self, **kwargs):
tracer_provider = kwargs.get("tracer_provider")
tracer = get_tracer(__name__, __version__, tracer_provider)

otelCallbackHandler = OpenTelemetryCallbackHandler(tracer)

wrap_function_wrapper(
module="langchain_core.callbacks",
name="BaseCallbackManager.__init__",
wrapper=_BaseCallbackManagerInitWrapper(otelCallbackHandler),
)

def _uninstrument(self, **kwargs):
unwrap("langchain_core.callbacks", "BaseCallbackManager.__init__")
if hasattr(self, "_wrapped"):
for module, name in self._wrapped:
unwrap(module, name)
self.handler = None

class _BaseCallbackManagerInitWrapper:
def __init__(self, callback_handler: "OpenTelemetryCallbackHandler"):
self.callback_handler = callback_handler
self._wrapped = []

def __call__(
self,
wrapped,
instance,
args,
kwargs,
) -> None:
wrapped(*args, **kwargs)
for handler in instance.inheritable_handlers:
if isinstance(handler, OpenTelemetryCallbackHandler):
return None
else:
instance.add_handler(self.callback_handler, True)
Loading