Skip to content

The agent engineering platform.

fix(huggingface): hide `huggingfacehub_api_token` from `repr` (#41047)

Emil F6564f7e017d8
diff --git a/libs/partners/huggingface/langchain_huggingface/llms/huggingface_endpoint.py b/libs/partners/huggingface/langchain_huggingface/llms/huggingface_endpoint.py
index 92c14bb18d..99a139f90b 100644
--- a/libs/partners/huggingface/langchain_huggingface/llms/huggingface_endpoint.py
+++ b/libs/partners/huggingface/langchain_huggingface/llms/huggingface_endpoint.py
@@ -108,7 +108,8 @@ class HuggingFaceEndpoint(LLM):
available providers can be found in the [huggingface_hub documentation](https://huggingface.co/docs/huggingface_hub/guides/inference#supported-providers-and-tasks)."""
huggingfacehub_api_token: str | None = Field(
- default_factory=from_env("HUGGINGFACEHUB_API_TOKEN", default=None)
+ default_factory=from_env("HUGGINGFACEHUB_API_TOKEN", default=None),
+ repr=False,
)
max_new_tokens: int = 512
diff --git a/libs/partners/huggingface/tests/unit_tests/test_huggingface_endpoint.py b/libs/partners/huggingface/tests/unit_tests/test_huggingface_endpoint.py
index 076f261464..9c95c5ff90 100644
--- a/libs/partners/huggingface/tests/unit_tests/test_huggingface_endpoint.py
+++ b/libs/partners/huggingface/tests/unit_tests/test_huggingface_endpoint.py
@@ -76,3 +76,24 @@ def test_huggingface_hosted_endpoint_keeps_api_key(
call_kwargs = mock_inference_client.call_args[1]
assert call_kwargs.get("api_key") == "hf_xxx"
+
+
+@patch("huggingface_hub.AsyncInferenceClient")
+@patch("huggingface_hub.InferenceClient")
+def test_api_token_not_in_repr_or_serialized(
+ mock_inference_client: MagicMock,
+ mock_async_client: MagicMock,
+) -> None:
+ """The token must not leak via `repr`, which tracers receive as `serialized`."""
+ mock_inference_client.return_value = MagicMock()
+ mock_async_client.return_value = MagicMock()
+
+ llm = HuggingFaceEndpoint( # type: ignore[call-arg]
+ endpoint_url="https://abc.huggingface.co/inference",
+ huggingfacehub_api_token="hf_secret_token", # noqa: S106
+ )
+
+ assert "hf_secret_token" not in repr(llm)
+ assert "hf_secret_token" not in str(llm._serialized)
+ # Still handed to the client.
+ assert mock_inference_client.call_args[1]["api_key"] == "hf_secret_token"