Repository navigation
fix: connect to Pinecone lazily instead of at import time #188
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,32 +1,41 @@ | ||
| """ | ||
| vector_store.py | ||
| ------------------ | ||
| Initializes and manages the Pinecone vector database connection for the Perspective API. | ||
| Manages the Pinecone vector database connection for the Perspective API. | ||
|
|
||
| This module: | ||
| - Loads Pinecone credentials from environment variables. | ||
| - Creates the Pinecone index if it does not exist. | ||
| - Connects to the specified index for vector operations. | ||
| The client and index are created lazily by get_index(), on the first vector | ||
| operation rather than at import. Importing this module never requires | ||
| credentials or network access, so the API can start while Pinecone is | ||
| unconfigured or unreachable; a missing key or a failed connection is then | ||
| reported where storage is actually requested, which is also what lets the | ||
| pipeline treat vector failures as non-fatal. | ||
|
|
||
| Attributes: | ||
| PINECONE_API_KEY (str): API key for authenticating with Pinecone. | ||
| index (pinecone.Index): Connected Pinecone index instance. | ||
| Functions: | ||
| get_index() | ||
| Returns the connected Pinecone index, creating the client and the | ||
| index itself on first call. The handle is cached and initialization | ||
| is serialized so concurrent first callers connect once. | ||
|
|
||
| The index name, dimensions, metric, cloud and region come from app.config. | ||
| The index name, dimensions, metric, cloud, region and readiness timeouts | ||
| come from app.config. | ||
|
|
||
| Raises: | ||
| ValueError: If `PINECONE_API_KEY` is not set in environment variables. | ||
| ValueError: If `PINECONE_API_KEY` is not set when a connection is requested. | ||
| RuntimeError: If Pinecone initialization or index connection fails. | ||
| """ | ||
|
|
||
| import os | ||
| import threading | ||
| import time | ||
| from dotenv import load_dotenv | ||
| from pinecone import Pinecone, ServerlessSpec | ||
| from app.logging.logging_config import setup_logger | ||
| from app.config import ( | ||
| PINECONE_CLOUD, | ||
| PINECONE_DIMENSIONS, | ||
| PINECONE_INDEX_NAME, | ||
| PINECONE_INDEX_READY_POLL_SECONDS, | ||
| PINECONE_INDEX_READY_TIMEOUT_SECONDS, | ||
| PINECONE_METRIC, | ||
| PINECONE_REGION, | ||
| ) | ||
|
|
@@ -36,31 +45,83 @@ | |
| # Load environment variables from .env file | ||
| load_dotenv() | ||
|
|
||
| # Load Pinecone credentials from environment variables | ||
| PINECONE_API_KEY = os.getenv("PINECONE_API_KEY") | ||
| if not PINECONE_API_KEY: | ||
| raise ValueError("PINECONE_API_KEY environment variable is required") | ||
| try: | ||
| # Initialize Pinecone client | ||
| pc = Pinecone(api_key=PINECONE_API_KEY) | ||
|
|
||
| except Exception as e: | ||
| raise RuntimeError(f"Error occured while intialising pinecone client:{e}") | ||
|
|
||
| # Create index if it doesn't exist | ||
| if not pc.has_index(PINECONE_INDEX_NAME): | ||
| logger.info(f"Creating index: {PINECONE_INDEX_NAME}") | ||
| pc.create_index( | ||
| name=PINECONE_INDEX_NAME, | ||
| dimension=PINECONE_DIMENSIONS, | ||
| metric=PINECONE_METRIC, | ||
| spec=ServerlessSpec(cloud=PINECONE_CLOUD, region=PINECONE_REGION), | ||
| ) | ||
| else: | ||
| logger.info(f"Index '{PINECONE_INDEX_NAME}' already exists") | ||
|
|
||
| try: | ||
| # Connect to the index | ||
| index = pc.Index(PINECONE_INDEX_NAME) | ||
| except Exception as e: | ||
| raise RuntimeError(f"Error occured while connecting to the index {PINECONE_INDEX_NAME}:{e}") | ||
| _index = None | ||
| # Sync callers can reach get_index() concurrently through the threadpool; | ||
| # without a lock every first caller would try to create the index. | ||
| _index_lock = threading.Lock() | ||
|
|
||
|
|
||
| def get_index(): | ||
| """ | ||
| Connect to the Pinecone index on first use and cache the handle. | ||
|
|
||
| A failed attempt caches nothing, so the next call retries the connection | ||
| instead of reusing a half-initialized state. | ||
| """ | ||
| global _index | ||
| if _index is not None: | ||
| return _index | ||
| with _index_lock: | ||
| if _index is None: | ||
| _index = _connect_index() | ||
| return _index | ||
|
|
||
|
|
||
| def _connect_index(): | ||
| """Open the client, ensure the index exists and return a handle to it.""" | ||
| api_key = os.getenv("PINECONE_API_KEY") | ||
| if not api_key: | ||
| raise ValueError("PINECONE_API_KEY environment variable is required") | ||
| try: | ||
| pc = Pinecone(api_key=api_key) | ||
| except Exception as e: | ||
| raise RuntimeError(f"Error occured while intialising pinecone client:{e}") | ||
|
|
||
| try: | ||
| # Create index if it doesn't exist | ||
| if not pc.has_index(PINECONE_INDEX_NAME): | ||
| logger.info(f"Creating index: {PINECONE_INDEX_NAME}") | ||
| pc.create_index( | ||
| name=PINECONE_INDEX_NAME, | ||
| dimension=PINECONE_DIMENSIONS, | ||
| metric=PINECONE_METRIC, | ||
| spec=ServerlessSpec(cloud=PINECONE_CLOUD, region=PINECONE_REGION), | ||
| ) | ||
| _wait_until_ready(pc) | ||
| else: | ||
| logger.info(f"Index '{PINECONE_INDEX_NAME}' already exists") | ||
| except Exception as e: | ||
| raise RuntimeError( | ||
| f"Error occured while preparing the index {PINECONE_INDEX_NAME}:{e}" | ||
| ) | ||
|
Comment on lines
+76
to
+96
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
|
||
| try: | ||
| return pc.Index(PINECONE_INDEX_NAME) | ||
| except Exception as e: | ||
| raise RuntimeError( | ||
|
Comment on lines
+88
to
+101
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| f"Error occured while connecting to the index {PINECONE_INDEX_NAME}:{e}" | ||
| ) | ||
|
|
||
|
|
||
| def _wait_until_ready(pc) -> None: | ||
| """ | ||
| Wait for a newly created index to finish provisioning, up to a deadline. | ||
|
|
||
| Serverless indexes accept writes only once ready, and the SDK reports | ||
| readiness through describe_index; an SDK that exposes no ready flag is | ||
| not blocked on. | ||
| """ | ||
| deadline = time.monotonic() + PINECONE_INDEX_READY_TIMEOUT_SECONDS | ||
| while True: | ||
| status = getattr(pc.describe_index(PINECONE_INDEX_NAME), "status", None) | ||
| ready = getattr( | ||
| status, "ready", status.get("ready") if isinstance(status, dict) else True | ||
| ) | ||
| if ready is not False: | ||
| return | ||
| if time.monotonic() >= deadline: | ||
| raise RuntimeError( | ||
| f"Index {PINECONE_INDEX_NAME} was still not ready after " | ||
| f"{PINECONE_INDEX_READY_TIMEOUT_SECONDS} seconds" | ||
| ) | ||
| time.sleep(PINECONE_INDEX_READY_POLL_SECONDS) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,10 +5,12 @@ | |
| vector database for Retrieval-Augmented Generation (RAG) workflows. | ||
|
|
||
| This module: | ||
| - Loads Pinecone credentials from environment variables. | ||
| - Connects to the Pinecone index named in app.config. | ||
| - Defines `search_pinecone()` to search stored vector embeddings and | ||
| retrieve the most relevant matches. | ||
| - Connects through app.db.vector_store.get_index(), which opens the | ||
| Pinecone connection lazily on the first store or search instead of at | ||
| import, so a missing PINECONE_API_KEY does not stop the API from | ||
| starting. | ||
|
|
||
| Functions: | ||
| search_pinecone(query: str, top_k: int = RAG_TOP_K) -> list[dict]: | ||
|
|
@@ -20,26 +22,19 @@ | |
|
|
||
| Dependencies: | ||
| - app.modules.chat.embed_query (for generating embeddings) | ||
| - pinecone (Pinecone client library) | ||
| - app.db.vector_store (for the shared Pinecone index connection) | ||
| """ | ||
|
|
||
|
|
||
| from pinecone import Pinecone | ||
| from dotenv import load_dotenv | ||
| from app.db.vector_store import get_index | ||
| from app.modules.chat.embed_query import embed_query | ||
| from app.config import PINECONE_INDEX_NAME, PINECONE_NAMESPACE, RAG_TOP_K | ||
| import os | ||
|
|
||
| load_dotenv() | ||
|
|
||
| pc = Pinecone(os.getenv("PINECONE_API_KEY")) | ||
| index = pc.Index(PINECONE_INDEX_NAME) | ||
| from app.config import PINECONE_NAMESPACE, RAG_TOP_K | ||
|
|
||
|
|
||
| def search_pinecone(query: str, top_k: int = RAG_TOP_K): | ||
| embeddings = embed_query(query) | ||
|
|
||
| results = index.query( | ||
| results = get_index().query( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| vector=embeddings, top_k=top_k, include_metadata=True, namespace=PINECONE_NAMESPACE | ||
| ) | ||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.