Skip to content
Closed
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
6 changes: 4 additions & 2 deletions sentry_sdk/integrations/langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@


try:
from langchain.agents import AgentExecutor
from langchain_core.agents import AgentFinish
from langchain_core.callbacks import (
BaseCallbackHandler,
Expand Down Expand Up @@ -72,10 +71,13 @@ def __init__(self, include_prompts=True, max_spans=1024):
def setup_once():
# type: () -> None
manager._configure = _wrap_configure(manager._configure)
try:
from langchain.agents import AgentExecutor

if AgentExecutor is not None:
AgentExecutor.invoke = _wrap_agent_executor_invoke(AgentExecutor.invoke)
AgentExecutor.stream = _wrap_agent_executor_stream(AgentExecutor.stream)
except ImportError:
pass


class WatchedSpan:
Expand Down
31 changes: 31 additions & 0 deletions tests/integrations/langchain/test_langchain.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import importlib
import re
import sys
from typing import List, Optional, Any, Iterator
from unittest import mock
from unittest.mock import Mock
Expand Down Expand Up @@ -382,6 +385,34 @@ def test_span_origin(sentry_init, capture_events):
assert span["origin"] == "auto.ai.langchain"


def test_langchain_module_is_optional(monkeypatch):
"""
Test that the LangchainIntegration can be imported and set up
even if the langchain module is not installed.
"""

lc_re = re.compile(r"^langchain(\..*)?$")

stripped_modules = {
name: mod for name, mod in sys.modules.items() if not lc_re.match(name)
}

class HideModuleImportHook(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=..., /):
if lc_re.match(fullname):
raise ModuleNotFoundError(f"No module named '{fullname}'")
return None

with (
mock.patch.dict(sys.modules, stripped_modules, clear=True),
mock.patch.object(sys, "meta_path", [HideModuleImportHook(), *sys.meta_path]),
mock.patch("sentry_sdk.integrations.langchain.manager"),
):
from sentry_sdk.integrations.langchain import LangchainIntegration

LangchainIntegration().setup_once()


def test_manual_callback_no_duplication(sentry_init):
"""
Test that when a user manually provides a SentryLangchainCallback,
Expand Down
Loading