Skip to content

Commit 33629d3

Browse files
committed
fix(integrations): make langchain package optional for LangchainIntegration
1 parent 567a91a commit 33629d3

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

sentry_sdk/integrations/langchain.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929

3030

3131
try:
32-
from langchain.agents import AgentExecutor
3332
from langchain_core.agents import AgentFinish
3433
from langchain_core.callbacks import (
3534
BaseCallbackHandler,
@@ -72,10 +71,13 @@ def __init__(self, include_prompts=True, max_spans=1024):
7271
def setup_once():
7372
# type: () -> None
7473
manager._configure = _wrap_configure(manager._configure)
74+
try:
75+
from langchain.agents import AgentExecutor
7576

76-
if AgentExecutor is not None:
7777
AgentExecutor.invoke = _wrap_agent_executor_invoke(AgentExecutor.invoke)
7878
AgentExecutor.stream = _wrap_agent_executor_stream(AgentExecutor.stream)
79+
except ImportError:
80+
pass
7981

8082

8183
class WatchedSpan:

tests/integrations/langchain/test_langchain.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import builtins
2+
import importlib
13
from typing import List, Optional, Any, Iterator
24
from unittest import mock
35
from unittest.mock import Mock
@@ -382,6 +384,30 @@ def test_span_origin(sentry_init, capture_events):
382384
assert span["origin"] == "auto.ai.langchain"
383385

384386

387+
def test_langchain_module_is_optional():
388+
"""
389+
Test that the LangchainIntegration can be imported and set up
390+
even if the langchain module is not installed.
391+
"""
392+
393+
def hide_langchain(name, *args):
394+
if name == "langchain" or name.startswith("langchain."):
395+
raise ModuleNotFoundError("mocked: langchain not installed")
396+
return mock.DEFAULT
397+
398+
integration_module = importlib.import_module(LangchainIntegration.__module__)
399+
400+
with (
401+
mock.patch("sentry_sdk.integrations.langchain.manager"),
402+
mock.patch.object(
403+
builtins, "__import__", side_effect=hide_langchain
404+
) as mock_import,
405+
):
406+
importlib.reload(integration_module)
407+
LangchainIntegration().setup_once()
408+
mock_import.assert_any_call("langchain.agents", *([mock.ANY] * 4))
409+
410+
385411
def test_manual_callback_no_duplication(sentry_init):
386412
"""
387413
Test that when a user manually provides a SentryLangchainCallback,

0 commit comments

Comments
 (0)