community: callbacks guard_imports (#21173)

Issue: we have several helper functions to import third-party libraries
like import_uptrain in
[community.callbacks](https://api.python.langchain.com/en/latest/callbacks/langchain_community.callbacks.uptrain_callback.import_uptrain.html#langchain_community.callbacks.uptrain_callback.import_uptrain).
And we have core.utils.utils.guard_import that works exactly for this
purpose.
The import_<package> functions work inconsistently and rather be private
functions.
Change: replaced these functions with the guard_import function.

Related to #21133
This commit is contained in:
Leonid Ganeline
2024-05-07 15:04:54 -07:00
committed by GitHub
parent 416549bed2
commit 791d59a2c8
13 changed files with 73 additions and 178 deletions

View File

@@ -2,6 +2,7 @@ from types import ModuleType, SimpleNamespace
from typing import TYPE_CHECKING, Any, Callable, Dict
from langchain_core.tracers import BaseTracer
from langchain_core.utils import guard_import
if TYPE_CHECKING:
from uuid import UUID
@@ -23,29 +24,15 @@ def _get_run_type(run: "Run") -> str:
def import_comet_llm_api() -> SimpleNamespace:
"""Import comet_llm api and raise an error if it is not installed."""
try:
from comet_llm import (
experiment_info,
flush,
)
from comet_llm.chains import api as chain_api
from comet_llm.chains import (
chain,
span,
)
comet_llm = guard_import("comet_llm")
comet_llm_chains = guard_import("comet_llm.chains")
except ImportError:
raise ImportError(
"To use the CometTracer you need to have the "
"`comet_llm>=2.0.0` python package installed. Please install it with"
" `pip install -U comet_llm`"
)
return SimpleNamespace(
chain=chain,
span=span,
chain_api=chain_api,
experiment_info=experiment_info,
flush=flush,
chain=comet_llm_chains.chain,
span=comet_llm_chains.span,
chain_api=comet_llm_chains.api,
experiment_info=comet_llm.experiment_info,
flush=comet_llm.flush,
)