fix: add check before setting up LangSmithTracer (#2771)

* fix: add check before setting up LangSmithTracer

Refactor the LangSmithTracer class in langsmith.py to improve error handling during initialization. The setup_langsmith method now checks for the presence of the LANGCHAIN_API_KEY environment variable before proceeding with the setup. This ensures that the tracer is only initialized when the necessary API key is available. Additionally, the order of operations within the __init__ method has been adjusted to ensure that the setup_langsmith method is called after the necessary attributes are assigned. These changes enhance the reliability and robustness of the LangSmithTracer.

* fix(langsmith.py): add conditional check to prevent executing code if tracer is not ready

---------

Co-authored-by: Lucas Oliveira <62335616+lucaseduoli@users.noreply.github.com>
This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-07-17 18:45:28 -03:00 committed by GitHub
commit 31a3c4985a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -17,13 +17,16 @@ if TYPE_CHECKING:
class LangSmithTracer(BaseTracer):
def __init__(self, trace_name: str, trace_type: str, project_name: str, trace_id: UUID):
from langsmith.run_trees import RunTree
self.trace_name = trace_name
self.trace_type = trace_type
self.project_name = project_name
self.trace_id = trace_id
try:
self._ready = self.setup_langsmith()
if not self._ready:
return
from langsmith.run_trees import RunTree
self.trace_name = trace_name
self.trace_type = trace_type
self.project_name = project_name
self.trace_id = trace_id
self._run_tree = RunTree(
project_name=self.project_name,
name=self.trace_name,
@ -32,7 +35,6 @@ class LangSmithTracer(BaseTracer):
)
self._run_tree.add_event({"name": "Start", "time": datetime.now(timezone.utc).isoformat()})
self._children: dict[str, RunTree] = {}
self._ready = self.setup_langsmith()
except Exception as e:
logger.debug(f"Error setting up LangSmith tracer: {e}")
self._ready = False
@ -42,6 +44,8 @@ class LangSmithTracer(BaseTracer):
return self._ready
def setup_langsmith(self):
if os.getenv("LANGCHAIN_API_KEY") is None:
return False
try:
from langsmith import Client
@ -113,6 +117,8 @@ class LangSmithTracer(BaseTracer):
error: Exception | None = None,
logs: list[Log | dict] = [],
):
if not self._ready:
return
child = self._children[trace_name]
raw_outputs = {}
processed_outputs = {}
@ -144,6 +150,8 @@ class LangSmithTracer(BaseTracer):
error: Exception | None = None,
metadata: dict[str, Any] | None = None,
):
if not self._ready:
return
self._run_tree.add_metadata({"inputs": inputs})
if metadata:
self._run_tree.add_metadata(metadata)