From 8c56e925665a4d325a10e58d57ff3aebaec8cc10 Mon Sep 17 00:00:00 2001 From: Felipe Lopes Date: Mon, 24 Apr 2023 17:55:34 -0700 Subject: [PATCH] feat: add private weaviate api_key support on from_texts (#3139) This PR adds support for providing a Weaviate API Key to the VectorStore methods `from_documents` and `from_texts`. With this addition, users can authenticate to Weaviate and make requests to private Weaviate servers when using these methods. ## Motivation Currently, LangChain's VectorStore methods do not provide a way to authenticate to Weaviate. This limits the functionality of the library and makes it more difficult for users to take advantage of Weaviate's features. This PR addresses this issue by adding support for providing a Weaviate API Key as extra parameter used in the `from_texts` method. ## Contributing Guidelines I have read the [contributing guidelines](https://github.com/hwchase17/langchain/blob/72b7d76d79b0e187426787616d96257b64292119/.github/CONTRIBUTING.md) and the PR code passes the following tests: - [x] make format - [x] make lint - [x] make coverage - [x] make test --- langchain/vectorstores/weaviate.py | 42 +++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/langchain/vectorstores/weaviate.py b/langchain/vectorstores/weaviate.py index dd5e79ca..0ad33b1a 100644 --- a/langchain/vectorstores/weaviate.py +++ b/langchain/vectorstores/weaviate.py @@ -25,6 +25,35 @@ def _default_schema(index_name: str) -> Dict: } +def _create_weaviate_client(**kwargs: Any) -> Any: + client = kwargs.get("client") + + if client is not None: + return client + + weaviate_url = get_from_dict_or_env(kwargs, "weaviate_url", "WEAVIATE_URL") + weaviate_api_key = get_from_dict_or_env( + kwargs, "weaviate_api_key", "WEAVIATE_API_KEY", None + ) + + try: + import weaviate + except ImportError: + raise ValueError( + "Could not import weaviate python package. " + "Please install it with `pip instal weaviate-client`" + ) + + auth = ( + weaviate.auth.AuthApiKey(api_key=weaviate_api_key) + if weaviate_api_key is not None + else None + ) + client = weaviate.Client(weaviate_url, auth_client_secret=auth) + + return client + + class Weaviate(VectorStore): """Wrapper around Weaviate vector database. @@ -248,18 +277,11 @@ class Weaviate(VectorStore): weaviate_url="http://localhost:8080" ) """ - weaviate_url = get_from_dict_or_env(kwargs, "weaviate_url", "WEAVIATE_URL") - try: - from weaviate import Client - from weaviate.util import get_valid_uuid - except ImportError: - raise ValueError( - "Could not import weaviate python package. " - "Please install it with `pip instal weaviate-client`" - ) + client = _create_weaviate_client(**kwargs) + + from weaviate.util import get_valid_uuid - client = Client(weaviate_url) index_name = kwargs.get("index_name", f"LangChain_{uuid4().hex}") embeddings = embedding.embed_documents(texts) if embedding else None text_key = "text"