diff --git a/.github/workflows/testing-integration.yaml b/.github/workflows/testing-integration.yaml index 3334becf5..c2ee05bf1 100644 --- a/.github/workflows/testing-integration.yaml +++ b/.github/workflows/testing-integration.yaml @@ -117,17 +117,17 @@ jobs: uses: ./.github/actions/setup-poetry - name: 'Run integration tests (REST, prod)' if: matrix.pineconeEnv == 'prod' - run: poetry run pytest tests/integration/control/serverless -s -v + run: poetry run pytest tests/integration/control/pod -s -v env: PINECONE_DEBUG_CURL: 'true' PINECONE_API_KEY: '${{ secrets.PINECONE_API_KEY }}' PINECONE_ENVIRONMENT: '${{ matrix.testConfig.pod.environment }}' GITHUB_BUILD_NUMBER: '${{ github.run_number }}-s-${{ matrix.testConfig.python-version}}' - DIMENSION: 1536 + DIMENSION: 2500 METRIC: 'cosine' - name: 'Run integration tests (REST, staging)' if: matrix.pineconeEnv == 'staging' - run: poetry run pytest tests/integration/control/serverless -s -v + run: poetry run pytest tests/integration/control/pod -s -v env: PINECONE_DEBUG_CURL: 'true' PINECONE_CONTROLLER_HOST: 'https://api-staging.pinecone.io' diff --git a/codegen/apis b/codegen/apis index fbd9d8d48..e9b47c76f 160000 --- a/codegen/apis +++ b/codegen/apis @@ -1 +1 @@ -Subproject commit fbd9d8d48c95b12c6b28aea4e496b6f28666d2d1 +Subproject commit e9b47c76f649656002f4911946ca6c4c4a6f04fc diff --git a/codegen/build-oas.sh b/codegen/build-oas.sh index 08074538a..21b9eca01 100755 --- a/codegen/build-oas.sh +++ b/codegen/build-oas.sh @@ -12,6 +12,7 @@ update_apis_repo() { echo "Updating apis repo" pushd codegen/apis git fetch + git checkout main git pull just build popd @@ -21,6 +22,7 @@ update_templates_repo() { echo "Updating templates repo" pushd codegen/python-oas-templates git fetch + git checkout main git pull popd } @@ -126,6 +128,8 @@ extract_shared_classes() { done done done + + echo "API_VERSION = '${version}'" > "${target_directory}/__init__.py" } update_apis_repo diff --git a/pinecone/__init__.py b/pinecone/__init__.py index 46d7fc186..029996119 100644 --- a/pinecone/__init__.py +++ b/pinecone/__init__.py @@ -14,8 +14,4 @@ from .data import * from .models import * -from .core.openapi.control.models import ( - IndexModel, -) - from .utils import __version__ diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index 426687095..57833659e 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -1,7 +1,7 @@ import time import warnings import logging -from typing import Optional, Dict, Any, Union, List, Tuple, cast, NamedTuple +from typing import Optional, Dict, Any, Union, List, Tuple, Literal from .index_host_store import IndexHostStore @@ -23,12 +23,14 @@ ConfigureIndexRequest, ConfigureIndexRequestSpec, ConfigureIndexRequestSpecPod, + DeletionProtection, IndexSpec, ServerlessSpec as ServerlessSpecModel, PodSpec as PodSpecModel, PodSpecMetadataConfig, ) -from pinecone.models import ServerlessSpec, PodSpec, IndexList, CollectionList +from pinecone.core.openapi.shared import API_VERSION +from pinecone.models import ServerlessSpec, PodSpec, IndexModel, IndexList, CollectionList from .langchain_import_warnings import _build_langchain_attribute_error_message from pinecone.data import Index @@ -229,6 +231,7 @@ def __init__( config=self.config, openapi_config=self.openapi_config, pool_threads=pool_threads, + api_version=API_VERSION, ) self.index_host_store = IndexHostStore() @@ -258,6 +261,7 @@ def create_index( spec: Union[Dict, ServerlessSpec, PodSpec], metric: Optional[str] = "cosine", timeout: Optional[int] = None, + deletion_protection: Optional[Literal["enabled", "disabled"]] = "disabled", ): """Creates a Pinecone index. @@ -278,6 +282,7 @@ def create_index( :type timeout: int, optional :param timeout: Specify the number of seconds to wait until index gets ready. If None, wait indefinitely; if >=0, time out after this many seconds; if -1, return immediately and do not wait. Default: None + :param deletion_protection: If enabled, the index cannot be deleted. If disabled, the index can be deleted. Default: "disabled" ### Creating a serverless index @@ -291,7 +296,8 @@ def create_index( name="my_index", dimension=1536, metric="cosine", - spec=ServerlessSpec(cloud="aws", region="us-west-2") + spec=ServerlessSpec(cloud="aws", region="us-west-2"), + deletion_protection="enabled" ) ``` @@ -310,7 +316,8 @@ def create_index( spec=PodSpec( environment="us-east1-gcp", pod_type="p1.x1" - ) + ), + deletion_protection="enabled" ) ``` """ @@ -320,6 +327,11 @@ def create_index( def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: return {arg_name: val for arg_name, val in args if val is not None} + if deletion_protection in ["enabled", "disabled"]: + dp = DeletionProtection(deletion_protection) + else: + raise ValueError("deletion_protection must be either 'enabled' or 'disabled'") + if isinstance(spec, dict): if "serverless" in spec: index_spec = IndexSpec(serverless=ServerlessSpecModel(**spec["serverless"])) @@ -376,6 +388,7 @@ def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: dimension=dimension, metric=metric, spec=index_spec, + deletion_protection=dp, ), ) @@ -454,7 +467,7 @@ def list_indexes(self) -> IndexList: index name, dimension, metric, status, and spec. :return: Returns an `IndexList` object, which is iterable and contains a - list of `IndexDescription` objects. It also has a convenience method `names()` + list of `IndexModel` objects. It also has a convenience method `names()` which returns a list of index names. ```python @@ -498,7 +511,7 @@ def describe_index(self, name: str): """Describes a Pinecone index. :param name: the name of the index to describe. - :return: Returns an `IndexDescription` object + :return: Returns an `IndexModel` object which gives access to properties such as the index name, dimension, metric, host url, status, and spec. @@ -530,13 +543,14 @@ def describe_index(self, name: str): host = description.host self.index_host_store.set_host(self.config, name, host) - return description + return IndexModel(description) def configure_index( self, name: str, replicas: Optional[int] = None, pod_type: Optional[str] = None, + deletion_protection: Optional[Literal["enabled", "disabled"]] = None, ): """This method is used to scale configuration fields for your pod-based Pinecone index. @@ -561,15 +575,28 @@ def configure_index( """ api_instance = self.index_api - config_args: Dict[str, Any] = {} + + if deletion_protection is None: + description = self.describe_index(name=name) + dp = DeletionProtection(description.deletion_protection) + elif deletion_protection in ["enabled", "disabled"]: + dp = DeletionProtection(deletion_protection) + else: + raise ValueError("deletion_protection must be either 'enabled' or 'disabled'") + + pod_config_args: Dict[str, Any] = {} if pod_type: - config_args.update(pod_type=pod_type) + pod_config_args.update(pod_type=pod_type) if replicas: - config_args.update(replicas=replicas) - configure_index_request = ConfigureIndexRequest( - spec=ConfigureIndexRequestSpec(pod=ConfigureIndexRequestSpecPod(**config_args)) - ) - api_instance.configure_index(name, configure_index_request=configure_index_request) + pod_config_args.update(replicas=replicas) + + if pod_config_args != {}: + spec = ConfigureIndexRequestSpec(pod=ConfigureIndexRequestSpecPod(**pod_config_args)) + req = ConfigureIndexRequest(deletion_protection=dp, spec=spec) + else: + req = ConfigureIndexRequest(deletion_protection=dp) + + api_instance.configure_index(name, configure_index_request=req) def create_collection(self, name: str, source: str): """Create a collection from a pod-based index @@ -634,7 +661,6 @@ def describe_collection(self, name: str): print(description.source) print(description.status) print(description.size) - print(description.) ``` """ api_instance = self.index_api diff --git a/pinecone/core/openapi/control/api/inference_api.py b/pinecone/core/openapi/control/api/inference_api.py index 6a14ef748..271190d1e 100644 --- a/pinecone/core/openapi/control/api/inference_api.py +++ b/pinecone/core/openapi/control/api/inference_api.py @@ -23,7 +23,7 @@ ) from pinecone.core.openapi.control.model.embed_request import EmbedRequest from pinecone.core.openapi.control.model.embeddings_list import EmbeddingsList -from pinecone.core.openapi.control.model.inline_response401 import InlineResponse401 +from pinecone.core.openapi.control.model.error_response import ErrorResponse class InferenceApi(object): diff --git a/pinecone/core/openapi/control/api/manage_indexes_api.py b/pinecone/core/openapi/control/api/manage_indexes_api.py index b1b9b512f..b0f67810b 100644 --- a/pinecone/core/openapi/control/api/manage_indexes_api.py +++ b/pinecone/core/openapi/control/api/manage_indexes_api.py @@ -26,9 +26,9 @@ from pinecone.core.openapi.control.model.configure_index_request import ConfigureIndexRequest from pinecone.core.openapi.control.model.create_collection_request import CreateCollectionRequest from pinecone.core.openapi.control.model.create_index_request import CreateIndexRequest +from pinecone.core.openapi.control.model.error_response import ErrorResponse from pinecone.core.openapi.control.model.index_list import IndexList from pinecone.core.openapi.control.model.index_model import IndexModel -from pinecone.core.openapi.control.model.inline_response401 import InlineResponse401 class ManageIndexesApi(object): @@ -46,7 +46,7 @@ def __init__(self, api_client=None): def __configure_index(self, index_name, configure_index_request, **kwargs): """Configure an index # noqa: E501 - This operation specifies the pod type and number of replicas for an index. It applies to pod-based indexes only. Serverless indexes scale automatically based on usage. # noqa: E501 + This operation configures an existing index. For serverless indexes, you can configure only index deletion protection. For pod-based indexes, you can configure the pod size, number of replicas, and index deletion protection. It is not possible to change the pod type of a pod-based index. However, you can create a collection from a pod-based index and then [create a new pod-based index with a different pod type](http://docs.pinecone.io/guides/indexes/create-an-index#create-an-index-from-a-collection) from the collection. For guidance and examples, see [Configure an index](http://docs.pinecone.io/guides/indexes/configure-an-index). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -55,7 +55,7 @@ def __configure_index(self, index_name, configure_index_request, **kwargs): Args: index_name (str): The name of the index to configure. - configure_index_request (ConfigureIndexRequest): The desired pod type and replica configuration for the index. + configure_index_request (ConfigureIndexRequest): The desired pod size and replica configuration for the index. Keyword Args: _return_http_data_only (bool): response data without head status diff --git a/pinecone/core/openapi/control/model/collection_model.py b/pinecone/core/openapi/control/model/collection_model.py index a0779fe9b..081eab8c9 100644 --- a/pinecone/core/openapi/control/model/collection_model.py +++ b/pinecone/core/openapi/control/model/collection_model.py @@ -63,7 +63,7 @@ class CollectionModel(ModelNormal): validations = { ("dimension",): { - "inclusive_maximum": 2000, + "inclusive_maximum": 20000, "inclusive_minimum": 1, }, } diff --git a/pinecone/core/openapi/control/model/configure_index_request.py b/pinecone/core/openapi/control/model/configure_index_request.py index 265a3ccc8..4966e804f 100644 --- a/pinecone/core/openapi/control/model/configure_index_request.py +++ b/pinecone/core/openapi/control/model/configure_index_request.py @@ -31,8 +31,10 @@ def lazy_import(): from pinecone.core.openapi.control.model.configure_index_request_spec import ConfigureIndexRequestSpec + from pinecone.core.openapi.control.model.deletion_protection import DeletionProtection globals()["ConfigureIndexRequestSpec"] = ConfigureIndexRequestSpec + globals()["DeletionProtection"] = DeletionProtection class ConfigureIndexRequest(ModelNormal): @@ -97,6 +99,7 @@ def openapi_types(): lazy_import() return { "spec": (ConfigureIndexRequestSpec,), # noqa: E501 + "deletion_protection": (DeletionProtection,), # noqa: E501 } @cached_property @@ -105,6 +108,7 @@ def discriminator(): attribute_map = { "spec": "spec", # noqa: E501 + "deletion_protection": "deletion_protection", # noqa: E501 } read_only_vars = {} @@ -113,12 +117,9 @@ def discriminator(): @classmethod @convert_js_args_to_python_args - def _from_openapi_data(cls, spec, *args, **kwargs): # noqa: E501 + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """ConfigureIndexRequest - a model defined in OpenAPI - Args: - spec (ConfigureIndexRequestSpec): - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -150,6 +151,8 @@ def _from_openapi_data(cls, spec, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + spec (ConfigureIndexRequestSpec): [optional] # noqa: E501 + deletion_protection (DeletionProtection): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -178,7 +181,6 @@ def _from_openapi_data(cls, spec, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.spec = spec for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map @@ -203,12 +205,9 @@ def _from_openapi_data(cls, spec, *args, **kwargs): # noqa: E501 ) @convert_js_args_to_python_args - def __init__(self, spec, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ConfigureIndexRequest - a model defined in OpenAPI - Args: - spec (ConfigureIndexRequestSpec): - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -240,6 +239,8 @@ def __init__(self, spec, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + spec (ConfigureIndexRequestSpec): [optional] # noqa: E501 + deletion_protection (DeletionProtection): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -266,7 +267,6 @@ def __init__(self, spec, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - self.spec = spec for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map diff --git a/pinecone/core/openapi/control/model/create_index_request.py b/pinecone/core/openapi/control/model/create_index_request.py index 4e21d13fa..4603e4479 100644 --- a/pinecone/core/openapi/control/model/create_index_request.py +++ b/pinecone/core/openapi/control/model/create_index_request.py @@ -30,8 +30,10 @@ def lazy_import(): + from pinecone.core.openapi.control.model.deletion_protection import DeletionProtection from pinecone.core.openapi.control.model.index_spec import IndexSpec + globals()["DeletionProtection"] = DeletionProtection globals()["IndexSpec"] = IndexSpec @@ -115,6 +117,7 @@ def openapi_types(): "dimension": (int,), # noqa: E501 "spec": (IndexSpec,), # noqa: E501 "metric": (str,), # noqa: E501 + "deletion_protection": (DeletionProtection,), # noqa: E501 } @cached_property @@ -126,6 +129,7 @@ def discriminator(): "dimension": "dimension", # noqa: E501 "spec": "spec", # noqa: E501 "metric": "metric", # noqa: E501 + "deletion_protection": "deletion_protection", # noqa: E501 } read_only_vars = {} @@ -174,6 +178,7 @@ def _from_openapi_data(cls, name, dimension, spec, *args, **kwargs): # noqa: E5 through its discriminator because we passed in _visited_composed_classes = (Animal,) metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. [optional] if omitted the server will use the default value of "cosine" # noqa: E501 + deletion_protection (DeletionProtection): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) @@ -269,6 +274,7 @@ def __init__(self, name, dimension, spec, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) metric (str): The distance metric to be used for similarity search. You can use 'euclidean', 'cosine', or 'dotproduct'.. [optional] if omitted the server will use the default value of "cosine" # noqa: E501 + deletion_protection (DeletionProtection): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) diff --git a/pinecone/core/openapi/control/model/deletion_protection.py b/pinecone/core/openapi/control/model/deletion_protection.py new file mode 100644 index 000000000..947b01066 --- /dev/null +++ b/pinecone/core/openapi/control/model/deletion_protection.py @@ -0,0 +1,293 @@ +""" + Pinecone Control Plane API + + Pinecone is a vector database that makes it easy to search and retrieve billions of high-dimensional vectors. # noqa: E501 + + The version of the OpenAPI document: 2024-07 + Contact: support@pinecone.io + Generated by: https://openapi-generator.tech +""" + +import re # noqa: F401 +import sys # noqa: F401 + +from pinecone.core.openapi.shared.model_utils import ( # noqa: F401 + PineconeApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from pinecone.core.openapi.shared.model_utils import OpenApiModel +from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError + + +class DeletionProtection(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ("value",): { + "DISABLED": "disabled", + "ENABLED": "enabled", + }, + } + + validations = {} + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ( + bool, + date, + datetime, + dict, + float, + int, + list, + str, + none_type, + ) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + "value": (str,), + } + + @cached_property + def discriminator(): + return None + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set( + [ + "_data_store", + "_check_type", + "_spec_property_naming", + "_path_to_item", + "_configuration", + "_visited_composed_classes", + ] + ) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """DeletionProtection - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): Whether [deletion protection](http://docs.pinecone.io/guides/indexes/prevent-index-deletion) is enabled/disabled for the index. . if omitted defaults to "disabled", must be one of ["disabled", "enabled", ] # noqa: E501 + + Keyword Args: + value (str): Whether [deletion protection](http://docs.pinecone.io/guides/indexes/prevent-index-deletion) is enabled/disabled for the index. . if omitted defaults to "disabled", must be one of ["disabled", "enabled", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + value = "disabled" + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """DeletionProtection - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): Whether [deletion protection](http://docs.pinecone.io/guides/indexes/prevent-index-deletion) is enabled/disabled for the index. . if omitted defaults to "disabled", must be one of ["disabled", "enabled", ] # noqa: E501 + + Keyword Args: + value (str): Whether [deletion protection](http://docs.pinecone.io/guides/indexes/prevent-index-deletion) is enabled/disabled for the index. . if omitted defaults to "disabled", must be one of ["disabled", "enabled", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop("_path_to_item", ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if "value" in kwargs: + value = kwargs.pop("value") + elif args: + args = list(args) + value = args.pop(0) + else: + value = "disabled" + + _check_type = kwargs.pop("_check_type", True) + _spec_property_naming = kwargs.pop("_spec_property_naming", False) + _configuration = kwargs.pop("_configuration", None) + _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) + + if args: + raise PineconeApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." + % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise PineconeApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." + % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/pinecone/core/openapi/control/model/inline_response401.py b/pinecone/core/openapi/control/model/error_response.py similarity index 96% rename from pinecone/core/openapi/control/model/inline_response401.py rename to pinecone/core/openapi/control/model/error_response.py index 5d8618bfc..0600b1188 100644 --- a/pinecone/core/openapi/control/model/inline_response401.py +++ b/pinecone/core/openapi/control/model/error_response.py @@ -30,12 +30,12 @@ def lazy_import(): - from pinecone.core.openapi.control.model.inline_response401_error import InlineResponse401Error + from pinecone.core.openapi.control.model.error_response_error import ErrorResponseError - globals()["InlineResponse401Error"] = InlineResponse401Error + globals()["ErrorResponseError"] = ErrorResponseError -class InlineResponse401(ModelNormal): +class ErrorResponse(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -97,7 +97,7 @@ def openapi_types(): lazy_import() return { "status": (int,), # noqa: E501 - "error": (InlineResponse401Error,), # noqa: E501 + "error": (ErrorResponseError,), # noqa: E501 } @cached_property @@ -116,11 +116,11 @@ def discriminator(): @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, status, error, *args, **kwargs): # noqa: E501 - """InlineResponse401 - a model defined in OpenAPI + """ErrorResponse - a model defined in OpenAPI Args: status (int): The HTTP status code of the error. - error (InlineResponse401Error): + error (ErrorResponseError): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -208,11 +208,11 @@ def _from_openapi_data(cls, status, error, *args, **kwargs): # noqa: E501 @convert_js_args_to_python_args def __init__(self, status, error, *args, **kwargs): # noqa: E501 - """InlineResponse401 - a model defined in OpenAPI + """ErrorResponse - a model defined in OpenAPI Args: status (int): The HTTP status code of the error. - error (InlineResponse401Error): + error (ErrorResponseError): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types diff --git a/pinecone/core/openapi/control/model/inline_response401_error.py b/pinecone/core/openapi/control/model/error_response_error.py similarity index 98% rename from pinecone/core/openapi/control/model/inline_response401_error.py rename to pinecone/core/openapi/control/model/error_response_error.py index 33774f42c..cc5227ab4 100644 --- a/pinecone/core/openapi/control/model/inline_response401_error.py +++ b/pinecone/core/openapi/control/model/error_response_error.py @@ -29,7 +29,7 @@ from pinecone.core.openapi.shared.exceptions import PineconeApiAttributeError -class InlineResponse401Error(ModelNormal): +class ErrorResponseError(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -73,6 +73,7 @@ class InlineResponse401Error(ModelNormal): "UNAVAILABLE": "UNAVAILABLE", "DATA_LOSS": "DATA_LOSS", "FORBIDDEN": "FORBIDDEN", + "UNPROCESSABLE_ENTITY": "UNPROCESSABLE_ENTITY", }, } @@ -131,7 +132,7 @@ def discriminator(): @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, code, message, *args, **kwargs): # noqa: E501 - """InlineResponse401Error - a model defined in OpenAPI + """ErrorResponseError - a model defined in OpenAPI Args: code (str): @@ -224,7 +225,7 @@ def _from_openapi_data(cls, code, message, *args, **kwargs): # noqa: E501 @convert_js_args_to_python_args def __init__(self, code, message, *args, **kwargs): # noqa: E501 - """InlineResponse401Error - a model defined in OpenAPI + """ErrorResponseError - a model defined in OpenAPI Args: code (str): diff --git a/pinecone/core/openapi/control/model/index_model.py b/pinecone/core/openapi/control/model/index_model.py index 60fe4ef3f..e95de6f14 100644 --- a/pinecone/core/openapi/control/model/index_model.py +++ b/pinecone/core/openapi/control/model/index_model.py @@ -30,9 +30,11 @@ def lazy_import(): + from pinecone.core.openapi.control.model.deletion_protection import DeletionProtection from pinecone.core.openapi.control.model.index_model_spec import IndexModelSpec from pinecone.core.openapi.control.model.index_model_status import IndexModelStatus + globals()["DeletionProtection"] = DeletionProtection globals()["IndexModelSpec"] = IndexModelSpec globals()["IndexModelStatus"] = IndexModelStatus @@ -119,6 +121,7 @@ def openapi_types(): "host": (str,), # noqa: E501 "spec": (IndexModelSpec,), # noqa: E501 "status": (IndexModelStatus,), # noqa: E501 + "deletion_protection": (DeletionProtection,), # noqa: E501 } @cached_property @@ -132,6 +135,7 @@ def discriminator(): "host": "host", # noqa: E501 "spec": "spec", # noqa: E501 "status": "status", # noqa: E501 + "deletion_protection": "deletion_protection", # noqa: E501 } read_only_vars = {} @@ -182,6 +186,7 @@ def _from_openapi_data(cls, name, dimension, host, spec, status, *args, **kwargs Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + deletion_protection (DeletionProtection): [optional] # noqa: E501 """ metric = kwargs.get("metric", "cosine") @@ -283,6 +288,7 @@ def __init__(self, name, dimension, host, spec, status, *args, **kwargs): # noq Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) + deletion_protection (DeletionProtection): [optional] # noqa: E501 """ metric = kwargs.get("metric", "cosine") diff --git a/pinecone/core/openapi/control/model/pod_spec.py b/pinecone/core/openapi/control/model/pod_spec.py index a20e22b13..9466d3b1b 100644 --- a/pinecone/core/openapi/control/model/pod_spec.py +++ b/pinecone/core/openapi/control/model/pod_spec.py @@ -62,15 +62,15 @@ class PodSpec(ModelNormal): allowed_values = {} validations = { - ("pods",): { - "inclusive_minimum": 1, - }, ("replicas",): { "inclusive_minimum": 1, }, ("shards",): { "inclusive_minimum": 1, }, + ("pods",): { + "inclusive_minimum": 1, + }, } @cached_property @@ -107,10 +107,10 @@ def openapi_types(): lazy_import() return { "environment": (str,), # noqa: E501 - "pod_type": (str,), # noqa: E501 - "pods": (int,), # noqa: E501 "replicas": (int,), # noqa: E501 "shards": (int,), # noqa: E501 + "pod_type": (str,), # noqa: E501 + "pods": (int,), # noqa: E501 "metadata_config": (PodSpecMetadataConfig,), # noqa: E501 "source_collection": (str,), # noqa: E501 } @@ -121,10 +121,10 @@ def discriminator(): attribute_map = { "environment": "environment", # noqa: E501 - "pod_type": "pod_type", # noqa: E501 - "pods": "pods", # noqa: E501 "replicas": "replicas", # noqa: E501 "shards": "shards", # noqa: E501 + "pod_type": "pod_type", # noqa: E501 + "pods": "pods", # noqa: E501 "metadata_config": "metadata_config", # noqa: E501 "source_collection": "source_collection", # noqa: E501 } @@ -142,6 +142,8 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 environment (str): The environment where the index is hosted. Keyword Args: + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. defaults to 1 # noqa: E501 + shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. defaults to 1 # noqa: E501 pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1" # noqa: E501 pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.'. defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types @@ -174,12 +176,12 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 metadata_config (PodSpecMetadataConfig): [optional] # noqa: E501 source_collection (str): The name of the collection to be used as the source for the index.. [optional] # noqa: E501 """ + replicas = kwargs.get("replicas", 1) + shards = kwargs.get("shards", 1) pod_type = kwargs.get("pod_type", "p1.x1") pods = kwargs.get("pods", 1) _check_type = kwargs.pop("_check_type", True) @@ -209,6 +211,8 @@ def _from_openapi_data(cls, environment, *args, **kwargs): # noqa: E501 self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.environment = environment + self.replicas = replicas + self.shards = shards self.pod_type = pod_type self.pods = pods for var_name, var_value in kwargs.items(): @@ -242,6 +246,8 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 environment (str): The environment where the index is hosted. Keyword Args: + replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. defaults to 1 # noqa: E501 + shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. defaults to 1 # noqa: E501 pod_type (str): The type of pod to use. One of `s1`, `p1`, or `p2` appended with `.` and one of `x1`, `x2`, `x4`, or `x8`.. defaults to "p1.x1" # noqa: E501 pods (int): The number of pods to be used in the index. This should be equal to `shards` x `replicas`.'. defaults to 1 # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types @@ -274,12 +280,12 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - replicas (int): The number of replicas. Replicas duplicate your index. They provide higher availability and throughput. Replicas can be scaled up or down as your needs change.. [optional] if omitted the server will use the default value of 1 # noqa: E501 - shards (int): The number of shards. Shards split your data across multiple pods so you can fit more data into an index.. [optional] if omitted the server will use the default value of 1 # noqa: E501 metadata_config (PodSpecMetadataConfig): [optional] # noqa: E501 source_collection (str): The name of the collection to be used as the source for the index.. [optional] # noqa: E501 """ + replicas = kwargs.get("replicas", 1) + shards = kwargs.get("shards", 1) pod_type = kwargs.get("pod_type", "p1.x1") pods = kwargs.get("pods", 1) _check_type = kwargs.pop("_check_type", True) @@ -307,6 +313,8 @@ def __init__(self, environment, *args, **kwargs): # noqa: E501 self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.environment = environment + self.replicas = replicas + self.shards = shards self.pod_type = pod_type self.pods = pods for var_name, var_value in kwargs.items(): diff --git a/pinecone/core/openapi/control/model/serverless_spec.py b/pinecone/core/openapi/control/model/serverless_spec.py index 2af0d1369..43176b22b 100644 --- a/pinecone/core/openapi/control/model/serverless_spec.py +++ b/pinecone/core/openapi/control/model/serverless_spec.py @@ -117,8 +117,8 @@ def _from_openapi_data(cls, cloud, region, *args, **kwargs): # noqa: E501 """ServerlessSpec - a model defined in OpenAPI Args: - cloud (str): The public cloud where you would like your index hosted. Serverless indexes can be hosted only in AWS at this time. - region (str): The region where you would like your index to be created. Serverless indexes can be created only in the us-east-1,us-west-2, and eu-west-1 regions of AWS at this time. + cloud (str): The public cloud where you would like your index hosted. + region (str): The region where you would like your index to be created. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -209,8 +209,8 @@ def __init__(self, cloud, region, *args, **kwargs): # noqa: E501 """ServerlessSpec - a model defined in OpenAPI Args: - cloud (str): The public cloud where you would like your index hosted. Serverless indexes can be hosted only in AWS at this time. - region (str): The region where you would like your index to be created. Serverless indexes can be created only in the us-east-1,us-west-2, and eu-west-1 regions of AWS at this time. + cloud (str): The public cloud where you would like your index hosted. + region (str): The region where you would like your index to be created. Keyword Args: _check_type (bool): if True, values for parameters in openapi_types diff --git a/pinecone/core/openapi/control/models/__init__.py b/pinecone/core/openapi/control/models/__init__.py index 29a7c69bf..b742b6a73 100644 --- a/pinecone/core/openapi/control/models/__init__.py +++ b/pinecone/core/openapi/control/models/__init__.py @@ -16,19 +16,20 @@ from pinecone.core.openapi.control.model.configure_index_request_spec_pod import ConfigureIndexRequestSpecPod from pinecone.core.openapi.control.model.create_collection_request import CreateCollectionRequest from pinecone.core.openapi.control.model.create_index_request import CreateIndexRequest +from pinecone.core.openapi.control.model.deletion_protection import DeletionProtection from pinecone.core.openapi.control.model.embed_request import EmbedRequest from pinecone.core.openapi.control.model.embed_request_inputs import EmbedRequestInputs from pinecone.core.openapi.control.model.embed_request_parameters import EmbedRequestParameters from pinecone.core.openapi.control.model.embedding import Embedding from pinecone.core.openapi.control.model.embeddings_list import EmbeddingsList from pinecone.core.openapi.control.model.embeddings_list_usage import EmbeddingsListUsage +from pinecone.core.openapi.control.model.error_response import ErrorResponse +from pinecone.core.openapi.control.model.error_response_error import ErrorResponseError from pinecone.core.openapi.control.model.index_list import IndexList from pinecone.core.openapi.control.model.index_model import IndexModel from pinecone.core.openapi.control.model.index_model_spec import IndexModelSpec from pinecone.core.openapi.control.model.index_model_status import IndexModelStatus from pinecone.core.openapi.control.model.index_spec import IndexSpec -from pinecone.core.openapi.control.model.inline_response401 import InlineResponse401 -from pinecone.core.openapi.control.model.inline_response401_error import InlineResponse401Error from pinecone.core.openapi.control.model.pod_spec import PodSpec from pinecone.core.openapi.control.model.pod_spec_metadata_config import PodSpecMetadataConfig from pinecone.core.openapi.control.model.serverless_spec import ServerlessSpec diff --git a/pinecone/core/openapi/shared/__init__.py b/pinecone/core/openapi/shared/__init__.py new file mode 100644 index 000000000..b740b5e0b --- /dev/null +++ b/pinecone/core/openapi/shared/__init__.py @@ -0,0 +1 @@ +API_VERSION = "2024-07" diff --git a/pinecone/models/__init__.py b/pinecone/models/__init__.py index e15ce43e4..d917323a2 100644 --- a/pinecone/models/__init__.py +++ b/pinecone/models/__init__.py @@ -1,6 +1,4 @@ from .index_description import ( - IndexDescription, - IndexStatus, ServerlessSpecDefinition, PodSpecDefinition, ) @@ -9,15 +7,15 @@ from .pod_spec import PodSpec from .index_list import IndexList from .collection_list import CollectionList +from .index_model import IndexModel __all__ = [ "CollectionDescription", - "IndexDescription", - "IndexStatus", "PodSpec", "PodSpecDefinition", "ServerlessSpec", "ServerlessSpecDefinition", "IndexList", "CollectionList", + "IndexModel", ] diff --git a/pinecone/models/index_description.py b/pinecone/models/index_description.py index f6d2d5bac..1d29b526e 100644 --- a/pinecone/models/index_description.py +++ b/pinecone/models/index_description.py @@ -1,14 +1,6 @@ from typing import NamedTuple, Dict, Optional, Union, Literal -class IndexStatus(NamedTuple): - state: str - ready: bool - - -PodKey = Literal["pod"] - - class PodSpecDefinition(NamedTuple): replicas: int shards: int @@ -18,50 +10,13 @@ class PodSpecDefinition(NamedTuple): metadata_config: Optional[Dict] -PodSpec = Dict[PodKey, PodSpecDefinition] - -ServerlessKey = Literal["serverless"] - - class ServerlessSpecDefinition(NamedTuple): cloud: str region: str -ServerlessSpec = Dict[ServerlessKey, ServerlessSpecDefinition] - - -class IndexDescription(NamedTuple): - """ - The description of an index. This object is returned from the `describe_index()` method. - """ - - name: str - """ - The name of the index - """ - - dimension: int - """ - The dimension of the index. This corresponds to the length of the vectors stored in the index. - """ - - metric: str - """ - One of 'cosine', 'euclidean', or 'dotproduct'. - """ - - host: str - """ - The endpoint you will use to connect to this index for data operations such as upsert and query. - """ - - spec: Union[PodSpec, ServerlessSpec] - """ - The spec describes how the index is being deployed. - """ +PodKey = Literal["pod"] +PodSpec = Dict[PodKey, PodSpecDefinition] - status: IndexStatus - """ - Status includes information on whether the index is ready to accept data operations. - """ +ServerlessKey = Literal["serverless"] +ServerlessSpec = Dict[ServerlessKey, ServerlessSpecDefinition] diff --git a/pinecone/models/index_list.py b/pinecone/models/index_list.py index d9823e219..6c524489d 100644 --- a/pinecone/models/index_list.py +++ b/pinecone/models/index_list.py @@ -1,22 +1,24 @@ from pinecone.core.openapi.control.models import IndexList as OpenAPIIndexList +from .index_model import IndexModel class IndexList: def __init__(self, index_list: OpenAPIIndexList): self.index_list = index_list + self.indexes = [IndexModel(i) for i in self.index_list.indexes] self.current = 0 def names(self): - return [i["name"] for i in self.index_list.indexes] + return [i.name for i in self.indexes] def __getitem__(self, key): - return self.index_list.indexes[key] + return self.indexes[key] def __len__(self): - return len(self.index_list.indexes) + return len(self.indexes) def __iter__(self): - return iter(self.index_list.indexes) + return iter(self.indexes) def __str__(self): return str(self.index_list) diff --git a/pinecone/models/index_model.py b/pinecone/models/index_model.py new file mode 100644 index 000000000..9d46b0ed7 --- /dev/null +++ b/pinecone/models/index_model.py @@ -0,0 +1,19 @@ +from pinecone.core.openapi.control.models import IndexModel as OpenAPIIndexModel + + +class IndexModel: + def __init__(self, index: OpenAPIIndexModel): + self.index = index + self.deletion_protection = index.deletion_protection.value + + def __str__(self): + return str(self.index) + + def __repr__(self): + return repr(self.index) + + def __getattr__(self, attr): + return getattr(self.index, attr) + + def __getitem__(self, key): + return self.__getattr__(key) diff --git a/tests/integration/control/pod/test_deletion_protection.py b/tests/integration/control/pod/test_deletion_protection.py new file mode 100644 index 000000000..f1aec19d0 --- /dev/null +++ b/tests/integration/control/pod/test_deletion_protection.py @@ -0,0 +1,45 @@ +import pytest +from pinecone import PodSpec + + +class TestDeletionProtection: + def test_deletion_protection(self, client, index_name, environment): + client.create_index( + name=index_name, dimension=2, deletion_protection="enabled", spec=PodSpec(environment=environment) + ) + desc = client.describe_index(index_name) + print(desc.deletion_protection) + print(desc.deletion_protection.__class__) + assert desc.deletion_protection == "enabled" + + with pytest.raises(Exception) as e: + client.delete_index(index_name) + assert "Deletion protection is enabled for this index" in str(e.value) + + client.configure_index(index_name, deletion_protection="disabled") + desc = client.describe_index(index_name) + assert desc.deletion_protection == "disabled" + + client.delete_index(index_name) + + def test_configure_index_with_deletion_protection(self, client, index_name, environment): + client.create_index( + name=index_name, dimension=2, deletion_protection="enabled", spec=PodSpec(environment=environment) + ) + desc = client.describe_index(index_name) + assert desc.deletion_protection == "enabled" + + # Changing replicas only should not change deletion protection + client.configure_index(name=index_name, replicas=2) + desc = client.describe_index(index_name) + assert desc.spec.pod.replicas == 2 + assert desc.deletion_protection == "enabled" + + # Changing both replicas and delete protection in one shot + client.configure_index(name=index_name, replicas=3, deletion_protection="disabled") + desc = client.describe_index(index_name) + assert desc.spec.pod.replicas == 3 + assert desc.deletion_protection == "disabled" + + # Cleanup + client.delete_index(index_name) diff --git a/tests/integration/control/serverless/test_create_index_sl_happy_path.py b/tests/integration/control/serverless/test_create_index_sl_happy_path.py index 4924b5905..33755e5e3 100644 --- a/tests/integration/control/serverless/test_create_index_sl_happy_path.py +++ b/tests/integration/control/serverless/test_create_index_sl_happy_path.py @@ -10,6 +10,7 @@ def test_create_index(self, client, create_sl_index_params): assert desc.name == name assert desc.dimension == dimension assert desc.metric == "cosine" + assert desc.deletion_protection == "disabled" # default value @pytest.mark.parametrize("metric", ["cosine", "euclidean", "dotproduct"]) def test_create_index_with_metric(self, client, create_sl_index_params, metric): diff --git a/tests/integration/control/serverless/test_deletion_protection.py b/tests/integration/control/serverless/test_deletion_protection.py new file mode 100644 index 000000000..0a656e8ea --- /dev/null +++ b/tests/integration/control/serverless/test_deletion_protection.py @@ -0,0 +1,31 @@ +import pytest + + +class TestDeletionProtection: + def test_deletion_protection(self, client, create_sl_index_params): + name = create_sl_index_params["name"] + client.create_index(**create_sl_index_params, deletion_protection="enabled") + desc = client.describe_index(name) + assert desc.deletion_protection == "enabled" + + with pytest.raises(Exception) as e: + client.delete_index(name) + assert "Deletion protection is enabled for this index" in str(e.value) + + client.configure_index(name, deletion_protection="disabled") + desc = client.describe_index(name) + assert desc.deletion_protection == "disabled" + + client.delete_index(name) + + @pytest.mark.parametrize("deletion_protection", ["invalid", None]) + def test_deletion_protection_invalid_options(self, client, create_sl_index_params, deletion_protection): + with pytest.raises(Exception) as e: + client.create_index(**create_sl_index_params, deletion_protection=deletion_protection) + assert "deletion_protection must be either 'enabled' or 'disabled'" in str(e.value) + + @pytest.mark.parametrize("deletion_protection", ["invalid"]) + def test_configure_deletion_protection_invalid_options(self, client, create_sl_index_params, deletion_protection): + with pytest.raises(Exception) as e: + client.create_index(**create_sl_index_params, deletion_protection=deletion_protection) + assert "deletion_protection must be either 'enabled' or 'disabled'" in str(e.value) diff --git a/tests/unit/models/test_index_list.py b/tests/unit/models/test_index_list.py index 548c672c8..44d368285 100644 --- a/tests/unit/models/test_index_list.py +++ b/tests/unit/models/test_index_list.py @@ -1,26 +1,41 @@ import pytest from pinecone import IndexList -from pinecone.core.openapi.control.models import IndexList as OpenApiIndexList +from pinecone.core.openapi.control.models import ( + IndexList as OpenApiIndexList, + IndexModel as OpenApiIndexModel, + IndexModelSpec, + IndexModelStatus, + DeletionProtection, + PodSpec as OpenApiPodSpec, +) @pytest.fixture def index_list_response(): return OpenApiIndexList( indexes=[ - { - "name": "test-index-1", - "dimension": 2, - "metric": "cosine", - "spec": { - "pod": {"environment": "us-west1-gcp", "pod_type": "p1.x1", "pods": 1, "replicas": 1, "shards": 1} - }, - }, - { - "name": "test-index-2", - "dimension": 3, - "metric": "cosine", - "spec": {"serverless": {"cloud": "aws", "region": "us-west-2"}}, - }, + OpenApiIndexModel( + name="test-index-1", + dimension=2, + metric="cosine", + host="https://test-index-1.pinecone.io", + status=IndexModelStatus(ready=True, state="Ready"), + deletion_protection=DeletionProtection("enabled"), + spec=IndexModelSpec( + pod=OpenApiPodSpec(environment="us-west1-gcp", pod_type="p1.x1", pods=1, replicas=1, shards=1) + ), + ), + OpenApiIndexModel( + name="test-index-2", + dimension=3, + metric="cosine", + host="https://test-index-2.pinecone.io", + status=IndexModelStatus(ready=True, state="Ready"), + deletion_protection=DeletionProtection("disabled"), + spec=IndexModelSpec( + pod=OpenApiPodSpec(environment="us-west1-gcp", pod_type="p1.x1", pods=1, replicas=1, shards=1) + ), + ), ], _check_type=False, ) @@ -42,12 +57,19 @@ def test_index_list_names_syntactic_sugar(self, index_list_response): def test_index_list_getitem(self, index_list_response): iil = IndexList(index_list_response) - assert iil[0] == index_list_response.indexes[0] - assert iil[1] == index_list_response.indexes[1] + input = index_list_response + assert input.indexes[0].name == iil[0].name + assert input.indexes[0].dimension == iil[0].dimension + assert input.indexes[0].metric == iil[0].metric + assert input.indexes[0].host == iil[0].host + assert input.indexes[0].deletion_protection.value == iil[0].deletion_protection + assert iil[0].deletion_protection == "enabled" + + assert input.indexes[1].name == iil[1].name def test_index_list_proxies_methods(self, index_list_response): # Forward compatibility, in case we add more attributes to IndexList for pagination - assert IndexList(index_list_response).index_list.indexes == index_list_response.indexes + assert IndexList(index_list_response).indexes[0].name == index_list_response.indexes[0].name def test_when_results_are_empty(self): iil = IndexList(OpenApiIndexList(indexes=[])) diff --git a/tests/unit/models/test_index_model.py b/tests/unit/models/test_index_model.py new file mode 100644 index 000000000..f80d4b741 --- /dev/null +++ b/tests/unit/models/test_index_model.py @@ -0,0 +1,33 @@ +from pinecone.core.openapi.control.models import ( + IndexModel as OpenApiIndexModel, + IndexModelStatus, + IndexModelSpec, + ServerlessSpec, + DeletionProtection, +) +from pinecone.models import IndexModel + + +class TestIndexModel: + def test_index_model(self): + openapi_model = OpenApiIndexModel( + name="test-index-1", + dimension=2, + metric="cosine", + host="https://test-index-1.pinecone.io", + status=IndexModelStatus(ready=True, state="Ready"), + deletion_protection=DeletionProtection("enabled"), + spec=IndexModelSpec(serverless=ServerlessSpec(cloud="aws", region="us-west-1")), + ) + + wrapped = IndexModel(openapi_model) + + assert wrapped.name == "test-index-1" + assert wrapped.dimension == 2 + assert wrapped.metric == "cosine" + assert wrapped.host == "https://test-index-1.pinecone.io" + assert wrapped.status.ready == True + assert wrapped.status.state == "Ready" + assert wrapped.deletion_protection == "enabled" + + assert wrapped["name"] == "test-index-1" diff --git a/tests/unit/test_control.py b/tests/unit/test_control.py index ec8100459..3dccb4b68 100644 --- a/tests/unit/test_control.py +++ b/tests/unit/test_control.py @@ -2,7 +2,7 @@ import re from unittest.mock import patch, MagicMock from pinecone import ConfigBuilder, Pinecone, PodSpec, ServerlessSpec -from pinecone.core.openapi.control.models import IndexList, IndexModel +from pinecone.core.openapi.control.models import IndexList, IndexModel, DeletionProtection from pinecone.core.openapi.control.api.manage_indexes_api import ManageIndexesApi from pinecone.core.openapi.shared.configuration import Configuration as OpenApiConfiguration @@ -20,6 +20,7 @@ def index_list_response(): host="asdf", status={"ready": True}, spec={}, + deletion_protection=DeletionProtection("enabled"), _check_type=False, ), IndexModel( @@ -29,6 +30,7 @@ def index_list_response(): host="asdf", status={"ready": True}, spec={}, + deletion_protection=DeletionProtection("enabled"), _check_type=False, ), IndexModel( @@ -38,6 +40,7 @@ def index_list_response(): host="asdf", status={"ready": True}, spec={}, + deletion_protection=DeletionProtection("disabled"), _check_type=False, ), ] @@ -72,15 +75,19 @@ def test_passing_additional_headers(self): for key, value in extras.items(): assert p.index_api.api_client.default_headers[key] == value assert "User-Agent" in p.index_api.api_client.default_headers - assert len(p.index_api.api_client.default_headers) == 3 + assert "X-Pinecone-API-Version" in p.index_api.api_client.default_headers + assert "header1" in p.index_api.api_client.default_headers + assert "header2" in p.index_api.api_client.default_headers + assert len(p.index_api.api_client.default_headers) == 4 def test_overwrite_useragent(self): # This doesn't seem like a common use case, but we may want to allow this # when embedding the client in other pinecone tools such as canopy. extras = {"User-Agent": "test-user-agent"} p = Pinecone(api_key="123-456-789", additional_headers=extras) + assert "X-Pinecone-API-Version" in p.index_api.api_client.default_headers assert p.index_api.api_client.default_headers["User-Agent"] == "test-user-agent" - assert len(p.index_api.api_client.default_headers) == 1 + assert len(p.index_api.api_client.default_headers) == 2 def test_set_source_tag_in_useragent(self): p = Pinecone(api_key="123-456-789", source_tag="test_source_tag")