From da9fbd97b97485cefb52fead40c123ea4d8010c4 Mon Sep 17 00:00:00 2001 From: Luca Mannini <48441989+italianconcerto@users.noreply.github.com> Date: Thu, 23 Jan 2025 10:17:58 +0100 Subject: [PATCH] refactor: enhance PineconeIndex API key handling and request headers - Updated the constructor to retrieve the API key from environment variables if not provided. - Added a validation step to ensure the API key is present, raising a ValueError if missing. - Consolidated header management by using the instance's headers attribute for API requests, improving code clarity and maintainability. --- semantic_router/index/pinecone.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/semantic_router/index/pinecone.py b/semantic_router/index/pinecone.py index 427e33df..733395c9 100644 --- a/semantic_router/index/pinecone.py +++ b/semantic_router/index/pinecone.py @@ -132,7 +132,9 @@ class PineconeIndex(BaseIndex): init_async_index: bool = False, ): super().__init__() - self.api_key = api_key + self.api_key = api_key or os.getenv("PINECONE_API_KEY") + if not self.api_key: + raise ValueError("Pinecone API key is required.") self.headers = { "Api-Key": self.api_key, "Content-Type": "application/json", @@ -161,7 +163,6 @@ class PineconeIndex(BaseIndex): self.client = self._initialize_client(api_key=self.api_key) - # try initializing index self.index = self._init_index() @@ -186,7 +187,6 @@ class PineconeIndex(BaseIndex): return Pinecone(**pinecone_args) - def _init_index(self, force_create: bool = False) -> Union[Any, None]: """Initializing the index can be done after the object has been created to allow for the user to set the dimensions and other parameters. @@ -884,12 +884,10 @@ class PineconeIndex(BaseIndex): elif self.namespace: params["namespace"] = [self.namespace] - headers = { - "Api-Key": self.api_key, - } - async with aiohttp.ClientSession() as session: - async with session.get(url, params=params, headers=headers) as response: + async with session.get( + url, params=params, headers=self.headers + ) as response: if response.status != 200: error_text = await response.text() logger.error(f"Error fetching metadata: {error_text}") -- GitLab